Demo entry 6780080

EXE8

   

Submitted by anonymous on Dec 22, 2018 at 15:31
Language: Python 3. Code size: 2.8 kB.

#question1 - write a list comprehension that return the length of each element in a sequence 

listOfWords = ["this","is","a","list","of","words"]

items = [len(word) for word in listOfWords ]

print(items)       # returns [4, 2, 1, 4, 2, 5]

#question2- write the same task with lambda

listOfWords = ["this","is","a","list","of","words"]

list(map(lambda word: len(word), listOfWords))     # returns [4, 2, 1, 4, 2, 5]

#question 3 - write a list comprehension that would return a list of strings for a list of numbers 
listOfnumbers = [1, 2, 3]
print(listOfnumbers)   #[1,2,3]
listOfstrings = [str(i) for i in listOfnumbers]
print(listOfstrings) #['1','2','3']

#question4 - write a list comprehension that would only return numbers that are divided by 2 and 3. use range(20)
'''
first i trieds newlist = [ i%2==0 or i%3==0 for i in range(20)]
print(newlist)
# but in this stage the list reurned  just true of false that is why i changed this as follows
'''
newlist = [ i  for i in range(20) if i%2==0 or i%3==0]
print(newlist)    # [0, 2, 3, 4....]

#question 5 - to write a list comprehension that returns a list of characters that are different from a letter 

string1 = ('this should be familiar')
list_char = [char for char in string1 if char is not 'a']
print(list_char)        # checked and this works 

#question 6 - take a string as input and return string with vowels removed 

string2 = ('i love to learn new things')
vowels = ('iaeou')
remove_vowels = [i for i in string2 if i not in vowels]
string3 = ' '.join(remove_vowels)
print(string3)   # i get :  lv t lrn nw thngs

#question 7- write a dict comprehension that would swap the order in dict

d = {'a':1, 'b':2, 'c':3, 'd':4}
dict_new = {key:value for value, key in d.items()}     # i asked the key to be the value of value in dict
print(dict_new)    # i got {1:'a', 2:'b'..... }

#question 8 - write a dict comprehension key : range(1,10) value : i*i
list1 = list(range(1,10))
list2 = [ i*i for i in list1]
print(list1)  #[1,2,3...]
print(list2)   #[1,4,9...]
dict_new1 = {list1[c]: number for c, number in enumerate(list2)}
print(dict_new1)   #[1:1,2:4,3:9.....]


#question 9 # pytagorean with python

#regular code 

n = int(input("Enter the value of n:"))

a = 0
b = 0
c = 0
m = 2
triples = []

while c < n:
    for i in range(1, m, 1):
        a = m*m - i*i
        b = 2*m*i
        c = m*m + i*i
        if c > n:
            break
        triples.append((a, b, c))
    m += 1

print(triples)

# in a list comprehension format

n = int(input("Enter the value of n:"))
#n = 17
print([(a,b,c) for a in range(1,n+1) for b in range(a,n+1) for c in range(b,n+1) if a**2 + b**2 == c**2])
# [(3,4,5), (5,12,13....)]

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).