I was doing this leetcode question:
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/
My code was:
res = []
for x in range(1,1001):
for y in range(1000,0,-1):
test = customfunction.f(x,y)
if test == z:
res.append([x,y])
return res
but this timed out,
a solution was:
def findSolution(self, customfunction, z):
res = []
y = 1000
for x in xrange(1, 1001):
while y > 1 and customfunction.f(x, y) > z:
y -= 1
if customfunction.f(x, y) == z:
res.append([x, y])
return res
given the for loop and the while loop. it seems like these two functions do exactly the same thing.
Why does my code time out but the while loop doesn't?
The working version breaks out of the inner loop once the result of the custom function is reaches z.
You can get the same result using a break in the for loop.
for x in range(1,1001):
for y in range(1000,0,-1):
test = customfunction.f(x,y)
if test == z:
res.append([x,y])
elif test < z:
break
i want to make an odd number list by using 'while' and 'for'
a = []
x = 1
while x < 101:
if x % 2 != 0:
a.append(x)
x = x + 1
print(a)
but nothing happened... and other unrelated codes which is in another sentence are also not executed.
what is my problem?
You should increase the value of x in each iteration and not only if the value is an odd number:
a = []
x = 1
while x < 101:
if x % 2 != 0:
a.append(x)
x += 1
print(a)
Though this is probably for learning purposes note that you could achieve this using the range function as follows: list(range(1,101, 2)).
When you increment x, it should be out of 'if' condition. increment should happen under while
a = list()
x = 1
while x <101:
if x%2 != 0:
a.append(x)
x += 1
print(a)
You can use the range function as well (for for loop) which handles the increment part in the loop as below:
FOR LOOP:
odd=[]
for i in range(101):
if (i%2!=0):
odd.append(i)
print (odd)
WHILE LOOP:
odd=[]
i = 1
while i<101:
if i%2 != 0:
odd.append(i)
i+=1
print (odd)
odd = [i for i in range(101) if i%2 != 0]
print(odd)
I am trying to implement the remove function with linear probing on a hash table.
I am having a problem with that, when I try to call the function remove it enter an infinite loop.
How can I fix that problem??
I have written the function taking the pseudocode:
remove(t, k):
z = 0
repeat
x = hash_function (k, z)
if hash_table[x] == k:
hash_table[x] = deleted return x
z = z+1
until hash_table[x] == NIL or z == m
return NIL
This is the code into a class:
class lin_prob:
def __init__(self, table_size):
self.hash_table = [None]*table_size
self.n_prime = 109169
self.a = random.randint(2, self.prime-1)
self.b = random.randint(2, self.prime-1)
self.n_keys = 0
def remove(self, k):
z = 0
while self.hash_table[x] != None or z < len (hash_table):
x = self.hash_function(k)
if self.hash_table[x] == k:
self.hash_table[x] = "deleted"
return x
else :
z = z+1
return "NIL"
def hash_function(self, k):
return ((self.a*k + self.b) % self.prime_number) % len(self.hash_table)
def len(self):
return self.n_keys
If you want to negate the until condition to create a while condition, you must change the or to an and:
while self.hash_table[x] != None and z < len (hash_table):
...
Also, you code cannot work because x is unknown in your remove method.
The problem arises with the condition you put into the while loop
while self.hash_table[x] != None and z < len (hash_table):
because the negation of equal == is not equal !=. I believe it will fix your problem.
I'm currently working on a small script that aims to find taxicab numbers. There is only one small problem, the for loop doesn't increment the variable x and is stuck looping forever. I'll paste the relevant part of the code below:
n = int(10)
counter = int(0)
m = int(m)
x = int(1)
y = int(n**(1/3))
cheatsheet = []
while counter in range(0,m):
for x in range(1,y):
if x**3 + y**3 < n:
print('less than')
print(x,y,n)
continue
elif x**3 + y**3 > n:
print('greater than')
y -= 1
continue
elif x > y:
if n in cheatsheet:
print('counting')
counter = counter+1
#checking if n occurs in the list, if so it will add 1 to the counter so that the program will know when to stop
n = n + 1
y = int(n**(1/3))
x = 1
print('break1')
#resetting values and bumping n so that it will continue the quest to find 'em all
break
else:
if x and y == 1:
#this is an error correction for low n values, i mean really low it might be redundant by now
n = n + 1
y = int(n**(1/3))
x = 1
print('break2')
break
cheatsheet.append((n,x,y))
print(cheatsheet)
This yields the following result in a terminal window:
image
Note that I killed the process by myself, the program did not.
As you can tell, the script just loops around and prints 'less than' and the values for x,y,n.
Help is greatly appreciated!
EDIT: the variable m is given by the user, but not included in this bit of code.
This has a number of issues wrong with it I'm not willing to post functional code but I will point some of the issues out.
For starters:
n = int(10)
isn't required, not an error but redundant. Use n = 10 with the same effect.
Then:
while counter in range(0,m):
will always evaluate to True. m is *never modified so the membership test always succeeds, maybe you need to re-evaluate your looping.
for x in range(1,y):
This will assign x the value 1 all the time. y evaluates to 2 by your arithmetic (int rounds floats to the floor, i.e int(2.9) -> 2) so either use math.ceil or add one to your y.
Appart from that you re-assign variable names all the time inside your loops, that's confusing and might lead to unexpected behavior.
In problem 4 from http://projecteuler.net/ it says:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
I have this code here
def isPalindrome(num):
return str(num) == str(num)[::-1]
def largest(bot, top):
for x in range(top, bot, -1):
for y in range(top,bot, -1):
if isPalindrome(x*y):
return x*y
print largest(100,999)
It should find the largest palindrome, it spits out 580085 which I believe to be correct, but project euler doesn't think so, do I have something wrong here?
When I revered the for loop I didn't think it through, I removed the thing that checks for the biggest, silly me. Heres the working code
def isPalindrome(num):
return str(num) == str(num)[::-1]
def largest(bot, top):
z = 0
for x in range(top, bot, -1):
for y in range(top,bot, -1):
if isPalindrome(x*y):
if x*y > z:
z = x*y
return z
print largest(100,999)
it spits out 906609
Iterating in reverse doesn't find the largest x*y, it finds the palindrome with the largest x. There's a larger answer than 580085; it has a smaller x but a larger y.
This would more efficiently be written as:
from itertools import product
def is_palindrome(num):
return str(num) == str(num)[::-1]
multiples = ( (a, b) for a, b in product(xrange(100,999), repeat=2) if is_palindrome(a*b) )
print max(multiples, key=lambda (a,b): a*b)
# (913, 993)
You'll find itertools and generators very useful if you're doing Euler in Python.
Not the most efficient answer but I do like that it's compact enough to fit on one line.
print max(i*j for i in xrange(1,1000) for j in xrange(1,1000) if str(i*j) == str(i*j)[::-1])
Tried making it more efficient, while keeping it legible:
def is_palindrome(num):
return str(num) == str(num)[::-1]
def fn(n):
max_palindrome = 1
for x in range(n,1,-1):
for y in range(n,x-1,-1):
if is_palindrome(x*y) and x*y > max_palindrome:
max_palindrome = x*y
elif x * y < max_palindrome:
break
return max_palindrome
print fn(999)
Here I added two 'break' to improve the speed of this program.
def is_palindrome(num):
return str(num) == str(num)[::-1]
def max_palindrome(n):
max_palindrome = 1
for i in range(10**n-1,10**(n-1)-1,-1):
for j in range(10**n-1,i-1,-1):
if is_palindrome(i*j) and i*j > max_palindrome:
max_palindrome = i * j
break
elif i*j < max_palindrome:
break
return max_palindrome
n=int(raw_input())
print max_palindrome(n)
Simple:
def is_pallindrome(n):
s = str(n)
for n in xrange(1, len(s)/2 + 1):
if s[n-1] != s[-n]:
return False
return True
largest = 0
for j in xrange(100, 1000):
for k in xrange(j, 1000):
if is_pallindrome(j*k):
if (j*k) > largest: largest = j*k
print largest
Each time it doesnot have to start from 999 as it is already found earlier.Below is a simple method using string function to find largest palindrome using three digit number
def palindrome(y):
z=str(y)
w=z[::-1]
if (w==z):
return 0
elif (w!=z):
return 1
h=[]
a=999
for i in range (999,0,-1):
for j in range (a,0,-1):
l=palindrome(i*j)
if (l==0):
h=h+[i*j]
a-=1
print h
max=h[0]
for i in range(0,len(h)):
if (h[i] > max):
max= h[i]
print "largest palindrome using multiple of three digit number=%d"%max
Here is my code to solve this problem.
lst = []
for i in range(100,1000):
for n in range(2,i) :
lst.append (i* n)
lst.append(i*i)
lst2=[]
for i in lst:
if str(i) == str(i)[::-1]:
lst2.append(i)
print max(lst2)
Here is my Python code:
max_pal = 0
for i in range(100,999):
for j in range(100,999):
mult = i * j
if str(mult) == str(mult)[::-1]: #Check if the number is palindrome
if mult > max_pal:
max_pal = mult
print (max_pal)
def div(n):
for i in range(999,99,-1):
if n%i == 0:
x = n/i
if x % 1 == 0:
x = n//i
if len(str(x)) == 3:
print(i)
return True
return False
def palindrome():
ans = []
for x in range(100*100,999*999+1):
s = str(x)
s = int (s[::-1])
if x - s == 0:
ans.append(x)
for x in range(len(ans)):
y = ans.pop()
if div(y):
return y
print(palindrome())
580085 = 995 X 583, where 906609 = 993 X 913.
Found it only by applying brute-forcing from top to bottom!
Here is the function I made in python to check if the product of 3 digit number is a palindrome
Function:
def is_palindrome(x):
i = 0
result = True
while i < int(len(str(x))/2):
j = i+1
if str(x)[i] == str(x)[-(j)]:
result = True
else:
result = False
break
i = i + 1
return result
Main:
max_pal = 0
for i in range (100,999):
for j in range (100,999):
x = i * j
if (is_palindrome(x)):
if x > max_pal:
max_pal = x
print(max_pal)
Here is my solution for that:
lst1 = [x for x in range(1000)]
palindrome = []
def reverse(x):
a = str(x)[::-1]
return int(a)
x = 0
while x < len(lst1):
for y in range(1000):
z = lst1[x] * y
if z == reverse(z):
palindrome.append(z)
x += 1
duppal = set(palindrome)
sortpal = sorted(duppal)
total = sortpal[-1]
print(sortpal)
print('Largest palindrome: ' + str(total))
ReThink: efficiency and performance
def palindrome(n):
maxNumberWithNDigits = int('9' * n) #find the max number with n digits
product = maxNumberWithNDigits * maxNumberWithNDigits
#Since we are looking the max, stop on the first match
while True:
if str(product) == str(product)[::-1]: break;
product-=1
return product
start=time.time()
palindrome(3)
end=time.time()-start
palindrome...: 997799, 0.000138998031616 secs