Reading from Lists in Python - python

I want to access the scores associated with each letter of the alphabet which are stored in a text file (stores.txt). Each line is an index and I just want to retrieve the number for each letter and print it when I enter a certain letter into a function. How would I split the item in order to get the number and return it.
Scores.txt is shown like this:
A 1
B 3
C 5
D 3
E 1
F 5
G 4
H 3
I 1
J 10
K 8
L 3
M 5
N 3
O 2
P 5
Q 20
R 3
S 3
T 2
U 1
V 10
W 12
X 16
Y 8
Z 20
This is the code ive used up to now, however this would result in displaying the whole line
(['A','1']) when i passed A to the function and I would like just 1 to be passed.
def getLetterScore(user_Input):
scoreFileT1 = open('D:/DELL/Desktop/Programming Assignment/scores.txt')
score = []
for line in scoreFileT1:
line = line.strip(' ')
line = line.split()
score.append(line)
scoreFileT1.close()
if user_Input =='a' or user_Input == 'A':
print(score[0])

Here is the code I came up with.
In this, if you give any letter as input, the corresponding number for the letter will be printed.
def getLetterScore(user_Input):
scoreFileT1 = open('C://Users//Naveendran//Desktop//scores.txt')
score = []
for line in scoreFileT1:
line = line.strip(' ')
line = line.split()
score.append(line)
scoreFileT1.close()
for i in range(len(score)):
if user_Input.upper() == score[i][0]:
print(score[i][1])
b = input("Enter a letter:")
getLetterScore(b)

I suggest you going with this code
rfile=open("score.txt") #add your path here
file=rfile.read()
filesplit=file.split("\n")
letter=input("enter The number").capitalize()
for i in filesplit:
if(i[0]==letter):
for j in range(2,len(i)):
print(i[j],end="")

Related

Why is it giving runtime error on codeforces for python?

So I am very new to code and have learnt the basics of python. I am testing out my skills on codeforces by first solving some of their easier problems. I am trying to do 158A on codeforces. I think I have got it because it passed a few tests I assigned. So, I tried submitting it and it told me something about a runtime error. I don't really know what it is so I would like it if someone could tell me what it is and how to fix it in my code. Here is the link to the problem: https://codeforces.com/problemset/problem/158/A
n = int(input())
k = int(input())
b = []
for i in range(n):
a = int(input())
b.append(a)
c = 0
for i in b:
if i >= b[k]:
c = c+1
else:
pass
print(c)
The input you are given is "8 5" and "10 9 8 7 7 7 5 5". That doesn't mean you are given "8" and "5" as two different inputs. It means you have a very long string that contains numbers separated by spaces. You should turn these into a list.
a = input()
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
a should equal "8 5". We then turn the string into a list using a.split(" "). This will produce ["8", "5"].
In the problem 158A the expected input are:
1. Two numbers (int) separated by a single space, where 1 ≤ k ≤ n ≤ 50
2. n space-separated integers, where ai ≥ ai + 1
There is also a condition: Scores MUST be positive (score>0) so you can advance
This is all you need, I tested it and I got the expected output everytime
a = input("Input n and k: ")
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
b = input("Input n scores: ")
willAdvance = 0
scores = b.split()
print(scores)
for element in scores:
if int(element) >= int(scores[k-1]) and int(scores[k-1]) > 0:
willAdvance += 1
print(willAdvance)
TEST
Input:
8 5
10 9 8 7 7 7 5 5
Output:
6
Input:
4 6
0 0 0 0
Output:
0

Count number's digits following by line

I have the number 444333113333 and I want to count every different digit in this number.
4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times
What I am trying to do is make a script that translates phone keypad taps to letters
like in this photo https://www.dcode.fr/tools/phone-keypad/images/keypad.png
if I press 3 times number 2, then the letter is 'C'
I want to make a script with it in python,but I cannot...
Using regex
import re
pattern = r"(\d)\1*"
text = '444333113333'
matcher = re.compile(pattern)
tokens = [match.group() for match in matcher.finditer(text)] #['444', '333', '11', '3333']
for token in tokens:
print(token[0]+' is '+str(len(token))+' times')
Output
4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times
You can use itertools.groupby
num = 444333113333
numstr = str(num)
import itertools
for c, cgroup in itertools.groupby(numstr):
print(f"{c} count = {len(list(cgroup))}")
Output:
4 count = 3
3 count = 3
1 count = 2
3 count = 4
Will this do the trick?
the function returns a 2d list with each number and the amount it found. Then you can cycle through the list and to get each all of the values
def count_digits(num):
#making sure num is a string
#adding an extra space so that the code below doesn't skip the last digit
#there is a better way of doing it but I can't seem to figure out it on spot
#essemtially it ignores the last set of char so I am just adding a space
#which will be ignored
num = str(num) + " "
quantity = []
prev_char = num[0]
count = 0
for i in num:
if i != prev_char:
quantity.append([prev_char,count])
count = 1
prev_char = i
elif i.rfind(i) == ([len(num)-1]):
quantity.append([prev_char,count])
count = 1
prev_char = i
else:
count = count + 1
return quantity
num = 444333113333
quantity = count_digits(num)
for i in quantity:
print(str(i[0]) + " is " + str(i[1]) + " times" )
Output:
4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times

Python 2.7: Return the total amount of lines with more than 5 words

This code was just given on the blackboard as an example in class, but when I try to execute it in python (we work with 2.7), it doesn't work.
The code is supposed to read all lines in the text file administration, each line can consist of digits only or characters only. If the line contains no digits and more than 5 words, the number_of_long_lines is increased by 1.
However, in number_of_words, the value of return doesn't go higher than 1 and thus def long(line) always returns false and the output of print number_of_long_lines stays stuck at 0. In this example, the output of print number_of_long_lines should be 3. Where does this code go wrong?
LONG_LINE_BORDER = 5
file = open('administration')
input = file.read()
lines = input.splitlines()
print(lines)
def word(string):
for c in string:
if not c.isalpha():
return False
return True
def number_of_words(line):
strings = line.split()
for string in strings:
result = 0
if word(string):
result += 1
return result
def long(line):
return number_of_words(line) > LONG_LINE_BORDER
number_of_long_lines = 0
for line in lines:
if long(line):
number_of_long_lines += 1
print number_of_long_lines
Administration input file:
a b c d
a b c d e f
a b c d e f g
5 6 7 3
1 2 3 4 5 6
a b c d e f g h
You re-define a 0 value for your result before every call of your word() function. Get result = 0 out of the for loop
LONG_LINE_BORDER = 5
file = open('administration')
input = file.read()
lines = input.splitlines()
print(lines)
def word(string):
for c in string:
if not c.isalpha():
return False
return True
def number_of_words(line):
strings = line.split()
result = 0 #put this here
for string in strings:
if word(string):
result += 1
return result
def long(line):
return number_of_words(line) > LONG_LINE_BORDER
number_of_long_lines = 0
for line in lines:
if long(line):
number_of_long_lines += 1
print number_of_long_lines

My code doesn't allow 2 times a character (how to fix)

I need to write a code that counts the amount of closed area's en the amount of ends within a word (so B has 2 closed area's) but when 1 character sits 2 times within 1 question it only counts 1 time.
I tried something that should count the amount of characters but that just gived me more errorzs
G = 0
Chosen_word = str(input("Choose a word of max 60 character(only uppercase)"))
if "A" in Chosen_word:
U = U + 2
G = G + 1
if you type AA it should print 4 ends en 2 closed area's but it prints 2 ends en 1 closed area
You're only going through this code once - for the first letter. To go through each letter, you need to use a loop (a for loop that goes through every character would be best here):
for letter in chosen_word:
if letter == 'A':
U = U + 2
G = G + 1
elif letter == 'B':
...
G = 0
U=0
Chosen_word = str(input("Choose a word of max 60 character(only uppercase)"))
n = Chosen_word.count("A")
U = n * 2
G = n
print (U)
print (G)
OUTPUT:
Choose a word of max 60 character(only uppercase)SADDSAAAA
10
5

python 3*n + 1 - calculate longest cycle for a list of numbers

for a given list of numbers (input.txt) I'm trying to have an output.txt that prints out the numbers and the length of the cycle associated with each line.
So what i have till now:
/input.txt that looks kinda like this:
4 6
2 11
3 20
etc...
A function that calculates the length of the cycle:
def calc_cycle(number):
count = 1
while number != 1:
if number % 2 != 0:
number = number * 3 + 1
else:
number = number / 2
count = count + 1
return count
A function that calculates the maximum cycle:
def max_cycle(n, m):
max_value=1
for i in range(n, m+1):
x = calc_cycle(i)
if max_value < x:
max_value = x
return n, m, max_value
And a function that reads the input.txt file and parse the values:
def read_input(list_of_urls):
with open(list_of_urls) as f:
for line in f:
#n,m = [int(i) for i in line.split(' ')]
n,m = line.split(' ')
n=int(n)
m=int(m)
print n,m
Basically I'm stuck at this part, I don't see how to get an output.txt file that would look like this:
4 6 9 #9 being the max cycle for all the numbers between 4 and 9
2 11 20 #20 being the max cycle for all numbers between 2 and 11
3 20 21 #21 being the max cycle for numbers between 3 and 20
Any guidance please!?
string formating
def read_input(list_of_urls):
with open(list_of_urls) as f, open('output.txt', 'w+') as f2:
for line in f:
n,m = line.split(' ')
n=int(n)
m=int(m)
_,_,thisMaxCycle = max_cycle(n,m)
f2.write("{0} {1} {2} #{2} being the max cycle for all numbers between {0} and {1}\n".format(n,m,thisMaxCycle))

Categories

Resources