I wrote the permutations for the 4-digit number using a list and loops in python.
a =list(input("enter a four digit number:"))
n=[]
for i in range (0,4):
for j in range (0,4):
if(j!=i):
for k in range(0,4):
if(k!=i and k!=j):
for w in range (0,4):
if(w!=i and w!=j and w!=k):
n.append(a[i]+""+a[j]+""+a[k]+""+a[w])
print(n)
If the input is 1234, the output will be the permutations of all 1234 i.e., 24 permutations. Can someone help me with the permutations of the n-digit number? I would prefer to see a pythonic solution.
Permutate [1..N]
import itertools
N = 4 # pick a number to permutate [1..N]
print(list(itertools.permutations(range(1, N + 1))))
Now if you want to permutate an arbitrary list:
import itertools
sample = [1,5,6,2,1]
print(list(itertools.permutations(sample)))
For the conditions inside if loop the condition recursion is used,
There should be dynamic number of for loops based on the length of the digits
so loop recursion method is used.
The digits are concatenated in the l variable
When there are repeated digits in number set method can make them as distinct
#n digit number as input converted into list
f=list(input("enter any number:"))
#dynamic array for dynamic for loop inside recursion
a=[0 for k in range(len(f))]
c=[]#list which is to be used for append for digits
ans=[]# result in which the
# recursion for if loop inside for loop
#1st argument is fixed inside the loop
#2nd argument will be decreasing
def conditn(k,m):
if(m==0):
return 1
if(m==1):
if(a[k]!=a[0]):
return 1
if(a[k]!=a[m-1] and conditn(k,m-1)):
return 1
#recursion for for loop
#1st argument y is the length of the number
#2nd argument is for initialization for the varible to be used in for loop
#3rd argument is passing the list c
def loop(y, n,c):
if n<y-1:
#recursion until just befor the last for loop
for a[n] in range(y):
if(conditn(n,n)):
loop(y, n + 1,c)
else:
# last for loop
if(n==y-1):
for a[n] in range(y):
#last recursion of condition
if(conditn(n,n)):
#concatinating the individual number
concat=""
for i in range(y):
concat+=f[a[i]]+""
c.append(concat)
#returning the list of result for n digit number
return c
#printing the list of numbers after method call which has recursion within
#set is used used to convert any of the iterable to the
#distinct element and sorted sequence of iterable elements,
for j in (set(loop(len(f),0,c))):
print(j)
def swapper(s , i,j) :
lst = list(s)
return "".join(lst)
def solve(string , idx, res) :
if idx == len(string) :
res.append(string)
return
for i in range(idx, len(string )) :
lst=list(string)
lst[i],lst[idx]=lst[idx],lst[i]
string = "".join(lst)
solve(string,idx+1,res)
lst=list(string)
lst[i],lst[idx]=lst[idx],lst[i]
string = "".join(lst)
n = 3
k = 3
lst = []
res = []
for i in range(1,n+1) :
lst.append(str(i))
string = "".join(lst)
solve(string, 0 , res)
res.sort()
n is the number of digits you may want in your answer
res will store all the permutations of the number
This is a simple resursion solution : )
Related
I was given range n and number k. Count the possible ways so that two (not identical) number in that range add up to number k. And can this be done without nested loops?
Here's my approach, the only thing is I'm using a nested loop, which takes times and not computer-friendly. Opposite pairs like (A, B) and (B, A) still count as 1.
n, k = int(input()), int(input())
cnt = 0
for i in range(1, n+1):
for s in range(1, n+1):
if i == 1 and s == 1 or i == n+1 and s==n+1:
pass
else:
if i+s==k:
cnt += 1
print(int(cnt/2))
example inputs (first line is n, second is k)
8
5
explanation(1, 4 and 2, 3), so I should be printing 2
You only need a single loop for this:
n = int(input('N: ')) # range 1 to n
k = int(input('K: '))
r = set(range(1, n+1))
c = 0
while r:
if k - r.pop() in r:
c += 1
print(c)
If I understood you well it's gonna be just a single while loop counting up to k:
counter = 0
while counter<min(n,k)/2:
if counter+(k-counter) == k: # This is always true actually...
print(counter,k-counter)
counter+=1
Starting from 0 up to k those pairs are gonna be counter and k - counter (complement to k, so result of subtracting the counter from k)
We should can count up to smaller of the two n and k, cause numbers bigger than k are not gonna add up to k
Actually we should count up to a half of that, cause we're gonna get symmetric results after that.
So considering you don't want to print each pair it's actually:
count = int(min(n,k)//2)
why are you iterating and checking number combinations when you can mathematically derive the count of valid pairs using n and k itself?
depending on whether n or k being larger the number of pairs can be calculated directly
Every number i within n range has a matching pair k-i
and depending on whether n or k which greater we need to validate whether k-i and i both are within the range n and not equal.
for n>=k case the valid range is from 1 to k-1
and for the other case the valid range is from k-n to n
and the count of a range a to b is b-a+1
since in both conditions the pairs are symmetrical these range count should be halved.
so the entire code becomes
n= int(input())
k=int(input())
if n>=k:print(int((k-1)/2))
if n<k:print(int((2*n-(k-1))/2))
A problem of combinatorics. The following code uses python's built-in library to generate all possible combinations
from itertools import combinations
n = 10
k = 5
n_range = [i for i in range(1, n+1)]
result = []
for i in n_range:
n_comb = combinations(n_range, i)
for comb in n_comb:
if sum(comb) == k:
result.append(comb)
print(result)
I need to make a program in Python that do this:
Write a program that, for a given sequence of digits, prints the number of different three-digit even numbers that can be formed from the given digits. When forming each three-digit even number, each element of the sequence of digits can be used at most once.
The first line of the standard input contains the number of digits N, such that 3≤N≤50000. In the second row is N digits separated by one space.
Print only one number to the standard output, the requested number of three-digit numbers.
n=int(input())
num=[]
for i in range (n):
num.append ()
Input
4
2 4 2 2
Output
4
Explanation
From the digits 2, 4, 2, 2, 4 different three-digit even numbers can be formed, namely 222, 224, 242, 422.
This is a general solution that checks all permutations of these digits and print even numbers out of them:
from itertools import permutations
k = 3
c = 0
n = int(input())
num = input().strip().split(" ")
perms = set(permutations(num, k))
for perm in perms:
t = int("".join(perm))
if t % 2 == 0 and len(str(t)) == k:
print(t)
c += 1
print(c)
This is another solution if you don't want to use this generalized approach and just want to solve it for 3 digits:
c = 0
n = int(input())
num = [int(x) for x in input().strip().split(" ")]
r = set()
for i in range(n):
for j in range(n):
for k in range(n):
if i == j or i == k or j == k:
continue
t = num[i] * 100 + num[j] * 10 + num[k]
if t % 2 == 0 and len(str(t)) == 3:
r.add(t)
print(r)
print(len(r))
First You should declare which user input u expect and how to handle false input.
Then the inputString is split into a list of Strings aka inputList. Now You can loop through each of those inputItem and check if they fit your expectations (is int and smaller then 10 ). Since You still deal with String Items You can try to cast ( convert them) into Int. That can fail and a unhandled failure could cripple Your script so it has to happen in an try- catch-block. If the casting works You wanna make sure to check your matchList if You allready added a simular number before You add the new Number to Your matchList.You do so again by looping through each item. If there is mo such number yet there is a last check for if the number is uneven or 0. In that case there is one possible combination less for each number that is 0 or uneven so they are counted in the variable minusOneCombi. That will be substrated from the maximum amount of combinations which is the amount of numbers in you matchList multiplied with itself (pow(2)). Be very careful with the Indentations. In Python they are determining the ends of if blocks and loops.
InputString=(input("Enter your number stream eg 1 0 0 5 ( non numeric signs and numbers greater 9 will be ignored): "))
inputList= inputString.split(‘ ’)
matchList=[]
minusOneCombi= 0
for inputItem in inputList:
try:
anInt= int(inputItem)
except ValueError:
# Handle the exception
print(“item is not an integer and therefore ignored”)
NotYetinMatchList= True
for MatchItem in MatchList:
If matchItem == inputItem:
notYetinMatchList= False
Break
If notYetinMatchList:
matchList.append(anInt)
if ((anInt % 2) != 0) OR (anInt ==0):
minusOneCombi++
NumofMatches=matchList.count()
NumOfMatchesPow= pow(NumofMatches,2)
Result=NumOfMatchesPow -minusOneCombi
Print(Result)
What's wrong with this code? Please, do not use built-in functions
Also, could you add condition for int(k) < int(size)
numbers = list()
size = input("Enter the size of an array: ")
for i in range(int(size)):
n = input("number: ")
numbers.append(int(n))
print(numbers)
k = input("k = ")
max = numbers[0]
top = list()
for j in range(int(k)):
for x in numbers:
if x > max:
max = x
top.append(max)
del numbers[numbers.index(max)]
print(top)
Here is the corrected version of your code:
size = int(input("Enter the size of an array: ")) # Ask the user for the amount of values that will be entered
numbers = [int(input("number: ")) for _ in range(size)] # Use a list comprehension to store each input
k = int(input("k = ")) # The number of greatest values to be printed
top = list() # List to store the greatest values
for i in range(0, k): # For every unit in the number of greatest values
max = numbers[0] # Set the maximum to any value, I chose index 0 to avoid IndexError
for j in numbers: # For every number in the list of numbers
if j > max: # If that number is greater than max
max = j # Set max to that number and repeat
top.append(max) # Add the gratest to the top list
numbers.remove(max) # Now remove the greatest so we can proceed to find the next greatest
print(top) # Print our result!
Please note that it is a bad practice to name any of your variables the names of built-in functions, so maybe change your max to mx.
You want to have largest k numbers in the list right?
You could just sort the array and take the last k elements with a backwards iteration. Because after you sort, the largest numbers will be at the end.
The algorithm would be as follows:
0. Take the array through a for loop # You seem to have done this
Sort the array (Python has a native sort function, but let's just define a simple bubble sort function as you said no libraries)
Initialize a list or a k-tuple to hold largest numbers
Starting from index = array.length - 1 iterate to index = array.length - 1 - k
Insert each element to the k-tuple in step 2.
In Python, it would be:
def kLargestNumbers(array,k):
### Considering the input array is taken
bubbleSort(array) ## if native python lib is available change it to sort()
largest_k_numbers = list()
for i in range(len(array)-1, len(array)-1-k,-1):
largest_k_numbers.append(array[i])
return largest_k_numbers
def bubbleSort(array):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] < arr[j+1] :
arr[j], arr[j+1] = arr[j], arr[j+1]
I need to take a number, lets say 6, and then find the smallest 4 digit number, whose digits do not repeat and add up to 6.
For example(These will not add up to the same number):
1023
3045
2345
These numbers are all ok because their digits do not repeat and are four digits
While:
1122
3344
123
These are not ok, because they either are not four digits or their numbers repeat
I'm currently at a roadblock where I can find said four digit number, but one: it is in a list which the program i need to plug this into wont accept and two: the digits aren't in the same order as the answers on the program (ie the smallest four digit number that does not have repeat digits, but adds up to six is 1023, but my program returns 0123, which is incorret.
Here is my current code:
x = 6
Sum = 0
#Find the four digit number
for i in range (999, 10000):
#Find the sum of those numbers
Sum = sum(map(int, str(i)))
#Check if sum is = to x
if Sum == x:
num = i
#Get rid of any identical numbers
result = list(set(map(int, str(num))))
#Make sure the length is 4
if len(result) == 4:
print(result)
#Output [0,1,2,3]
Any help on how I could change this to work for what I want would be great
Using recursive algorithm:
def get_num(n, s, v=""):
for el in range(1 if v=="" else 0, 10):
if str(el) not in v:
temp_sum=sum(int(l) for l in v+str(el))
if(temp_sum>s):
break
elif len(v)==n-1:
if(temp_sum==s):
return v+str(el)
else:
ret=get_num(n, s, v+str(el))
if(ret): return ret
Outputs:
print(get_num(4,6))
>> 1023
I've changed your program to print i instead of result, and break out of the loop when it finds the first number (which logically must be the smallest):
x = 6
Sum = 0
#Find the four digit number
for i in range (999, 10000):
#Find the sum of those numbers
Sum = sum(map(int, str(i)))
#Check if sum is = to x
if Sum == x:
num = i
#Get rid of any identical numbers
result = list(set(map(int, str(num))))
#Make sure the length is 4
if len(result) == 4:
print(i)
break
This program will print 1023.
You could neaten it up a bit by turning it into a function with x as a parameter and returning the result instead of breaking and printing. Also it looks as if the num variable is redundant, you can just stick with i.
Changed your code a little:
x = 6
Sum = 0
result={}
#Find the four digit number
for i in range (999, 10000):
#Find the sum of those numbers
Sum = sum(map(int, str(i)))
#Check if sum is = to x
if Sum == x:
num = i
aux = ''.join(list(set(map(str, str(num)))))
if not aux in result:
result[aux] = []
result[aux].append(i)
for k in result:
print(k, min(result[k]))
You might be interested in itertools package which is designed for solving combinatoric problems like yours.
for n in combinations(range(10),4):
if sum(n)==6 and n[0]!=0:
print(n)
break
combinations method used here returns a generator of all tuples of length 4 that contains distinct digits from 0 to 9, they are sorted alphabetically.
You need to use from itertools import combinations to make it work.
Since you need the smallest integer, you can stop the search at the first encountered with a break:
sum=6 # The sum of digits required.
found=0
for i in range(1000, 10000): # i from 1000 to 9999.
a=i%10;
b=i//10%10
c=i//100%10
d=i//1000%10
if (a!=b)&(a!=c)&(a!=d)&(b!=c)&(b!=d)&(c!=d)&(a+b+c+d==sum):
found=True
break
if found:
print(i)
else:
print('Not found such a number.')
What the program is supposed to do is take a users input that generates a collatz sequence then prints out each item from the sequence with a tab between each number but after 6 elements from the list it prints on the next line and so on so forth and the last line (the remaining elements) do not need 6. The last part is it's supposed to find the largest number from the sequence.
I've got the sequence to generate and I can find the largest number, I just can't figure out how to do the spacing.
What I have tried:
(that first print just has to be there)
def display_sequence(sequence)
print()
for i in sequence:
print(i, end = " \t")
Rather than iterating over an increasing sequence of indices, iterate over a repeating cycle of 0, ..., 5. The if statement can be reduced to a conditional expression to select '\t or '\n' as the end character.
from itertools import cycle
for index, item in zip(cycle(range(1, 7)), sequence):
print(item, end='\t' if item < 6 else '\n')
Or, iterate over the starting indices of each slice:
for s in range(0, len(sequence), 6):
print('\t'.join(sequence[s:s+6]))
The documentation of the itertools modules also provides a recipe of iterating over the slices sequence[0:6], sequence[6:12], etc. directly.
i want to see what everyone else does but this is what i did:
def display_sequence(sequence):
print()
for index, item in enumerate(sequence):
if (index + 1) % 6 == 0:
print(item)
else:
print(item, end = " \t")
A small for loop that doesn't require any conditionals:
from string import ascii_lowercase as seq
step = 6
for i in range(0, len(seq), step):
print(*seq[i:i+step], sep="\t", end="\n")
# a b c d e f
# g h i j k l
# m n o p q r
# s t u v w x
# y z
As a function:
def display_seq(seq, step=6):
for i in range(0, len(seq), step):
print(*seq[i:i+step], sep="\t", end="\n")