Here is the question I am working on:
Write a program that first gets a list of integers from input. The last value of the input represents a threshold. Output all integers less than or equal to that threshold value. Do not include the threshold value in the output.
For simplicity, follow each number output by a comma, including the last one.
Ex: If the input is:
50 60 140 200 75 100
the output should be:
50,60,75,
My code is:
n = int(input())
lst = []
for i in range(n):
lst.append(int(input()))
threshold = int(input())
for i in range(n):
if list[i] <= threshold:
print(last[i],end=',')
I keep getting an error, and I can't seem to know why:
ValueError: invalid literal for int() with base 10: '50 60 140 200 75 100'
This is a clean way to do this:
# import numbers separated with a space
n = input()
n = n.split(' ')
n = [int(x) for x in n] # <-- converts strings to integers
# threshold is the last number
threshold = n[-1]
# get the result
result = [x for x in n if x < threshold]
print(result)
the result:
[50, 60, 75]
The following expects one number. Not a list of them.
n = int(input())
Seems like you want to get a list of numbers through one/few prompts. Try something like the following:
n = list(map(int,input("\nEnter the numbers : ").strip().split()))[:]
So your code would look like:
n = list(map(int,input("\nEnter the numbers : ").strip().split()))[:]
lst = []
for i in range(n):
lst.append(int(input()))
threshold = int(input())
for i in range(n):
if list[i] <= threshold:
print(last[i],end=',')
Source: https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/
Related
A question is asking me to convert an int into binary, but it also must be in reverse (why!??!?!). After a bunch of tinkering, I was able to get it to print the number in binary. But I can't for the life of me figure out how to make it output in reverse.
The instructions say:
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary.
For an integer x, the algorithm is:
As long as x is greater than 0
Output x modulo 2 (remainder is either 0 or 1)
Assign x with x divided by 2
My code is:
x = int(input())
while x > 0:
x = x//2
print( x % 2, end = ' ')
Testing with input of 6, I get 1 1 0 but it wants me to output 011.
I even tried putting the answer into a list but when I try to reverse the list, I get an error. List method I tried:
x = int(input())
while x > 0:
x = x//2
J = [x % 2]
L = reversed(J)
print(L)
output using list method:
<list_reverseiterator object at 0x7f2cd69484f0>
<list_reverseiterator object at 0x7f2cd6948ee0>
<list_reverseiterator object at 0x7f2cd69484f0>
I feel like there's no way this needs some sort of slicing since that method hasn't even been covered yet in the material I'm learning.
You didn't follow the provided algorithm steps in the given order. Swap the statements in the while loop so they align with what was described.
And a small detail: there was no instruction to separate the output with spaces, so you should provide end = '':
x = int(input())
while x > 0:
print( x % 2, end = '')
x = x//2
You're reading in the least significant bit first, which results in the output being reversed. You don't need to make an explicit call to reversed().
This produces the desired output:
x = int(input())
result = []
while x > 0:
result.append(x % 2)
x = x // 2
# str() transforms each integer to a string.
# We then concatenate them all together
# to get the desired output using ''.join().
print(''.join(str(item) for item in result))
>>> x = 100
>>> res = []
>>> while x > 0:
... x = x//2
... J = x%2
... res.append(J)
...
>>> res
[0, 1, 0, 0, 1, 1, 0]
>>> "".join(str(i) for i in res[::-1])
'0110010'
step1 = input("what number? ")#gets your input
step2 = int(step1) #makes sure it's an int not float
step3 = bin(step2) #converts it to binairy (you method doesn't work for e.g. 7)
step4 = step3.replace("0b", "") #removes 0b from the binairy number
step5 = step4[::-1] #reveses the string
print (step5)
should work
or
print(bin(int(input("what number? "))).replace("0b", "")[::-1])
if you want in more compressed
you can use special function of python to convert integer to binary input and the print reverse of binary input by [:1:-1] in J list, so:
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
print(binary_of_integer_input[2:]) # Print binary of integer input
print(binary_of_integer_input[:1:-1]) # Print reverse binary of integer input
Example:
integer number = 8
binary of input = 1000
reverse of binary = 0001
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
x = binary_of_integer_input[2:]
J = binary_of_integer_input[:1:-1]
print(x) # Print binary of integer input
print(J) # Print reverse binary of integer input
I am taking This class!!!! Here's a code with materials learned so far that works! For actual Binary. Except reversing a string may not have been mentioned [::-1].
The lab wants answers per strictly that algorithm. So reversed binary and expects it to end with new line.
num = int(input())
while num > 0:
y =(num % 2)
print(y, end='')
num = (num//2)
print()
The Note: The above algorithm outputs the 0's and 1's in reverse order. If interpreted "as Convert to binary using this algorithm but reverse it"
num = int(input("Enter a number"))
string = ""
while num > 0:
y =str(num % 2)
string+=y
num = (num//2)
reverse=string[::-1]
print(reverse)
Python Program to Print all Numbers in a Range Divisible by a Given Numbers
L=int(input()) #L=[2,4,5] take all input at a time to process with range number divisible with give inputs those numbers print output is 20,40 bcuz of 2,4,5 divisible 20, 40 only
L=int(input))
for i in l:
for j in range(1,50):
if j%i==0:
print(j)
I want out put 20,40
Range divisible with all list l
I'm not sure quite sure what you're asking, but I think the gist of it is that you want to print all numbers in a given range that are divisible by a list.
In that case, there is no need to do a type coercion to int on your list, I'm not sure why you did that.
my_list = [2, 4, 5]
# create an empty output list
output = []
# iterate through a range.
for i in range(1, 50):
# create a boolean array that checks if the remainder is 0 for each
# element in my_list
if all([i % j == 0 for j in my_list]):
# if all statements in the boolean list created above are true
# (number is divisible by all elements in my_list), append to output list
output.append(i)
print(output)
First you need to calculate the least common multiple (lcm) of the numbers in the list. Math library in python 3.9 has included a lcm function, so you can use it. If you dont have python 3.9 you can search some solutions.
import math
lcm = math.lcm(2,4,5)
At this point you know that every integer number that you multiply by 20 is going to be divisible by all the numbers in the list (2 * 20=40, 3 * 20=60 ...). So for a range you must divide the maximum range number (in your case 50) and truncate the result.
high = 50
low = 1
n = int(high/lcm)
Make a loop and multiply from 1 to n by the lcm result. Then for each result check if it is equal or higher than the lower range.
for j in range(1,n):
res = j*lcm
if res >= low:
print(res)
values = int(input('enter value count :'))
n = []
for k in range(values):
temp = int(input('enter int value :'))
n.append(temp)
for i in range(1,50):
count = 0
for j in n:
if i%j == 0:
count=count+1
else:
if count==len(n):
print(i,end=',')
Hello guys i have a problem that that contain any number (eg- 167) will be split into 12 random numbers the sum of the 12 random numbers should be the original number And the numbers be positive, larger than zero, integers
for this i have written a code :
a = 167
n = 12
out = diff([0,sort(randperm(a-1,n-1)),a])
here i'm getting a error
name 'diff' is not defined
Another way:
a = 50390
b = rand(10,1)
b = b/sum(b)*a
out=round(b)
out(1) = out(1) - (a-sum(out))
Note: this both code is not working so please tell me how to do it
please help me get it..thanks
This should do it.
from random import randint
a = 167
n = 12
assert a >= n >= 1
pieces = []
for idx in range(n-1):
# Number between 1 and a
# minus the current total so we don't overshoot
# minus 1 for each number that hasn't been picked
# so they can all be nonzero
pieces.append(randint(1,a-sum(pieces)-n+idx))
pieces.append(a-sum(pieces))
Note that these numbers aren't independent; any time you add a constraint like THE n VALUES MUST TOTAL a, you're taking away some of the randomness. Here, the numbers later in the distribution are likely to be smaller than the earlier numbers, until the last number which is expected to be average again. If you don't like that trend, you can shuffle() the resultant list, pieces.
Edit: For floats, you don't have to save space for the next value (ditto for non-negative int instead of positive int), so it'd look a little different. Basically, you just remove the -n+idx term from the expression, since you no longer need to allocate n-idx more pieces >=1.
from random import uniform
a = 166.667
n = 12
assert a > 0
assert n >= 1
pieces = []
for idx in range(n-1):
# Number between 0 and a
# minus the current total so we don't overshoot
pieces.append(uniform(0,a-sum(pieces)))
pieces.append(a-sum(pieces))
def num_pieces(num,lenght):
ot = list(range(1,lenght+1))[::-1]
all_list = []
for i in range(lenght-1):
n = random.randint(1, num-ot[i])
all_list.append(n)
num -= n
all_list.append(num)
return all_list
num_pieces(167,12)
input:
5
30
50
10
70
65
5 is how many numbers follow after.
My code:
n = int(input())
list = []
i = 0
while len(list) < n:
integer = int(input())
list.append(integer)
i = i + 1
minList = min(list)
integers = list[i - 1] - minList
print(integers)
I'm suppose to subtract the smallest number from the 5 integers.
The correct output:
20
40
0
60
55
My output:
0
20
0
60
55
I understand why my output is wrong since the smallest number is 20 until 10 is inputed, but I don't know how to correct it. I tried different ways, but none of them work. How do I subtract the smallest number from each integer?
Collect all the input first, then find the minimum value and print the numbers.
n = int(input())
numbers = []
while len(numbers) < n:
integer = int(input())
numbers.append(integer)
smallest = min(numbers)
for number in numbers:
print number - smallest
size = int(input())
lst = [int(input()) for _ in range(size)]
m = min(lst)
res = [abs(n - m) for n in lst]
Get the inputs to a list. Take minimum of this list using min() and then subtract minimum value from each of the list elements:
n = int(input()) # Read number of numbers
lst = []
for _ in range(n):
lst.append(int(input())) # Append to list
min_value = min(lst) # Take the minimum number
final_lst = [abs(x-min_value) for x in lst] # Subtract minimum from each number
This looks like a default puzzle for sites like Hackerrank ... take all the inputs , then perform your operations on all inputs. Do not meddle with data while still gathering inputs (unless it makes sense to do so).
A nice way of getting all the data is:
n = int(input()) # get how many inputs follow
# get n inputs, perform the int() conversion, store as list.
data = list(map(int, (input().strip() for _ in range(n))))
# calculate the min value
min_value = min(data)
# print all reduced values in order each on one line
print( *[x-min_value for x in data], sep = "\n")
# or comma seperated:
print( *[x-min_value for x in data], sep = ",")
Output:
# print with sep="\n"
20
40
0
60
55
# print with sep=","
20,40,0,60,55
Read the doku for map(), int(), min() and look at Built in functions: do not use those as names for your variables, neither use list,dict,set,tuple.
Try this:
l = list()
for _ in range(int(input())):
l.append(int(input()))
xmin = min(l)
print(*[x - xmin for x in l])
Output:
C:\Users\Documents>py test.py
5
30
50
10
70
65
20 40 0 60 55
I have a problem I can't seem to figure out. I am very new to Python and have only been coding for three weeks. Any help is appreciated.
Problem:
We are passing in 3 inputs:
a list of numbers
a multiplier value, M
a value, N
You should multiply every Nth element (do not multiply the 0th element) by M. So if N is 3, you start with the 3rd element, which is index 2.
If there are less than N elements then you should output the unchanged input list.
I can't seem to figure this out. I have tried many different things here. Currently, I have the following, which is not working at all.
Provided:
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
My Code:
for N in numbers:
if numbers[i] > 0:
total = N * M
print(total)
else:
print(numbers)
Output:
I am not even close to what the output should be. Feeling lost on this. Here is what my code comes to. It looks like they want the output in a list.
Program Failed for Input: 1,2,3,4,5,6 5 3
Expected Output: [1, 2, 15, 4, 5, 30]
Your Program Output:
5
10
15
20
25
30
You could try a list comprehension with slicing.
numbers[N-1::N] = [x * M for x in numbers[N-1::N]]
A more elegant solution using list comprehensions ;)
[item*M if (index and not (index+1)%N) else item for index, item in enumerate(items)]
This solution is based on your original one. A more pythonic one would use for instance, a list comprehension so keep that in mind in the future,
output = [numbers[0]]
if len(numbers) >= N:
for i in range(1,len(numbers)):
if ((i+1)%N) is 0:
output.append(numbers[i]*M)
else:
output.append(numbers[i]);
else:
output = numbers
If N is not larger than the list size, the program constructs a new list of numbers with each Nth number being multiplied by M. This is done with a simple modulo operator. Indexing in Python starts with zero and i iterates through index values but your desired output counts the elements as if starting from 1 - thus i+1 in the modulo. If it is not every Nth - program just append the old value. If the list is shorter than N altogether, it assigns the whole unchanged list to the output list.
will this work for you?
res = []
for num in numbers:
if num > 0:
total = num * M
res.append(total)
if len(res) != len(numbers):
print (numbers)
else:
res.reverse()
print (res)
So after many attempts and bouncing this off of a friend who works as a programmer, I ended up with this that gave me the proper output:
newlist = []
if len(numbers) < N:
newlist = numbers
else:
for i in range(0, len(numbers)):
num = numbers[i]
if (i+1) % N == 0:
newlist.append(num*M)
else:
newlist.append(num)
i+=1
print(newlist)
# Input
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
# convert strings to integers
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
# if the length of our list is greater than our supplied value
# loop to multiply(starting at the 3rd position in the list) by M
if len(numbers) > N :
for num in range(2, len(numbers), 3) :
numbers[num] = numbers[num] * M
print(numbers)