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.
Related
I need to make a program in Python that do this:
Write a program that, for a given sequence of digits, prints the number of different three-digit even numbers that can be formed from the given digits. When forming each three-digit even number, each element of the sequence of digits can be used at most once.
The first line of the standard input contains the number of digits N, such that 3≤N≤50000. In the second row is N digits separated by one space.
Print only one number to the standard output, the requested number of three-digit numbers.
n=int(input())
num=[]
for i in range (n):
num.append ()
Input
4
2 4 2 2
Output
4
Explanation
From the digits 2, 4, 2, 2, 4 different three-digit even numbers can be formed, namely 222, 224, 242, 422.
This is a general solution that checks all permutations of these digits and print even numbers out of them:
from itertools import permutations
k = 3
c = 0
n = int(input())
num = input().strip().split(" ")
perms = set(permutations(num, k))
for perm in perms:
t = int("".join(perm))
if t % 2 == 0 and len(str(t)) == k:
print(t)
c += 1
print(c)
This is another solution if you don't want to use this generalized approach and just want to solve it for 3 digits:
c = 0
n = int(input())
num = [int(x) for x in input().strip().split(" ")]
r = set()
for i in range(n):
for j in range(n):
for k in range(n):
if i == j or i == k or j == k:
continue
t = num[i] * 100 + num[j] * 10 + num[k]
if t % 2 == 0 and len(str(t)) == 3:
r.add(t)
print(r)
print(len(r))
First You should declare which user input u expect and how to handle false input.
Then the inputString is split into a list of Strings aka inputList. Now You can loop through each of those inputItem and check if they fit your expectations (is int and smaller then 10 ). Since You still deal with String Items You can try to cast ( convert them) into Int. That can fail and a unhandled failure could cripple Your script so it has to happen in an try- catch-block. If the casting works You wanna make sure to check your matchList if You allready added a simular number before You add the new Number to Your matchList.You do so again by looping through each item. If there is mo such number yet there is a last check for if the number is uneven or 0. In that case there is one possible combination less for each number that is 0 or uneven so they are counted in the variable minusOneCombi. That will be substrated from the maximum amount of combinations which is the amount of numbers in you matchList multiplied with itself (pow(2)). Be very careful with the Indentations. In Python they are determining the ends of if blocks and loops.
InputString=(input("Enter your number stream eg 1 0 0 5 ( non numeric signs and numbers greater 9 will be ignored): "))
inputList= inputString.split(‘ ’)
matchList=[]
minusOneCombi= 0
for inputItem in inputList:
try:
anInt= int(inputItem)
except ValueError:
# Handle the exception
print(“item is not an integer and therefore ignored”)
NotYetinMatchList= True
for MatchItem in MatchList:
If matchItem == inputItem:
notYetinMatchList= False
Break
If notYetinMatchList:
matchList.append(anInt)
if ((anInt % 2) != 0) OR (anInt ==0):
minusOneCombi++
NumofMatches=matchList.count()
NumOfMatchesPow= pow(NumofMatches,2)
Result=NumOfMatchesPow -minusOneCombi
Print(Result)
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)
def find_outlier(lstOfints):
for integer in lstOfints:
#print(integer)
if integer % 2 ==1:
integer
elif integer % 2 == 0:
integer
return integer
I keep getting the incorrect answer and I don't know what's going on.
This is the problem:
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
This seems to work for me:
def find_outlier(lstOfints):
if lstOfints[0] % 2 == 1 and lstOfints[1] % 2 == 1:
for integer in lstOfints[2::]:
if integer % 2 == 0:
return integer
elif lstOfints[0] % 2 == 0 and lstOfints[1] % 2 == 0:
for integer in lstOfints[2::]:
if integer % 2 == 1:
return integer
else:
if lstOfints[0] % 2 == lstOfints[2] % 2:
return lstOfints[1]
else:
return lstOfints[0]
Firstly, I am seeing if this list is either all odds, or all evens, bar the outlier. Then if it is even, it goes through the list looking for an odd number, the same for if the list is all odd. However, if the outlier is in the first two numbers, then it checks to see whether the outlier is the first number or the second number by comparing the modulos to the modulo of the third number in the list.
A pythonic answer might be something like that:
def find_outlier(lst):
mods = [n % 2 for n in lst]
return lst[mods.index(0)] if sum(mods[:3]) > 1 else lst[mods.index(1)]
print(find_outlier([5, 31, 57, 45, 9, 17, 8, 37, 123, 67])) # --> 8
print(find_outlier([4, 30, 56, 44, 8, 16, 7, 36, 122, 66])) # --> 7
Explanation: first create the list of all n % 2 for all n in the provided list. Then you simply have to check the sum of the first 3 elements of this new list to know whether the outlier is odd or even. Then find index of the outlier remainder (either 0 or 1) and return the corresponding integer from the first list...
There are many things to change in your code, so I will try to change it at steps to get it working at the end.
Run the function from the question
Well, I tested your code here and I see why it is confusing. I have this script:
def find_outlier(lstOfints):
for integer in lstOfints:
#print(integer)
if integer % 2 ==1:
integer
elif integer % 2 == 0:
integer
return integer
print(find_outlier([1,3,4,5]))
print(find_outlier([1,2,3,4]))
...and if I run it, we get this:
$ python disparity.py
5
4
It is just printing the last number! Why so?
Why is it always printing the last number from the list?
Well, because you just return at the end of the function. You expect the function to return from inside the if statement, but you did not used the return command. It is easy to solve:
def find_outlier(lstOfints):
for integer in lstOfints:
if integer % 2 ==1:
return integer
elif integer % 2 == 0:
return integer
return integer
print(find_outlier([1,3,4,5]))
print(find_outlier([0,2,3,4]))
So now we run it and get
$ python disparity.py
1
0
Now it is just returning the first element!
Why is it now always printing the first number from the list?
It prints the first element because your if statements are complementary. Given any element, regardless of its parity, it modulo 2 will be either 0 or 1. If it is zero, the first if returns; if it is 1, the second returns! Since it is true to all elements, it is true to the first one, so the function ends at the very first iteration.
This is not the algorithm you want. What you want is to first know which parity is the outlier, and then look for the outlier number.
How to discover which parity is an outlier if I don't know which number is the outlier?
Since the list has at least three elements, that is easy: we consider two scenarios.
The first scenario is, the outlier is one of the first three elements. In this case, we will have one outlier parity and two "normal" parities.
The second scenario is, the outlier is not one of the first three elements. In this case, we will have three equal parities, and the outlier will be the opposite one.
So, if we count the number of even numbers and odd numbers in the first three values, we know that the parity with less numbers is the outlier one.
If there are more even numbers than odd numbers (either two even and one odd, or three even and no odd), then we know the outlier is odd.
If there are more odd numbers than even numbers, we know the outlier is even.
Now, how to do it in code?
To do that, I will write pieces of code below that, at then end, put together, will give us the answer. First I create two variables to count the even and odd numbers (with 0 at first).
even_numbers = 0
odd_numbers = 0
Then, I see if the first element is even. If so, I increment the counter of even numbers:
if listOfints[0] % 2 == 0:
even_numbers = even_numbers + 1
else:
odd_numbers = odd_numbers + 1
Then I do the same thing with the second and third elements:
if listOfints[1] % 2 == 0:
even_numbers = even_numbers + 1
else:
odd_numbers = odd_numbers + 1
if listOfints[2] % 2 == 0:
even_numbers = even_numbers + 1
else:
odd_numbers = odd_numbers + 1
If we have more even numbers than odd numbers, we know the outlier parity is odd (that is, the rest of the division of the outlier to 2 is 1); if we have more odd numbers than even numbers, the outlier parity will be even (that is, the rest will be zero)
if even_numbers > odd_numbers:
outlier_parity = 1
else:
outlier_parity = 0
So, now I know if the outlier number is even or odd, I agree. But I want to know what is the number!
Now that we do know the parity of the outlier, we just need to look for it:
for integer in lstOfints:
if integer % 2 == outlier_parity:
return integer
Bundling all together, this is our new function:
def find_outlier(lstOfints):
even_numbers = 0
odd_numbers = 0
if lstOfints[0] % 2 == 0:
even_numbers = even_numbers + 1
else:
odd_numbers = odd_numbers + 1
if lstOfints[1] % 2 == 0:
even_numbers = even_numbers + 1
else:
odd_numbers = odd_numbers + 1
if lstOfints[2] % 2 == 0:
even_numbers = even_numbers + 1
else:
odd_numbers = odd_numbers + 1
if even_numbers > odd_numbers:
outlier_parity = 1
else:
outlier_parity = 0
for integer in lstOfints:
if integer % 2 == outlier_parity:
return integer
print(find_outlier([1,3,4,5]))
print(find_outlier([0,2,3,4]))
Does it work? Let's test:
$ python disparity.py
4
3
Oh, it worked! Not bad, right? :)
Some considerations
This code here isn't the most elegant, but my purpose here is mostly that you understand what is going on. It could be done with a waaaaaay shorter, more readable function, but since you are still looking for basic concepts, I did a more detailed, explainable function, which is kind of cumbersome as a consequence.
my solution is:
def find_outlier(integers):
odd = []
even = []
for i in integers:
if i% 2 != 0:
odd.append(i)
elif i% 2 == 0:
even.append(i)
if len(odd) < len(even):
return odd[0]
else:
return even[0]
I am currently trying to use the luhn method to determine whether a credit card is valid or not in python and here is what I have so far:
print('What is your Credit Card number? :) (please put a space between each number)')
a = [int(x) for x in input().split()]
lengthy = len(a)
print(lengthy)
a.reverse()
print(a)
listx2 = []
listx1 = []
for x in range(len(a)):
modulus = x % 2
print(x, a[x])
if modulus != 0:
listx2.append(a[x]*2)
else:
listx1.append(a[x])
print(listx2)
print(listx1)
I don't know how to do the next step which is getting the sum of all of the digits of the numbers multiplied by two.(listx2) I have looked at different programs with the luhn method but I just can't seem to pick that part out. Thanks!
This is my interpretation of the Luhn algo.
def luhn(sequence):
digits = [int(digit) for digit in str(sequence)] # converts a full string of nums to a list comp of individual numbers
odd = digits[-1::-2] # string stepping (-1) indicates last item in list (-2) means to travel back another 2
even = digits[-2::-2]
checksum = 0
checksum += sum(odd)
evenmod = []
for digit in even:
if digit * 2 > 9:
digit = digit * 2
digit = int(str(digit)[0]) + int(str(digit)[1])
else:digit = digit * 2
evenmod.append(digit)
checksum += sum(evenmod)
if checksum % 10 == 0:
return True
else:
return False
print luhn(378282246310005)
print luhn(111111111111111)
print luhn(4751290083628479)
print luhn(5573485043994670)
Separate the even and the odd indeces to separate lists, then use a for statement to loop through the list, multiplying the list entries by two.
Notice the if statement that catches the issue with (e.g) 8 * 2 = 16.
Use sum:
summed_x2 = sum(listx2)
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,))