Ejemplo n.º 1
0
def get_songs(artists_list, genres_list):
    """
    Check if songs are valid and add them to the array; counts length of all songs

    :param artists_list: list of artists
    :param genres_list: list of genres
    :return: list of Song-objects, total legnth of songs
    """
    songs = DynamicArray()
    length = 0
    for artist_inp in artists_list:
        artist = itunespy.search_artist(artist_inp[0].artist_name)
        albums = artist[0].get_albums()
        for album in albums:
            if album.primary_genre_name in genres_list:
                try:
                    album_search = itunespy.search_album(album.collection_name)
                except LookupError:
                    continue
                tracks = album_search[0].get_tracks()
                for track in tracks:
                    if track.primary_genre_name in genres_list:
                        print(track)
                        songs.append(
                            Song(track.track_name, track.artist_name,
                                 track.collection_name, track.track_time))
                        length += track.track_time

    return songs, length
Ejemplo n.º 2
0
 def __init__(self):
     """Initialises the attributes and call starting functions"""
     self.db_lst = DynamicArray()
     self.get_db_lst()
     self.start()
     while True:
         ch = msvcrt.getch()
         if ch == b'\r':
             break
Ejemplo n.º 3
0
class IntSet:
    """Represents collection of integer"""
    def __init__(self, n):
        """Initializes IntSet"""
        self._nums = DynamicArray()
        for i in range(n):
            self._nums.append(random.randint(0, 100))

    def __len__(self):
        """Return number of integers"""
        return len(self._nums)

    def __getitem__(self, index):
        """Returns i element of IntSet"""
        return self._nums[index]

    def append(self, item):
        """Add element"""
        self._nums.append(item)

    def _digits(self, num):
        """Returns digits from number"""
        digits = str(num)
        for digit in digits:
            yield int(digit)

    def merge(self, other):
        """Combines two IntSets in one IntSet from digits of their sum
        :param IntSet, IntSet
        :returns InteSet"""
        result = IntSet(0)
        len_first = len(self)
        len_second = len(other)
        if len_first >= len_second:
            for i in range(len_second):
                num = self._nums[i] + other[i]
                for digit in self._digits(num):
                    result.append(digit)
            for i in range(len_second, len_first):
                for digit in self._digits(self._nums[i]):
                    result.append(digit)
        else:
            for i in range(len_first):
                num = self._nums[i] + other[i]
                for digit in self._digits(num):
                    result.append(digit)
            for i in range(len_first, len_second):
                for digit in self._digits(other[i]):
                    result.append(digit)
        return result

    def __str__(self):
        """Represents as string"""
        result = ''
        for i in range(len(self._nums)):
            result += str(self._nums[i]) + ' '
        return result[:-1]
Ejemplo n.º 4
0
 def user_input(self, city):
     """
             Reads the CSV file and returns a city code.
             """
     lst = DynamicArray()
     with open("city_list.csv", "r") as csvFile:
         reader = csv.reader(csvFile)
         for row in reader:
             lst.append(row)
     for i in range(len(lst)):
         if lst[i][0] == city or lst[i][0] == city.title():
             code = lst[i][1]
     return code
Ejemplo n.º 5
0
    def __init__(self, cityname=None, icao=None):
        '''
        Initializing new AirlinesADT object with 
        cityname and icao parameters are None by default

        ___init___: str, str -> NoneType
        :param cityname: city for doing research
        :param icao: ICAO identifier of the airport chosen by user
        '''
        self._cityname = cityname
        self._icao = icao
        self._location = None
        self._destinations = None
        self._airports_nearby = DynamicArray()
        self._routes_available = DynamicArray()
Ejemplo n.º 6
0
 def convert(self):
     """
     The function that returns array with angles that means the amount of degrees for which the line should move
     the line
     """
     start = 0
     new_arr = DynamicArray()
     for letter in self.message:
         lst = [ord(letter) // 16, ord(letter) % 16]
         for i in lst:
             angle = i * 22.5
             if start + angle < 360:
                 start += angle
             else:
                 start += angle - 360
             new_arr.append(start)
     return new_arr
Ejemplo n.º 7
0
def build_playlist(songs, length, time):
    """

    :param songs: list of songs
    :param length: total length of all songs
    :param time: estimated time
    :return: songs which are included in playlist
    """
    result_songs = DynamicArray()

    ch = time <= length

    while time > 0:
        song = random.choice(songs)
        time -= song.length
        result_songs.append(song)
        if ch:
            songs.remove(song)

    return result_songs
Ejemplo n.º 8
0
 def read_from_file(self):
     '''
     '''
     fl = open(self._file, "r")
     learned_words_full = DynamicArray()
     learned_words = DynamicArray()
     for line in fl:
         line = line.strip()
         if '===' not in line and line != '' and line[0] not in '123456789':
             line = line.split(',')
             learned_words_full.append(line)
             learned_words.append(line[0])
     return learned_words_full, learned_words
Ejemplo n.º 9
0
    def convert(self, message):
        res_2 = 0
        new_arr = DynamicArray()
        for letter in message:
            res_1 = ord(letter) % 16
            angle = (res_1 - res_2) * 22.5
            if angle > 180:
                angle = -360 - angle
            if angle < -180:
                angle = 360 + angle


            # new_arr.append((res_1 - res_2) * 22.5)
            res_2 = ord(letter) // 16
            angle_2 = (res_2 - res_1) * 22.5
            if angle_2 > 180:
                angle_2 = -(360 - angle_2)
            if angle_2 < -180:
                angle_2 = 360 + angle_2
            new_arr.append(angle_2)
            new_arr.append(angle)
            print(res_2, res_1)
            # new_arr.append((res_2 - res_1) * 22.5)

            # new_arr.append((res_1, res_2))
        return new_arr
Ejemplo n.º 10
0
 def convert(self, message):
     arr = DynamicArray()
     for letter in message:
         res_2 = ord(letter) % 16
         res_1 = ord(letter) // 16
         arr.append(res_1)
         arr.append(res_2)
     angle = 0
     result = DynamicArray()
     for i in range(len(arr)):
         angle_turn = arr[i] * 22.5 - angle
         angle += angle_turn
         result.append(angle_turn)
     return result
Ejemplo n.º 11
0
 def read_from_file(self):
     '''
     Reads information from file.
     Returns tuple of two lists: words with translation and definition,
     korean words.
     '''
     fl = open(self._file, "r")
     learned_words_full = DynamicArray()
     learned_words = DynamicArray()
     for line in fl:
         line = line.strip()
         if '===' not in line and line != '' and line[0] not in '123456789':
             line = line.split(',')
             learned_words_full.append(line)
             learned_words.append(line[0])
     return learned_words_full, learned_words
Ejemplo n.º 12
0
    def test_dynamic_array(self):
        '''Testing dynamic array class'''
        arr = DynamicArray()

        self.assertIsInstance(arr, DynamicArray)
        self.assertEqual(arr._size, 0)
        self.assertEqual(len(arr), 0)
        
        arr.append('green')
        arr.append('green')
        self.assertEqual(arr[0], 'green')

        arr.remove('green')
        self.assertEqual(arr._size, 1)
Ejemplo n.º 13
0
 def setUp(self):
     self.arr = DynamicArray()
     self.arr.append("a")
Ejemplo n.º 14
0
class TestDynamicArray(TestCase):
    def setUp(self):
        self.arr = DynamicArray()
        self.arr.append("a")

    def test_init(self):
        self.assertEqual(self.arr._n, 1)

    def test_len(self):
        self.assertEqual(self.arr._n, len(self.arr))

    def test_getitem(self):
        self.assertEqual(self.arr[0], self.arr._A[0])
        with self.assertRaises(IndexError):
            el = self.arr[-1]

    def test_append(self):
        self.arr.append("b")
        self.assertEqual(self.arr[0], "a")
        self.assertEqual(self.arr[1], "b")
        self.assertEqual(len(self.arr), 2)

    def test_resize(self):
        self.arr._resize(3)
        self.assertEqual(self.arr._A._size, 3)

    def test_make_array(self):
        self.assertEqual(type(self.arr._make_array(4)), Array)

    def test_insert(self):
        self.arr._resize(1)
        self.arr.insert(0, "A")
        self.assertEqual(self.arr._A._size, 2)
        self.assertEqual(self.arr._A[0], "A")
        self.assertEqual(self.arr._n, 2)

    def test_remove(self):
        with self.assertRaises(ValueError):
            self.arr.remove("b")
        self.arr.insert(1, "A")
        self.arr.remove("a")
        self.assertEqual(self.arr._n, 1)

    def test_str(self):
        self.assertEqual(type(str(self.arr)), str)

    def test_pop(self):
        self.arr.insert(1, "A")
        last = self.arr._A[self.arr._n - 1]
        self.assertEqual(self.arr.pop(), last)
        self.assertEqual(self.arr._n, 1)

    def test_clear(self):
        self.assertEqual(self.arr[0], "a")
        self.arr.clear()
        for i in range(len(self.arr._A)):
            self.assertTrue(self.arr._A[i] is None)
        self.assertTrue(self.arr._n == 0)
Ejemplo n.º 15
0
class TestDynamicArray(TestCase):
    def setUp(self):
        self.arr = DynamicArray()
        self.arr.append("item1")
        self.arr.append("item2")

    def test_init(self):
        self.assertEqual(self.arr._n, 2)

    def test_len(self):
        self.assertEqual(self.arr._n, len(self.arr))

    def test_getitem(self):
        self.assertEqual(self.arr[0], self.arr._A[0])

    def test_append(self):
        self.arr.append("item3")
        self.assertEqual(self.arr[0], "item1")
        self.assertEqual(self.arr[1], "item2")
        self.assertEqual(self.arr[2], "item3")
        self.assertEqual(len(self.arr), 3)

    def test_resize(self):
        self.arr._resize(3)
        self.assertEqual(self.arr._A._size, 3)

    def test_make_array(self):
        self.assertEqual(type(self.arr._make_array(13)), Array)

    def test_insert(self):
        self.arr._resize(2)
        self.arr.insert(0, "item0")
        self.assertEqual(self.arr._A._size, 3)
        self.assertEqual(self.arr._A[0], "item0")
        self.assertEqual(self.arr._n, 3)

    def test_remove(self):
        self.arr.insert(1, "item1_2")
        self.arr.remove("item1")
        self.assertEqual(self.arr._n, 2)

    def test_str(self):
        self.assertEqual(type(str(self.arr)), str)

    def test_pop(self):
        self.arr.insert(2, "item3")
        last = self.arr._A[self.arr._n - 1]
        self.assertEqual(self.arr.pop(), last)
        self.assertEqual(self.arr._n, 2)

    def test_clear(self):
        self.assertEqual(self.arr[0], "item1")
        self.assertEqual(self.arr[1], "item2")
        self.arr.clear()
        for i in range(len(self.arr._A)):
            self.assertTrue(self.arr._A[i] is None)
        self.assertTrue(self.arr._n == 0)
Ejemplo n.º 16
0
class AirlinesADT:
    '''
    Abstact class representing AirlinesADT
    Processes data collected from API's and saves the
    results of research using DynamicArray
    '''
    def __init__(self, cityname=None, icao=None):
        '''
        Initializing new AirlinesADT object with 
        cityname and icao parameters are None by default

        ___init___: str, str -> NoneType
        :param cityname: city for doing research
        :param icao: ICAO identifier of the airport chosen by user
        '''
        self._cityname = cityname
        self._icao = icao
        self._location = None
        self._destinations = None
        self._airports_nearby = DynamicArray()
        self._routes_available = DynamicArray()

    def get_nearby_airports(self):
        '''
        Defines the coordinates of the given city.
        Searches for nearby airports using API_location
        Saves result of the research in  dynamic array

        airports_nearby: array of Airport objects - airports
                         found using API_location
        '''
        geolocator = Nominatim(user_agent="airport finder")
        location = geolocator.geocode(self._cityname)
        self._location = API_location(location.latitude, location.longitude,
                                      50, 10)

        for airport in self._location['items']:
            name = airport['name']
            icao = airport['icao']
            location = airport['location']
            self._airports_nearby.append(Airport(name, location, icao))

    def get_routes_available(self):
        '''
        Searches for avaliable routes and average 
        number of daily flights  from the chosen airport
        (ICAO identifier)in these directions using API_destination
        If any of the parameters (name, location, average flights)
        is absent, the route is skipped

        routes_available: array of Airport objects - directions
                          available for travelling                        
        '''
        self._destinations = API_destination(self._icao)

        for route in self._destinations['routes']:
            try:
                location = route['destination']['location']
                name = route['destination']['name']
                average_flights = route['averageDailyFlights']
                self._routes_available.append(
                    Airport(name, location, average_fligths=average_flights))
            except KeyError:
                pass
Ejemplo n.º 17
0
 def setUp(self):
     self.arr = DynamicArray()
     self.arr.append("item1")
     self.arr.append("item2")
Ejemplo n.º 18
0
def input_data():
    """
    None -> array, array

    Return user's input and check if such data exist.

    :return: artists and genres arrays
    """
    artists_list = DynamicArray()
    genres_list = DynamicArray()
    print("Enter at least one artist")
    while True:
        artist_inp = input("Enter artist's name or Enter to finish: ")
        try:
            if len(artist_inp) > 0 or len(artists_list) == 0:
                artist = itunespy.search_artist(artist_inp)
                artists_list.append(artist)
            else:
                break
        except LookupError:
            print(
                "There is no such artist in iTunes database. Try someone else."
            )
            continue

    while True:
        answer = input(
            "Would you like to know genres of your artists?(yes/no) ")
        if answer.lower() == "no":
            break
        elif answer.lower() == "yes":
            genres_set = set()
            for i in artists_list:
                for a in i[0].get_albums():
                    genres_set.add(a.primary_genre_name)

            genres_set = sorted(list(genres_set))
            print("\nGenres of your artists:\n")
            for g in genres_set:
                print(g)
            print("\n")
            break
        else:
            print("Invalid answer!")
            continue

    while True:
        genre = input("Enter genre or Enter to finish: ")
        if len(genre) > 0 or len(genres_list) == 0:
            if len(genre) == 0:
                continue
            ch = False
            for art in artists_list:
                albums = art[0].get_albums()
                for album in albums:
                    if album.primary_genre_name == genre:
                        ch = True
            if not ch:
                print(
                    "Your artist does not work in this genre. Try another one."
                )
                continue
            genres_list.append(genre)
        elif len(genre) == 0:
            break

    return artists_list, genres_list
Ejemplo n.º 19
0
 def __init__(self, n):
     """Initializes IntSet"""
     self._nums = DynamicArray()
     for i in range(n):
         self._nums.append(random.randint(0, 100))
Ejemplo n.º 20
0
class ComUser:
    """The class communicate with the user and controls the whole work"""
    def __init__(self):
        """Initialises the attributes and call starting functions"""
        self.db_lst = DynamicArray()
        self.get_db_lst()
        self.start()
        while True:
            ch = msvcrt.getch()
            if ch == b'\r':
                break

    @staticmethod
    def start():
        """Prints the starting text"""
        file = open("../text/StartText.txt")
        lines = file.readlines()
        for i in lines:
            print(i, end="")
        print("\n")

    def get_gene_name(self, n=""):
        """Asks user the name of gene he/she wants to analyse.
        Returns the given name.
        Raises exception if that name is not valid."""
        if n == "":
            n = input("Please enter a gene to analyse (ex. AT1G36060): ")
        gene = GeneFasta(n)
        try:
            gene.get_gene_id()
            return gene
        except Exception:
            print("No genes found with name:\"" + gene.gene_name + "\"")
            return self.get_gene_name()

    def get_db_lst(self):
        """Makes the list of available databases"""
        file = open("../text/DataBases.txt")
        lines = file.readlines()
        for line in lines:
            tup = tuple(line.split(" | "))
            self.db_lst.append(tup)
        return self.db_lst

    def get_db_number(self, numb1=""):
        """Asks user the number of database he/she wants to analyse at.
        Returns the given number.
        If that number is not valid, asks again."""
        if numb1 == "":
            print(
                "Please choose the database of organism you want your gene to compare with:"
            )
            for i in range(len(self.db_lst)):
                datab = self.db_lst[i][0]
                print(str(i + 1) + ") " + datab)
            numb1 = input("Enter a number of your database: ")
        if int(numb1) > len(self.db_lst):
            print("The number is not valid!")
            numb1 = self.get_db_number()
        return int(numb1)

    def get_db_str(self, number):
        """Returns the part of link to database."""
        datab = self.db_lst[number - 1][1]
        return datab
 def setUp(self):
     self.wordcontrol1 = WordController("julia_poch.txt")
     self.wordcontrol2 = WordController("julia.txt")
     self.arr = DynamicArray()