Description
You are given an array A of n integers. You have to make a queue and stack of the given integers. Queue should contain only prime numbers and stack should contain only composite numbers. All numbers in the array will be .
The rule to form the stack and queue is that you should be able to generate the array using the pop and dequeue operations.
Note : Please read this explanation carefully
Let the array A contains 5 integers : 7 , 21 , 18 , 3 , 12 then the content of queue and stack will be :
Queue : 7 , 3
Stack : 12 , 18 , 21
Now if you follow the rules of stack and queue then you see that you can generate the array using the pop operations of stack and dequeue operation of queue as follows :
dequeue from queue : 7
pop from stack : 7 , 21
pop from stack : 7 , 21 , 18
dequeue from queue : 7 , 21 , 18 , 3
pop from stack : 7 , 21 , 18 , 3 , 12
Thus for every array A you have to print the contents of queue in the first line and contents of stack in the second line.
Input Format
First line contains an integer n as input denoting total numbers of integers in the array.
Next line contains n space separated integers denoting the elements of array A.
Your output should print two arrays , one in each line. First line should be the contents of queue and second line should be the contents of stack.
Output Format
In the first line print the contents of queue and in second line print the contents of the stack.
SAMPLE INPUT
5
7 21 18 3 12
SAMPLE OUTPUT
7 3
12 18 21
My code
backwas = input()
num1 = list(map(int, input().split()))
dic = {}
for num in num1:
output = []
for i in range(2,num+1):
if num%i == 0:
output.append(i)
for item in set(output):
output1 = list(set(output))
dic[num] = output1
prime = []
comp = []
for num in num1:
list1 = []
list1 = list(dic[num])
if len(list1) != 1:
comp.append(str(num))
else:
prime.append(str(num))
print(" ".join(prime))
print(" ".join(comp))
Problem with my code
If you read properly you will immediately notice that the difficult part of this question is making two lists with a correct order, that is when some operations are done on them they give back the original list. My code fails to do so. How should I solve this?
The jist of the problem requires that given a sequence of space separated integers separate the list into primes stored in a Queue and Composite integers stored in a Stack. Output the primes in the que in FIFO order and the composite integers in the stack in LIFO order.
A queue is a linear First In First Out (FIFO) data structure. A List data structure can be used as a queue if we use append() to implement enqueue() and pop() to implement dequeue(). However, lists are quite slow for this purpose because inserting or deleting an element at the beginning requires O(n) time. Using the dequeue class from the collections mnodule is the preferred queue implementation mechanism because append and pop operations take O(1) time.
A stack is a linear Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) data structure. In a similar manner to queue, a list data structure can be used to implement a stack, however as with the queue situation if the list is long, performanvce issues will arise. The dequeue class is therefore preferred for implementing a stack.
Based on the instructions, the first line of input gives the number of integers in the second line of input.
The second line consists of space separated integers. The output is to consist of two lines.
The first output line should present the prime numbers from the input in the order in which they were entered.
The second line should present the composite numbers from the input in the reverse order in which they were entered.
Here is how I would have solved the problem:
#Utility to detect a Prime
def is_prime(n: int) -> bool:
"""
Integer -> Boolean
returns True if n is a prime number
"""
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(sqrt(n))
f = 5
while f <= r:
if n%f == 0:
return False
if n%(f+2) == 0:
return False
f +=6
return True
Using a List approach
# Implementation with Lists assuming instr is list of integers
def list_method(instr: str):
qlist = []
stklist = []
inLst = list(map(lambda x:int(x) ,instr.split()))
for n in inLst:
if is_prime(n):
qlist.append(n)
else:
stklist.append(n)
print(" ".join(map(lambda x: str(x), qlist)))
print(" ".join(map(lambda x: str(x), stklist[::-1])))
Using dequeue Class
from collections import deque
def queue_method(instr: str):
q = deque()
stk = deque()
inLst = list(map(lambda x:int(x) ,instr.split()))
for n in inLst:
if is_prime(n):
q.append(n)
else:
stk.append(n)
print(" ".join([str(q.popleft()) for i in range(len(q))]))
print(" ".join([str(stk.pop()) for i in range(len(stk))]))
Here's a simple approach using Sieve of Eratosthenes and 2 arrays.
num1 = [7,21,18,3,12] # your list
n = max(num1)
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n): #creating a Sieve using standard operations
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
prim, comp = [], []
for i in num1:
if prime[i]:
prim.append(i)
else:
comp.append(i)
for i in prim:
print(i, end = " ")
print()
for i in comp[::-1]:
print(i, end = " ")
print()
Related
Help! I'm a Python beginner given the assignment of displaying the Collatz Sequence from a user-inputted integer, and displaying the contents in columns and rows. As you may know, the results could be 10 numbers, 30, or 100. I'm supposed to use '\t'. I've tried many variations, but at best, only get a single column. e.g.
def sequence(number):
if number % 2 == 0:
return number // 2
else:
result = number * 3 + 1
return result
n = int(input('Enter any positive integer to see Collatz Sequence:\n'))
while sequence != 1:
n = sequence(int(n))
print('%s\t' % n)
if n == 1:
print('\nThank you! The number 1 is the end of the Collatz Sequence')
break
Which yields a single vertical column, rather than the results being displayed horizontally. Ideally, I'd like to display 10 results left to right, and then go to another line. Thanks for any ideas!
Something like this maybe:
def get_collatz(n):
return [n // 2, n * 3 + 1][n % 2]
while True:
user_input = input("Enter a positive integer: ")
try:
n = int(user_input)
assert n > 1
except (ValueError, AssertionError):
continue
else:
break
sequence = [n]
while True:
last_item = sequence[-1]
if last_item == 1:
break
sequence.append(get_collatz(last_item))
print(*sequence, sep="\t")
Output:
Enter a positive integer: 12
12 6 3 10 5 16 8 4 2 1
>>>
EDIT Trying to keep it similar to your code:
I would change your sequence function to something like this:
def get_collatz(n):
if n % 2 == 0:
return n // 2
return n * 3 + 1
I called it get_collatz because I think that is more descriptive than sequence, it's still not a great name though - if you wanted to be super explicit maybe get_collatz_at_n or something.
Notice, I took the else branch out entirely, since it's not required. If n % 2 == 0, then we return from the function, so either you return in the body of the if or you return one line below - no else necessary.
For the rest, maybe:
last_number = int(input("Enter a positive integer: "))
while last_number != 1:
print(last_number, end="\t")
last_number = get_collatz(last_number)
In Python, print has an optional keyword parameter named end, which by default is \n. It signifies which character should be printed at the very end of a print-statement. By simply changing it to \t, you can print all elements of the sequence on one line, separated by tabs (since each number in the sequence invokes a separate print-statement).
With this approach, however, you'll have to make sure to print the trailing 1 after the while loop has ended, since the loop will terminate as soon as last_number becomes 1, which means the loop won't have a chance to print it.
Another way of printing the sequence (with separating tabs), would be to store the sequence in a list, and then use str.join to create a string out of the list, where each element is separated by some string or character. Of course this requires that all elements in the list are strings to begin with - in this case I'm using map to convert the integers to strings:
result = "\t".join(map(str, [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]))
print(result)
Output:
12 6 3 10 5 16 8 4 2 1
>>>
I am trying to write my own code for generating permutation of items represented by numbers. Say 4 items can be represented by 0,1,2,3
I've seen the code from itertools product. That code is pretty neat. My way of coding this is using binary or ternary,... My code below only works for bits of less than 10. Part of this code split the str using list(s). Number 120 in base 11 is 1010, splitting '1010' yields, 1,0,1,0. For it to work correctly, I need to to split to 10, 10. Is there a way around this and still work with the rest of the code?
Alternatively, what is a recursive version for this? Thanks
aSet = 11
subSet = 2
s = ''
l = []
number = aSet**subSet
#finding all permutation, repeats allowed
for num in range(number):
s = ''
while num//aSet != 0:
s = str(num%aSet) + s
num = num//aSet
else:
s = str(num%aSet) + s
s = s.zfill(subSet)
l.append(list(s))
Indeed, the problem with using a string, is that list(s) will chop it into individual characters. You should not create a string at all, but use a list for s from the start:
aSet = 11
subSet = 2
l = []
number = aSet**subSet
#finding all permutation, repeats allowed
for num in range(number):
s = []
for _ in range(subSet):
s.insert(0, num%aSet)
num = num//aSet
l.append(s)
I want to execute a function certain number of times as specified by the user, for user-specified values. I have written the following code
queries = int(raw_input("The number of queries to run: "))
for i in range(0, queries):
a, b = raw_input().split(" ")
def count_substring(str):
length = len(str) + 1
found = []
for i in xrange(0, length):
for j in xrange(i+1, length):
if str[i] == a and str[j-1] == b:
found.append(str[i:j])
print len(found)
string = 'aacbb'
print count_substring(string)
The function gives the number of sub-strings that start and end with user specified characters.
For ex:
In the string "aacbb" the number of sub strings starting with a and ending with c are 2.
Queries indicates the number of inputs, ex for queries = 2 , there will be two inputs of the sub strings, i.e a & c or a & b
I want this code to return 2 values as answers, but it returns only 1.
Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?
Am trying to solve a Codechef problem (Turbo Sort). The problem is
Given the list of numbers, you are to sort them in non decreasing
order.
Input
t – the number of numbers in list, then t lines follow [t <= 10^6].
Each line contains one integer: N [0 <= N <= 10^6]
Output
Output given numbers in non decreasing order.
Example
Input:
5 5 3 6 7 1
Output:
1 3 5 6 7
My Solution is :
l = []
t = input()
MAX = 10**6
while t <= MAX and t != 0:
n = input()
l.append(n)
t = t - 1
st = sorted(l)
for x in st:
print x
The challenge is this program should run in 5 sec. When i submit the file, codechef says it is exceeding the time and needs optimization.
Can some one help, how to optimize it ?
My accepted solutions:
import sys
from itertools import imap
T = int(raw_input())
lines = sys.stdin.readlines()
lis = imap(str, sorted(imap(int, lines)))
print "\n".join(lis)
A readable version(accepted solution) :
import sys
T = raw_input()
lines = sys.stdin.readlines() #fetch all lines from the STDIN
lines.sort(key=int) #sort the list in-place(faster than sorted)
print "\n".join(lines) #use `str.join` instead of a for-loop
Things like readlines should be supported. I've just made an attempt and got this as an accepted solution:
import sys
print '\n'.join(map(str, sorted(map(int, sys.stdin.read().split()[1:]))))
Not pretty but functional. Took me a bit before I figured out you had to skip the first number, debugging is a bit annoying with this system ;)