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?
Related
I don't know why, but I am getting value of scope as final as 0 even len(s) as zero in the last line of countfrequency(s) function.
import collections
def countfrequency(s):
final = 0
flag = 1
d = dict(collections.Counter(s))
for item in d:
if d[item] <= k:
flag = 0
if flag == 1: #Here
final = max(final, len(s))
print(final)
s = "ababbc"
k = 2
for x in range(len(s)):
for y in range(1, len(s)):
countfrequency(s[x:y + 1])
It is because of 2 reasons :
Value of flag is 0 at last so it wont change the value of final
Length function takes object as a parameter and when unchanged it gives 0
So you can can either make flag 1 so that control goes inside if condition or print the value of len(s) out side the if condition
In addition to the answer posted by shaktiraj jadeja, the modified code is as follows:
import collections
def countfrequency(s, k):
final = 0
flag = 0
d = dict(collections.Counter(s))
# print(d)
for item in d:
if d[item] > k:
flag = 1
break
if flag == 1: #Here
# print("Inside:", final, len(s))
final = max(final, len(s))
print(final)
s = "ababbc"
k = 2
for x in range(len(s)):
for y in range(1, len(s)):
# print(s[x:y])
countfrequency(s[x:y + 1], k)
To start with there is no problem of scope.
Now lets get back to the problem
Lets define a rule.
Rule: If a sub string has each character repeated more than k(=2) times in it. Then it is a good substring. Else it is a bad substring
Then your code simply prints the length of good sub string or 0 in case of bad substring
In short in your example string s= "ababbc" contains no good substring
if you try S = "aaaaaa" you will see many numbers printed other than 0 (exactly 11 0's and 10 other numbers)
Now either this was your confusion or you wrote the wrong code for some logic
I hope this helps
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()
Now I'm using while loops to try and do this because I'm not too good at using for loops. As the title reads, I'm trying to print out a table which has the line number next to the length of each line.
Error: When I hit run all I get is the above print out (line and number of words with dashes below). I do not get a series of printouts of y and z
Note: I'm probably making this way harder than it needs to be
Code:
list1 = ['Lets go outside','pizza time','show me the money']
list2 = []
print('line number of words')
print('---- ---------------')
x = 0
len_l1 = len(list1)
while len_l1 > 0:
split_lis1 = list1[0+x].split(' ')
list2.append(split_lis1)
len_l1 -= 1
x += 1
while len_l1 > 0:
q = 1
y = len(list1) - len(list1) + q(x)
z = len(list2[0+x])
print(y, z)
len_l1 -= 1
x += 1
what I want the print out to look like:
line number of words
---- ---------------
0 3
1 2
2 4
Thanks.
Yes, you might have overcomplicated the solution as there are out of the box Python methods that help you easily solve problems like this. For iteration with indexes, use enumerate, in the example below we set the index to start at 1. We can also use some simple string formatting defined in fmt to ensure consistent spacings.
li = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
fmt = ('{} {}')
for idx, sentence in enumerate(li,1):
no_of_words = len(sentence.split())
print(fmt.format(idx, no_of_words))
Then simple use split to split the whitespaces and get the total number of words and let enumerate manage the whole thing for you.
>>
line number of words
---- ---------------
1 3
2 2
3 4
list1 = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
for i in range(0, len(list1)):
length = len(list1[i].split(" "))
print(i + 1, " ", length)
Check out python docs for range and for details.
str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2)
for j in str2:
for i in str1:
if (j[0]==i[0]):
print('number is {}'.format(i))
Hey, I was making program where I needed to to access lists elements particular digits like if one list is [12,23,34] and another is [13,34],I want to access the first elements i.e 12's digits i.e 1 & 2 and compare it with another list and if any equal digit occurs i want to print the first element of the first list.
Like in our example 12 & 13 have 1 as equal digit I want to print 12.I am trying it from several days but getting stuck.And also I tried converting it in string then also some problem arised.
In the above example I am getting the particular digits printed like this:
number is 1
number is 3
number is 3
number is ,
number is ,
number is 1
number is 4
I dont want the 'comma' ,and if a match occurs the number should be printed as mentioned in the example.Any help would be highly appreciated.
Thanks.
Wouldn't keeping them as lists be easier to work with?
If you only want to compare the same indexes, then:
In []:
l1 = [12,23,34]
l2 = [13,34]
for a, b in zip(l1, l2):
if a//10 == b//10:
print(a)
Out[]:
12
Or you want to check any index:
In []:
import itertools as it
l1 = [12,23,34]
l2 = [13,34]
for a, b in it.product(l1, l2):
if a//10 == b//10:
print(a)
Out[]:
12
34
try this
str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2)
for j in str2:
for i in str1:
if (j[0]==i[0] and (i and j != ',')):
print('number is {}'.format(i))
output
12,23,34
13,34
number is 1
number is 3
number is 3
number is 3
number is 3
number is 4
This should work for your use-case
list1 = [123, 12, 32232, 1231]
list2 = [1232, 23243, 54545]
def find_intersection(list1, list2):
list2_digits = set.union(*[get_digits(x) for x in list2])
for num1 in list1:
digits1 = get_digits(num1)
for num2 in list2:
digits2 = get_digits(num2)
if digits1.intersection(digits2):
print 'Found Match', num1, num2 # We found a match
# Break here unless you want to find all possible matches
def get_digits(num):
d = set()
while num > 0:
d.add(num % 10)
num = num / 10
return d
find_intersection(list1, list2)
I'm not sure I totally understand the question, however:
list1 = [13,23,34]
list2 = [24,18,91]
list1 = list(map(str,list1)) #Map the arrays of ints to arrays of strings
list2 = list(map(str,list2))
for j in list1:
for i in list2:
for character in j:
if character in i:
print(j+' matches with '+i)
break
Prints out:
13 matches with 18
13 matches with 91
23 matches with 24
34 matches with 24
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 ;)