How to access lists elements particular digits in python? - python

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

Related

FInding the most frequent number only using for loop

I know there are multiple questions asked reguarding finding the most frequent numbers and how many times they have been repeated. However, I have a problem that requires to sole the question only using for loop, if, etc.
I'm not allowed to use .count, dic, arrary or any other fancy functions.
My_list=[1,1,1,1,1,1,1,1,2,2,2,3,4,5,6,6,7,7,8,7,8,8,8,8,8,8,8]
The answer that is required to print would be
1, 8times 8, 8times
I know it may be a pain to use only for loop, but it's killing me and i'm craving for hlep :(
There are a lot of questions that exist will practice iterative and list. I do not think so this is a good practice. For your pain, I thought to provide you a little bit of a messy answer (messy means a lot of use of variables).
You have not mentioned length of your list. Therefore, I have created this code to work with any range.
Code with comments
My_list=[1,1,1,1,1,1,1,1,2,2,2,3,4,5,6,6,7,7,8,7,8,8,8,8,8,8,8]
list1 = []
list2 = []
list3 = []
c = 0
k = 1
y = 1
while y == 1: # Use while loop until all objects read and store in another lists
for i in My_list: # read oblectsa in My_list one by one
if i == k:
list1.append(k) # append all same digits into list1
list2.append(len(list1)) # Get the length of list1 that have same digits and store it in list2
list3.append(list1[0]) # Get the first value of list1 that have same digits and store it in list2
list1 = [] # Reset the list one for store next same digits
k = k + 1
if k == My_list[-1] + 1: # get the value of last digit of the list
y = 0
m = 0
for j in list2: # use this for loop to get final outcome
print(m, ",", j, "times", list3[m], ",", j, "times")
m = m + 1
Code without comments
My_list=[1,1,1,1,1,1,1,1,2,2,2,3,4,5,6,6,7,7,8,7,8,8,8,8,8,8,8]
list1 = []
list2 = []
list3 = []
c = 0
k = 1
y = 1
while y == 1:
for i in My_list:
if i == k:
list1.append(k)
list2.append(len(list1))
list3.append(list1[0])
list1 = []
k = k + 1
if k == My_list[-1] + 1:
y = 0
m = 0
for j in list2:
print(m, ",", j, "times", list3[m], ",", j, "times")
m = m + 1
Output -:
0 , 8 times 1 , 8 times
1 , 3 times 2 , 3 times
2 , 1 times 3 , 1 times
3 , 1 times 4 , 1 times
4 , 1 times 5 , 1 times
5 , 2 times 6 , 2 times
6 , 3 times 7 , 3 times
7 , 8 times 8 , 8 times
Note -:
You can use print(list2) and print(list3) end of the code to see what happens. And also try to understand the code by deleting part by part.

Multiplying corresponding elements from 2 lists in Python

I'm new to Python and I was wondering if anyone could help explain how to code the following task in Python using stdin
Programming challenge description:
You have 2 lists of positive integers. Write a program which multiplies corresponding elements in these lists.
Input:
Your program should read lines from standard input. Each line contains two space-delimited lists. The lists are separated with a pipe char (|). Both lists have the same length, in range [1, 10]. Each element in the lists is a number in range [0, 99].
Output:
Print the multiplied list.
Test Input:
9 0 6 | 15 14 9
Expected Output:
135 0 54
Try this:
input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join([str(n1*n2) for n1, n2 in zip(list1, list2)])
OR,
input_string = input().strip()
list1 = input_string.split("|")[0].split()
list2 = input_string.split("|")[1].split()
result = " ".join([str(int(n1)*int(n2)) for n1, n2 in zip(list1, list2)])
OR,
import operator
input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join(map(str, map(operator.mul, list1, list2)))
OUTPUT of print(result):
135 0 54
Since you are asking for help and not just a solution, here are some useful functions that should give you some inspiration:)
input("give me some") #reads a string from stdin.
"abcabcbbbc".split("c") #splits the string on "c" and returns a list.
int("123") #converts the string to an int object.
#Input comma seperated values
a = input("Values of first list: ")
a = a.split(",")
b = input("Valies of second list: ")
b = b.split(",")
c = []
counter = 0
for each in a:
c.append(int(each) * int(b[counter]))
counter += 1

How does str.replace() method work?

I have this input:
'0472/91.39.17'
I want to replace my input with '1234567890' one by one like this:
'1234/56.78.90'
But my outcome is
0472/91.09.17
Here's my code
phone = '0472/91.39.17'
repl = 1234567890
for i in phone:
if i.isdigit():
for j in str(repl):
x = phone.replace(i, j)
print(x)
What is the proper way to do this?
You can turn repl into an iterator and use a generator expression to replace any value in phone with the next value in the repl iter if the original value is a digit. Re-combine that together with ''.join to get a string as a result, and Bob's your uncle.
repliter = iter(str(repl))
result = ''.join(next(repliter) if c.isdigit() else c for c in phone)
# the ternary expression here evaluates to:
# if c.isdigit():
# next(repliter)
# else:
# c
Note that this will crash with a StopIteration error if your phone number contains more than 10 digits, so consider using itertools.cycle for repliter instead.
import itertools
repliter = itertools.cycle(str(repl)) # 1 2 3 4 5 6 7 8 9 0 1 2 3 ...
I was thinking you could use itertools count with modulus for numbers higher than 10.
from itertools import count
c = count(0) # start number
phone = '0472/91.39.17'
''.join(str(next(c) % 10) if item.isdigit() else item for item in phone)

Python - replay values in list

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?

How to iterate through alpha and numeric numbers

I would like to know how in Python I can iterate through a set of conditions.
string that has 2-6 lower alpha or numeric characters
the first character is always a number
So a short progression would be:
1a
1b
1c
...
1aa
1ab
1ac
...
2aaa
2aab
2aac
etc.
A horrible example that can do the first two is
##Loop through 1a-z0-9
start = '1'
l = 97
while l < 123:
num = start
num += chr(l)
print num
l += 1
l = 48
while l < 58:
num = start
num += chr(l)
print num
l += 1
I found itertools but can't find good examples to go off of.
You can do this using itertools.product and itertools.chain. First define strings of the numbers and letters:
numbers = '0123456789'
alnum = numbers + 'abcdefghijklmnopqrstuvwxyz'
Using itertools.product, you can get tuples with the characters for the strings of various length:
len2 = itertools.product(numbers, alnum) # length 2
len3 = itertools.product(numbers, alnum, alnum) # length 3
...
Chain the iterators for all the lengths together, joining the tuples into strings. I'd do it with a list comprehension:
[''.join(p) for p in itertools.chain(len2, len3, len4, len5, len6)]
I would go with product function from itertools.
import itertools
digits = '0123456789'
alphanum = 'abcdef...z' + digits # this should contain all the letters and digits
for i in xrange(1, 6):
for tok in itertools.product(digits, itertools.product(alphanum, repeat=i)):
# do whatever you want with this token `tok` here.
You can think of this problem in base 26 (Ignoring the first number, we will put this in a separate case.) So with the letters we want to range from 'a' to 'zzzzz' in the base 26 would be 0 and (26,26,26,26,26) = 26 ^ 0 + 26 + 26^2 + 26^3 + 26^4 + 26^5. So now we have a bijection from numbers to letters, we just want to write a function that takes us from a number to a word
letters = 'abcdef..z'
def num_to_word( num ):
res = ''
while num:
res += letters[num%26]
num //= 26
return res
Now to write our function that enumerates this
def generator():
for num in xrange(10):
for letter_num in xrange( sum( 26 ** i for i in xrange( 6 ) ) + 1 ):
tok = str(num) + num_to_word( letter_num )
yield tok
lets do this with a breadth first search type algorithm
starting from
Root:
have 10 children, i = 0,1,...,9
so , this root must have an iterator, 'i'
therefore this outermost loop will iterate 'i' from 0 to 9
i:
for each 'i', there are 5 children (ix , ixx, ixxx, ixxxx, ixxxxx)
( number of chars at the string )
so each i should have its own iterator 'j' representing number of chars
the loop inside Root's loop will iterate 'j' from 1 to 5
j:
'j' will have 'j' number of children ( 1 -> x , 2 -> xx ,..., 5-> xxxxx)
so each j will have its own iterator 'k' representing each "character"
so, 'k' will be iterated inside this j loop, from 1 to j
( i=2, j=4, k = 3 will focus on 'A' at string "2xxAx" )
k:
each 'k' represents a character, so it iterates from 'a' to 'z'
each k should have a iterator(value) 'c' that iterates from 'a' to 'z' (or 97 to 122)
i think this will make sense than what i wanted to show u earlier. :)
if u dont get the idea please tell me.. btw, its an interesting question :)

Categories

Resources