+ 3
Counting Numbers in a range
# how can we modify this code to count the numbers in a given range which can divide by 2 we can’t use lists etc. import math while True: num1 = int(input("input lower number: ")) num2 = int(input("input upper number: ")) for numbers in range(num1, num2 + 1): if numbers % 2 == 0: print(numbers) else: break
13 Respuestas
+ 2
Well you don't need to import math and you don't need the while loop or the else block
+ 1
can you use sets?
print({x for x in range(0,100) if x%2==0})
what about dictionaries?
print({i:x for i,x in enumerate(range(0,100),1) if x%2==0})
tuples?
print(tuple(x for x in range(0,100) if x%2==0))
+ 1
there are other ways, yeah, but I don't think they will be as efficient as the ones we have already identified, the for loop does a pretty good job and the comprehensions do as well, the only other thing would be maybe a lambda or recursive function
+ 1
You can use Pandas, but you are still storing your values in an array, you need to store the values somehow
import pandas as pd
x=int(input())
y=int(input())
z=range(x,y+1)
df=pd.Series(z,index=z).apply(lambda x: x%2==0)
print(df)
print(f"There are {sum(df)} in even numbers in {z}")
+ 1
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ This is what I’m looking for. thank you so much :)
+ 1
print([1 for i in range(int(input()),int(input())+1) if i%2==0].count(1))
+ 1
Kunevich Evgeniyy Evgenievich this is short and effective. thanks.
0
No we can’t use any of them. is there any other way?
0
so what should I do? for example if I give the first number 10 and second 20. then the numbers between this range is which can divide by 2 are:
10, 12, 14, 16, 18, 20
now I want another print that says “there are 6 even numbers”
how can I count these even numbers there?
0
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ yes but I want to print how many even numbers between that range. for example if I entered 10 and 20 then it should give me the print that says “there are 6 even numbers”