Giving a list of Harshad numbers using Python script - python

After looking around on SO for similair questions and not finding any, I will give it a shot by asking it here. I'll try to be as specific as possible.
Using Python, I am trying to make a piece of code that runs through all possible Harshad numbers and give back an [i] amount of Harshad numbers in a list. To do this, I first made a method isHarshad, which figures out if a number in a list is a Harshad number. Afterwards, I implement this method to print only Hardshad numbers in a list.
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
top = 999999999
for x in (range (1,top)):
if isHarshad(x):
a = a + [x]
count += 1
if count == i:
print(a)
ithHarshad(25)
Running this code returns the first 25 Harshad numbers, which is what I want it to do.
Now my question is: Is it possible to form a loop where it checks a range for Harshad numbers, without making a "top" variable as performed in my code? It feels messy to loop to an arbitrary number like 999999.
I hope my question is a bit clear, and thanks in advance for any input!

Try replacing it with while True: And break the loop when enough numbers are generated. In your code you are running through all the possible numbers which is highly inefficient.
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x = 0
while True:
x += 1
if isHarshad(x):
a = a + [x]
count += 1
if count == i: # Breaks when enough numbers are generated.
break
print(a)
ithHarshad(25)
This will keep adding 1 to x until your count terminates it.

I'm not really sure about what do you mean "checks a range". Did you means you want to show all Hardshad numbers between start to end? Is that true, you can do this:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(start, end):
a = []
count = 0
for x in (range (start,end)):
if isHarshad(x):
a = a + [x]
print(a)
ithHarshad(50,100)

Thanks for the feedback, using a while True: worked for me.
Here is my solution:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x=1
while True:
if isHarshad(x):
a = a + [x]
count += 1
x+=1
if count == i:
print(a)
else:
x+=1
ithHarshad(25)

My way is literally the easiest and smallest way
#get Nums
def getHarshadNums(i):
return [i for i in range(whatever_the_range_is) if isHarshad(i)]

Related

Python Beginner Question “Prime Number Count”

def prime_count(a, b):
for i in range(a,b):
if i % 2 != 0:
return sum(i)
else:
return 0 "
I am a beginner programmer, I have been practicing on some challenges on Edabit, small problems but that require some thinking (for me).
I am trying to count how many prime numbers are on a and b, they are already integers and there is no user input.
I am not very good at loops yet and thought this was going to be a good challenge to practice, what am I doing wrong? I keep getting int object is not iterable
If reference need, here is the link for the challenge.
Link : https://edabit.com/challenge/6QYwhZstMuHYtZRbT
it is an interesting problem that you are solving. You will have to run two-loops here. One to iterate from a to b and the inner loop to check if each element in a -->b is prime or not (the inner loop should run from 2 to j in [a,b).
def primecheck(a,b):
printlist=[]
if a > 1:
for i in range(a,b+1):
for j in range(2,i):
if i % j == 0:
break
else:
printlist.append(i)
if len(printlist) == 0:
return 0
else:
return len(printlist), printlist
Try this out.
As people say in the comment section, calling sum() is what's causing an error.
But, even if you somehow got that part right, you wouldn't quite get what you want. Maybe you were just trying a simple for loop to check if numbers are odd...?
Anyway, I normally like using Sieve of Eratosthenes to generate prime numbers because it's simple.
def sieve_of_eratosthenes(start, end):
if start > end:
raise AssertionError
# end = end + 1 # If end is inclusive, then uncomment this line.
if end < 2:
return 0
sieve = [i for i in range(2, end)] # Initialize an array of number from 2 to end.
size = len(sieve)
p = 2 # Initial prime.
count = 0
# This block implements Sieve of Eratosthenes.
while count < size:
for i in range(count, size):
num = sieve[i]
if num != p and num % p == 0:
sieve[i] = 0
if count == size-1:
break
count += 1
while sieve[count] == 0:
count += 1
if count == size-1:
break
p = sieve[count] # Update the next prime.
# This block calculates the numbers of primes between start and end.
num_of_primes = 0
for p in sieve:
if p == 0 or p < start:
continue
num_of_primes += 1
print(sieve)
return num_of_primes
sieve_of_eratosthenes(1, 100) # This should return 25.

if function inside function returns true, do something (python 3)

have 2 functions. first one generates a list and the second one checks if theres duplicates. if theres duplicates it returns True
so i want to call function 2 from function 1 and if it returns true do something
heres my code
import random
def x(list):
for i in range(len(list)):
count = 0
for k in range(len(list)):
if list[i] == list[k]:
count += 1
if count > 1:
return True
if count == 1:
return False
def generated_list(N):
list = []
for i in range(N):
list.append(random.randint(1, 365))
x(list)
if generated_list(25) is True:
print('is true')
There were some logical errors, check this one :
import random
def check_duplicate(numbers):
for i in range(len(numbers)):
count = 0
for k in range(len(numbers)):
if i == k:
continue
if numbers[i] == numbers[k]:
count += 1
if count > 1:
return True
return False
def generated_list(n):
numbers = []
for i in range(n):
numbers.append(random.randint(1, 365))
return check_duplicate(numbers)
if generated_list(25) is True:
print('is true')
Also, avoid reserved keyword for naming your variables.

how to print sum of primes in a list in python?

How do I print sum of primes in a list in Python?
I'm a new to Python, therefore I might be making a terrible mistake.
Please help out.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
l1 = []
l = len(l1)
i = 0
sum = 0
for i in range(0,l):
if(prime(l1[i]) is True):
sum = sum +l1[i]
print(sum)
l1 = [3,4,5,6]
print(sumprimes(l1))
Output should be equal to 8.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
sum=0
for x in l1:
if prime(x):
sum += x
return sum
l1 = [3,4,5,6]
print(sumprimes(l1))
Use the above code. You need to use the return statement to print the result of a function. And there is no need for your range() loop, there is a more elegant way to do this in python, use a for loop over all elements of the list.
You can do it using below code too.
lst = [1,2,5,7,9,10,12]
def isPrime(x):
if x == 1:
return False
for i in range(2,x-1):
if x%i == 0:
return False
return True
def getPrimeSum(l):
l = [i for i in l if isPrime(i)]
return sum(l)
print(getPrimeSum(lst))
#Check and add into the list of primeval numbers (all primeval number under a specific number)
H = int(input("What the maxium number?: "))
RangeFinding = list(range(3, H+1))
import math
Prime = [2]
for a in RangeFinding:
x = True
y = 2
while x:
NCanA = math.floor(math.sqrt(a))
if a %y == 0:
print(f'{a} is not prime')
x = False
else:
if y > NCanA:
print(f'{a} is prime')
Prime.append(a)
x = False
else:
y = y + 1
x = True
print(Prime)
#**this function will check weather number is prime or not**
def prime(k):
i = 2
j = 0
for i in range(1,k+1):
if(k % i == 0):
j = j + 1
if(j == 2):
return True
else:
return False
#**this function will add all prime numbers**
def sumOfPrimes(l1):
sum=0
for y in l1:
if prime(y):
sum += y
return sum
list1 = [3,4,5,6]
print(sumOfPrimes(list1))
**You Will get output as 8**
Explain
I have created a function prime() that will check whether numbers are prime or not.
I have created a function sumOfPrime() that will add all the prime numbers.
list1
4)Called the function sumOfPrime(list1)
I have shared a Screenshot of the code and outputProgram and Output

Comparing member of a list in Python

I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line if x == a[i]: when a number is not in the list.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
found = False
while found == False:
if x == a[i]:
found = True
break
i += 1
if found == True:
return "True"
else:
return "False"
If there is no element in the list, then your i gets bigger and bigger until it becomes i = len(a). At this point a[i] throws an IndexError since you went above the list size. Simple fix would be to use while i < len(a): instead of while found == false: since you break the loop at x == a[i] anyway.
That's because you are going outside the bounds of the list.
You should add a check so you can return when i > len(a).
You can also use a for loop to avoid the index error, try this
def is_member(x):
a = [1,5,3,9,4,100]
for i in range(len(a)):
if x == a[i]:
return True
return False
You need to add a condition that if (i == len(a)-1): return False.
Because the index can not exceed the length of list a.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
found = False
while found == False:
if i >= len(a):
return False # end of list reached
if x == a[i]:
found = True
break
i += 1
if found == True:
return "True"
else:
return "False"
to handle end of list, a piece of code has been added
In fact you do not another variable like Found, you can do it in below way.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
while True:
if i >= len(a):
print 'test'
return False # end of list reached
if x == a[i]:
return True
i += 1
Try something like this instead:
def is_member(x):
a = [1,5,3,9,4,100]
for i in a:
if i == x:
return "True"
return "False"
Here we iterate over a, and if any member == x we return "True" right away. If we have not returned by the end of the loop then the element is not present.

What is wrong with my code to find the prime factors of a number?

What is wrong with this code to find the primes of a number and store them in a list?
def primes(num):
res = num
i = 2
z = []
while res != 1:
if num%i == 0:
z.append(i)
res = num/i
else:
i += 1
if num=4 and i=2 you got an infinite loop, cause "i" and "res" never changes ...
It's python compliant, but your algorithm is not good.
Try res = res/i.

Categories