I'm trying to find sum of first n palindromes using python - python

Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help

i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)

def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")

Related

Best way to run a function in main function when one of the parameters is not in the scope

Basically my brain is not working right now can't figure out the best way to resolve this error. builtins.NameError: name 'numIters' is not defined
I know this problem is that numIters is not defined in its scope but don't know the best solution to fix that.
Here is the bulk of my code
import random
alg = int(input("Select the sorting algorithm \n 1 - linear search \n 2 - binary search \nEnter Choice: "))
n = int(input("Choose the size of the list: "))
def main():
createList(n,alg)
print(runTest(values,n,alg))
printResults(alg,n,numIters)
#print(linearSearch(values,2))
#print(binarySearch(values, 2))
def createList(n,alg):
global values
values = []
random.seed(1456)
for j in range(n):
values.append(random.randint(0, 2*n))
while len(values) == n:
if alg == 2:
values.sort()
print(values)
return values
elif alg == 1:
print(values)
return values
def linearSearch(values, target):
numIters = 0
for i in range(len(values)):
numIters = numIters + 1
if values[i] == target:
return numIters
return -1
def binarySearch(values, target):
numIters = 0
start = 0
high = len(values) - 1
while start <= high:
middle = (start + high)//2
if values[middle] == target:
numIters = numIters + 1
return numIters
elif values[middle] > target:
numIters = numIters + 1
high = middle - 1
else:
numIters = numIters + 1
start = middle + 1
return -1
def runTest(values,n,alg):
if alg == 2:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
binarySearch(values, tgt)
return count
elif alg == 1:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
linearSearch(values, tgt)
return count
def printResults(alg, n, numIters):
avgIter = n / numIters
if alg == 2:
algType = Binary
if alg == 1:
algType = Linear
print("Results \n n = %d \n %s = %f.2 " % (n,algtype,avgIter))
main()
Thank you in advance for any help given as I am still trying to learn and understand how python works as a whole.
You need to return numIters so that you can pass it to the next function. It looks like it currently gets returned from binarySearch and linearSearch to runTest, but it gets discarded there; just bubble it up like this (I'm going to add type annotations and comments to help me keep track of what's going on):
from typing import List, Tuple
def runTest(values: List[int], n: int, alg: int) -> Tuple[int, int]:
"""Returns count, numIters"""
numIters = 0 # default value in case n is so small we don't iterate
if alg == 2:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
numIters = binarySearch(values, tgt)
return count, numIters
elif alg == 1:
count = 0
for j in range(n * 2):
count = count + 1
tgt = random.randint(0, 2*n)
numIters = linearSearch(values, tgt)
return count, numIters
raise ValueError("alg needs to be 1 or 2!")
Now in your main() you can do:
def main():
createList(n, alg)
count, numIters = runTest(values, n, alg)
print(count)
printResults(alg, n, numIters)

What are the time complexity of these two codes

Following are two different dynamic programming codes for fibonacci series. I cannot figure out the time complexity of these. Results of both are the same. Any help is appreciated.
#Code 1
def fibo(n) :
if mem[n] is not None:
return mem[n]
if n == 1 or n == 2 :
res = 1
else :
res = fibo(n - 1) + fibo(n - 2)
mem[n] = res
return res
n = int(input("Enter position :"))
mem = [None] * (n + 1)
fibo(n)
Code 2
def fibo(n) :
if len(mem) == n-1 :
return mem[n-1]
if n == 1 or n == 2 :
res = 1
else :
res = fibo(n - 1) + fibo(n - 2)
mem.append(res)
return res
n = int(input("Enter position :"))
mem = []
fibo(n)

How to print summation line

def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
command = input("Enter a command: ")
while command == 'squares' :
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
print('Sum = ', sq_sum)
I want to know how to print out a summation line (Ex: Sum = 2**2 + 3**2 + 4**2 + 5**2 = 54). My code only prints out Sum = 54.
You can use for loop to generate strings "number**2" and keep on list, and later you can use ' + '.join(list) to concatename this strings
def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
terms = []
for number in range(a, a+b):
terms.append("{}**2".format(number))
terms = ' + '.join(terms)
print(terms, '=', sq_sum)
EDIT: or shorter:
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = sum(i**2 for i in range(a, a+b))
terms = ' + '.join("{}**2".format(i) for i in range(a, a+b))
print(terms, '=', sq_sum)
You can change your squares() to return a string as well.
def squares(start, num):
s_sum = 0
output = ""
for i in range(num):
s_sum += start**2
output += '{}**2+'.format(start)
start += 1
return s_sum, output[:-1]

Trying to find the next prime number

MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1

Python says: "IndexError: string index out of range."

I am making some practice code for a game similar to the board game, MasterMind-- and It keeps coming out with this error, and I can't figure out why it's doin it. Here's the code:
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)
Okay, the Guess is specified to be 4 integers, and the Answer is a list containing 4 numbers. They both have the same 'len' after the code, so i don't have a clue.
The point of this code is to turn the Answer into a string of 4 numbers, and see if any of those numbers match thoise of the guess, and return how many total matches there are.
See if this helps
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
if len(g) >= 5 and len(a) >=4:
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)

Categories