Iteratory i listy składane


    
    1. Czym jest operator?
    def cleanup(string):
      # Inicjalizujemy iterator dla napisu
      letter_iterator = iter(string)
      
      # Inicjalizujemy pusty napis, do którego będziemy dodawać tylko litery alfanumeryczne
      cleaned_string = ""
      
      # Pętla while do iteracji przez napis
      while True:
          try:
              letter = next(letter_iterator)
              # Jeśli litera jest literą alfanumeryczną, dodaj ją do cleaned_string
              if letter.isalnum():
                  cleaned_string += letter
          except StopIteration:
              # Wyjście z pętli, gdy iterator się skończy
              break
      
      return cleaned_string

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    2. Ćwiczenie: Garfield
    def countGarfield(names):
      # Inicjalizujemy licznik
      count = 0
      
      # Inicjalizujemy iterator
      iterator = iter(names)
      
      # Pętla while do iteracji przez iterator
      while True:
          try:
              name = next(iterator)
              count += 1
              # Jeśli nazwa to "Garfield", zwracamy aktualny numer
              if name == "Garfield":
                  return count
          except StopIteration:
              # Jeśli nie znaleziono "Garfield", zwracamy None
              return None

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    3. Listy składane
    def powersOfTwo():
      return [2 ** i for i in range(100)]
    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    4. Ćwiczenie - daty
    def USToISO8601(dateList):
      # Użyj list comprehension do przekształcenia każdej daty
      iso_dates = [date.split('/')[2] + '-' + date.split('/')[0] + '-' + date.split('/')[1] for date in dateList]
      return iso_dates
    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    5. Zakres
    def formatNr(numbers):
      # Użyj list comprehension do przekształcenia każdego numeru
      formatted_numbers = ['0061' + ''.join(number.split()) for number in numbers]
      return formatted_numbers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    6. Sumy: Rozgrzewka
    def sumOfElements(numbers):
      return sum(numbers)
    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    7. Wbudowana funkcja sum()
    def sumOfElements(numbers):
      return sum(numbers)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    8. Wbudowana funkcja round()
    def avgTempPerHour(temperatures):
      # Użyj list comprehension do obliczenia średnich temperatur
      avg_temperatures = [round(sum(hour_temperatures) / len(hour_temperatures), 1) for hour_temperatures in temperatures]
      return avg_temperatures
    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    9. Listy składane + warunek
    def longStrings(strings):
      # Użyj list comprehension do filtrowania napisów o długości 10 lub dłuższej
      long_strings = [string for string in strings if len(string) >= 10]
      return long_strings
          
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    10. Ćwiczenie - uznania
    def convertCurrency(bill, ex_rate):
      # Użyj list comprehension do przeliczenia wpływów na euro
      euro_amounts = [round(amount * ex_rate, 2) for amount in bill if amount > 0]
      
      return euro_amounts

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    11. Ćwiczenie - średnie wyniki
    def testAvg(tests):
      # Użyj list comprehension do obliczenia średnich arytmetycznych
      avg_results = [round(sum(test) / len(test), 4) for test in tests if len(test) > 1]
      
      return avg_results
 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    12. Listy składane - 2D
    def genMulTable(size):
      # Używamy zagnieżdżonego list comprehension do wygenerowania tabliczki mnożenia
      mul_table = [[x * y for y in range(size)] for x in range(size)]
      
      return mul_table
    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    13. Wbudowana funkcja abs()
    def miniDeviation(readings):
      # Wykorzystujemy list comprehension do znalezienia najbliższej wartości od zera dla każdej serii danych
      deviations = [min(abs(x) for x in series) for series in readings]
      
      return deviations

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    14. Ćwiczenie: crimes 1
    def crimes(crimesList):
      # Używamy list comprehension do obliczenia sumarycznej liczby przestępstw dla każdego okręgu
      result = [[okreg[0], sum(okreg[2:7])] for okreg in crimesList]
      
      return result

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    15. Ćwiczenie: crimes 2
    def crimes(crimesList):
      # Używamy list comprehension do znalezienia roku z najmniejszą i największą liczbą przestępstw
      result = [
          [okreg[0], min(okreg[2:7]), max(okreg[2:7])]
          for okreg in crimesList
          if okreg[7] >= 4000  # Filtrujemy okręgi, w których populacja wynosi co najmniej 4000
      ]
      
      return result

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    16. Ćwiczenie: suma długości napisów
    def sumOfLengths(strings):
      # Użyj list comprehension, aby stworzyć listę długości każdego napisu
      lengths = [len(s) for s in strings]
      
      # Użyj funkcji sum(), aby zsumować długości napisów
      total_length = sum(lengths)
      
      return total_length

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    17. Zliczanie elementów
    def countLucky(numbers):
      # Użyj list comprehension, aby stworzyć listę wartości logicznych wskazujących, czy liczba jest podzielna przez 7
      is_divisible_by_7 = [num % 7 == 0 for num in numbers]
      
      # Użyj funkcji sum(), aby zsumować wartości logiczne (True jest traktowane jako 1, False jako 0)
      count = sum(is_divisible_by_7)
      
      return count
    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    18. Ćwiczenie - lustrzane odbicie
    def tripleMirror(triple_data):
      # Sprawdź, czy to jest lista
      if isinstance(triple_data, list):
          # Użyj rekurencji do odwrócenia kolejności elementów w liście na każdym poziomie zagnieżdżenia
          return [tripleMirror(sublist) for sublist in reversed(triple_data)]
      else:
          # Jeśli to nie jest lista, to zwróć wartość bez zmiany
          return triple_data

    
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    19. Ćwiczenie: Przestępne urodziny

    def isLeapYear(year):
      # Funkcja sprawdzająca, czy rok jest przestępny
      return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

    def leapUsers(users):
        # Licznik użytkowników urodzonych w roku przestępnym
        leap_count = 0
    
        # Iteruj się po każdym napisie w liście users
        for user_info in users:
            # Podziel napis na części, rozdzielając go po spacji
            parts = user_info.split()
            
            # Pobierz datę urodzenia w formacie "RRRR-MM-DD"
            birth_date = parts[0]
            
            # Pobierz rok urodzenia z daty
            birth_year = int(birth_date.split("-")[0])
            
            # Sprawdź, czy rok urodzenia jest przestępny
            if isLeapYear(birth_year):
                leap_count += 1
        
        return leap_count

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    20. Słowniki składane
    def birthdayDict(users):
      # Użyj dict comprehension do stworzenia słownika
      # Kluczem będzie konkatenacja imienia i nazwiska, a wartością będzie data urodzenia
      return {f"{user.split()[1]} {user.split()[2]}": user.split()[0] for user in users}


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -