Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have been given this question to do in Python:
Take in a list of numbers from the user and run FizzBuzz on that list.
When you loop through the list remember the rules:
If the number is divisible by both 3 and 5 print FizzBuzz
If it's only divisible by 3 print Fizz
If it's only divisible by 5 print Buzz
Otherwise just print the number
Also remember elif!
I have the following script created, but it gives me an error at if n%3=True
n = input()
if n % 3 = True:
print("Fizz")
else if n % 5 = True:
print("Buzz")
elif print n
Can anyone help? Thank you very much!
A few issues with your code here. The first issue is that, for comparison, you should be using ==, not =, which is for assignment.
The second issue is that you want to check that the remainder of the divisions (which is what the modulo operator calculates) is zero, not that it's true, which doesn't really make sense.
You should be using elif for "otherwise if..." and else for "otherwise." And you need to fix the formatting of your else clause.
You want:
n=input()
if n%3 == 0:
print("Fizz")
elif n%5 == 0:
print ("Buzz")
else:
print n
Finally, your code does not meet the spec:
1) If the number is divisible by both 3 and 5 print "FizzBuzz"
The above will not do this. This part I'm going to leave to you because I'm not here to solve the assignment for you :)
Based on this
FizzBuzz: For integers up to and including 100, prints FizzBuzz if the integer is divisible by 3 and 5 (15); Fizz if it's divisible by 3 (and not 5); Buzz if it's divisible by 5 (and not 3); and the integer otherwise.
def FizzBuzz():
for i in range(1,101):
print {
3 : "Fizz",
5 : "Buzz",
15 : "FizzBuzz"}.get(15*(not i%15) or
5*(not i%5 ) or
3*(not i%3 ), '{}'.format(i))
The .get() method works wonders here.
Operates as follows
For all integers from 1 to 100 (101 is NOT included),
print the value of the dictionary key that we call via get according to these rules.
"Get the first non-False item in the get call, or return the integer as a string."
When checking for a True value, thus a value we can lookup, Python evaluates 0 to False. If i mod 15 = 0, that's False, we would go to the next one.
Therefore we NOT each of the 'mods' (aka remainder), so that if the mod == 0, which == False, we get a True statement. We multiply True by the dictionary key which returns the dictionary key (i.e. 3*True == 3)
When the integer it not divisible by 3, 5 or 15, then we fall to the default clause of printing the int '{}'.format(i) just inserts i into that string - as a string.
Some of the output
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
n % 3 (or n % any number) does not evaluate to True or False, it's not a Boolean expression. n % 3 == 0 on the other hand, does.
As an aside, what happens when n % 3 == 0 and n % 5 == 0 both evaluate to True?
Here's how I did it using generators.
Explanations are added as comments.
# the factors to check for, along with its
# associated text data.
FACTORS = {
3 : "Fizz",
5 : "Buzz",
}
def fizzbuzz(start, stop):
"""FizzBuzz printer"""
for i in range(start, stop+1):
string = "" # build string
# iterate through all factors
for j, dat in FACTORS.items():
# test for divisibility
if i % j == 0:
# add data to string if divisible
string += dat
if not string:
# if string's length is 0, it means,
# all the factors returned non-zero
# modulus, so return only the number
yield str(i)
else:
# factor had returned modulo as 0,
# return the string
yield string
if __name__ == "__main__":
for each in fizzbuzz(1, 100):
print(each)
This version has the advantage of not depending on any extra factor checks.
one of the shortest answers i have found is
c=1
while c<101:print((c%3<1)*'Fizz'+(c%5<1)*'Buzz'or c);c+=1
61 characters
Make it universal for any integer, positive or negative.
Also make it easily expandable to other keywords for any integer by creating a dictionary of keywords.
def checkdict(divdict, i):
out = ""
for key in divdict:
if key != 0:
if i%key==0:
out+=divdict[key]
if key == 0 and i == 0:
out+=divdict[key]
if out == "":
out = i
print(out)
if __name__ == "__main__":
mydict = {3:"Fizz",5:"Buzz"}
for i in range(-50,50):
checkdict(mydict, i)
def check(num):
finalWord = ''
for k,v in numWordDict.items():
if num % k == 0:
finalWord += v
if not finalWord:
return num
else:
return finalWord
def FizzLoop(start=0, stop=10, step=1):
for i in range(start, stop, step):
print(check(i))
numWordDict = {3:'fizz', 6:'buzz', 5:'fiver'}
FizzLoop(0, 10)
print("----------")
FizzLoop(0, 50, 5)
Numbers = [3, 5]
Labels = ["Fizz", "Buzz"]
for i in range(1, 101):
Output =""
for j in range (len(Numbers) ) :
if i % Numbers[j] == 0:
Output = Output + Labels[j]
if Output =="" :
print(i)
else:
print(Output)
Nothing fancy, using a while loop to achieve the same result:
x,xx = 1,100
xy,xz = 3,5
mylist = []
while x <= xx:
y = (x/xy).is_integer()
z = (x/xz).is_integer()
if y and z:
mylist.append("fizzbuzz")
elif y:
mylist.append("fizz")
elif z:
mylist.append("buzz")
else:
mylist.append(x)
x+=1
print(mylist)
Please find the 1 liner code (list comprehension) code below. Hope this is easy to understand . if it's not please do let me know. I will elaborate.
N = 10 #user_input
print(list(map(lambda n: "Fizz" if (n % 3 == 0) else ( "Buzz" if (n % 5 == 0) else n),[i for i in range(1,N+1)])))
def fizz_buzz(input):
if (input % 3 == 0) and (input % 5 == 0):
return "FizzBuzz"
if input % 3 == 0:
return "Fizz"
if input % 5 == 0:
return "Buzz"
return input
print(fizz_buzz(15))
Related
I am writing a program that will print a list of numbers 1:n. However, every number divisible by 2 should be replaced with 'x' and every number divisible by 3 should be replaced with 'y'. Lastly, every number both divisible by 2 and 3 should be replaced with 'xy'. This is my code so far, I can get the function to print the correct result with my input. But it wont print the entire list of numbers. Instead I am just getting the end result (x,y, or xy) for the given input. Here is my code thus far with the output.
def replace(n):
for i in range(n):
print(i)
if n%2== 0 and n%3 == 0:
return 'xy'
elif n%2==0:
return 'y'
elif n%3 == 0:
return 'x'
else:
print(i)
replace(12)
This is my output:
0
'xy'
I would like the output to be something like:
1
x
y
x
5
xy
7
x
y
x
11
xy
Any advice would be appreciated, you guys rock!
Your code has multiple errors:
At line 4, you print(i) - this means that each number will be printed
At lines 6, 9 and 12 you are using the n variable instead of i in the modulo operation
You want to check for numbers [1, n], but your loop checks for [0, 11]
You return instead of printing - the return keyword will stop the function's execution (and thus the loop) and return the value you specified. In case you are confused, consider the following example:
def get_number():
return 5
print("This will never print, as the function has already returned")
number = get_number() # number now equals 5, since it was returned
get_number() # 5 still gets returned, but is never assigned to a variable
Here is the code that gives the output that you mention above:
def replace(n):
for i in range(1, n + 1):
if i%2 == 0 and i%3 == 0:
print('xy')
elif i%2 == 0:
print('x')
elif i%3 == 0:
print('y')
else:
print(i)
replace(12)
I was working on a problem that determines whether the digits in the numbers are in the increasing sequence. Now, the approach I took to solve the problem was, For instance, consider the number 5678.
To check whether 5678 is an increasing sequence, I took the first digit and the next digit and the last digit which is 5,6,8 and substitute in range function range(first,last,(diff of first digit and the next to first digit)) i.e range(5,8+1,abs(5-6)).The result is the list of digits in the ascending order
To this problem, there is a constraint saying
For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. Now my program breaks at the input 7890. I don't know how to encode this logic. Can someone help me, please?.
The code for increasing sequence was
len(set(['5','6','7','8']) - set(map(str,range(5,8+1,abs(5-6))))) == 0
You can simply check if the number, when converted to a string, is a substring of '1234567890':
str(num) in '1234567890'
you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.
num = 7890
result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))
I would create a cycling generator and slice that:
from itertools import cycle, islice
num = 5678901234
num = tuple(str(num))
print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))
This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:
def digits(num):
while num:
yield num % 10
num //= 10
def check(num):
num = list(digits(num))
num.reverse()
for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
if i != j:
return False
return True
Since you already have the zip version, here is an alternative solution:
import sys
order = dict(enumerate(range(10)))
order[0] = 10
def increasing(n):
n = abs(n)
o = order[n % 10] + 1
while n:
n, r = divmod(n, 10)
if o - order[r] != 1:
return False
o = order[r]
return True
for n in sys.argv[1:]:
print n, increasing(int(n))
Here's my take that just looks at the digits and exits as soon as there is a discrepancy:
def f(n):
while (n):
last = n % 10
n = n / 10
if n == 0:
return True
prev = n % 10
print last, prev
if prev == 0 or prev != (last - 1) % 10:
return False
print f(1234)
print f(7890)
print f(78901)
print f(1345)
Somehow this question got me thinking of Palindromes and that got me to thinking of this in a different way.
5 6 7 8
8 7 6 5
-------------
13 13 13 13
9 0 1
1 0 9
---------
10 0 10
9 0 1 2
2 1 0 9
-------------
11 1 1 11
And that leads to this solution and tests.
pos_test_data = [5678, 901, 9012, 9012345678901]
neg_test_data = [5876, 910, 9021]
def monotonic_by_one(n):
fwd = str(n)
tgt = ord(fwd[0]) + ord(fwd[-1])
return all([ord(f) + ord(r) in (tgt, tgt - 10) for f, r in zip(fwd, reversed(fwd))])
print("Positive: ", all([monotonic_by_one(n) for n in pos_test_data]))
print("Negative: ", all([not monotonic_by_one(n) for n in neg_test_data]))
Results:
Positive: True
Negative: True
Instead of using to full list comprehension you could use a for loop and bail out at the first failure. I'd want to look at the size of the numbers being checked and time somethings to decide which was faster.
I would try this, a little verbose for readability:
seq = list(input())
seq1 = seq[1:]
seq2 = seq[:-1]
diff = [x-y for x,y in zip([int(x) if int(x)>0 else 10 for x in seq1],[int(x) if int(x)>0 else 10 for x in seq2])]
if any (t != 1 for t in diff) :
print('not <<<<<')
else :
print('<<<<<<')
A simple solution that checks the next number in the sequence and then using current_number + 1 == next_number to detect sequence.
import bisect
def find_next(x, a):
i = bisect.bisect_right(x, a)
if i:
return x[i]
return None
def is_sequence(x):
ans = True
for i in x[:-1]:
next_num = find_next(x, i)
if next_num and i+1 != next_num:
ans = False
break
return ans
print(is_sequence([1,2,3,4])) # True
I seem to have created an infinite loop in my python code. My aim was to create a function 'check' which uses my previous 'goldbach' function to confirm that every even number greater than 4 and up to the inputted N comply with the Goldbach Conjecture (a pretty pointless procedure, I know, but it's for my assignment). I know that my 'goldbach' function is working well and produces a pair of primes that sum to N for 'good' inputs and (0,0) for 'bad' inputs. I want my check function to return True for all even inputs greater than 4 (as these comply with the conjecture), and False for any odd inputs. However, my code won't run when I try my check function in the console so something has gone wrong - any ideas what it is?
def goldbach(N):
x, y = 0, 0
result = 0
if N % 2 == 0:
prime = odd_primes(N)
while result != N:
for i in range(len(prime)):
if result == N: break
x = prime[i]
for j in range(len(prime)):
y = prime[j]
result = x + y
if result == N: break
return x, y
def check(N):
for n in range(4, N+1):
if n % 2 ==0:
g = goldbach(n)
if g == (0,0):
return False
else:
return True
You're returning immediately after checking the first item in the range. You need to return False as soon as you encounter an item that doesn't match expectations, and return True at the end if all of them match expectations.
If you only want to look at even numbers, use a stride of 2 in the range() function rather than testing each number to see if it's even or odd.
def check(N):
for n in range(4, N+1, 2):
if goldbach(n) == (0, 0):
return False
return True
You don't need the while loop in goldbach(). The two for loops test all combinations of primes. If they don't find a matching pair, there's no reason to restart them.
You can also simplify and optimize your loops. The inner loop only needs to test primes starting from x, because pairs of primes where y < x would have already been tested in an earlier iteration of x.
def goldbach(N):
if N % 2 == 0:
prime = odd_primes(N)
for i, x in enumerate(prime):
for y in prime[i:]:
if x + y == N:
return x, y
return 0, 0
However, I think your code should still work, which suggests that the problem is actually that odd_primes() isn't returning all primes up to N.
I just created a replacement for your function odd_primes(N), to return a list of all the primes less than or equal to N (having 2 in the there doesn't seem to make a difference). Your check() function seems to check all integers between 4 and N inclusive, and return False if it finds something for which no Goldbach sum was found. However, as somebody else pointed out, it also immediately returns True once it finds a pair. So what happens when you run check() is that starts with the number 4, finds that its Goldbach pair is (2,2), then immediately quits the function by returning True, ignoring any other values between 4 and N.
When I replace the return True with a print statement and just add a `return True after the entire loop:
def check(N):
for n in range(4, N+1):
if n % 2 ==0:
g = goldbach(n)
if g == (0,0):
print("No sum found for %d !" % n)
return False
else:
print("%d is equal to %d + %d" % (n, g[0], g[1]))
return True
and then run check(20) for example, I get:
4 is equal to 2 + 2
6 is equal to 3 + 3
8 is equal to 3 + 5
10 is equal to 3 + 7
12 is equal to 5 + 7
14 is equal to 3 + 11
16 is equal to 3 + 13
18 is equal to 5 + 13
20 is equal to 3 + 17
By the way, if you just want to know whether a given even number can be written as the sum of two primes but you don't care what the actual pair of primes is, you could do something like this:
def goldbach(N):
if N % 2 == 0:
primes = odd_primes(N)
# Generate a list of all the i+j sums where j >= i (skipping
# most duplicates this way), and see if N is among the sums.
sums = [i + j for i in primes for j in primes[primes.index(i):]]
return(N in sums)
else:
print("N must be even.")
return(False)
This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 6 years ago.
I am new to programming and I found a problem on the internet to show the 1000th prime number. But the problem is that my code but I have some problems with it.
count=0
prime=[]
n=2
while count != 1000:
if n == 2 or n == 3 or n == 5 or n == 7 or n == 11:
prime.append(n)
n=n+1
count=count+1
elif n%2 == 0 or n%3 == 0 or n%5 == 0 or n%7 == 0 or n%11 == 0:
n=n+1
else:
prime.append(n)
n=n+1
count=count+1
print(prime[999])
The problem comes when I have a number like 403. According to the code I wrote it is prime but actually it is not because it can be divided by 13 and 31.
I came up a solution but I don't know how to do it and if there is a better solution. If you help me, please try preserve my code, please don't give me entirely new code.
My solutions is:
elif n%prime[:]==0
n=n+1
So basically what I'm trying to do is trying to divide the number 403, for example, to any of the other prime numbers that I've recorded earlier. But for some reason this code gives me an error. I want to tell the program "devide n to EVERY number in the list". Thanks for the help :)
You can use "any".
In [15]: prime = [2, 3, 5, 7, 11]
In [16]: n = 15
In [17]: any(n%p == 0 for p in prime)
Out[17]: True
In [18]: n = 17
In [19]: any(n%p == 0 for p in prime)
Out[19]: False
In [20]: n = 19
In [21]: any(n%p == 0 for p in prime)
Out[21]: False
Basically, it will tell you if given number is divisible by "any" of the number in the list.
there are several algorithm to count prime numbers, what you need first is first how to decide whether a function isPrime(n) will return true or false and if you need that this funciton isPrime(n) should be under o(n). There are several approach to do this, here are the possibilities:
def isPrime(n):
i = 2;
while i*i < n:
if n % i == 0:
return false
i = i + 1
return true;
this one will give you prime or not with complexity o(n^1/2), should be sufficient for you, after this the next thing you need to do is:
counter = 0
number = 2
while counter < 1000:
if isPrime(number):
counter = counter + 1;
number = number + 1
print number;
i havent tried this code yet but the concept should be there
I need to print out numbers between 1 and n(n is entered with keyboard) that do not divide by 2, 3 and 5.
I need to use while or for loops and the remainder is gotten with %.
I'm new here and I just don't understand the usage of %?
I tried something like this:
import math
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0:
print("The number", i, "is ok.")
else:
pass
if i%3 != 0:
print("The number", i, "is ok.")
else:
pass
if i%5 != 0:
print("The number", i, "is ok.")
help?
You need to test for all 3 conditions in one statement, not in 3:
for i in range(1, entered_number):
if i % 2 != 0 and i % 3 != 0 and i % 5 != 0:
print("The number", i, "is ok.")
The and operators here make sure that all three conditions are met before printing.
You are testing each condition in isolation, which means that if the number is, say, 10, you are still printing The number 10 is ok. because it is not divisible by 3. For numbers that are okay, you were printing The number ... is ok. 3 times, as your code tests that it is not divisible by 3 different numbers separately, printing each time.
If something divides by 7 then:
something % 7 == 0
If something divides by 7 and 9 then:
something % 7 == 0 and something % 9 == 0
Conversely, if something divides by 7 or 9 then:
something % 7 == 0 or something % 9 == 0
Something that does not divide by 7 or 9 is given by the expression:
not (something % 7 == 0 or something % 9 == 0)
You don't require the else: pass bits from your code and one if statement with an if-expression that has three %, == bits in it should suffice.
You should probably check the three conditions at the same time:
if i%2 != 0 and i%3 != 0 and i%5 != 0:
print("The number", i, "is ok.")
Otherwise, you would print the same message several times for a single number.
Anyway, for your second question, the% operation is called modulo and it gives you the remainder of a division. For instance, 5%3 = 2 because 5 = 3*1 + 2. And when you check i%2 != 0, you actually check if i can be divided by 2.
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0 and i%3 !=0 and i%5!=0:
print("The number", i, "is ok.")
a%b returns the remainder when a is divided by b. Example:
>> 5%3
2
What you are doing wrong here is that you are printing after checking a single condition so it will print even if i is divisible by other numbers. For example if i is 3, it will satisfy the first condition and therefore print that the number is ok but it is actually divisible by 3.
I saw you've solved your problem but my answer may worth reading.
This problem is actually doing filtering over a list of numbers 1..n. You can define a base function to test if number x is dividable by number y, and then use this base function to filter the list to get the result.
Here's my version.
import math
from functools import partial
print("Hey. Enter a number.")
entered_number = int(input())
def not_dividable_by(x, y):
return False if x % y == 0 else True
number_list = range(1, entered_number)
for i in [2, 3, 5]:
test_func = partial(not_dividable_by, y=i)
number_list = filter(test_func, number_list)
for number in number_list:
print("%d is OK" % (number,))