I am using the following code to assign a value to a given letter (A = +1, B= -1)
letList = []
let1 = ['A','A','B']
count = 0
for l in let1:
if l == "A":
count = count + 1
else:
count = count - 1
print(letList.append(count)) #doesnt work
Goal: I want to create a list of counts with the final output that looks something like this: letList = [1,2,1]
Problem: But when I try to append using letList.append(count) I get a none output
Suggestions?
You are trying to print the append function and the append needs to be in your loop to do what you want. Below is an example that prints [1,2,1] using append.
letList = []
let1 = ['A','A','B']
count = 0
for l in let1:
if l == "A":
count = count + 1
else:
count = count - 1
letList.append(count)
print(letList)
Related
records = [["chi", 20.0],["beta", 50.0],["alpha", 50.0]]
a = len(records)
i = 0
b = []
while i < a:
print(records[i][1])
b.append(records[i][1])
i = i + 1
print(b)
c = len(b)
#from previous question
unique_list = []
for el in b:
if el not in unique_list:
unique_list.append(el)
else:
print ("Element already in the list")
print(unique_list)
second_lowest_score = unique_list[1]
print(second_lowest_score)
names_list = []
g = 0
while g < a:
if records[g][1] == second_lowest_score:
names_list.append(records[g][0])
g = g + 1
print(names_list)
What I want to do is to append the names of records which have the second lowest score (50) to the names_list. However, the while loop gives me no result. There is no syntax error so I am not sure why my code is wrong. However, when I use the previous while loop for appending the numbers, it seems to work fine. Is it not possible to use an if statement in a while loop?
This is a pretty simple problem. The g variable is not getting incremented if the if statement does not run, so the loop will endlessly continue on the same value of g.
The fix for this is to move the increment of g outside of the if statement (but still in the while loop). That way it will continue past values even if they do not match the if condition.
if records[g][1] == second_lowest_score:
names_list.append(records[g][0])
g = g + 1
I have list of two websites and I want to count '.' dot and '-' hyphen
number of times it repeated and I want to assign this to the empty
list for each iteration in for loop. When I executed below code it
counts dots and hyphen but for each iteration its counts previous
value and increase the count like [1,2,3,6,12...] but I want to store
each iteration values separate in list like [1,3,2,5....] how to do?
tdots=[]
tphen = []
dots = 0
phen = 0
named_url = ['www.facebook.com','yahoo.com/index-true']
for i in named_url:
for j in i:
if '.' in str(j):
dots = dots + 1
Dots = []
Dots.append(dots)
else:
print('No more "."')
tdots.append(sum(Dots))
for i in named_url:
for j in i:
if '-' in str(j):
phen = phen + 1
Phen = []
Phen.append(phen)
else:
print('No more "-"')
tphen.append(sum(Phen))
print(tdots,'Dots')
print(tphen,'Hyphen')
Try this:-
dots = []
phens = []
named_url = ['www.facebook.com','yahoo.com/index-true']
for name in named_url:
dots.append(name.count('.'))
for name in named_url:
phens.append(name.count('-'))
tdots = sum(dots)
tphens = sum(phens)
print(dots, phens, tdots, tphens)
Output:-
[2, 1]
[0, 1]
3
1
named_url = ['www.facebook.com','yahoo.com/index-true']
dots_sum = []
hyphens_sum = []
dots = []
hyphens = []
for url in named_url:
dots.append(url.count('.'))
hyphens.append(url.count('-'))
print(sum(dots), sum(hyphens))
dots_sum.append(sum(dots))
hyphens_sum.append(sum(hyphens))
dots.clear()
hyphens.clear()
Code that works for that using count which then appends the sum of the dots and hyphens found in the list to two other lists and then clears the two lists that were only holding the counts of dots per url.
You can use collections.Counter to make this easier:
from collections import Counter
named_url = ['www.facebook.com', 'yahoo.com/index-true']
for url in named_url:
c = Counter(url)
dots = c["."]
dash = c["-"]
print("{} contains: {} dot(s) and {} hyphen(s)".format(url, dots, dash))
Output:
www.facebook.com contains: 2 dot(s) and 0 hyphen(s)
yahoo.com/index-true contains: 1 dot(s) and 1 hyphen(s)
The first occurrence of the character in the string will be replaced with a 1, the second occurrence with a 2, etc.
ive tried using for loop and the max function to replace the last occurence but it doesnt seem to work.
string=str(input('string: '))
x=input('character: ')
list=[]
for i in range(len(string)):
if string[i]==x:
list.append(i)
Z=str(max(list))
print(string.replace(x,Z,[::-1]))
the output should be as following
string: departmentofcomputerscience
character: e
d1partm2ntofcomput3rsci4nc5
Here's a way to do it.
Use a counter for each character in the loop, and store values in the list, then merge the list. Use the current value if not equal to the character, counter otherwise:
string=str(input('string: '))
x=input('character: ')
# Use list to store results and a counter
l = []
counter = 0
for c in string:
if c==x:
counter += 1
l.append(str(counter))
else:
l.append(c)
# Merge the resulting list into string
res = "".join(l)
# Output the result
print(res)
For the input string: departmentofcomputerscience
and the character: e
The output is
d1partm2ntofcomput3rsci4nc5
Here is another way to achieve the goal using a list and the method replace():
string = str(input('string: '))
x = input('character: ')
list = []
for i in range(len(string)):
if string[i] == x:
list.append(i) # add all indexes to replace to the list
if len(list) > 0:
j = 0
for i in range(len(list)):
j += 1
string = string.replace(string[list[i]], str(j), 1) # replace the element once at time
print(string)
For string: departmentofcomputerscience
character: e
Output: d1partm2ntofcomput3rsci4nc5
def replace(s, c):
'''
#parameter s: input string
#parameter c: input character to be replaced
#return s: where every occurence of c is
replaced by it's nth occurence
'''
so = list(s)
j = 1
for i in range(len(so)):
if so[i] == c:
so[i] = str(j)
j = j + 1
return ''.join(so)
I have a string that indicates a range of values: "A1C - A1H"
I need to be able to create a list of all the values in that range, meaning: ['A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
list = []
range = "A1C - A1H"
code = range[:2]
range_end = range[-3:]
for letter in ascii_uppercase:
order = code+letter
if order not in range_end:
list.append(order)
else:
list.append(range_end)
break
print(list)
The code runs, as is but it creates a list with the first 'A1A', 'A1B' values which I don't need:
['A1A', 'A1B', 'A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
How can I generate the list starting with 'A1C'?
Start the "for letter in ascii_uppercase" two char later
list = []
range = "A1C - A1H"
code = range[:2]
range_end = range[-3:]
count = 0
for letter in ascii_uppercase:
if count > 1:
order = code+letter
if order not in range_end:
list.append(order)
else:
list.append(range_end)
break
count += 1
print(list)
You can use the built-in ord and chr functions with a list comprehension instead to generate the desired list:
l = ['A1' + chr(i) for i in range(ord('C'), ord('H') + 1)]
l would become:
['A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
You can compare letter code and start loop when it is greater than starting point of string :
import string
def generate(string_data):
code = string_data[:2]
range_end = string_data[-3:]
sub_range = string_data[2:-6]
result=[]
for letter in string.ascii_uppercase:
if ord(letter)< ord(sub_range):
pass
elif code+letter == range_end:
result.append(code+letter)
break
else:
result.append(code+letter)
return result
output:
['A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
alternative solution:
This is not best solution but you can also slice the list from list in your code:
list_data = []
range_data = "A1C - A1H"
code = range_data[:2]
range_end = range_data[-3:]
for letter in string.ascii_uppercase:
order = code+letter
if order not in range_end:
list_data.append(order)
else:
list_data.append(range_end)
break
print(list_data[list_data.index(range_data[:3]):list_data.index(range_end)+1])
Note: Don't use list and range as variable name , They have special meaning in Python.
I essentially have two list containing strings:
com = ['746365', '6365']
dec = ['6d955s2359d757bb40d0cf36bd7a35662d8b3']
I take the length of the first element in list a '746365' and cut list b into the same length as the first element, (len('746365') = 6) and the result of b is '6d955s'. I now wish to move along the element in b by one place until i reach the end ('62d8b3').
I currently have:
count = 0
for a in com:
for b in dec:
print(com.index(a), a)
length_of = len(a)
print(b[0 + count:length_of + count])
count = count + 1
This doesn't work. However if I remove the count parts and leave whats displayed beneath it works but I can't get it to move along by one
for a in com:
for b in dec:
print(com.index(a), a)
length_of = len(a)
print(b[0:length_of])
how can I adjust this code so that I print then move along by one and print the next?
The initial result should be:
6d955s d955s2 955s23 etc etc..
once the end of dec has been reached, it'll move onto the next value in com.
Thanks.
Try this:
for a in com:
for b in dec:
for i in range(0,len(b)-len(a)+1):
clipped_str = b[i:i+len(a)]
print(clipped_str)
Try this code:
start = 0
for c_element in com:
current_length = len(c_element)
end = start + current_length
for d_element in dec:
for _ in range(len(d_element) - current_length + 1):
print(d_element[start:end])
start += 1
end += 1
else:
start = 0