the sum of all numbers below N that contain the digit 7 - python

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))

Related

Write a python program to input an integer n and print sum of all its even and odd digits separately

Digits mean numbers not places
I tried but the logic is wrong I know
N=input()
L=len(N)
N=int(N)
sum_e=0
sum_o=0
for i in range(0,L+1):
if i%2==0:
sum_e=sum_e+i
else:
sum_o=sum_o+i
print(sum_e, sum_o)
You can implement this more succinctly by modulating the input value as follows:
N = abs(int(input('Enter a number: ')))
eo = [0, 0]
while N != 0:
v = N % 10
eo[v & 1] += v
N //= 10
print(*eo)
Sample:
Enter a number: 1234567
12 16
N=input()
sum_e=0
sum_o=0
for i in N:
if int(i)%2==0:
sum_e += int(i)
else:
sum_o += int(i)
print(sum_e, sum_o)
Let it remain string so we can iterate the digits and later convert it to Integer
Using a dictionary:
N = input()
# N = '1234567'
out = {}
for c in N:
c = int(c)
key = 'odd' if c%2 else 'even'
out[key] = out.get(key, 0) + c
print(out['even'], out['odd'])
# 12 16
Or with a method similar to #Cobra's:
N = int(input())
# N = 1234567
out = [0, 0]
while N>0:
N, n = divmod(N, 10)
out[n%2] += n
print(*out)
# 12 16

Finding even numbers with while as

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")

How do you find the first N prime numbers in python?

I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.

How to make loop repeat until the sum is a single digit?

Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.
This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement
n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
this is a sample output of the code
Input an integer: 98765678912398
8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88
8 + 8 = 16
1 + 6 = 7
This should work, no division involved.
n = int(input("Input an integer:"))
while n > 9:
n = sum(map(int, str(n)))
print(n)
It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.
You could utilize recursion.
Try this:
def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
you can try this solution,
if n=98 then your output will be 8
def repitative_sum(n):
j=2
while j!=1:
n=str(n)
j=len(n)
n=list(map(int,n))
n=sum(n)
print(n)
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.
n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
Again I am unsure about the recursion within a function in Python, but hey, it works :)
If you like recursion, and you must:
>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
def digit_sum(num):
if num < 10:
return num
last_digit = num % 10
num = num / 10
return digit_sum(last_digit + digit_sum(num))
input_num = int(input("Enter an integer: "))
print("result : ",digit_sum(input_num))
This may help you..!
Try with strings comprehension:
new = input("insert your number: ")
new = new.replace(" ","")
new =sum([int(i) for i in new])
if new not in range (10):
new = str(new)
new = sum ([int(i) for i in new])
print (new)
Note that the answers which convert int to str are relying on the python conversion logic to do internally the divmod calculations that we can do explicitly as follows, without introducing the non-numeric string type into an intrinsically numerical calculation:
def boilItDown(n):
while n >= 10:
t = 0
while n:
d, m = divmod(n, 10)
n, t = d, t + m
n = t
return n
n = 98765678912398
print(boilItDown(n))
Output:
7

Advanced Python Code Assistance

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())

Categories