Find the Number which does not contain the digit d - python

I need the numbers from 1-100 which does not having the digit 1 and 7, eg 0,2,3,4,5,6,8,9,22,23,24,25 so on. Below is the sample code to find the Number which contain the digit d. I need to modify according to my requirement.
def isDigitPresent(x, d):
# Breal loop if d is present as digit
while (x > 0):
if (x % 10 == d):
break
x = x / 10
# If loop broke
return (x > 0)
# function to display the values
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n+1):
# checking for digit
if (i = d or isDigitPresent(i, d)):
print(i,end=" ")
# Driver code
n = 500
d = 0
print("The number of values are")
printNumbers(n, d)

It's a lot easier if you convert the integer into a string and check just check if '7' or '1' are in the string. If not, print it.
def printNumbers(n):
for i in range(0, n + 1):
str_int = str(i)
if not '7' in str_int and not '1' in str_int:
print(i, end=" ")
# Driver code
n = 500
print("The number of values are")
printNumbers(n)
returns
The number of values are
0 2 3 4 5 6 8 9 20 22 23 24 25 26 28 29 30 32 33 ...

You can create a function that checks a digit individually.
def not_contain(num):
nums = list(str(num))
res = [i for i in nums if i not in ['1', '7']]
return True if len(res) == len(nums) else False
Then use filter() to get the results you want.
mylist = [i for i in range(101)]
res = list(filter(not_contain, mylist))
# [0, 2, 3, 4, 5, 6, 8, 9 ------, 99]

Here's modifying your way to work:
def isDigitPresent(x, d):
# Breal loop if d is present as digit
while x > 0:
if int(x % 10) in set(d):
return True
x //= 10
return False
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n + 1):
# checking for digit
if not isDigitPresent(i, d):
print(i, end=" ")
# Driver code
n = 500
d = [1, 7]
print("The number of values are")
printNumbers(n, d)

Related

Python | addition of pattern 1 22 333 4444 55555​ ....?

How do i do addition of 1 22 333 4444 55555​ ....?
i) case 1: n = 1, v = 1
ii) case 2: n= 2, v = 23 (Note: 23 is derived as 1 + 22)
def create_sequence():
n = int(input('Enter the number till which you want the sequence:'))
for i in range(1,n+1):
print(str(i) * i)
create_sequence()
You generate a sequence of elements of the form str(i)*i, which you cast into an integer, then sum that sequence.
def create_sequence(n):
return sum(int(str(i)*i) for i in range(1, n+1))
create_sequence(int(input('Enter the number till which you want the sequence: ')))
Take advantage of loops, they are your friend
def create_sequence():
n = int(input('Enter the number till which you want the sequence:'))
sum = 0
for x in range(1, n+1):
string = ""
for i in range(1, x+1):
string += str(x)
sum += int(string)
return sum
print(create_sequence())

i'm not understanding where i did the mistake

problem:
For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().
------------------------------------------------------------------------
round_sum(16, 17, 18) → 60
round_sum(12, 13, 14) → 30
round_sum(6, 4, 4) → 10
my code:
def round_sum(a, b, c):
round10(a)
round10(b)
round10(c)
return a+b+c
def round10(num):
if num%10>=5:
while num%10!=0:
num = num+1
else:
while num%10!=0:
num = num-1
enter link description here
You don't modify a,b,c. round10 computes the value you want but since you don't keep it in any variable it's forgotten immediately. Try this:
def round_sum(a, b, c):
a = round10(a)
b = round10(b)
c = round10(c)
return a+b+c
also round10 needs to return your final value:
def round10(num):
if num%10>=5:
while num%10!=0:
num = num+1
else:
while num%10!=0:
num = num-1
return num # <----
My Code
def round_sum(a, b, c):
count = 0
for i in (a,b,c):
if i<5: i = 0
if i>4 and i<10: i = 10
if i%10 in [5,6,7,8,9]and i!= 0 and i > 9:
i = i + (10-i%10)
elif i%10 in [1,2,3,4] and i!=0 and i > 9:
i = i - (i%10)
count = count + i
return count
def roundsum(a, b, c):
sum=0
for x in (a,b,c):
if 5<=x<=10:
y=x-x+10
sum+=y
elif x>10:
if x%10<5:
y=x-(x%10)
sum+=y
elif x%10>=5:
y=x-(x%10)+10
sum+=y
return sum

Magic square python

I'm coding a program that reads a line in a file and determines whether or not the line makes a Lo Shu Magic square. In this magic square, the sum of the rows, sum of the columns, and sum of the diagonals have to equal 15, and each number 1-9 can only occur once in the square. This is what I have so far:
def main():
for line in open("Magic Square Input.txt"):
items = line.split(" ")
items = [int(x) for x in items]
result = [items[0:3], items[3:6], items[6:9]]
isMagic(result)
def isMagic(result):
checks1 = ''
for x in result:
for y in range(3):
if sum (result[y][y] for y in range(3)) == 15:
if sum(x[y] for x in result) == 15:
checks1 = checkDupe(result)
else:
checks1 = 'Invalid'
else:
checks1 = 'Invalid'
print(checks1)
def checkDupe(result):
checks1 = ''
for i in range(0,8):
counter = 0
for j in result:
if (j == i):
counter += 1
if counter > 0:
checks1 = 'Invalid'
else:
checks1 = 'Valid'
return checks1
main()
the contents of my text file are as follows:
4 3 8 9 5 1 2 7 6
8 3 4 1 5 9 6 7 2
6 1 8 7 5 3 2 9 4
6 9 8 7 5 3 2 1 4
6 1 8 7 5 3 2 1 4
6 1 3 2 9 4 8 7 5
5 5 5 5 5 5 5 5 5
The first three numbers in each line represent the top row of the square, the next three are the middle row, and the last three are the bottom row. The problem im having is that the first three squares ARE valid, and the last four are supposed to be invalid. But what my code keeps printing out for me is
Valid
Valid
Valid
Valid
Valid
Invalid
Valid
Could somebody show me where I'm screwing up here? I'm fairly new to python and I've been staring at this for hours trying to make sense of it.
This problem is much easier to think about if you start with a flat list:
[4, 3, 8, 9, 5, 1, 2, 7, 6]
and then work out which indexes you need to check. There are only eight in all:
indexes = (
(0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # cols
(0, 4, 8), (2, 4, 6), # diag
)
With that set up, the check function becomes very simple:
def main():
for line in open('Magic Square Input.txt'):
square = [int(n) for n in line.split()]
if len(set(square)) != len(square):
print('Invalid: Duplicates')
else:
for idx in indexes:
if sum(square[i] for i in idx) != 15:
print('Invalid: Sum')
break
else:
print('Valid')
My version without spliting items into rows
data = '''4 3 8 9 5 1 2 7 6
8 3 4 1 5 9 6 7 2
6 1 8 7 5 3 2 9 4
6 9 8 7 5 3 2 1 4
6 1 8 7 5 3 2 1 4
6 1 3 2 9 4 8 7 5
5 5 5 5 5 5 5 5 5'''
def main():
for line in data.split("\n"):
# create list with all numbers
items = list(map(int, line.split()))
print(is_magic(items))
def is_magic(items):
# --- dups ---
#print('dups')
#print(len(set(items)) == 9)
#for x in range(1, 10):
# print(x, x in items)
if len(set(items)) != 9:
return 'Invalid'
# --- rows ---
#print('rows')
for x in range(0, 9, 3):
l = items[x:x+3]
#print(l, sum(l) == 15)
if sum(l) != 15:
return 'Invalid'
# --- cols ---
#print('cols')
for x in range(3):
l = [items[x], items[x+3], items[x+6]]
#print(l, sum(l) == 15)
if sum(l) != 15:
return 'Invalid'
# --- diags ---
#print('diags')
l = [items[0], items[4], items[8]]
#print(l, sum(l) == 15)
if sum(l) != 15:
return 'Invalid'
l = [items[2], items[4], items[6]]
#print(l, sum(l) == 15)
if sum(l) != 15:
return 'Invalid'
# --- OK ---
return 'Valid'
main()
def magic_square(n):
num=(n*((n*n)+1))/2
print('\nThe Magic Number Is:-',num,'\n')
f=[]
for i in range(0,n):
a=[]
for j in range(0,n):
a.append(0)
f.append(a)
(x,i,p,q)=(n*n,1,int(n/2),n-1)
while x!=0:
if x==0:
(f[p][q],i,p,q,x)=(i,i+1,p-1,q+1,x-1)
continue
else:
if p==-1 and q==n:
p=0
q=n-2
if f[p][q]==0:
(f[p][q],i,p,q,x)=(i,i+1,p-1,q+1,x-1)
continue
else:
p=p+1
q=q-2
f[p][q]=i
i=i+1
p=p-1
q=q+1
x=x-1
continue
if p==-1:
p=n-1
if f[p][q]==0:
(f[p][q],i,p,q,x)=(i,i+1,p-1,q+1,x-1)
continue
else:
p=p+1
q=q-2
f[p][q]=i
i=i+1
p=p-1
q=q+1
x=x-1
continue
if q==n:
q=0
if f[p][q]==0:
(f[p][q],i,p,q,x)=(i,i+1,p-1,q+1,x-1)
continue
else:
p=p+1
q=q-2
f[p][q]=i
i=i+1
p=p-1
q=q+1
x=x-1
continue
else:
if f[p][q]==0:
(f[p][q],i,p,q,x)=(i,i+1,p-1,q+1,x-1)
continue
else:
p=p+1
q=q-2
f[p][q]=i
i=i+1
p=p-1
q=q+1
x=x-1
continue
for i in range(len(f)):
for j in range(len(f[i])):
print(f[i][j] ,end = " ")
print("\n")
INPUT
magic_square(5)
OUTPUT
The Magic Number Is:- 65.0
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
In order to help you, I should start saying that your code is very difficult to read. Since you are new to Python, soon you will find out that one of the major benefits of Python is its clear syntax, which makes very easy to figure out what a piece of code is doing. That being said, I solve your problem, using the same logic as you did, but making the code more readable and using some of Python tricks to make the solution shorter and cleaner.
def main():
"""Open the file, parse the input and check if it is a magic cube"""
with open("Magic Square Input.txt") as f:
for line in f.readlines():
numbers = line.split(" ")
cube = [int(x) for x in numbers]
is_magic(cube)
def is_magic(cube):
"""Check if cube is magic.
There are two conditions that must be satisfied:
1 - There must not be any repetitions of the numbers
2 - All vertical/horizontal/diagonal sums must be 15
"""
if not dupe(cube) and check_sum(cube):
print ('Valid')
else:
print ('Invalid')
def dupe(cube):
"""Check if there are repetitions in the cube."""
if len(cube) == len(set(cube)):
return False
return True
def check_sum(cube):
"""Check if all vertical/horizontal/diagonal sums are 15"""
if vertical_check(cube) and horizontal_check(cube) and diagonal_check(cube):
return True
def vertical_check(cube):
if sum(cube[0:9:3]) == sum(cube[1:9:3]) == sum(cube[2:9:3]) == 15:
return True
return False
def horizontal_check(cube):
if sum(cube[0:3]) == sum(cube[3:6]) == sum(cube[6:9]) == 15:
return True
return False
def diagonal_check(cube):
if sum(cube[0:9:4]) == sum(cube[2:7:2]) == 15:
return True
return False
main()
I hope you can understand the solution from the comments in the code. If this is not the case, please post here again.
I had to make some major changes, but it seemed like your checkDupe method wasn't working right. You also only checked for one diagonal instead of both. Also, note that instead of saving whether the answer is valid or not using a checks1 variable, it simply returns 'Invalid' if anything is wrong, this generally makes code much cleaner and simplified the problem quite a bit. If 'Invalid' is never returned, then the method just returns 'Valid' at the end.
def main():
for line in open("Magic Square Input.txt"):
items = line.split(" ")
items = [int(x) for x in items]
result = [items[0:3], items[3:6], items[6:9]]
print isMagic(result)
def isMagic(result):
# check duplicates
if(checkDupe(result) == 'Invalid'):
return 'Invalid'
# diagonals
if sum (result[y][y] for y in range(3)) != 15:
return 'Invalid'
# other digonals
if sum (result[2 - y][2 - y] for y in range(3)) != 15:
return 'Invalid'
# rows and columns
for i in range(3):
if sum(result[i][y] for y in range(3)) != 15:
return 'Invalid'
if sum(result[x][i] for x in range(3)) != 15:
return 'Invalid'
return 'Valid'
def checkDupe(result):
for x in range(1,9):
if(not x in (result[0]+result[1]+result[2])):
return 'Invalid'
return 'Valid'
main()
Here I have created sample method to solve this issue. In this method, we are maintaining following lists
lstAvailableNumbers: list of available numbers (in your case it would be 1-9)
lstTraversedNumbers: list of traversed numbers (once a item is traversed, it is moved to this list)
list of duplicate numbers (all the duplicate numbers will be added to this list)
duplicate number index (it will store the index of the duplicate number so that it can used to replace the non-existing number
It also return the cost of replacement
For debugging purpose, I have also added print statement to check the value of different list
def createMagicSquare(s):
lstAvailableNumbers = list()
lstAvailableNumbers=[1,2,3,4,5,6,7,8,9]
lstTraversedNumbers=set()
lstDuplicateNumbers=list()
dictDuplicateNumberIndex = dict()
lstMissingNumbers=set()
cost=0
for item in range(len(s)):
for colItem in range(len(s[item])):
num= s[item][colItem]
#print('Print traversed number - ' )
#print(num)
#print(lstTraversedNumbers)
if(num in lstAvailableNumbers):
#print('Inside if condition for num in lstAvailableNumbers ' )
lstAvailableNumbers.remove(num)
#print(num)
if(num in lstTraversedNumbers):
#print('Inside if condition for num in lstTraversedNumbers ' )
#print(num)
lstDuplicateNumbers.append(num)
lstIndexPosition =[]
lstIndexPosition.append(item)
lstIndexPosition.append(colItem)
dictDuplicateNumberIndex[num]=lstIndexPosition
lstTraversedNumbers.add(num)
#print(lstTraversedNumbers)
else:
lstDuplicateNumbers.append(num)
lstIndexPosition =[]
lstIndexPosition.append(item)
lstIndexPosition.append(colItem)
dictDuplicateNumberIndex[num]=lstIndexPosition
i=0
#print("Available Numbers -")
#print(lstAvailableNumbers)
#print("Traversed Numbers -")
#print(lstTraversedNumbers)
#print("Duplicate Numbers -")
#print(lstDuplicateNumbers)
#print("Duplicate Number index -")
#print(dictDuplicateNumberIndex)
for item in lstAvailableNumbers:
itemToReplace= lstDuplicateNumbers[i]
value= dictDuplicateNumberIndex[itemToReplace]
s[value[0]][value[1]] = item
i+=1
cost += abs(itemToReplace - item)
#print(cost)
return cost

Python List Index Error

Here is my version of the code right now and I keep getting list index error.
n = 0
y = len(list1)-1
while n < y:
for k in list1:
if list1[n]+ k == g:
print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
break
else:
n = n+1
You are incrementing n in the for loop but testing its contraint in the outer while loop.
Perhaps this is what you wanted:
n = 0
y = len(list1)-1
found = 0
while n < y:
for k in list1:
if list1[n]+ k == g:
print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
found = 1
break # for loop
if found:
break # while loop
n = n + 1
A much better way to do it is using itertools.combinations_with_replacement:
import itertools
for (v1,v2) in itertools.combinations_with_replacement(list1, 2):
if v1 + v2 == g:
print("blah blah blah")
break
combinations_with_replacement(list1,2) will return all the unordered combinations of two elements of list1. For instance, combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
You left a few bits of information out, but I gather that you are trying to find 2 primes that match a target. In order to access a list in this manner, you need to enumerate it.
y = len(list1) - 1
while n < y:
for n, k in enumerate(list1):
if list1[n]+ k == g :
print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
break
However, you don't really need the index, two for loops would accomplish the same thing.
target = 8
primes = [2, 3, 5, 7, 11, 13, 17, 19]
message = 'The 2 prime numbers that add up to {target} are {value1} and {value2}'
for index1, value1 in enumerate(primes):
for value2 in primes[index1 + 1:]:
if value1 + value2 == target:
print(message.format(target=target, value1=value1, value2=value2))

Collatz conjecture sequence

The Collatz conjecture
what i am trying to do:
Write a function called collatz_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1, it returns the empty list [].
background on collatz conjecture:
Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
What I have so far:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x= x/2
else:
x= 3*x+1
return seq
When I run this with a number less than 1 i get the empty set which is right. But when i run it with a number above 1 I only get that number i.e. collatz_sequence(6) returns [6]. I need this to return the whole sequence of numbers so 6 should return 6,3,10,5,16,8,4,2,1 in a list.
You forgot to append the x values to the seq list:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
seq.append(x) # Added line
return seq
Verification:
~/tmp$ python collatz.py
[6, 3, 10, 5, 16, 8, 4, 2, 1]
def collatz_sequence(x):
seq = [x]
while seq[-1] > 1:
if x % 2 == 0:
seq.append(x/2)
else:
seq.append(3*x+1)
x = seq[-1]
return seq
Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.
>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)
Here's another way of doing it:
while True:
x=int(input('ENTER NO.:'))
print ('----------------')
while x>0:
if x%2==0:
x = x/2
elif x>1:
x = 3*x + 1
else:
break
print (x)
This will ask the user for a number again and again to be put in it until he quits
def collatz(x):
while x !=1:
print(int(x))
if x%2 == 0:
x = x/2
else:
x = 3*x+1
this is what i propose..
seq = []
x = (int(input("Add number:")))
if (x != 1):
print ("Number can't be 1")
while x > 1:
if x % 2 == 0:
x=x/2
else:
x = 3 * x + 1
seq.append (x)
print seq
This gives all the steps of a single number. It has worked with a 50-digit number in 0,3 second.
collatz = []
def collatz_sequence(x):
while x != 1:
if x % 2 == 0:
x /= 2
else:
x = (3*x + 1)/2
collatz.append(int(x))
print(collatz)
collatz_sequence()
Recursion:
def collatz(n):
if n == 1: return [n]
elif n % 2 == 0: return [n] + collatz(int(n/2))
else: return [n] + collatz(n*3+1)
print(collatz(27))
steps=0
c0 = int(input("enter the value of c0="))
while c0>1:
if c0 % 2 ==0 :
c0 = c0/2
print(int(c0))
steps +=1
else:
c0 = (3 * c0) + 1
print(int(c0))
steps +=1
print("steps= ", steps)
import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show
def collatz_sequence(N):
seq = [N]
m = 0
maxN = 0
while seq[-1] > 1:
if N % 2 == 0:
k = N//2
seq.append(N//2)
if k > maxN:
maxN = k
else:
k = 3*N+1
seq.append(3*N+1)
if k > maxN:
maxN = k
N = seq[-1]
m = m + 1
print(seq)
x = np.arange(0, m+1)
y = np.array(seq)
xlim(0, m+1)
ylim(0, maxN*1.1)
step(x, y)
show()
def collatz_exec():
print('Enter an Integer')
N = int(input())
collatz_sequence(N)
This is how you can use it:
>>> from collatz_sequence import *
>>> collatz_exec()
Enter an Integer
21
[21, 64, 32, 16, 8, 4, 2, 1]
And a plot that shows the sequence:
seq = []
def collatz_sequence(x):
global seq
seq.append(x)
if x == 1:
return
if (x % 2) == 0:
collatz_sequence(x / 2)
else:
collatz_sequence((x * 3) + 1)
collatz_sequence(217)
print seq
def collataz(number):
while number > 1:
if number % 2 == 0 :
number = number //2
print(number)
elif number % 2 ==1 :
number = 3 * number + 1
print(number)
if number == 1 :
break
print('enter any number...!')
number=int(input())
collataz(number)

Categories