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)
Related
I'm trying to see if the Collatz Conjecture is really true, it says that every integer number which is divided per 2 if it's even and multiplied by 3 and added 1 if it's odd, will eventually come to a loop of 4, 2, 1. But it gets stuck in a while loop and doesn't break or gets inside the if statement that I want
integers = [5]
#Returns true if a number is even and false if it's odd
def even(num):
if (num % 2 == 0):
return True
else:
return False
#Returns true if a list of a number is in a loop
def loop(numbers):
for x in numbers:
if (numbers.count(x) > 1 or 4 in x == True):
return True
break
else:
return False
continue
#Print a list of numbers that agree with the Collatz conjecture
def collatz(list):
for x in list:
collatz_nums = []
l = loop(collatz_nums)
list.append(list[-1] + 1)
#Add the first number to the "collatz_nums" list
if (even(x) == True):
collatz_nums.append(x / 2)
elif (even(x) == False):
collatz_nums.append(x * 3 + 1)
#Adds numbers to the collatz_nums variable
while (l != True):
print("Start")
if (l == False):
if (even(collatz_nums[-1]) == True):
collatz_nums.append(collatz_nums[-1] / 2)
print("/2")
else:
collatz_nums.append(collatz_nums[-1] * 3 + 1)
print("*3+1")
else:
print("Exit")
break
print(F'{x} = {collatz_nums}')
collatz(integers)
Let's start here
collatz_nums = []
l = loop(collatz_nums)
You're passing an empty list to a function with only return statements in the event that you have data to loop over, so the function returns, setting l = None
Now while (None!=True) is an infinite loop since you're never modifiying value of l
Perhaps you should move the "add first number" if statements (which really only need to call even function once using if-else) above those two lines? Or above for x in list so that you only add the first number once?
I'd also recommend removing 4 in x == True since I doubt that does what you want
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)
I'm doing some CodeEval challenges and am doing the fizzbuzz one. Now im sure this is a very simple problem and I'm just over looking it, but I'm doing this in python which I'm fairly new to and just learning.
Players generally sit in a circle. The first player says the number “1”, and each player says next number in turn. However, any number divisible by X (for example, three) is replaced by the word fizz, and any divisible by Y (for example, five) by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates, or makes a mistake is eliminated from the game.
Write a program that prints out the final series of numbers where those divisible by X, Y and both are replaced by “F” for fizz, “B” for buzz and “FB” for fizz buzz.
Input sample:
Your program should accept a file as its first argument. The file contains multiple separated lines; each line contains 3 numbers that are space delimited. The first number is the first divider (X), the second number is the second divider (Y), and the third number is how far you should count (N). You may assume that the input file is formatted correctly and the numbers are valid positive integers.
For example:
3 5 10
2 7 15
Output sample:
1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15
Print out the series 1 through N replacing numbers divisible by X with “F”, numbers divisible by Y with “B” and numbers divisible by both with “FB”. Since the input file contains multiple sets of values, your output should print out one line per set. Ensure that there are no trailing empty spaces in each line you print.
Constraints:
The number of test cases ≤ 20
"X" is in range [1, 20]
"Y" is in range [1, 20]
"N" is in range [21, 100]
When I run my program I get the following output from the file:
1
1
What am I doing wrong to where my program is not running through the file correctly?
def fizzbuzz(num_range, div_low=3, div_high=5):
for x in num_range:
if x % div_low == 0:
return "F"
elif x % div_high == 0:
return "B"
elif x % div_low == 0 and x % div_high == 0:
return "FB"
else:
return x
if __name__ == '__main__':
with open("numbers.txt", "r") as nums:
for i in nums.readlines():
high = int(i.rstrip().split(" ")[1])
low = int(i.rstrip().split(" ")[0])
nums = range(1, int(i.rstrip().split(" ")[2]))
print(fizzbuzz(nums, low, high))
Your function returns on the first value of x. You need to build up a string of responses within the loop, and then return that string only after you complete the loop.
Also note that your logic can't ever return "FB", since that's in else clauses for both "F" and "B".
series = ""
for x in num_range:
if x % div_low == 0 and x % div_high == 0:
series += "FB"
elif x % div_low == 0:
series += "F"
elif x % div_high == 0:
series += "B"
else:
series += str(x)
return series
Since you return a string, you have to convert the number before appending it. I haven't fixed everything for you, but this should get you moving.
I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))
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,))