Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
When I put 'HelLO' into this code, it should put out 10, but only puts out 5, why?
The programme is meant to add 5 to the score if a word contains a lower case letter, and another if it contains a upper case letter. However, it only has to have at least one in for the score to be added. HellO has both uppercase and lowercase letters, so should add up to 10.
capitals="A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T","U",
"V","W","X","Y","Z"
characters="a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z"
word=raw_input("word please")
score=0
for i in range(0,len(word)):
a=i
for i in range(0,26):
if word[a]==characters[i]:
score=score+5
break
for i in range(0,26):
if word[a]==capitals[i]:
score=score+5
break
print score
After the execution of the loop for i in range(0,len(word)): a=i the value of a becomes len(word)-1 (in your case, 4) and never changes again. Here's what you are looking for:
import string
score = 0
# Does the string have at least one uppercase char?
if set(string.ascii_uppercase) & set(word):
score += 5
# Does the string have at least one lowercase char?
if set(string.ascii_lowercase) & set(word):
score += 5
It looks like what you want to do is have nested for loops. so that you check each letter in word to see if it meets the criteria.
but in that case you would also need to have a flag or some indication that a capital or lower case letter has been found so you don't double count.
Here are some changes you can make to get to your intended answer, however I'd also add that you there are a couple of other improvements you could make to this code for simplification/efficiency.
look into using the in functionality of lists: like letter in capitals
look into .upper() functionality built into all strings
list comprehensions
Anyways here is a fix that gets to your intended functionality.
capitals="A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
characters="a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
word=raw_input("word please")
score=0
capital_found = False
lower_found = False
for i in range(0,len(word)):
a=i
if not lower_found:
for i in range(0,26):
if word[a]==characters[i]:
score=score+5
lower_found = True
break
if not capital_found:
for i in range(0,26):
if word[a]==capitals[i]:
score=score+5
capital_found = True
break
print score
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I am within my first week of python coding. well, first week of coding ever. I am trying to do a random name generator. However, I want to have it that if certain letters are chosen, another letter is added
I have lists for the consonants and vowels:
import random
vowels = ["a","e","i","o","u","y"]
consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z"]
first = (consonants[random.randint(0,19)])
second = (vowels[random.randint(0,5)])
third = (consonants[random.randint(0,19)])
...
(however many letters desired. might do more randomness up to x letters)
However, I wanted:
if first == "q":
first == "qu"
Let's say qezba was the name generated. I am trying to make conditions so that if a "q" is the first letter, it auto adds a "u" onto the string of the variable first. Or, if an "l" was the third letter, to add a "j" after it, half of the time
How could this be done?
You can.
if first == "q":
first = "qu"
Given your usecase, you can try:
if first == "q":
first = first + "u"
== is the equality operator ( whether a equal to b ). = is the assignment operator.
There are several ways to do it:
if first=="q":
first="qu"
if first=="q":
first+="u"
first = (consonants[random.randint(0,19)])+"u"
Provided you are just starting out I suggest trying to solve the question yourself before asking here. Good luck
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Use while and if statements to count how many 0’s are before the first 1 (from left to right).
code = '00000000101100110001111110110011'
num_zero_before_1 = 0
for i in code:
if i != '1':
num_zero_before_1+=1
print(num_zero_before_1)
I cannot seem to get the answer
loops in python have two control statements: continue and break. Continue skips the rest of the iteration and starts from the top and break completely leaves the loop. So what you want here is to break on the else condition.
You have made a small mistake. You are counting zeroes by if condition using i != '1' but you should add else also to break the loop whenever the first '1' encountered, otherwise your loop will go on counting all zeroes.
Here is correct solution:
code = '00000000101100110001111110110011'
num_zero_before_1 = 0
for i in code:
if i != '1':
num_zero_before_1+=1
else:
break
print(num_zero_before_1)
Shouldn't you use while loop instead of for... in loop?
This solution should fulfill exercise assumptions:
iterator = 0
while True:
if code[iterator] != '1':
iterator += 1
else:
break # it stops the loop, goes out of it
print(iterator) # number of zero before '1'
However, this solution is shorter and easier, maybe it'll be useful to you:
iterator = 0
while code[iterator] != '1':
iterator += 1
print(iterator) # number of zero before '1'
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to make a password generator. I've tried using a for loop to generate each digit. I then appended each digit to a list. However, I want the output to be something along the lines of:
54324
rather than:
[5, 4, 3, 2, 4]
The following is my code:
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0,9))
digit += code
What happens in this scenario is that my output is just blank. I am somewhat new to python, so I may be missing something obvious, but I would appreciate if you could explain what I've done wrong and how to fix it.
Corrected version of your code
from random import randint
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0,9))
code += digit
print(code)
by the way, you can just use
code = randint(0,99999)
print(code)
to generate your password, just saying
Your code is overwriting digit each time. You generate a random integer between 0 and 9, then turn it into a string. Then you add a code to this digit string. Then the next iteration of the for loop, you generate a new value for digit. So you shouldn't be getting a blank value- you should be getting a one-digit value for digit, a string representation of an integer between 0 - 9.
Your values should be assigned and added onto code, not digit.
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0, 9))
code += digit
print(code)
Beside the obvious error in your code, fixing it will give you an underperformant code:
ugly for loop
5 calls to the random generator
5 conversions from int to string
string concatenation
If you want to generate a password made of exactly 5 numbers, since there's no requirement of uniqueness of the digits (as seen in another similar question where this technique could not apply), you could generate a number < 100000 and format it with leading zeros using a nested format:
import random
nb_digits = 5
for _ in range(10):
print("{:0{}}".format(random.randrange(0,10**nb_digits),nb_digits))
example of output:
58260
12986
69233
42343
02760
58934
06396
22262
07662
00182
At each loop, you are erasing the previous value contained by the variable digit, and you variable code is not useful here because it is empty.
You could just do:
chars = 5
for i in range(chars):
digit += str(randint(0,9))
you were trying to print digit which is single digit random number, you have to append it to some other string to store
from random import randint
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0,9))
code = code +digit
print(code)
hope this helps
Since you are appending to code it should go like:
code +=digit
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am looking for a function in Python where you give a string as input where a certain word has been repeated several times until a certain length has reached.
The output would then be that word. The repeated word isn't necessary repeated in its whole and it is also possible that it hasn't been repeated at all.
For example:
"pythonpythonp" => "python"
"hellohello" => "hello"
"appleapl" => "apple"
"spoon" => "spoon"
Can someone give me some hints on how to write this kind of function?
You can do it by repeating the substring a certain number of times and testing if it is equal to the original string.
You'll have to try it for every single possible length of string unless you have that saved as a variable
Here's the code:
def repeats(string):
for x in range(1, len(string)):
substring = string[:x]
if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
print(substring)
return "break"
print(string)
repeats("pythonpytho")
Start by building a prefix array.
Loop through it in reverse and stop the first time you find something that's repeated in your string (that is, it has a str.count()>1.
Now if the same substring exists right next to itself, you can return it as the word you're looking for, however you must take into consideration the 'appleappl' example, where the proposed algorithm would return appl . For that, when you find a substring that exists more than once in your string, you return as a result that substring plus whatever is between its next occurence, namely for 'appleappl' you return 'appl' +'e' = 'apple' . If no such strings are found, you return the whole word since there are no repetitions.
def repeat(s):
prefix_array=[]
for i in range(len(s)):
prefix_array.append(s[:i])
#see what it holds to give you a better picture
print prefix_array
#stop at 1st element to avoid checking for the ' ' char
for i in prefix_array[:1:-1]:
if s.count(i) > 1 :
#find where the next repetition starts
offset = s[len(i):].find(i)
return s[:len(i)+offset]
break
return s
print repeat(s)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a question about lists in python and how to print from them. Which of the following code snippets prints all 7 words found in the list "words"? I have compiled and tried it but I still don't know which of this snippets is correct.
1.
i = 0
while i < 7:
print(words[i], end=" ")
i += 1
2.
i = 0
while i < 7:
print(words[i], end=" ")
i += 1
3.
i = 1
while i < 7:
print(words[i], end=" ")
i += 1
4.
i = 0
sum = ""
while i < 7:
sum += words[i]
i += 1
print(sum)
5.
i = 0
sum = ""
while i <= 7:
sum += words[i]
i += 1
print(sum)
If your list looks something like this, words = ["a","b","c"..],
All you have to do is iterate over them using the for statement,
for i in words:
print i
That should print out the words:
a
b
c
....
This shouldn't be all that difficult to follow as a dry run (use pen and paper if you need to).
You'll need to remember that if words has 7 elements, they are words[0]...words[6]. ie the list index starts at 0
Obviously you haven't been able to run them. How did you try to run them? What went wrong?
If you still can't work it out, a good strategy is to fall back to the answer that has the most in common with the other answers...answer 2 :)
Answer: None are correct. They are all wrong. Presuming to know how many words that should be found is the starting point of why this is wrong.
The point of putting the words you found into a list is so that you can separate the responsibility of finding results to printing them. To decouple them one can't know about the other. More specifically; you don't care how many are in the list, you just need to know how print the list. As such you are really just asking "How do I print a list".
Secondly, there is no compiling in python. Have you tried reading http://docs.python.org/2/tutorial/ ?
or http://docs.python.org/3/tutorial/
For code of a correct answer see #enginefree's answer.
Even if you are going to do it the way you are doing it with indexes i would suggest
for i in range(0..MAX_ELEMENTS-1):
print words[i]
I also would strongly discourage use of while loops for a problem with a definite knowable boundary of operations such as iteration over a collection from the outset of the operation. While generally implies changing conditions, unknowable endpoints and the need for custom increment control.