FizzBuzz with commas instead of newlines - python-3.x

def fizz_buzz(i):
if i % 15 == 0:
return ("FizzBuzz")
elif i % 5 == 0:
return ("Buzz")
elif i % 3 == 0:
return ("Fizz")
else:
return (i)
for i in range(1, 21):
print(fizz_buzz(i))
Where and how would do a new line command here with commas?
Trying to get an output like this: 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19, Buzz
but sideways and with commas.

Pass end=',' to print()
def fizz_buzz(i):
if i % 15 == 0:
return ("FizzBuzz")
elif i % 5 == 0:
return ("Buzz")
elif i % 3 == 0:
return ("Fizz")
else:
return (i)
for i in range(1, 21):
print(fizz_buzz(i), end=',')
# prints
1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19,Buzz,
If you do not want the trailing comma, end the range at 20 and follow with print(fizz_buzz(20))

Consider making a list & joining the elements with a comma. There are some great examples here.
For example:
def fizz_buzz(i):
# your code
my_list = []
for i in range(1,21):
my_list.append( str(fizz_buzz(i)) )
print ",".join(my_list)
There are more elegant ways of doing this -- using generators &c, as in the linked answer --, but this simple code will do what you want. Note that the join() method accepts string only, hence the str() in the list.append(); alternatively you could ensure that your fizz_buzz function returns strings regardless.

Related

How do I write the fizzbuzz function in Python 3 with an input value?

I am writing a function fizzbuzz and what I want to do is input value and return it as fizz, buzz or fizzbuzz. However, there is a problem with my code. Whenever I run this, I just only get the first condition and it does not continue. Here is the code below for you:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0:
return ('Fizz')
elif a % 5 == 0:
return ( 'Buzz' )
elif a % 15 == 0:
return ('Fizzbuzz')
else:
return a
print(fizzbuzz(a))
The problem is in the ordering of your if conditionals.
Consider that if a is divisible by 15 then it is also divisible by 3 and 5 and so your code will just enter the first conditional and not the one you want.
Arrange the conditionals in descending order of 15, 5, 3 etc. and you should see what you want.
def fizzBuzz(n):
for n in range(1,n+1):
if n % 3 == 0 and n % 5 == 0:
print('FizzBuzz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
else:
print(n)
if __name__ == '__main__':
n = int(input().strip())
fizzBuzz(n)
Be sure that your conditions are checked in the right order.
A Fizzbuzz number is also a Fizz (divisible by 3) and a Buzz (divisible by 5), just to be clear.
In the code you wrote if you ask the function if 15 is a Buzz, since it is the 1st check, you will get a positive result.
The condition you want to test here is not if a number is divisible by 15 but if a number is divisible by 3 and 5 at the same time.
Given this explanation you need to write conditions a bit differently:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0 and a % 5 == 0:
return('Fizzbuzz')
elif a % 3 == 0:
return('Fizz')
elif a % 5 == 0:
return('Buzz')
else:
return a
print(fizzbuzz(a))

def function to compare two strings

we need to define a function that compares two strings and if they are different we want to know the index. the problem is that no matter what insert we use we always get -1 even when they are not the same.
def mutation_detector(seq1,seq2):
if DNAval(seq1) and DNAval(seq2) == True:
if len(seq1) == len(seq2):
for i in range(0, len(seq1)) and range(0, len(seq2)):
if seq1[i] != seq2[i]:
return(i)
else:
return(-1)
else:
return('Wrong input')
else:
return('Wrong input')
print(mutation_detector('ATCGGGTA','ATCGGCTA'))
Basically you're using and wrong and have some basic Logic errors I think:
and doesn't say "do A and B" but rather"if A is True and B is True"
My attempt at fixing it is as follows:
if DNAval(seq1) and DNAval(seq2):
if len(seq1) == len(seq2):
for (i, (elem1, elem2)) in enumerate(zip(seq1, seq2)):
if elem1 != elem2:
return i
return -1
Your if-else in the loop always returns in the First loop iteration: it takes the first two chars and compares them; are they equal? No -> return -1
If you follow the logic, it begins comparing strings. If the two letters are the same, it goes for the ELSE (because they are not different) and ends the routine after checking only the first letter.
You only want the routine to return -1 if it makes it all the way through the for loop without returning an index number. So,
Change as below:
def test(seq1, seq2):
if len(seq1) == len(seq2):
for i in range(0, len(seq1)):
if seq1[i] != seq2[i]:
return(i)
return(-1)
else:
return('Wrong input')
print( test('Hello1', 'Hello2'))
print('done')
The problem is, that you are returning -1 on the first time you run through the for loop, because the else-clause is immediately entered.
Use the else clause with the for loop itself instead.
For example:
def compare_strings(seq1, seq2):
if len(seq1) == len(seq2):
for i in range(0, len(seq1)):
if seq1[i] != seq2[i]:
return i
else:
return -1
else:
return 'Wrong input'
(mind you, raising a custom exception might be better than returning "Wrong input" here...)
Here's how I would do it
def mutation_detector(seq1, seq2):
if not DNAval(seq1) or not DNAval(seq2) or len(seq1) != len(seq2):
return "Wrong input" # maybe raise ValueError if DNAval fails instead?
for index, (base1, base2) in enumerate(zip(seq1, seq2)):
if base1 != base2:
return index
return -1
Try this,
It will return index when unable to compare otherwise it will compare two character and to print equal again compare it with length of string.
def mutation_detector(seq1,seq2):
count=0
if len(seq1) == len(seq2):
for i in range(0, len(seq1)) and range(0, len(seq2)):
if seq1[i] != seq2[i]:
return i
else:
count=count+1
if count==len(seq1):
return 'Equal'
print(mutation_detector('ATCGGCTA','ATCGGCTA'))
def comp_string(string1,string2):
if len(string1)!=len(string2):
return "length not equal"
else:
for i in range(len(string1)):
if string1[i] != string2[i]:
return i
return "equal"

who to pass index of a loop (for loop) in python

I put this pre defined part in my python code, the aim of code is to get last 2 digits and put it on cluster list based on the predefined logic in cluster (index as list[1] and variable of index in cluster(2).
Now I have problem with my loop that says there are indentation error.
def find_min(matrix=[]):
i,j=0,0
min1=[1000,0,0]
while i <len(matrix):
while j <len(matrix):
if matrix[i][j] != 0:
if min1[0]>matrix[i][j]:
min1[0]=matrix[i][j]
min1[1]=i
min1[2]=j
j+=1
j=0
i+=1
return min1[1:]
def check_min(variable,list2=[]):
i=0
min=1000
list3=list2[:]
result=0
while i<len(list3):
if variable-list3[i]>0:
result=variable-list3[i]
list3[i]=result
else:
result=list3[i]-variable
list3[i]=result
i+=1
i=0
while i<len(list3):
if min>list3[i]:
min=list3[i]
i+=1
return min
def grouped(variable,cluster=[]):
cluster1=cluster[:]
k=0
list3=[]
index=0
while k<3:
index=k
if variable in cluster1[index]:
list3.append(1)
list3.append(cluster[index])
return list1
else:
continue
K+=1
return [0,-1]
list1=[10,11,30,40,70,80]
cluster=[[0,1][10,11],[2,3],[30,40],[],[]]
Then I want to have this loop to work but it shows me idiot errors!
w, h = len(list1), len(list1)
matrix = [[None for x in range(w)] for y in range(h)]
i,j,z=0,0,0
check=0
check2=0
k,e=0,0
flag1=0
index1,index2=0,0
index_i=0
index_j=0
index_cluster_i=0
index_cluster_j=0
temp1=[]
while i <len(list1):
index1=i
while j <len(list1):
index2=j
#if i is in a cluster already
temp1=grouped(index1,cluster)
index_i=temp1[0]
index_cluster_i=temp1[1]
#if j is in a cluster already
temp1=grouped(index2,cluster)
index_j=temp1[0]
index_cluster_j=temp1[1]
if(i>j):
matrix[i][j]=0
elif (index_i==1 and index_j==1):
matrix[i][j]=0
elif(index_i==1 and index_j==0):
matrix[i][j]=check_min(list1[j],cluster[index_cluster_i])
elif(index_i==0 and index_j==0):
if list1[i]>list1[j]:
matrix[i][j]=list1[i]-list1[j]
else:
matrix[i][j]=list1[j]-list1[i]
j+=1
i+=1
error is:
unindent does not match any outer indentation level
This error is for improper indentations align each block under its statement.
Like:
if i === True:
pass
else:
pass

Update list in for loop using list.append

The variable mult is not updated as the program runs. What is the issue with this code? The run results show me that the loop is actually working as I wanted but for the list update and final print
number = 18
for i in range(int(number/2)):
i += 1
mults = []
if number % i == 0:
mults = mults.append(i)
print(i)
elif number % i != 0:
pass
elif i == int(number/2):
print(mults)
with this other code I get the error: AttributeError: 'NoneType' object has no attribute 'append'
number = 18
mults = []
for i in range(int(number/2)):
i += 1
if number % i == 0:
mults = mults.append(i)
print(i)
elif number % i != 0:
pass
print(mults)
number = 18
mults = []
for i in range(int(number/2)):
i += 1
if number % i == 0:
mults.append(i)
print(i)
elif number % i != 0:
pass
print(mults)
Few notes, move mults outside of the for loop so you aren't over writing it every time the loop runs.
You don't need that last elif statement, just print(mults) when the for loop is done, is basically the last elif statement.
mults.append(i) is in line meaning it changes the list mults automatically and you don't need to reassign it.

Resolving syntax error in line 7

Here is my code, where I get the syntax error:
def cube(number):
return number*number*number
def by_three(number):
if number % 3==0:
cube(number)
return number
else:
return False
Please note that indentation in Python is extremely important since it defines where blocks start and end. I guess your code should be:
def by_three(number):
if number % 3==0:
cube(number)
return number
else:
return False
This should work:
First, indent your code correctly.
def by_three(number):
if number % 3==0:
cube(number)
return number
else:
return False
For cube(number), you can use base**exponent
def cube(number):
return number**3
Alternatively, number^3 is the same as number*number*number, so
def cube(number):
return number*number*number
In addition to indentation, you might want to use mathematical order of precedence and indicating a * for the multiplication.
This works for me with python 3
#!/usr/local/bin/python3
def cube(number):
return (number * number * number)
def by_three(number):
if (number % 3) == 0:
cubed = cube(number)
return cubed
else:
return False
def main():
x = 3
output = '%d' % by_three(x)
print(output)
if __name__ == "__main__":
main()

Resources