lines repeat in List python - python

I need your help with the next problem,
i need that a python recieve an string "EEEEDDSGES" and the output would by the sum of charactes that repeat in line,
E 4
D 2
S 1
G 1
E 1
S 1
my code is the next,
diccionario = {}
contador = 0
for palabra in cadena:
if palabra.upper() in diccionario:
diccionario[palabra.upper()] += 1
else:
diccionario[palabra.upper()] = 1
for palabra in diccionario:
frecuencia = diccionario[palabra]
print(palabra, end=" ")
print(frecuencia) ```
the output is ,
S,S,d,f,s
S 1
S 2
d 3
f 4
s 5

Try itertools.groupby:
from itertools import groupby
s = "EEEEDDSGES"
for v, g in groupby(s):
print(v, sum(1 for _ in g))
Prints:
E 4
D 2
S 1
G 1
E 1
S 1

I'm sorry I don't understand what this language is, but I guess I understand what you are trying to do. I have changed the variable names for my comprehension.
s="EEEEDDSGES"
letters={}
for i in s:
i=i.upper()
try:
letters[i]+=1
except(KeyError):
letters.update({i:1})
for i in letters: print(f"{i}: {letters[i]}", end=" ")

Related

delete first/last occurrence in list python

I need to delete all first occurrence in list.
time limit = 2 s.
memory limit = 256 mb.
Given list a. Some elements in a repeated. If len(a) = 1 print 0.
Input: 1 1 5 2 4 3 3 4 2 5.
Output: 1 3 4 2 5
My solution: For 48 test 22 - good. Else - limited time. How it solve without .count
n = int(input())
A = list(map(int, input().split()))
C = []
if len(A) == 1:
print(0)
else:
for j in range(n):
if A[:j].count(A[j]):
C.append(A[j])
print(len(C))
print(*C)
Pls help
Another way than using sets
First
n = input().split(" ")
u = []
if(len(n) == 1): print(0, end="")
else:
d = {}
for a in n:
if a in d: u.append(int(a))
else: d[a] = 1
print(*u, end="")
# input: 1 1 5 2 4 3 3 4 2 5
# output: 1 3 4 2 5
# input: 5
# output: 0
# input: 1 1 1 1
# output: 1 1 1
Last
n = input().split(" ")
u = []
if(len(n) == 1): print(0, end="")
else:
n.reverse()
d = {}
for a in n:
if a in d: u.append(int(a))
else: d[a] = 1
u.reverse()
print(*u, end="")
# # input: 1 1 5 2 4 3 3 4 2 5
# # output: 1 5 2 4 3
# # input: 5
# # output: 0
# # input: 1 1 1 1
# # output: 1 1 1
To remove duplicates use set()
_ = input()
A = set(map(int, input().split()))
print(*list(A))

Python Printing Row and Column number on 2d matrix?

I'm trying to print output as follows.
Strings: ["cat", "dog", "big"]
Print:
0 1 2
0 c a t
1 d o g
2 b i g
But I can't seem to print the indices properly
for i in a:
for j in i:
print(j, end=' ')
print()
I know this prints the matrix itself but doesn't give me the row and column numbers I need
Ideal job for pandas:
import pandas as pd
lst = ["cat", "dog", "big"]
df = pd.DataFrame([[y for y in x] for x in lst])
print(df)
# 0 1 2
# 0 c a t
# 1 d o g
# 2 b i g
please try below:
str_list = ["cat", "dog", "big"]
print (" ", " ".join([str(x) for x in range(len(str_list))]))
for i, x in enumerate(str_list):
print (i, " ".join(x))
Demo
Ta-da! This solution should work regardless of list dimensions.
str_list = ['cat', 'dog', 'loooong', 'big']
max_row_len = len(max(str_list, key=len))
#header
print(' ', end='')
print(*range(max_row_len), sep=' ')
#rows
for idx, val in enumerate(str_list):
print(idx, end=' ')
print(*val, sep=' ')
Output:
0 1 2 3 4 5 6
0 c a t
1 d o g
2 l o o o o n g
3 b i g
You can achieve your output without using any library by following code, Otherwise PANDAS would be helpful for oneliner
str = ['cat','dog','big']
r = 0
c = 0
print(' ',end='')
for i in range(0,(max([len(i) for i in str]))):
print(c,end=' ')
c+=1
print()
for i in str:
print(r,end=' ')
for j in i:
print(j , end=' ')
print()
r+=1
Output :

code not running as aspected given wrong result

I want to print
A
B C
C D E
E F G H
I tried but showing the result
A
B C
C D D
D E E E
a = chr(65)
for i in range(0, 4):
i = i + 1
for j in range(65, 65+i):
print(a, end=" ")
a = chr(65 + i)
print("\n")
Make it simple:
letter_a_code = ord('A')
for i in range(4):
for j in range(i+1):
letter = chr(letter_a_code+j+i)
print(letter, end=" ")
print()
prints:
A
B C
C D E
D E F G
You have to print 4 rows. i is your index.
Each row is made of i elements.
Add the offset for letter A code (don't hardcode it, use ord('A')): done.

How to do this program without a counter?

lista = []
for i in range(5):
i = int(input("Digite um valor para o vetor: "))
lista = lista + [i]
x = int(input("Digite um valor para ver sua posição: "))
counter = 0
for j in range(5):
if lista[j] == x:
counter =+ 1
print(j)
if counter == 0:
print(x-1)
In the above program you put any 5 numbers in the list, then you look for the position of the number you inputted in the list, if the number inputted is not in the list it will print x-1.
For example List = [1, 2, 3, 4, 5]
x = 5 then it will print 5
x = 7 it will print 6
How do I make it print x-1 without counter? I tried using:
else:
print(x-1)
but then it will print x-1 5 times, I only want to print it once.
You don't need a counter at all, as you're only using it to check that there were no matches. You can use the for..else structure to check whether the loop completed without exiting from a break.
for j in range(5):
if lista[j] == x:
print(j)
break
else:
print(x-1)
If you want to print each index that matches your search query, I would move to a different approach:
>>> x = 1
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
1 1 1 1 1
0 1 2 3 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10 1
2 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10
2

Conway sequence in python

I have an assignement for which I have to write an algorithm who generates the l lines of the Conway sequence of a chosen r integer.
Example for l=8 and r=1 :
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
I have tried to write an algorithm in Python3, but I can't manage to get the correct output. I'd appreciate if you could help me to figure out what's wrong... Anyway, here's what I've wrote so far :
r = int(input())
l = int(input())
cur=str(r).strip()
print(r)
for j in range(l-1):
r=cur
cur=""
i=0
while i<len(r) :
c=1 #counts the consecutive same "numbers"
while ((i+c*2)<len(r)) and (r[i]==r[i+c*2]):
c+=1
cur+=str(c)+" "+r[i]+" "
i+=c+1
cur=cur.strip()
print(cur)
And that's the output I'm getting for l=8 and r=1 :
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 1 1 2 2 1
1 3 3 1 1 1 2 2 1
1 1 2 3 6 2 2 1
I also feel that my code is pretty ugly so feel free to give your remarks
Really, groupby is built for this:
from itertools import groupby
def lookandsay(i):
digits = str(i) #convert to string
newdigits = []
for k, g in groupby(digits):
newdigits += [sum(1 for _ in g), k]
return int("".join(map(str, newdigits)))
def conway(i):
yield i
while True:
i = lookandsay(i)
yield i
cw01 = conway(1)
for _ in range(8):
print(" ".join(str(next(cw01))))
Look at this logic,
I got below code from: HERE
r = [input()]
l = int(input())
# Write an answer using print
# To debug: print("Debug messages...", file=sys.stderr, flush=True)
for i in range(l - 1):
temp = list()
lastChar = r[0]
counter = 0
for char in r:
if lastChar == char:
counter += 1
else:
temp.extend([str(counter), lastChar])
lastChar = char
counter = 1
temp.extend([str(counter), lastChar])
r = temp
print(r)
print(" ".join(r))

Categories