5 ms·
Could it be possible to explain what does Print "Fizz" [x%3*4::] Since range is going from 0 to 101 I have the impression the result won't match the direc
by chmike 14y ago
Could it be possible to explain what does
Print "Fizz" [x%3*4::]
Since range is going from 0 to 101 I have the impression the result won't match the directive.
- Wicher 14y agoIt prints a substring from "Fizz" using slicing. The thing is, the x%3*4 determines the start of that slice. It's either 0, which is when X modulo 3 == 0 (which is every third number in range(101) ), or something larger than 4, in which case the slice would start at the end of "Fizz" thus yielding an empty string.
- lifeisstillgood 14y ago"fizz" is a string - treated as a list in python "fizz"[0] is the zeroth character in the list / string Note "fizz"[:] will output all chars in the string (implicitly it's [0:] - from zeroth string to end X % 3 is x modulo 3, producing 0 only if x is divisible by three - so we want to print fizz here. 4 is the number of chars in both fizz and buzz - so the meat is "fizz"[x%3*4:] is "fizz"[0:] if x%3 is 0 - when we want tp print fizz, otherwise it's [somevaluegreaterthan4: to the end of the list (ie nothing). The extra : stops index error
- d0mine 14y agoI don't see any difference between a single : and double :: in this case. The second : might be included to make the slicing more visible.
- jvdh 14y agoA second : may be used to define a step value. In this case it's not used, so it's superfluous.
- chmike 14y agoNow I understand it. I wasn't aware one could append a subscript operator after a litteral string. I also didn't know of the second : role. Thank you. But what do you get if x is 0 ? As I now uneerstand it, you would get "fizzbuzz". Shouldn't the list start at value 1 ? So shouldn't the range be (1, 101) instead of (101) ?
- mburst 14y agoYou're correct. That was my mistake. Here's the updated version: for x in range(1,101):print"Fizz"[x%34:]+"Buzz"[x%54:]or x I basically just removed the extra colons and added 1, to the range so that it starts at 1. lifeisstillgood was spot on with the reasoning that this works.