Suppose we have a list of 3-letter words with 3 elements, but each word is also a list. The function return the character at the given index - python-3.x

Suppose we have a list of 3-letter words with 3 elements, but each word is also a list. See example below:
word_list = [ ['r','e','d'] , ['p','e','a'] , ['z','i','p'] ]
Create a function named getCharacterAt that accepts 2 arguments - word_list and index_of_character. The function should be able to return the character at the given index. (If index_of_character is 3, we get 3rd letter in the whole list which is 'd'. If it is 5, we get 'e'. If 9, we get 'p'.

word_list = [ ['r','e','d'] , ['p','e','a'] , ['z','i','p'] ]
new_word_list = []
for i in word_list:
new_word_list = new_word_list + i
def getCharacterAt(word_list: list, index_of_character: int):
return word_list[index_of_character - 1]
print(getCharacterAt(new_word_list, 3))
# Output: d
In this case, I have created a 'new_word_list' with the union of each element of 'word_list'. Then, following your description, you just return the index - 1 element of the request (remember that first list index is 0)

Related

List Comprehension with "if" is not returning the same output as when I make a For Loop when counting the number of unique letters in a word

Can someone explain to me why there is a difference in output when using nested loops vs nested list comprehension?
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters (word) :
unique = []
for i in word:
if i not in unique:
unique.append(i)
return len(unique)
print(unique_english_letters("mississippi"))
# outputs 4 (my expected output)
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters (word) :
unique = []
unique = [i for i in word if i not in unique]
return len(unique)
print(unique_english_letters("mississippi"))
#outputs 11 (length of mississippi"
^ Output
In the second example, this:
unique = []
unique = [i for i in word if i not in unique]
is equivalent to:
unique = [i for i in word if i not in []]
unique is an empty list while the list comprehension is evaluated, and then unique is re-assigned the results.
To do what you want in simple terms, use a set which can only contain unique values, and use set intersection(& operator) to generate the set of letters contained in word:
letters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
def unique_english_letters(word):
return len(letters & set(word))
print(unique_english_letters("mississippi"))
# output: 4

How to iterate through all keys within dic with same values one by one with sequence

I'm working on some text file which contains too many words and i want to get all words with there length . For example first i wanna get all words who's length is 2 and the 3 then 4 up to 15 for example
Word = this , length = 4
hate :4
love :4
that:4
china:5
Great:5
and so on up to 15
I was trying to do with this following code but i couldn't iterate it through all keys one by one .And through this code I'm able to get just words which has the length 5 but i want this loop to start it from 2 to up to 15 with sequence
text = open(r"C:\Users\israr\Desktop\counter\Bigdata.txt")
d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word not in d:
d[word] = len(word)
def getKeysByValue(d, valueToFind):
listOfKeys = list()
listOfItems = d.items()
for item in listOfItems:
if item[1] == valueToFind:
listOfKeys.append(item[0])
return listOfKeys
listOfKeys = getKeysByValue(d, 5)
print("Keys with value equal to 5")
#Iterate over the list of keys
for key in listOfKeys:
print(key)
What I have done is:
Changed the structure of your dictionary:
In your version of dictionary, a "word" has to be the key having value equal to its length. Like this:
{"hate": 4, "love": 4}
New version:
{4: ["hate", "love"], 5:["great", "china"]} Now the keys are integers and values are lists of words. For instance, if key is 4, the value will be a list of all words from the file with length 4.
After that, the code is populating dictionary from the data read from file. If the key is not present in the dictionary it is created otherwise the words are added to the list against that key.
Keys are sorted and their values are printed. That is all words of that length are printed in sequence.
You Forgot to close the file in your code. Its a good practice to release any resource being used by a program when it finishes execution. (To avoid Resource or Memory Leak and other such errors). Most of the time this can be done by just closing that resource. Closing the file, for instance, releases the file and it can thus be used by other program now.
# 24-Apr-2020
# 03:11 AM (GMT +05)
# TALHA ASGHAR
# Open the file to read data from
myFile = open(r"books.txt")
# create an empty dictionary where we will store word counts
# format of data in dictionary will be:
# {1: [words from file of length 1], 2:[words from file of length 2], ..... so on }
d = dict()
# iterate over all the lines of our file
for line in myFile:
# get words from the current line
words = line.lower().strip().split(" ")
# iterate over each word form the current line
for word in words:
# get the length of this word
length = len(word)
# there is no word of this length in the dictionary
# create a list against this length
# length is the key, and the value is the list of words with this length
if length not in d.keys():
d[length] = [word]
# if there is already a word of this length append current word to that list
else:
d[length].append(word)
for key in sorted(d.keys()):
print(key, end=":")
print(d[key])
myFile.close()
Your first part of code is correct, dictionary d will give you all the unique words with their respective length.
Now you want to get all the words with their length, as shown below:
{'this':4, 'that':4, 'water':5, 'china':5, 'great':5.......till length 15}
To get such dictionary you can sort the dictionary by their values as below.
import operator
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
sorted_d will be in the below format:
{'this':4, 'that':4, 'water':5, 'china':5, 'great':5,......., 'abcdefghijklmno':15,...}

the code that i've wrote works fine with a list of four elements but when the length of the list increases it is not giving the right answer

I'm trying to write a python code for a problem wherein I will be given with a list of string characters for example ["A", "B", "B", "C"] and the output that I should get is B and if there are more than one repeated value with equal number of repetitions or no elements in the list it should give"NONE" AS output. and my code is doing good so far but when the size of the list is increasing my code is giving wrong output please help me in optimizing the code so that it takes a list of any size and gives a correct output
lis = ["A","B","B","A"] #INPUT LIST
catch = []
final_catch=[]
for i in range(len(lis)):
for j in range(i + 1, len(lis)):
if lis[i] == lis[j]:
catch.append(lis[i])
final_catch =list(set(catch))
print(final_catch)
if len(final_catch)>=2 or len(final_catch) == 0:
print("NONE")
else:
print(final_catch.pop())
for input ["A,"B","B","A"] expected output:"NONE" actual output: "NONE"
for input ["A","A","A","A"] expected output :"A" actual output : "A"
for input ["A","A","B","B","A","B","A","B","B"] expected output : "B"
Try this,
>>> from collections import Counter
>>> l = ["A","A","B","B","A","B","A","B","B"]
>>> d = Counter(l)
>>> result = d.most_common() # result looks like [('B', 5), ('A', 4)]
Output:
>>> result[0][0] if result[0][1] >2 else 'None' # conditional if-else statement
'B'
Explanation:
Use Counter to get number of occurrences of each element in a list
Use .most_common() to get list of most occurrence in the form of tuplesi.e., [(element, no. of occurrence)]
Return a list of the n most common elements and their counts from the
most common to the least
result[0][0] - we are passing index values to get first element of tuple in list.
result[0][1] - This gives you second element of tuple in a list.
*result[0] - select first element in a list

I am not able to understand the code. Can any one help me out?

marks = {}
for _ in range(int(input())):
line = input().split()
marks[line[0]] = list(map(float, line[1:]))
print('%.2f' %(sum(marks[input()])/3))
I am new to python. Can you tell me the meaning of this code?
I'm not able to understand it.
What this code does:
# initialized a dictionary type names marks
marks = {}
# The input() method will pause and wait for someone to input data in the command line
# The range() method will create an array of int given the a number
# example: range(5) will create [0, 1, 2, 3, 4]
# In this case it will take the string returned from input() convert it to an integer
# and use that as the value.
# The for loop will, run as many times as there are elements "in" the array created
# the _ is just a silly variable name the developer used because
# he is not using the value in the array anywhere.
for _ in range(int(input())):
# Get a new input from the user
# split the string (it uses spaces to cut the string into an array)
# example if you type "one two three" it will create ["one", "two", "three"]
# store the array in the variable line
line = input().split()
# add/replace the element using the first string in the line as key
# line[0] is the first element in the array
# lint[1:] is the array containing all the elements starting at index 1 (the second element)
# map() is a function that will call the function float on each elements of the array given. basically building an array with the values [float(line[1]), float(line[2])…]
# list will convert the array into a list.
marks[line[0]] = list(map(float, line[1:]))
# this last line asks the user for one more value
# gets the list in the marks dictionary using the value inputed by the user
# calculates the sum of all the floats in that list.
# divides it by 3 and prints the results as a floating point number with 2 decimal places.
print('%.2f' %(sum(marks[input()])/3))

split a string in list

I have a list containing string values:
a_list = ['1/one','2/two','3/three']
I want to split the number from a word like this:
number = [1,2,3]
words = [one,two,three]
Then I make a condition if the number equal one or three then add the numbers to a new list. here is my code:
import re
new_list = []
for i in a_list:
word =re.findall(r"[\w']+",i)[1]
number = re.findall(r"[\w']+",i)[0]
if word == 'one' or word == 'three' :
new_list.append(number)
I got an error :
IndexError: list index out of range
any help?... Thanks in advance

Resources