String equivalent of += - python

Is there an equivalent of += for a string?
ie:
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += 'Foo'
if x % 11 == 0:
y += 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
This should return a string and a second string if the same rules as with numbers applied. Is it possible to do this? Because just doing that returns TypeError: unsupported operand type(s) for +=: 'int' and 'str', even though y is a string to begin with, not an int.

If you do this:
You are concatenating a string to string:
x = 'a string'
x += '6'
print x
If you do this:
You concatenate int to string so you get error:
x = 'a string'
x += 6
print x
error:
TypeError: cannot concatenate 'str' and 'int' objects
You have to make sure variable type before doing '+' operation; based on variable type, python can add or concatenate

The following code works for me for Python 2.7.4 and Python 3.0:
a='aaa'
a+='bbb'
print(a)
aaabbb

That would be s1 += s2:
>>> s1 = "a string"
>>> s1 += " and a second string"
>>> s1
'a string and a second string'
>>>
Unlike Perl, Python mostly refuses to perform implicit conversions (the numeric types being the principal exception). To concatenate the string representation of an integer i to a string s, you would have to write
s += str(i)

I don't know, but maybe you are looking for operator
operator.iadd(a, b)ΒΆ
operator.__iadd__(a, b)
a = iadd(a, b) is equivalent to a += b.
http://docs.python.org/2/library/operator.html
x = 'a string'
x += ' and a second string'
print x
operator.iadd(x, ' and a third string')
print x
How can I concatenate a string and a number in Python?

I managed to fix it using isinstance()
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
if isinstance(y, str):
y += 'Buzz'
else:
y = 'Buzz'
if x % 7 == 0:
if isinstance(y, str):
y += 'Foo'
else:
y = 'Foo'
if x % 11 == 0:
if isinstance(y, str):
y += 'Bar'
else:
y = 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
Please tell me if this particularly bad code (which I have a habit of writing).

x = 1
while x <= 100:
y = str(x)
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += 'Foo'
if x % 11 == 0:
y += 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
It's quite simple.
You start off by defining X as an integer, then you increese it in a while loop.
At the very beginning of each iteration you define y = x which essentially tells python to set y into an integer.
Then depending on what x modulus <nr> you got, you add a string to the integer called y (yes, it is an integer as well).. This leads to an error because it's an illegal operation because of the way a INT and a WORD works, they're just different so you need to treat one of them prior to merging them into the same variable.
How to debug your own code: Try doing print(type(x), type(y)) and you get the differences of the two variables.. Might help you wrap your head around this.
The solution is y = str(x).
So, no.. Y is NOT a string to begin with
Because you redefine y each iteration of your while loop.
y = x <-- Makes Y a int, because that's what x is :)
Also, try using .format()
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = '{0}Fizz'.format(x)
if x % 5 == 0:
y += '{0}Buzz'.format(x)
if x % 7 == 0:
y += '{0}Foo'.format(x)
if x % 11 == 0:
y += '{0}Bar'.format(x)
print y
x += 1
raw_input('Press enter to exit...')
Another personal observation is that if x % 3 == 0 you replace y = ..., but in all other if-cases you append to y, why is this? I left it just the way you gave us the code but either do elif on the rest or why not concade on allif's

Related

I want when the user doesn't give any input this program will give 1's multiplication as output

def multiplication_maker(m=1):
n = 1
while n < 11:
print(m,"*",n,"=",m*n)
n += 1
x = input("Enter the multiplication you want =" )
x = int(x)
multiplication_maker(x)
You could check the length by using len() then assigning 1 to it
def multiplication_maker(m=1):
n = 1
while n < 11:
print(m,"*",n,"=",m*n)
n += 1
x = input("Enter the multiplication you want =" )
if len(x) == 0:
x = 1
x = int(x)
multiplication_maker(x)
Solution
You can use the fact that an empty string is evaluated as false and set a condition
x = input("Enter the multiplication you want =")
if not x:
x = "1"
x = int(x)
multiplication_maker(x)
Smart
Using the fact that is a the left operand is false (ie empty string) then the right operand will be evaluated and returned you can do that trick
x = int(input("Enter the multiplication you want =") or "1")
multiplication_maker(x)
def multiplication_maker(m=None):
try:
m = int(m)
except:
m = 1
n = 1
while n < 11:
print(m, "*", n, "=", m * n)
n += 1
x = input("Enter the multiplication you want =")
multiplication_maker(x)

boolean string not counted in while/if statement in python[3.8]

I'm a beginner programmer and chose python[3.8] as my choice to learn. I don't even know what to ask or how to search this site. My program counts 30 to 40 and prints 'Go' for multiples of 3 and strings of 3 and remainders of 3. It counts Go's. Output should be 10 but it's 3. It's not counting the strings. There is no error msgs.
`enter code here`
s = '3'
x = 40
y = 30
num = 0
while y < x :
y=y+1
if y % 3 == 0 or y % 10 == 3 or s in 'y' :
print('Go',y)
num = num + 1
print(num, 'Go\'s')
I think the problem here is to understand how python works.
When you write s in 'y' it will always return false because y here is a character that composes the string which value is ythe character.
So what you'll need to do is use the function str(param) to convert your integer to a string with the same value.
This is a code that works the way you want to.
s = '3'
x = 40
y = 30
num = 0
while y < x :
if y % 3 == 0 or y % 10 == 3 or s in str(y) :
print('Go',y)
num = num + 1
y=y+1
print(num, 'Go\'s')

why is my try- except block stuck in the loop?

I am trying to catch an Index out of range error with the following try and except block.
def getStepList(r, h, d):
x = len(r)-1
y = len(h)-1
list = []
while True:
try:
if x == 0 and y == 0:
break
elif x >= 1 and y >= 1 and d[x][y] == d[x-1][y-1] and r[x-1] == h[y-1]:
x = x - 1
y = y - 1
elif y >= 1 and d[x][y] == d[x][y-1]+1:
#insertion
x = x
y = y - 1
list.append(h[y])
print('insertion')
elif x >= 1 and y >= 1 and d[x][y] == d[x-1][y-1]+1:
#substitution
x = x - 1
y = y - 1
list.append(r[x])
print('substitution')
else:
#deletion
x = x - 1
y = y
list.append(r[x])
print('deletion')
except IndexError:
print('index error')
return list[::-1]
but it gets stuck in a infinite loop. I want it to ignore it and proceed appending the next instances. (For reference its a piece of code that uses a metric of another function to determine which words were inserted, substituted or deleted at each operation).
I feel like I should know this, but in all honesty I am stuck.
Don't do a while True. Change your while condition to:
while(not (x == 0 and y == 0)):
Inside your exception also add a break
except IndexError:
print('index error')
break
You could also add some checks to see what the specific Index Error might be:
d_len = len(d)
r_len = len(r)
h_len = len(h)
d_x_of_y_len = len(d[x][y])
if(x > d_len):
print("x is too big")
if(y > d_x_of_y_len):
print("y is too big")

Popty Ping is not working

For my homework I need to make a popty ping application, if you don't know what this is then here is a brief summary:
In popty ping, there are 3 words you can say: 'pop', 'ping' and 'popty ping'. 'Pop' is when a number can be divided into 2. 'Ping' is when a number can be divided into 3, and finally, 'Popty Ping' is when a number can be divided into 2 and 3. Let's say that you get the number 4, it would be 'Pop' since it can be divided into 2. If the number were 6 it would be 'Popty Ping' since it can be divided into 2 and 3.
Here is my code:
!!UPDATED!! The x now increased!!! Could you now give me suggestions on how I can improve the code please? THANK YOU!!!
def endValue():
x = 1
endValue = int(input("Please enter your end value: "))
main(endValue, x)
def main(endValue, x):
print(x)
poptyPingChoice = input("Is this 'ping', 'pop', 'popty ping' or 'nothing'? ")
if poptyPingChoice.lower() == "pop":
pop(endValue, x)
elif poptyPingChoice.lower() == "ping":
ping(endValue, x)
elif poptyPingChoice.lower() == "popty ping":
poptyPing(endValue, x)
elif poptyPingChoice.lower() == "nothing":
nothing(endValue, x)
def pop(endValue, x):
if x % 2 == 0 and x % 3 == 0:
return
else:
if x % 2 == 0:
print("Pop!")
x = x + 1
main(endValue, x)
def ping(endValue, x):
if x % 2 == 0 and x % 3 == 0:
return
else:
if x % 3 == 0:
print("Ping!")
x = x + 1
main(endValue, x)
def poptyPing(endValue, x):
if x % 2 == 0 and x % 3 == 0:
print("Popty Ping!")
x = x + 1
(endValue, x)
def nothing(endValue, x):
x = x + 1
main(endValue, x)
endValue()
Basically, when I type 'nothing' for the number '1', it doesn't add a + 1 to the x. I'm sure there is an obvious answer to this but I also want to know how this can be improved to be more efficient because I just know that someone will cringe at this terrible code XD.
Thank you for your help and I appreciate your opinions and suggestions on how to improve this!

Trying to turn fizzbuzz into a function in python 3

I have only just started to learn python as my first language and whilst i worked out the code for fizzbuzz, i cannot for the life of me get it to do the items below. I also want it to print horizontally instead of vertically. Any help would be great (heads spinning).
Create a function which does this.
For example
fizzbuzz(20)
would print
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz
def fizzbuzz(n):
for x in range (101):
if x%3==0 and x%5==0:
print("fizz buzz")
elif x%3==0:
print('fizz')
elif x%5==0:
print('buzz')
else:
print (x)
def main():
print(fizzbuzz(20))
Shorter yet:
for n in range(100):
print("Fizz"*(not n % 3) + "Buzz"*(not n % 5) or n)
Yes, but why?
To understand this, let's look at the parts separately.
"Fizz"*(not n % 3)
In Python, we can "multiply" strings, so "a"*3 would result in "aaa". You can also multiply a string with a boolean: "a" * True is "a", whereas "a" * False is an empty string, "". That's what's happening to our "Fizz" here. When n % 3 == 0 (ie. n is 3, 6, 9, ...), then not n % 3 will be the same as not 0, which is True. Conversely, when n is 1, 2, 4, 5, 7, ... then n % 3 will be either 1 or 2, and not n % 3 will be false. In Other words, whenever n is divisible by 3, the term "Fizz"*(not n % 3) will multiply the string "Fizz" by True, and when it's not, it will multiply by False, resulting in an empty string.
The same logic applies to the next part, "Buzz"*(not n % 5). It'll give us an empty string when n is not divisible by 5, and the string "Buzz" when it is.
Now we're adding those two things together:
"Fizz"*(not n % 3) + "Buzz"*(not n % 5)
When n is neither divisible by 3 nor 5, this will be adding two empty strings together (ie. "" + ""), which will of course give us another empty string. In that case, the whole print statement reads print("" or n). Since an empty string is False-y, it will print our number n. If n is divisible by 3 (but not 5), this would be print("Fizz" or n), and since "Fizz" is Truthy, it will just print that and omit the number.
Bonus points
Or, if you really want to impress your interviewer,
for n in range(100):
print("FizzBuzz"[n%-3&4:12&8-(n%-5&4)] or n)
Collect the items into a list. Then print the list at the end of function. You can join the items together with a comma in between using ', '.join(...).
def fizzbuzz(n):
result = []
for x in range(1, n+1):
if x % 3 == 0 and x % 5 == 0:
result.append("fizz buzz")
elif x % 3 == 0:
result.append('fizz')
elif x % 5 == 0:
result.append('buzz')
else:
result.append(str(x))
return result
def main():
print(', '.join(fizzbuzz(20)))
main()
It's good to also know that print(..., end=', ') would print "horizontally" with a comma and space at the end, and this would almost solve your problem except that the very last item would also have a comma and space at the end, which is not what you desire.
It's usually a good idea to (1) separate printing from computing, (2) make functions reusable. You often want to compute more frequently than print. In the future you may wish to pass the computation on to some other function before you print. So functions that immediate print are not as useful. So I recommend taking the print statements out of fizzbuzz.
You could return the string ', '.join(result), but how useful would that be? The list result might be (in the future) more useful for further processing, so I chose to return result. The printing I left for the main function.
def fizzbuzz(numbers, fizz, buzz):
x = ['Fizzbuzz' if x % fizz == 0 and x % buzz == 0 else 'Fizz' if x % fizz == 0 else 'Buzz' if x % buzz == 0 else x for x in numbers]
return x
Slightly more elegant
def fizzbuzz(n):
for x in range(1,n+1):
if not x % 15:
yield 'fizz buzz'
elif not x % 3:
yield 'fizz'
elif not x % 5:
yield 'buzz'
else:
yield x
if __name__ == "__main__":
print ','.join(fizzbuzz(20))
I'm a novice coder so some of the answers I did not understand or it did not seems to directly apply to my problem. This answer incorporates Fizz_Buzz as a variable and the range of x is determined by the user. I looked at the above solutions and came up with this:
def Fizz_Buzz(x):
for x in range (0,x):
if x % 3 == 0 and x % 5 == 0:
print('FizzBuzz')
elif x % 3 == 0:
print('Fizz')
elif x % 5 == 0:
print ('Buzz')
else:
print (x)
You can add end=', ' to print in order to print on the same line, with whatever character you want separating the values.
class FizzBuzz:
#staticmethod
def fizz_buzz(n):
if n % 15 == 0:
return 'FizzBuzz'
elif n % 3 == 0:
return 'Fizz'
elif n % 5 == 0:
return 'Buzz'
else:
return str(n)
def __str__(self, rng):
[print(self.fizz_buzz(n), end=', ') for n in range(1, rng + 1)]
But it leaves , at the end. Instead:
def __str__(self, rng):
print(', '.join(self.fizz_buzz(n) for n in range(1, rng + 1)))
one more :) just for fun :)
get_index = lambda i: bool(i%3)+2*bool(i%5) if i !=0 else 3
afb = lambda x: ('fizzbuzz','buzz', 'fizz', str(x))[get_index(x)]
fizzbuzz = lambda inpt: print(','.join([ afb(i) for i in inpt ]))
fizzbuzz(range(101))
'0,1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz,fizz,22,23,fizz,buzz,26,fizz,28,29,fizzbuzz,31,32,fizz,34,buzz,fizz,37,38,fizz,buzz,41,fizz,43,44,fizzbuzz,46,47,fizz,49,buzz,fizz,52,53,fizz,buzz,56,fizz,58,59,fizzbuzz,61,62,fizz,64,buzz,fizz,67,68,fizz,buzz,71,fizz,73,74,fizzbuzz,76,77,fizz,79,buzz,fizz,82,83,fizz,buzz,86,fizz,88,89,fizzbuzz,91,92,fizz,94,buzz,fizz,97,98,fizz,buzz'
i made a fizzbuzz that works for any number and words, so you can do fizzbuzzfuzz if you wanted. i made it in 6 lines (7 if you count the line that runs through the fizzfuzz)
def f(n:int,m:list,w:list):
s=''
for x in m:
if n%x==0: s+=w[m.index(x)]
if s=='': s=n
return s
for i in range(1, 100 +1): print(f(i,[3,5],['Fizz','Buzz']))
def fizzbuzz(num):
if x % 3 == 0 and x % 5 == 0:
return "Fizz Buzz"
elif x % 3 == 0:
return "Fizz"
elif x % 5 == 0:
return "Buzz"
else:
return x
MAXNUM = 100
for x in range (MAXNUM):
print fizzbuzz(x)
I've found the following works well (Python 3):
def fizzbuzz():
for i in range(1,101):
print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i)
print (fizzbuzz())
Here's a fun one (obviously not the best for readability, but still kinda fun to think about list comprehensions):
def fizzBuzz():
print(", ".join(["FizzBuzz" if x%15==0 else "Fizz" if x%3 == 0 else "Buzz" if x%5==0 else str(x) for x in range(1,101)]))
Don't forget, 3 and 5 are coprime! So you can check x % 15 instead of (x % 3 and x % 5) for "FizzBuzz".
Yet another one with list comprehension and Python3
def is_mod_zero(num, *div):
return not [d for d in div if num % d is not 0]
def fizz_buzz(num):
if is_mod_zero(num, 3, 5):
return 'FizzBuzz'
if is_mod_zero(num, 3):
return 'Fizz'
if is_mod_zero(num, 5):
return 'Buzz'
return num
if __name__ == "__main__":
for i in range(100):
print(fizz_buzz(i))
def fizzBuzz(n):
for x in range(1, n + 1):
if x % 3 == 0 and x % 5 == 0:
print("fizzbuzz")
elif x % 3 == 0:
print("fizz")
elif x % 5 == 0:
print("buzz")
else:
print(x)
print(fizzBuzz(50))

Categories