January 8, 2023

Programming

  • Python Math
  • File Handling
  • Generators
  • List comprehensions
  • Named Tuples

Generators

# def square_numbers(nums):
# for i in nums:
#    yield (i*i) 

# my_nums = square_numbers([1,2,3,4,5]) 

my_nums = (x*x for x in [1,2,3,4,5]) 
print list(my_nums) # [1, 4, 9, 16, 25] 

# for num in my_nums:
#    print num

List comprehensions

# nums = [11, 22, 33, 44, 55, 66]
# Har bir nums dagi 'n' uchun 'n' ni xohlayman
# my_list = list()
# for num in nums:
#    my_list.append(num)
# print(my_list)
# 
# my_list = [n for n in nums]
# print(my_list)
# my_list = map(lambda n: n, nums)
# print(list(my_list))
# my_list = list()
# for num in nums:
#    if not num % 2 == 0:
#    my_list.append(num)
# print(my_list)

# my_list = [n for n in nums if not n % 2 == 0]
# print(my_list)

# my_list = filter(lambda n: not n % 2 == 0, nums)
# print(list(my_list))
# Biz 'abcd' dagi har bir harf uchun '12' 
# sonlarini (harf, son) juftligicha xohlaymiz
# my_list = list()
# for letter in "abcd":
#    for number in range(1, 3):
#       my_list.append((letter, number))
# print(my_list)

# my_list = [(letter, number) for letter in 
# "abcd" for number in range(1, 3)]
# print(my_list)
# names = ["Taylor", "Daniel", "Tim", "Elon", "Christopher"]
# jobs = ["Singer", "Actor", "CEO(Apple)", "CEO(Twitter)", "Filmmaker"]
# # pair = zip(names, jobs)
# # print(list(pair))
# # my_dict = dict()
# # for name, job in zip(names, jobs):
# #    my_dict[job] = name
# # print(my_dict)

# my_dict = {job: name for name, job in zip(names, jobs) if name != "Tim"}
# print(my_dict)
# nums = [1, 1, 2, 1, 3, 4, 3, 4, 5, 5, 6, 7, 8, 7, 9, 9]
# my_set = set()
# for num in nums:
#    my_set.add(num)
# print(my_set)

# my_set = {n for n in nums}
# print(my_set)
# nums = [5, 6, 7, 8, 9, 10]
# 'nums' dagi har bir 'n' uchun 'n*n' ni xohlayman
# def gen_funct(numbers):
#    for num in numbers:
#       yield num * num

# my_gen_funct = gen_funct(nums)
# for x in my_gen_funct:
#    print(x)

# my_gen_comp = (n * n for n in nums)
# for x in my_gen_comp:
#    print(x)

Named Tuples

from collections import namedtuple 

# list / tuplecolor = (55,155,255) 

# dictionarycolor = {'red': 55, 'green': 155, 'blue': 255} 
# namedtupleColor = namedtuple('Color', ['red', 'green', 'blue'])

color = Color(blue=55,green=155,red=255)
from collections import namedtuple 

Color = namedtuple('Color', ['red', 'green', 'blue']) 
color = Color(55,155,255)
white = Color(255,255,255) 

print color.blue

That's it.