I am trying to complete a Python code that counts each beat and places an X if its divisible by a number.
Example :
Divisions: 3
Divisible by: 2
Divisible by: 3
Divisible by: 4
Number of beats to print: 10
1:
2:X
3: X
4:X X
5:
6:XX
7:
8:X X
9: X
10:X
You see how 2 is divisible by 2 so it prints an X on the first column? And 6 is divisible by both 2 and 3 so it prints an X on the first and second column? I need help doing that :)
This is my code so far, can anyone please complete it or help me complete it? I think i need to put the second loop inside another loop, because i need to loop over the numbers from 1 to c, working out for each beat whether it is divisible by each d (the numbers from list1). I probably need to make the loop increment b from 1 to c.
My Workaround :
list1 = []
a = int(input("Divisions: "))
for b in range(1,a+1):
z = int(input("Divisible by: "))
list1.append(z)
c = int(input("Number of beats to print: "))
for e in range(1,c+1):
for d in list1:
remainder = b%d
if remainder == 0:
print(" "+str(e)+":","X")
divs = [int(input('Divisible by: ')) for _ in range(int(input('Divisions: ')))]
for beat in range(1, int(input('Number of beats to print: ')) + 1):
print '%2d:%s' % (beat, ''.join(
'X' if (beat % div) == 0 else ' ' for div in divs).rstrip())
Using the test case you provided:
Divisions: 3
Divisible by: 2
Divisible by: 3
Divisible by: 4
Number of beats to print: 10
1:
2:X
3: X
4:X X
5:
6:XX
7:
8:X X
9: X
10:X
list1 = []
a = int(input("Divisions: "))
for b in range(1,a+1):
z = int(input("Divisible by: "))
list1.append(z)
c = int(input("Number of beats to print: "))
for e in range(1,c+1):
print('%3d:'%(e), end='')
string=''
for d in list1:
remainder = e%d
if remainder == 0:
string += 'X'
else:
string += ' '
print(string.rstrip())
Related
I want the n numbers to be entered on one line, with just spaces. I'm trying to use .split in ai = [int(input()) for ai in range(n)], but the following error appears:
ai = [int(input()) for ai in range(n)].split(' ')
ValueError: invalid literal for int() with base 10: '2 6 3 7 1'
So I don't know which part of the code I should change to reach the correct format.
The wrong input:
n: 5
2
6
3
7
1
The correct input and its respective output:
Input:
n: 5
2 6 3 7 1
Output:
**
*
***
*
*
The wrong code is:
n = int(input('n: '))
ai = [int(input()) for ai in range(n)]
for i in ai:
if i == 1:
print('*')
elif i == 2:
print('**')
elif i == 3:
print('***')
elif i > 3:
print('*')
This works. But I guess you want to validate that the amount of entered numbers match n, right?
n = int(input('n: '))
ai = [int(i) for i in input().split()]
for i in ai:
if i == 1:
print('*')
elif i == 2:
print('**')
elif i == 3:
print('***')
elif i > 3:
print('*')
In the case you want to validate the input of n numbers:
n = int(input('n: '))
ai = []
while len(ai) != n:
ai = [int(i) for i in input('Enter ' + str(n) + ' values: ').split()]
for i in ai:
if i == 1:
print('*')
elif i == 2:
print('**')
elif i == 3:
print('***')
elif i > 3:
print('*')
Here it is in one line:
>>> print('\n'.join('*' * (n if n in (2, 3) else 1) for n in map(int, input().split())))
2 6 3 7 1
**
*
***
*
*
Note that prompting for the number of inputs ahead of time isn't needed if you're entering them on one line, since the end of the string tells you when the user is done entering numbers.
The key thing is to apply the int function to the list produced by the split() function, rather than attempting to turn the entire string into an int before you split it.
With a superfluous input() included in the single print call it'd be:
>>> print(input() * 0 + '\n'.join('*' * (n if n in (2, 3) else 1) for n in map(int, input().split())))
5
2 6 3 7 1
**
*
***
*
*
The problem with your code is that you tried on it to convert the whole string, with the whitespaces between the numbers, to int.
the solution is to use str.split() on the input to get a list with the inputted numbers, and then convert each number in the list to int using map() function
Try this code:
n = int(input('n: '))
ai = list(map(int, input().split()))
for i in ai:
if i == 1:
print('*')
elif i == 2:
print('**')
elif i == 3:
print('***')
elif i > 3:
print('*')
You have to split the input before you can convert it to integer values:
n = input('n: ')
ai = [int(a) for a in n.split(' ')[1:]]
I'm doing this assignment:
Write a program that prints all even numbers less than the input
number using the while loop.
The input format:
The maximum number N that varies from 1 to 200.
The output format:
All even numbers less than N in ascending order. Each number must be
on a separate line.
N = int(input())
i = 0
while 200 >= N >= 1:
i += 1
if i % 2 == 0 and N > i:
print(i)
and its output like:
10 # this is my input
2
4
6
8
but there is an error about time exceed.
The simple code would be:
import math
N = int(input(""))
print("1. " + str(N))
num = 1
while num < math.ceil(N/2):
print (str(num) + ". " + str(num * 2))
num += 1
The problem is that the while loop never stops
while 200 >= N >= 1 In this case because you never change the value of N the condition will always be true. Maybe you can do something more like this:
N = int(input())
if N > 0 and N <= 200:
i = 0
while i < N:
i += 2
print(i)
else
print("The input can only be a number from 1 to 200")
Can you please help me to find the issue in my code?
The exercise is; Write a program to input number N in range of [1-1000] and print the sum of all numbers below N that contain the digit 7. Print an error message if the user inserts an out of range number and ask to insert again.
var = 1
while var == 1:
n=int(input("Enter the Number in range [1,1000]:"))
while n in range(0,1001):
k = 0
i=0
m=0
s=0
e=0
f=0
g=0
if n in range(100,1001):
for c in range(100,n+1):
if c%10 == 7:
i += c
if (c//10)%10 == 7:
c%10 != 7
s += c
if c//100 == 7:
(c//10)%10 != 7
c%10 != 7
e += c
print(1188 + i + s + e)
if n in range(0,100):
for b in range(1,n+1):
if b%10 == 7:
f += b
if b//10 == 7:
g += b
if b >= 77:
g=g-77
print(f+g)
break
else:
print("n is not in the range")
It counts the sum in range (170,180) by adding always 170 and not only in this range.
In while block, we are testing if n is valid or not. After while block there is a list comprehension.
contains_seven = [x for x in range(0,n+1) if '7' in str(x)]
We are taking every number in range 0 to n+1 which has '7' in it.
After that, we are summing them via sum() function and print it. Full implementation is:
while True:
n = int(input("input n: "))
if (n>0 and n<=1000):
break
print("n is not in the range")
contains_seven = [x for x in range(0,n+1) if '7' in str(x)]
a = sum(contains_seven)
print(a)
We can convert our number to a str() and then to a list().
After that we from, for example, 456 get ['4', '5', '6'].
And now we can easily check if 7 is in our number. PROFIT!
Then we take our list with numbers which contain 7 to *args in sum() and get final result! Uhhuuuu! Yeah
N = int(input("Write number: "))
while (N < 1) or (N > 1000):
N = int(input("Write number again: "))
all_numbers_with_seven = [n for n in range(1, N) if '7' in list(str(n))]
print(sum(all_numbers_with_seven))
I already solved this with list.append() function however my instructor told me to just use the basic python functions. Here is my code:
a = 0
b = 0
s = 0
x = str(s)
print ('Enter the first number: ', end = '')
c = input()
a = int(c)
finished = False
while not finished:
print ('Enter the next number (0 to finish): ', end ='')
n = input()
b = int(n)
if b != 0:
if b == a:
x = ('Same')
elif b > a:
x = ('Up')
elif b < a:
x = ('Down')
a = b
s = x
else:
finished = True
print (str(x))
I am aiming to print (e.g. Up Down Up Down Same in comparing the input integers) in one line at the end of the while loop. Let me know how can I improve my code. Thank you very much
Use string concatenation to get the result you want without using a list:
http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
I'll give you two hints on how to do this for your program:
Initialize x as an empty string by replacing
x=str(s)
with
x=""
There is no need for it to begin as the string "0", which str(s) does since s is 0.
Instead of saying
x=('SAME')
x=('UP')
x=('DOWN')
try saying
x=x+'SAME'
x=x+'UP'
x=x+'DOWN'
I removed the parentheses because they are not necessary.
As for style, it is good practice to name your variables as useful things instead of just letters. Last staement in an if/else chain that covers all bases should just be else. Best of luck to you sir
Not sure what result you're looking for, but perhaps this works:
a = 0
b = 99
result = ""
a = int(input('Enter the first number: '))
while b != 0:
b = int(input('Enter the next number (0 to finish): '))
if b == a:
result += ' Same'
elif b > a:
result += ' Up'
elif b < a:
result += ' Down'
a = b
print(result.strip())
Output:
Enter the first number: 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 5
Enter the next number (0 to finish): 0
Same Same Down Same Up Down
You can simply initialize x with an empty string and keep concatenating to it.
a = 0
b = 0
s = 0
x = ''
print('Enter the first number: ', end='')
c = input()
a = int(c)
finished = False
while not finished:
print('Enter the next number (0 to finish): ', end='')
n = input()
b = int(n)
if b != 0:
if b == a:
x += 'Same\n'
elif b > a:
x += 'Up\n'
elif b < a:
x += 'Down\n'
a = b
s = x
else:
finished = True
print(str(x))
I don't realize what is my mistake, this is how far I got now:
x = 1
e = 0
while x <= 50:
print "Please enter a number (from 1 to 9):"
b = float(raw_input())
asd = 0
if asd == 0:
h = b
l = b
asd = 1
if b < l:
l = b
elif b > h:
h = b
if 1 <= b or b <= 9:
x = x * b
print x
else:
print "Number is too large or too small."
e = e + 1
print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e
This is the program's output:
Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3
Why is the program giving me 5 instead of 4 as lowest number entered and how can I correct that?
You keep resetting asd each iteration, you need to set the variables outside the loop, I would use a list and that will enable you to get the min/max and number of valid inputs :
nums = [] # hold all nums outside the loop
limit = 1
while 50 >= limit:
num = float(raw_input("Please enter a number (from 1 to 9)")
if 1 <= num <= 9:
limit *= num
nums.append(num) # add all to list
else:
print "Number is too large or too small."
print "You have reached a value over 50."
print "Highest number entered:", max(nums)
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)
Everytime you go through the loop, you are setting asd to 0, causing the if statement below it to execute every single time, so you are always blindly updating l with the value the user just entered, which you have named as b
just for fun :)
def get_float_input(msg="Enter a Number:"):
while True:
try:
return float(raw_input(msg))
except ValueError:
print "Invalid Input Please Enter A Float!"
from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)