I have ran into a logic error that I cannot solve and would like some assistance towards it.
Here's my code
Mysentence = MySentence
print(Mysentence)
MysentenceList = Mysentence.split()
List = []
for k in MysentenceList:
position = MysentenceList.index(k)
position = position + 1
position = str(position)
List.append(position)
Basically cannot handle unique words
If you want to assign each word a "unique id", you'd have to manage this in another data structure. Another list would do the trick:
UniqueWords = []
for k in ThesentenceList:
if k in UniqueWords:
position = UniqueWords.index(k)
else:
position = len(UniqueWords)
UniqueWords.append(k)
position = position + 1
position = str(position)
TheList.append(position)
Your list after splitting is ["Hello", "Hello", "I", "Hello"] which you then use to assign the word index value.
The first instance of "Hello" is index 0, the first instance of "I" is index 2. If you want to assign a "unique word ID" counting from zero without gaps in the sequence you're going to have to change your ID assignment algorithm to manage the duplicate words.
I'd propose using something like a Python dictionary to track the unique words as you find them (it's a hash map, so avoids list iteration with "index" which is going to get pretty slow with long inputs).
list.index(item) is giving you the position of first instance of item in list. The first instance of "Hello" is in position 0, but you're adding 1 to the position, so it's going to report 1 each time. "I" is located in position 2, so it's reporting 3.
Related
I have a code where I cut each string in my list in half (approximately). Then, for each half I have, I take a random first half and combine it with a random second half. Lastly, I want to call/print each newly made string. For example, in my code, I want print(final[0]) to have an output agray, however, the first letter of it (a) is the output. How do I call each individual row?
import random
lis = ['have', 'agreat', 'day']
first = []
second = []
for x in lis:
first.append(x[:len(x)//2])
second.append(x[len(x)//2:])
for x in first+second:
final = random.choice(first) + random.choice(second)
print(final)
print(final[0])
output:
agray
a
have
h
haeat
h
You never put your resulting random words into any list; how do you expect that indexing an individual word will make a list? In each iteration of your loop, you select random halves, splice them into a new word, print the word, and then overwrite that word on the next iteration.
Let's walk through this in stages. Taking lis as a given item, let's make the two lists of half-words:
for x in lis:
first.append(x[:len(x)//2])
second.append(x[len(x)//2:])
Now, you want each list to be in a random order:
random.shuffle(first)
random.shuffle(second)
Now, paste your new words together into a new list:
final = [left+right for left, right in zip(first, second)]
You now have your list of three new words.
I think that using this print might help you to print the whole string as you mentioned.
print(final[0:])
I'm trying to print the "least" character in a string, where the a character is smaller if it's closer to the beginning of the alphabet than another character, and it's first index position.
I'm supposed to use only 1 loop to determine the index of the character, and am not allowed to use min, max, index, find, ord, chr, or lists.
For example:
leastChar("yRrcDefxBqubSlyjYelskd")
should yield:
The least char is 'B' and occurs at position 8.
Currently I have:
def leastChar(inputString):
lowerString = inputString.lower()
print(lowerString)
indexLength = (len(lowerString) - 1)
print(indexLength)
index = 0
for i in range(indexLength):
if lowerString[i] < lowerString[i+1]:
index = i
print("The least char is '{0}' and occurs at position {1}".format(inputString[index], index))
Which returns:
leastChar("yRrcDefxBqubSlyjYelskd")
yrrcdefxbqubslyjyelskd
21
The least char is 'l' and occurs at position 18
I've tried multiple variations, but even using more than 1 loop I find myself getting consistently wrong answers in various positions.
Also, in case it matters, leastChar('blAh') will return 'A' in position 2 like it's supposed to.
The closest I've come to what seems correct, I think, is when I put another for loop inside the initial for loop hoping that I could increment that variable to compare 'i' to it such as:
for i in range(indexLength):
for j in range(indexLength):
if lowerString[i] < lowerString[j]:
And do something with that, but I was unable to make it work.
Thanks for the help.
Expanding on #melpomene’s comment, the algorithm trick (or as fancy computer scientists call it, heuristic) is to keep track of both the minimum position and minimum value as you are iterating through the string.
def leastChar(inputString):
# handle cases where inputString is `None` or empty
if not inputString:
print('Oh no, inputString is blank! Run away!')
return
lowerString = inputString.lower()
print(lowerString)
# use enumerate to keep track of the index as
# you are iterating over a list
min_value = lowerString[0]
min_pos = 1
for index, ch in enumerate(lowerString, 1):
# check to see if current char is closer to
# front of alphabet than our current minimum
if ch < min_value:
# if so, keep track of the current pos/value
# as the new minimum
min_pos = index
min_value = ch
# pythonic: min_pos, min_value = index, ch
print("The least char is '{0}' and occurs at position {1}".format(min_value, min_pos))
There are different ways:
1) You're not allowed to use min, max, index, find, ord, chr, or lists?
I would try to work with rfind() or rindex(). :^)
2) Copy your string and use sort() to find the smallest char in your copy. Then you should use search() to return the position of this char in your original InputString.
3) Create an alphabetic string "abcdef...." and build up a complex while-if-try-except construct to get a result, but everyone would hate it. :^)
I have ruthlessly searched the internet. I know there will be an answer somewhere . However I cant find it. Below is code ( in a nutshell, my code changes a stored array into numbers then saves it as a text file ).Line 3 is the code I cannot comprehend.
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY" #Stores these words in the array
s = sentence.split() #splits the variable 'sentence' into seperate words and stores them into the variable 's'
positions = [s.index(x)+1 for x in s]
print(sentence) #prints the variable 'sentence'
print(positions) #prints the variable 'positions'
sentence=str(sentence) #converts the variable 'sentence' into a string
positions=str(positions) #converts the variable 'positons' into a string
inputFile=open("thelist.txt","w") #
inputFile.write(sentence)
inputFile.write("\n")
inputFile.write(positions)
inputFile.close()
The line I cannot understand is 'positions = [s.index(x)+1 for x in s]' can someone please explain it?
It is a list comprehension, equivalent to
positions = []
for x in s:
positions.append(s.index(x)+1)
s.index() returns the position of word x in your list of words s.
Note that multiple occurrences of the same word will all point to the first index of that word. e.g. the second occurrence of "ASK" will still point to 1.
Hi – translated to Human, it means put the position (+1) of each word of the sentence in the positions array.
positions = let positions be:
[s.index(x) index of x in s, or sentence.split()
+1 add one to the index, as indices start from 0 in most languages
for x in s] and do this for all the elements in s.
The code would look nicer if it looked something like:
splitsentence = sentence.split()
positions = splitsentence.index(word)+1 for word in splitsentence.
Longer, but readable.
I'm following a book and i ran into this sample program. I'm not sure how the numbers[position] in line 5 is working here? What is the relationship between position and numbers in that variable assignment?
numbers = [1, 3, 5]
position = 0
while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print "Found even number", number
break
position = position + 1
else:
print "No even number found"
That number inside square brackets is an index of the list,
like so
lst = ["b", "c", 3] # Take care not to use "list" as a variable name by the way.
print lst[0] # I used lst in my example
gives you:
"b"
The first element of the list.
However I could not pass without saying that for loop is a far better way of doing this. Rather than incrementing position one-by-one and telling while loop to stop when it reaches to the length of the list is just good for understanding the concepts. I am sure your textbook is going to cover that next.
It's not variable assignment, it's lookup. position is an index; when it has a value of 0, numbers[position] returns 1 (the first element in numbers), for position 1 it gets 3, etc.
Python sequences like list are indexed 0-up, so the first element in a sequence is at index 0, and the last is at index len(seq) - 1.
In number = numbers[position] literally means what it says. position is a position in the list. First it is assigned to zero, so when doing numbers[position] it is actually calling the number in the list at position zero which is 1. Then it does position = position + 1 which will ask it for the number in position 1 in the list and so on.
I wasn't familiar with this style of variable assignment. I've seen lists referenced directly using index numbers. But since this post, I've tried the following and it cleared it up. Thank you very much!
list1 = ["apples", "oranges"]
position = 1
output1 = list1[0]
output2 = list1[position]
print output1
print output2
I'm absolutely terrible at Python and my Computer Programming class ends in two days (thank god), but I am having the hardest time figuring out what is probably the easiest code ever.
The instructions to my assignment state, "Write a program which reads in text until a '!' is found. Use an array of integers subscripted by the letters 'A' through 'Z'."
From what i have done so far:
msg = input("What is your message? ")
msg = msg.upper()
int_array = [0] * 26
for alph in range (65, 91):
char = chr(alph)
print(char)
(int_array[char])
any help would be greatly appreciated! thanks!
EDIT: This is the full assignment:
Write a program which reads in text from the keyboard until a ('!') is found.
Using an array of integers subscripted by the letters 'A' through 'Z', count the number occurrences of each letter (regardless of whether it is upper or lower case). In a separate counter, also count the total number of "other" characters ('.', '?', ' ', '2', etc.).
Print out the count for each letter found. Also, print the count of the non-letter characters.
By inspecting the array, print out the count of the number of vowels, and the number of consonants.
Print out which letter was found the most times. (Note there may be more than one letter which has the maximum count attached to it.) Print out which letter (or letters) was found the least number of times, but make certain to exclude letters which were not found at all.
UPDATE:
I have gotten this far with my code
msg = input("What is your message? ")
print ()
num_alpha = 26
int_array = [0] * num_alpha
for alpha in range(num_alpha):
int_array[alpha] = chr(alpha + 65)
print(int_array[alpha], end = "")
print()
lett = 0
otherch = 0
num_vowels = 0
num_consanants = 0
count_character = [0] * 100000
length = len(msg)
for character in msg.upper():
if character == "!":
print("lett =", lett)
print("other char = ", otherch)
print("num_vowels = ", num_vowels)
print("num_consanants = ", num_consanants)
elif character < "A" or letter > "Z":
otherch = otherch + 1
count_character[ord(character)] = count_character[ord(character)] + 1
else:
lett = lett + 1
count_character[ord(character)] = count_character[ord(character)] + 1
for character in msg:
print("character", character, "appeared" , count_character[ord(character)] , "times")
it's obviously not finished yet, but every time i print the last print statement, it says that each character appeared 0 times. can anybody help?
You're going to need to get clarification on this, because there's no such thing as "an array of integers subscripted by the letters 'A' through 'Z'" in Python.
Possible interpretations that I can think of:
It's supposed to be a dictionary rather than an array. Python dictionaries are similar to lists (the Python datatype that is roughly equivalent to "arrays" in other languages), but they can be subscripted by strings, whereas lists can be subscripted only by integers. This way, you can store an integer to be associated with each letter. This is how most Python programmers would generally do something like this.
You're supposed to use parallel lists. You can do this by making two lists of 26 elements each, one containing the letters 'A' through 'Z' and one containing integers. For each letter, you could then use the list.index method to find the index in the first list where that letter is, then look up that index in the second list. (In theory, you wouldn't really need the first list, since Python strings are like lists in that they can be subscripted with integers and support the index method. So you could use the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' instead of a list. Or you could use the ord function, which is the inverse of the chr function. But I don't know if you're supposed to use these features.)
I'm not 100% sure the following is right because I agree with the others that the assignment description is wonky. It looks like a C-based homework assignment lazily ported to Python. That said:
In principle rather than hardcoding the bounds of the alphabet I'd go with ord('A') and ord('Z')+1, so that I can say something like alphabet = list(range(ord('A'), ord('Z')+1))
Renaming int_array to counter might make it more obvious what you need to do in your inner loop (keeping in mind that you're using the letters as your indices. Or rather, you'd need something more like ord(letter)-ord('A') as your indices)
You don't want to loop over the alphabet; you want to loop over the input.
count should be initialized to [0]*27 to track "other" values. You can increment counter[-1] for non-alphabetic characters.
Your final value is chr of counter.index(max(counter)). You may find it more straightforward, or your teacher may find it more acceptable, to just write a for loop.