text
stringlengths
37
1.41M
# data structures # list ---> this chapter # ordered collection of items # you can store anything in lists int, float, string numbers = [1,2,3,4] print(numbers[1]) words = ['word1', 'word2', 'word3', 'word4'] print(words[:2]) mixed = [1, 2, 3, 4, "five", "six", 2.3, None] print(mixed[-1]) mixed[1:] = ['three', 'four'] print(mixed)
# you have to have a complete understanding of functions, # first class function / closure # then finally we will learn about decorators def square(a): return a**2 s = square # assign square function to another variable # print(s(7)) print(s.__name__) # gives function name i.e square print(square.__name__) # gives function name i.e square # both are on same memory location print(s) # <function square at 0x007EB660> print(square)# <function square at 0x007EB660>
# generators # generators are iterators # create your first generator with generator # 1. generator function # 2. generator comprehension def nums(n): for i in range(1, n+1): yield i numbers = nums(10) # generator # print(numbers) # <generator object nums at 0x03150570> for i in numbers: print(i) for i in numbers: # cannot repeat print(i) # normal method :- # def number(n): # for i in range(1, n+1): # print(i) # number(10) # memory (list) - [..................] # memory (gen) - (3)
# add and delete data user_info = { 'name' : 'harshit', 'age' : 24, 'fav_tunes' : ['alan walker', 'shakira'], 'fav_movies' : ['minions', 'spiderman'] } # how to add data # user_info['fav_foods'] = ['biryani', 'chicken nuggets'] # print(user_info) # pop() method # popped_item = user_info.pop('fav_tunes') # print(f"popped item is {popped_item}") # print(user_info) # popitem() method deletes last key value pair popped_item = user_info.popitem() print(popped_item) print(user_info)
name = "Harshit" # in keyword # if with in if 'b' in name: print("a is present in name") else: print("not presents")
import time # list vs generator # memory usage , time # when to use list , when to use generator # t1 = time.time() # l = [i**2 for i in range(10000000)] # 10 million # t2 = time.time() # print(t2-t1) t1 = time.time() g = (i**2 for i in range(10000000000)) # 10 million t2 = time.time() print(t2-t1)
def is_palindrome(s): n = len(s) if n == 0 or n == 1: return 1 return s[0] == s[n - 1] and is_palindrome(s[1:n - 1])
class Account: # linked to setup.py def __init__(self, cnx, username): self.cnx = cnx self.username = username # method to delete user account. calls MySQL procedure within def delete_account(self): while True: try: action = input("Are you sure you want to delete account? Enter 'yes' or 'no:\n") action = action.lower() if action == 'no': break elif action == 'yes': c5 = self.cnx.cursor() c5.callproc('delete_user', (self.username,)) self.cnx.commit() c5.close() print('Sad to see you go :(') return 'bye' else: print('Not a valid input. Try Again') continue except: print('Looks like something when wrong with deleting account\n') return 'bye' # method update certain aspects of user account. calls MySQL procedures within def update_account(self): while True: try: choice = input('What would you like to update?:\n' "Type 'p' for Password\n" "Type 'f' for First Name\n" "Type 'l' for Last Name\n" "Type 'e' for Email\n") choice = choice.lower() if choice == 'p': new_password = input('Enter new password:\n') c4a1 = self.cnx.cursor() c4a1.callproc('update_password', (self.username, new_password)) self.cnx.commit() c4a1.close() print('Changes to password made!') break elif choice == 'f': new_first = input('Enter new first name:\n') c4a2 = self.cnx.cursor() c4a2.callproc('update_first', (self.username, new_first)) self.cnx.commit() c4a2.close() print('Changes to first name made!') break elif choice == 'l': new_last = input('Enter new last name:\n') c4a3 = self.cnx.cursor() c4a3.callproc('update_last', (self.username, new_last)) self.cnx.commit() c4a3.close() print('Changes to last name made!') break elif choice == 'e': new_email = input('Enter new email:\n') c4a4 = self.cnx.cursor() c4a4.callproc('update_email', (self.username, new_email)) self.cnx.commit() c4a4.close() print('Changes to email made!') break else: print('Not a valid input. Try Again') continue except: print('Something went wrong trying to update account') return 'bye'
""" Example of bubble sort, in this example, Complexity is O(N*(N+1))= O(N^2+N)~=O(N^2) """ def bubbleSort(array): for i in range(len(array)): for j in range(len(array)-1): if array[j] > array[j+1]: array[j],array[j+1] = array[j+1],array[j] return array print(bubbleSort([1,3,2,6,1,3,8,9,2,4,9]))
from bs4 import BeautifulSoup as bs from splinter import Browser import pandas as pd import time # Initialize browser def init_browser(): executable_path = {'executable_path': '/usr/local/bin/chromedriver'} return Browser('chrome', **executable_path, headless=False) def scrape(): # # NASA Mars News # Initialize browser browser = init_browser() # Create a dictionary for storing all scraped data mars_data = {} # URL of NASA Mars News Site to be scraped url = 'https://mars.nasa.gov/news/' browser.visit(url) # 5 second wait for loading data time.sleep(5) # HTML object html = browser.html # Parse HTML with Beautiful Soup soup = bs(html, 'html.parser') # Retrieve the latest news title and paragraph text and assign correponding variables news = soup.find('div', class_='list_text') title = news.find('div', class_='content_title').text text = news.find('div', class_='article_teaser_body').text # Add the news title and paragraph text to dictionary mars_data['title'] = title mars_data['text'] = text # # JPL Mars Space Images - Featured Image # Initialize browser browser = init_browser() # URL of JPL Featured Space Image to be scraped using Splinter url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars' browser.visit(url) # Click on "Full Image" button browser.find_by_id('full_image').click() # HTML object html = browser.html # Parse HTML with Beautiful Soup soup = bs(html, 'html.parser') # Get relative path of full image image_url = soup.find("a", class_="button fancybox")['data-fancybox-href'] # Create variable for base URL base_url = 'https://www.jpl.nasa.gov' # Create full URL for featured image featured_image_url = base_url + image_url # Add featured image URL to dictionary mars_data['featured_image_url'] = featured_image_url # # Mars Facts # Initialize browser browser = init_browser() # Visit the Mars Facts Webpage url = 'http://space-facts.com/mars/' browser.visit(url) # Use Pandas to scrape the table containing Mars facts table = pd.read_html(url) # Select table mars_facts_DF = table[0] # Format table by adding column names and setting index mars_facts_DF.columns = ['Description', 'Values'] mars_facts_DF = mars_facts_DF.set_index('Description') # Use Pandas to convert the data to a HTML table string and store in variable mars_table = mars_facts_DF.to_html().replace('\n', ' ') # Add mars facts to dictionary mars_data['mars_table'] = mars_table # # Mars Hemispheres # Initialize browser browser = init_browser() # Visit the USGS Astrogeology site url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' browser.visit(url) # HTML object html = browser.html # Parse HTML with Beautiful Soup soup = bs(html, 'html.parser') # Lists to store hemisphere title and full image URL hemisphere_image_urls = [] # Loop through all products and get relevant information for x in range(4): # Identify item link and click on it item = browser.find_by_tag('h3') item[x].click() # Create HTML browser object and parse with Beautiful Soup html = browser.html soup = bs(html, 'html.parser') # Get hemisphere title and full image URL img_title = soup.find('h2', class_='title').text img_url = soup.find('a', target='_blank')['href'] # Create dictionary and append to list storing all hemisphere titles and image URLs. dictionary = {"title":img_title,"img_url":img_url} hemisphere_image_urls.append(dictionary) # Click on Back button to return to previous site browser.back() # Add list storing all hemisphere titles and image URLs to mars data dict mars_data['hemisphere_image_urls'] = hemisphere_image_urls # Print mars_info dictionary return mars_data
from typing import List, Dict from itertools import product class Person(object): """A person that is going on the trip""" _name: str def __init__(self, name: str, gender: str = "hello", days_staying: int = 1): """A person that will be there during the holiday :type name: str :param name: Name of person :param gender: Gender of person ('m' or 'f') :param days_staying: Number of nights the person is staying """ self._name = name self._gender = gender self._days_staying = days_staying self.partner = None self._bids = {} def get_name(self): """"Name of person""" return self._name def get_gender(self): """Gender of person""" return self._gender def get_nights_staying(self): """Number of days the person is staying""" return self._days_staying def get_partner(self): """Partner of person""" return self.partner def add_partner(self, partner): """Add a partner to a person""" self.partner: Person = partner partner.partner = self def get_bids(self): """The bids of this person""" return self._bids def add_bids(self, bids: Dict[str, float]): """Add bids to a person""" self._bids = bids def is_couple(self, other_person): """Is the other person, this person's partner. Are they a couple? """ if self.get_partner() == other_person: return True else: return False def __repr__(self): return self._name class Bed: """A bed in the house. Can be double or single""" def __init__(self, name: str, size: str): """A bed in the house. Can be double or single""" self._name: str = name self._size: str = size if self._size == "single": self._spaces: int = 1 elif self._size == "double": self._spaces: int = 2 else: raise IOError def get_type(self): """type of bed""" return self._size def get_spaces(self): """number of people that can sleep in this bed""" return self._spaces def __repr__(self): return self._name class Room: """A room with beds of the same type in it""" def __init__(self, name: str, beds: List[Bed]): """Has beds in it""" self._name = name self._beds = beds self.capacity: int = self.calculate_capacity() self.people: List[Person] = [] def add_bed(self, bed: Bed): """Add a bed to a room""" self._beds.append(bed) def calculate_capacity(self): total = 0 for i in self._beds: total += i.get_spaces() return total def get_capacity(self): """Gets the number of people that can sleep in this room""" return self.capacity def add_person(self, person: Person) -> bool: """Add a person to the room. Will return false if the room is already full or there is no bed for someone of their gender in the room""" # If there is space in the room if self.get_capacity() <= len(self.get_people()): return False # If the bed is a double if self._beds[0].get_type() == "double": other_person = self.people[0] if other_person.get_gender() != person.get_gender() and other_person.get_partner() != person: return False elif len(self.get_people()) < self.get_capacity(): self.people.append(person) return True else: raise IOError def get_people(self): """The people in the room""" return self.people def is_gender_restricted(self): """Whether this room is gender restricted Essentially whether it has a double bed or not""" for bed in self._beds: if bed.get_type() == "double": return True return False def get_name(self): """Name of the room""" return self._name def __repr__(self): return self._name class House: """House with beds""" def __init__(self, price: float, nights: int = 1): """House that you are staying in. Has beds and a price :param price: Total price of accommodation :param nights: Number of nights you are staying at accommodation """ self._price = price self.rooms: List[Room] = [] self.nights = nights def get_total_price(self): """ The price per night of the house""" return self._price def get_rooms(self): """The beds in the house""" return self.rooms def add_room(self, room: Room): """Add a bed to the house""" self.rooms.append(room) def get_nights(self): """Number of nights you are staying""" return self.nights def price_per_night(self): """Price the group is paying per night""" return self._price / self.nights class Calculator(object): """Calculates the best permutation of bed selections""" house: House def __init__(self, couple_force=False, couple_priority=False, price_by: str = "individual", bid_value: str = "direct"): """Calculate the best permutation of bed/room assignments. And the prices that everyone has to pay for them :param price_by can be either 'room' or 'individual' :param bid_value can be either "direct" or "extra" """ self._people: list = [] self._highest_utility: int = 0 self.best_arrangements: Dict[List[float]: int] = {} self.couple_force = couple_force self.couple_priority = couple_priority self.price_by = price_by self.bid_value = bid_value def get_house(self): """"Returns house""" return self.house def get_people(self): """Returns list of people in the experiment """ return self._people def add_person(self, person: Person): """Add a person to the calculator""" self._people.append(person) def add_people(self, people: List[Person]): """Add a list of people to the calculator""" self._people.extend(people) def get_highest_utility(self): """Returns highest utility value found""" return self._highest_utility def add_house(self, house: House): """Add a house to the calculator""" self.house = house def get_house(self): """Get house that is in calculator""" return self.house def calculate(self): """Calculates the room assignment for every person in the house In the form of a dictionary which maps {person: room} """ # Get a list of all possible ways people could be put in rooms possible_arrangements: List[tuple] = self.calculate_arrangements() count = 0 total = len(possible_arrangements) # Calculate the utility of every arrangement for arrangement in possible_arrangements: count += 1 arrangement = list(arrangement) if self.is_valid_arrangement(arrangement): utility = self.calculate_utility(arrangement) print(round(count / total, 2)) if utility >= self._highest_utility: self._highest_utility = utility self.best_arrangements[str(arrangement)] = utility return self.filter_highest_utility() def filter_highest_utility(self): """Goes through all the potential best arrangements and only keeps the values with the highest utility""" max_dictionary: Dict[str: int] = {} max_value: float = max(self.best_arrangements.values()) for i in self.best_arrangements.keys(): if self.best_arrangements[i] == max_value: max_dictionary[i] = max_value self.best_arrangements = max_dictionary @staticmethod def string_to_list(n: str) -> List[int]: """Converts a string that used to be a list of integers, back into a list of integers""" n = n.replace(" ", "") n = n.strip("[]") n = n.split(",") n = list(map(int, n)) return n def is_valid_arrangement(self, arrangement: List[int]): """Bool of whether the tuple is a valid arrangement for rooms""" rooms: List[Room] = self.house.get_rooms() for room in range(len(rooms)): # How many people were assigned to the room assigned_to_room = arrangement.count(room + 1) # Have less than 2 people been assigned to the room if assigned_to_room < 2: continue # More assigned than there is space space_in_room = rooms[room].get_capacity() if assigned_to_room > space_in_room: return False # Is this a gender restricted room if rooms[room].is_gender_restricted(): # Find the people assigned to this room indexed_people: List[Person] = self.indexed_people(room + 1, arrangement) # Couple force if self.couple_force: # If you have a partner if indexed_people[0].get_partner() is not None: if not indexed_people[0].is_couple(indexed_people[1]): return False # Are they a couple? if indexed_people[0].is_couple(indexed_people[1]): continue # Are the genders all the same if indexed_people[0].get_gender() != indexed_people[1].get_gender(): return False else: if self.couple_force: # couples can only be in gender restricted rooms indexed_people: List[Person] = self.indexed_people(room + 1, arrangement) for person in indexed_people: if person.get_partner() in indexed_people: return False return True def calculate_utility(self, arrangement: List[int]): """Calculates the utility of a particular arrangement. This value is the sum of the bids for each person with each group""" utility_score: float = 0 # For every person for person in self.get_people(): # Find out what room they were put in arrangement_index: int = self.get_people().index(person) room_index = arrangement[arrangement_index] - 1 room: Room = self.house.get_rooms()[room_index] room_name: str = room.get_name() # How much did they bid on that room bid: int = person.get_bids()[room_name] bid *= person.get_nights_staying() # Add to the total utility score utility_score += bid # If person has a partner if person.get_partner() is not None and self.couple_priority: # If the partner is in this room partner: Person = person.get_partner() partner_index = self.get_people().index(partner) partner_room_index = arrangement[partner_index] - 1 partner_room: Room = self.house.get_rooms()[partner_room_index] if partner_room == room: partner_bid = partner.get_bids()[room_name] partner_bid *= partner.get_nights_staying() utility_score += partner_bid return utility_score def get_room_mapping(self, arrangement: List[int]): """Create a dictionary mapping a person to a room""" if isinstance(arrangement, str): arrangement = self.string_to_list(arrangement) the_map: Dict[Person: Room] = {} for person_index in range(len(arrangement)): person: Person = self.get_people()[person_index] room_index: int = arrangement[person_index] - 1 room: Room = self.house.get_rooms()[room_index] the_map[person] = room return the_map def room_average(self, arrangement: List[int]): """Calculates the average value bid of everyone in that room""" room_bids = [] for i, room in enumerate(self.get_house().get_rooms()): index_people: List[Person] = self.indexed_people(i + 1, arrangement) room_total = 0 for person in index_people: room_total += person.get_bids()[room.get_name()] room_bids.append(room_total / len(index_people)) return room_bids def total_average(self): """Calculates the average value bid of everyone""" room_bids = [] for i, room in enumerate(self.get_house().get_rooms()): room_total = 0 for person in self.get_people(): room_total += person.get_bids()[room.get_name()] room_bids.append(room_total / len(self.get_people())) return room_bids @staticmethod def median(numbers: List[float]): """Calculates the median of a list of numbers If the list is even it calculates the average of the two middle numbers""" if len(numbers) % 2 == 0: after: int = int(len(numbers) / 2) before: int = after - 1 return (numbers[before] + numbers[after]) / 2 else: return numbers[int((len(numbers) + 1) / 2)] def total_median(self): """Calculates the median value bid of everyone""" room_bids = [] for i, room in enumerate(self.get_house().get_rooms()): individual_bids = [] for person in self.get_people(): individual_bids.append(person.get_bids()[room.get_name()]) room_bids.append(self.median(individual_bids)) return room_bids def room_median(self, arrangement: List[int]): """Calculates the median value bid of everyone in the same room""" room_bids = [] for i, room in enumerate(self.get_house().get_rooms()): index_people: List[Person] = self.indexed_people(i + 1, arrangement) individual_bids = [] for person in index_people: individual_bids.append(person.get_bids()[room.get_name()]) room_bids.append(self.median(individual_bids)) return room_bids def get_price_mapping(self, arrangement: List[int]): """Create a dictionary mapping a person to a price""" if isinstance(arrangement, str): arrangement = self.string_to_list(arrangement) the_map: Dict[Person: float] = {} room_bids = [] if self.price_by == "individual": # Calculate by how much people actually bid directly room_bids = self.individual(arrangement) elif self.price_by == "room average": # Calculate the average cost per night of each room room_bids = self.room_average(arrangement) elif self.price_by == "total average": room_bids = self.total_average() elif self.price_by == "total median": room_bids = self.total_median() elif self.price_by == "room median": room_bids = self.room_median(arrangement) else: raise ValueError # Scale the room bids depending on the bid by options original = room_bids if self.bid_value == "extra": equal_bids = [self.house.get_total_price()/len(room_bids)] * len(room_bids) room_bids = [x + y for x, y in zip(equal_bids, room_bids)] scale = self.house.get_total_price() / sum(room_bids) scaled_room_bids = [i * scale for i in room_bids] # Dictionary matching rooms to prices room_prices = {} for i, room in enumerate(self.get_house().get_rooms()): room_prices[room] = scaled_room_bids[i] # Create dictionary matching prices to people for i, person in enumerate(self.get_people()): # What is their assigned room? their_room_map = self.get_room_mapping(arrangement) their_room = their_room_map[person] # What is the value of that room the_map[person] = round(room_prices[their_room]) test = sum(the_map.values()) return the_map def individual(self, arrangement): bids: List[int] = [] # Calculate the total value of bids for person_index in range(len(arrangement)): person: Person = self.get_people()[person_index] room_index: int = arrangement[person_index] - 1 room: Room = self.house.get_rooms()[room_index] bid = person.get_bids()[room.get_name()] * person.get_nights_staying() bids.append(bid) # Calculate individual costs for person_index in range(len(arrangement)): # Get the first person person: Person = self.get_people()[person_index] room_index: int = arrangement[person_index] - 1 room: Room = self.house.get_rooms()[room_index] # What is the persons bid for their assigned room bid = person.get_bids()[room.get_name()] * person.get_nights_staying() bids[person_index] = bid return(bids) def get_best_arrangement(self): """Returns best arrangement""" return self.best_arrangements def calculate_arrangements(self): """Calculates a list of lists which map people to rooms""" x = list(product(range(1, len(self.house.get_rooms()) + 1), repeat=len(self.get_people()))) return x def indexed_people(self, room_number: int, arrangement: List[int]) -> List[Person]: """People at indexes""" indexed_people: List[Person] = [] # People indexed to room n for i in range(len(arrangement)): if room_number == arrangement[i]: indexed_people.append(self.get_people()[i]) return indexed_people def view_results(self): """View the results of the calculation""" # print(self.best_arrangements) # print(len(self.best_arrangements)) print("Room assignment: ") arrangement = list(self.best_arrangements.keys())[0] print(self.get_room_mapping(arrangement)) print("Prices assigned per person: ") payment = self.get_price_mapping(arrangement) print(payment) print("Total amount paid per week is ${0}".format(sum(payment.values())))
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ARRAYS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> An array is collection of items stored at contiguous memory locations. The idea is to store multiple items of same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array) Advantages of using arrays: Arrays allow random access of elements. This makes accessing elements by position faster. Arrays have better cache locality that can make a pretty big difference in performance. from array import * array1 = array('i', [10,20,30,40,50]) for x in array1: print(x) # left rotation of an array def leftrotate(arr,d,n): for j in range(d): new_node=arr[0] for i in range(n-1): arr[i]=arr[i+1] arr[n-1]=new_node def printarr(arr,n): for i in range(n): print(arr[i],end=" ") arr=[1,2,3,4,5] n=5 d=2 leftrotate(arr,d,n) printarr(arr,n) # DYNAMIC ARRAY What is a dynamic array? A dynamic array is similar to an array, but with the difference that its size can be dynamically modified at runtime. Don’t need to specify how much large an array beforehand. The elements of an array occupy a contiguous block of memory, and once created, its size cannot be changed. A dynamic array can, once the array is filled, allocate a bigger chunk of memory, copy the contents from the original array to this new space, and continue to fill the available slots #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< LINKED LIST >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dynamic data structure made of nodes data is not stored in continuous manner insertion and deletion of elements is easier can be used to implement abstract data types like stack , queue , list efficient random access is not possible implementation recquires some extra memory types:- single linked list double linked list circular linked list linked list with header node sorted linked list # SINGLE LINKED LIST class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def insert_at_beginning(self,data): new_node=Node(data) if self.head is None: self.head=new_node else: new_node.next=self.head self.head=new_node def insert_at_end(self,data): new_node=Node(data) if self.head is None: self.head=new_node else: temp=self.head while temp.next is not None: temp=temp.next temp.next=new_node def insert_at_after (self,data,x): new_node=Node(data) temp=self.head while temp.data is not x: temp=temp.next new_node.next=temp.next temp.next=new_node def insert_at_before (self,data,x): new_node=Node(data) temp=self.head if temp.data is x: new_node.next=temp temp=new_node return else: while temp.next.data is not x: temp=temp.next new_node.next=temp.next temp.next=new_node def createList(self): n=int(input("Enter the no. of elements in the linkedlist : ")) if n==0: print("list is empty") else: for i in range(n): data=int(input("enter the elements to be inserted : ")) self.insert_at_end(data) def printList(self): temp=self.head while temp: print(temp.data) temp=temp.next llist=LinkedList() llist.createList() # llist.insert_at_after(100,2) llist.insert_at_before(20,1) llist.printList() class Node: def __init__(self,value): self.value=value self.next=None class SingleLinkedList: def __init__(self): self.head=None def display_list(self): if self.head is None: print("list is empty") return else: print("List is : ") temp=self.head while temp is not None: print(temp.value," ", end =' ') temp=temp.next print() def count_node(self): temp=self.head n=0 if temp is None: print("the no of node is - ",n) else: while temp is not None: n=n+1 temp=temp.next print("the no of nodes are: ",n) def search(self,x): position=1 temp=self.head if temp is None: print("Not found because list is empty") else: while temp is not None: if temp.value==x: print("element found at position : ",position) break else: temp=temp.next position=position+1 def insert_in_beginning(self,data): #it also work if the list is empty new_node=Node(data) #new_node=Node(data) new_node.next=self.head #new_node.next=None self.head=new_node #self.head=new_node def insert_at_end(self,data): new_node=Node(data) if self.head is None: self.head=new_node return temp=self.head while temp.next is not None: temp=temp.next temp.next=new_node def create_list(self): n=int(input("enter the no of nodes : ")) if n==0: return else: for i in range(n): data=int(input("enter the elements to be inserted : ")) self.insert_at_end(data) def insert_after(self,data,x): temp=self.head while temp is not None: if temp.value==x: break temp=temp.next if temp is None: print(x," is not present in the list ") else: new_node=Node(data) new_node.next=temp.next temp.next=new_node def insert_before(self,data,x): temp=self.head #if list is empty if temp is None: print(x," is not present because list is empty") return #if insertion is done before first node if x==temp.value: new_node=Node(data) new_node.next=temp temp=new_node return #find reference to redecesor of node containing x while temp.next is not None: if temp.next.value==x: break temp=temp.next if temp.next is None: print(x," not present in the list") else: new_node=Node(data) new_node.next=temp.next temp.next=new_node def insert_at_position(self,data,x): if k==1: new_node=Node(data) new_node.next=self.head self.head=new_node return temp=self.head i=1 while i<k-1 and temp is not None: temp=temp.next i+=1 if temp is None: print("you can insert only upto",i) else: new_node=Node(data) new_node.next=temp.next temp.next=new_node def delete_node(self,x): if self.head is None: print("list is empty") return #deletion of first node if self.head.value==x: self.head=self.head.next return #deletion in between or end temp=self.head while temp.next is not None: if temp.next.value==x: break temp=temp.next if temp.next is None: print("element", x , "not in the list") else: temp.next=temp.next.next def delete_first_node(self): if self.head is None: return self.head=self.head.next def delete_last_node(self): if self.head is None: return if self.head.next is None: self.head=None return temp=self.head while temp.next.next is not None: temp=temp.next temp.next=None def reverse_list(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev def bubble_sort_exdata(self): i=0 while i< len(list1): j=0 while j<i: if list1[i]<list1[j]: #swap operation new_node=list1[j] list1[i]=list1[j] list1[j]=new_node j=j+1 i=i+1 def bubble_sort_elinks(self): pass def has_cycle(self): pass def find_cycle(self): pass def remove_cycle(self): pass def insert_cycle(self,x): pass def merge2(self,list2): pass def _merge2(self,p1,p2): pass def merge_sort(self): pass def _merge_sort_rec(self,listhead): pass def _divide_list(self,temp): pass list1 =SingleLinkedList() list1.create_list() while True: print("1. Display the list") print("2. count no of nodes") print("3. search for an element") print("4. insert in emptylist/insert at the beginning of the list") print("5. insert a node at the end of the list") print("6. insert a node after a speified node") print("7. insert a node before a specified node") print("8. insert a node at a given position") print("9. delete the first node") print("10. delete last node") print("11. delete any node") print("12. reverse the list") print("13. bubble sort by exchanging data") print("14. bubble sort by exchanging lists") print("15. mergesort") print("16. insert cycle") print("17. detect cycle") print("18. remove cycle") print("19. quit") option =int(input("enter your option : ")) if option ==1: list1.display_list() elif option==2: list1.count_node() elif option==3: data = int(input("enter the element to be searched : ")) list1.search(data) elif option==4: data=int(input("enter the elements to be inserted : ")) list1.insert_in_beginning(data) elif option ==5: data=int(input("enter the elements to be inserted : ")) list1.insert_at_end(data) elif option==6: data=int(input("enter the elements to be inserted : ")) x=int(input("enter the elements after which to be inserted : ")) list1.insert_after(data,x) elif option ==7: data=int(input("enter the elements to be inserted : ")) x=int(input("enter the elements before which to be inserted : ")) list1.insert_before(data,x) elif option==8: data=int(input("enter the elements to be inserted : ")) k=int(input("enter the position at which to be inserted : ")) list1.insert_at_position(data,k) elif option==9: list1.delete_first_node() elif option==10: list1.delete_last_node() elif option==11: data=int(input("enter the elements to be deleted : ")) list1.delete_node(data) elif option==12: list1.reverse_list() elif option==13: list1.bubble_sort_exdata() elif option==14: list1.bubble_sort_elinks() elif option==15: list1.merge_sort() elif option==16: data=int(input("enter the elements at which cycle has to be inserted : ")) list1.insert_cycle(data) elif option==17: if list1.has_cycle(): print("list has a cycle") else: print("list does not have a cycle ") elif option==18: list1.remove_cycle() elif option==19: break else: print("wrong option") print() #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< DOUBLE LINKED LIST >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>. in this list and every node with one another in both direction so the traversal can be done from head to tail or vice versa pointer head points first/head node previous part of first node and next part of last node will always be null next part of each node contain address of succeror node previous part of each node contains address of predecessor node class Node: def __init__(self,data): self.next=None self.prev=None self.data=data class DoubleLinkedList: def __init__(self): self.head=None def insert_at_beginning(self,data): new_node=Node(data) new_node.next=self.head # temp=self.head here it does not print the result if we use temp if self.head is not None: self.head.prev=new_node self.head=new_node def insert_at_end(self,data): new_node=Node(data) new_node.next=None # temp=self.head here it does not print the result if we use temp if self.head is None: self.head=new_node return temp=self.head while temp.next is not None: temp=temp.next temp.next=new_node new_node.prev=temp return def delete_node(self): pass def createList(self): n=int(input("Enter the no. of elements present in the list : ")) for i in range(n): data=int (input(f"Enter the {i}st element : ")) self.insert_at_end(data) def printList(self): temp=self.head while temp is not None: print(temp.data,end=" ") temp=temp.next llist=DoubleLinkedList() llist.createList() llist.insert_at_beginning(50) llist.insert_at_end(100) llist.printList() #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< CIRCULAR LINKED LIST >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Why have we taken a pointer that points to the last node instead of first node ? For insertion of node in the beginning we need traverse the whole list. Also, for insertion and the end, the whole list has to be traversed. If instead of head pointer we take a pointer to the last node then in both the cases there won’t be any need to traverse the whole list. So insertion in the begging or at the end takes constant time irrespective of the length of the list. class Node: def __init__(self,data): self.data=data self.next=None class CircularLinkedList(): def __init__(self): self.last=None def insert_at_empty(self,data): newnode=Node(data) if self.last is None: self.last=newnode newnode.next=newnode def insert_at_beginning(self,data): newnode=Node(data) if self.last is None: self.last=newnode newnode.next=newnode else: newnode.next=self.last.next self.last.next = newnode def insert_at_end(self,data): newnode=Node(data) if self.last is None: self.last=newnode newnode.next=newnode else: newnode.next=self.last.next self.last.next=newnode self.last=newnode def insert_in_between(self,data,item): if self.last is None: return None newnode=Node(data) temp=self.last.next while temp: if (temp.data == item): newnode.next = temp.next temp.next = newnode if (temp == self.last): self.last = newnode return self.last else: return self.last temp = temp.next if (temp == self.last.next): print(item, "not present in the list") break def printlist(self): if (self.last == None): print("List is empty") return new_node=self.last.next while new_node is not None : print(new_node.data,end=" ") new_node=new_node.next if new_node== self.last.next: break if __name__ == "__main__": llist=CircularLinkedList() llist.insert_at_empty(55) llist.insert_at_beginning(99) llist.insert_at_beginning(109) llist.insert_at_end(39) llist.insert_at_end(40) llist.insert_in_between(67,99) llist.printlist() #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< STACK >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). Stack can be implemented using [ LIST, QUEUE, LIQUEUE] Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition. Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition. Peek or Top: Returns top element of stack. isEmpty: Returns true if stack is empty, else false. # Python program to # demonstrate stack implementation # using list stack = [] # append() function to push # element in the stack stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) # pop() fucntion to pop # element from stack in # LIFO order print('\nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are poped:') print(stack) # uncommenting print(stack.pop()) # will cause an IndexError # as the stack is now empty #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< QUEUE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. Queue can also be implemented using [ LIST,QUEUE,LIQUEUE] # PRIORITY QUEUE Priority Queue is an extension of queue with following properties. Every item has a priority associated with it. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. Heap data structure is mainly used to represent a priority queue. In Python, it is available using “heapq” module. The property of this data structure in python is that each time the smallest of heap element is popped(min heap). Whenever elements are pushed or popped, heap structure in maintained. The heap[0] element also returns the smallest element each time. Operations on heap : 1. heapify(iterable) :- This function is used to convert the iterable into a heap data structure. i.e. in heap order. 2. heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained. 3. heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained 4. heappushpop(heap, ele) :- This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after this operation. 5. heapreplace(heap, ele) :- This function also inserts and pops element in one statement, but it is different from above function. In this, element is first popped, then the element is pushed.i.e, the value larger than the pushed value can be returned. heapreplace() returns the smallest value originally in heap regardless of the pushed element as opposed to heappushpop() nlargest(k, iterable, key = fun) :- This function is used to return the k largest elements from the iterable specified and satisfying the key if mentioned. 7. nsmallest(k, iterable, key = fun) :- This function is used to return the k smallest elements from the iterable specified and satisfying the key if mentioned # Python code to demonstrate working of # heappushpop() and heapreplce() # importing "heapq" to implement heap queue import heapq # initializing list 1 li1 = [5, 7, 9, 4, 3] # initializing list 2 li2 = [5, 7, 9, 4, 3] # using heapify() to convert list into heap heapq.heapify(li1) heapq.heapify(li2) # using heappushpop() to push and pop items simultaneously # pops 2 print ("The popped item using heappushpop() is : ",end="") print (heapq.heappushpop(li1, 2)) # using heapreplace() to push and pop items simultaneously # pops 3 print ("The popped item using heapreplace() is : ",end="") print (heapq.heapreplace(li2, 2)) #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< DEQUEUE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. # Python code to demonstrate working of # append(), appendleft(), pop(), and popleft() # importing "collections" for deque operations import collections # initializing deque de = collections.deque([1,2,3]) # using append() to insert element at right end # inserts 4 at the end of deque de.append(4) # printing modified deque print ("The deque after appending at right is : ") print (de) # using appendleft() to insert element at right end # inserts 6 at the beginning of deque de.appendleft(6) # printing modified deque print ("The deque after appending at left is : ") print (de) # using pop() to delete element from right end # deletes 4 from the right end of deque de.pop() # printing modified deque print ("The deque after deleting from right is : ") print (de) # using popleft() to delete element from left end # deletes 6 from the left end of deque de.popleft() # printing modified deque print ("The deque after deleting from left is : ") print (de) #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< CIRCULAR QUEUE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called ‘Ring Buffer’. class CircularQueue(): # constructor def __init__(self, size): # initializing the class self.size = size # initializing queue with none self.queue = [None for i in range(size)] self.front = self.rear = -1 def enqueue(self, data): # condition if queue is full if ((self.rear + 1) % self.size == self.front): print(" Queue is Full\n") # condition for empty queue elif (self.front == -1): self.front = 0 self.rear = 0 self.queue[self.rear] = data else: # next position of rear self.rear = (self.rear + 1) % self.size self.queue[self.rear] = data def dequeue(self): if (self.front == -1): # codition for empty queue print ("Queue is Empty\n") # condition for only one element elif (self.front == self.rear): new_node=self.queue[self.front] self.front = -1 self.rear = -1 return new_node else: new_node = self.queue[self.front] self.front = (self.front + 1) % self.size return new_node def display(self): # condition for empty queue if(self.front == -1): print ("Queue is Empty") elif (self.rear >= self.front): print("Elements in the circular queue are:", end = " ") for i in range(self.front, self.rear + 1): print(self.queue[i], end = " ") print () else: print ("Elements in Circular Queue are:", end = " ") for i in range(self.front, self.size): print(self.queue[i], end = " ") for i in range(0, self.rear + 1): print(self.queue[i], end = " ") print () if ((self.rear + 1) % self.size == self.front): print("Queue is Full") # Driver Code ob = CircularQueue(5) ob.enqueue(14) ob.enqueue(22) ob.enqueue(13) ob.enqueue(-6) ob.display() print ("Deleted value = ", ob.dequeue()) print ("Deleted value = ", ob.dequeue()) ob.display() ob.enqueue(9) ob.enqueue(20) ob.enqueue(5) ob.display() #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< BINARY TREE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. A Binary Tree node contains following parts. Data Pointer to left child Pointer to right child Traversal Breadth First Search (1) - Level order (visit all node at same level from top then left of same level and then right ) Depth First Search (a) Inorder (Left, Root, Right) (b) Preorder (Root, Left, Right) (c) Postorder (Left, Right, Root) # Python program to for tree traversals # A class that represents an individual node in a # Binary Tree class Node: def __init__(self,key): self.left = None self.right = None self.val = key # A function to do inorder tree traversal def printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversal def printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversal def printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print ("Preorder traversal of binary tree is") printPreorder(root) print ("\nInorder traversal of binary tree is") printInorder(root) print ("\nPostorder traversal of binary tree is") printPostorder(root) # INSERTION IN A BINARY TREE # Python program to insert element in binary tree class newNode(): def __init__(self, data): self.key = data self.left = None self.right = None """ Inorder traversal of a binary tree""" def inorder(new_node): if (not new_node): return inorder(new_node.left) print(new_node.key,end = " ") inorder(new_node.right) """function to insert element in binary tree """ def insert(new_node,key): q = [] q.append(new_node) # Do level order traversal until we find # an empty place. while (len(q)): new_node = q[0] q.pop(0) if (not new_node.left): new_node.left = newNode(key) break else: q.append(new_node.left) if (not new_node.right): new_node.right = newNode(key) break else: q.append(new_node.right) # Driver code if __name__ == '__main__': root = newNode(10) root.left = newNode(11) root.left.left = newNode(7) root.right = newNode(9) root.right.left = newNode(15) root.right.right = newNode(8) print("Inorder traversal before insertion:", end = " ") inorder(root) key = 12 insert(root, key) print() print("Inorder traversal after insertion:", end = " ") inorder(root) #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< BINARY SEARCH TREE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Binary Search Tree is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. Elements are always unique in BST # A utility function to search a given key in BST def search(root,key): # Base Cases: root is null or key is present at root if root is None or root.val == key: return root # Key is greater than root's key if root.val < key: return search(root.right,key) # Key is smaller than root's key return search(root.left,key)
dict = {'jason':'dichoso','gloria':'tran'} listConvert = dict.items() #print(str(dict)) print(str(listConvert)) for firstName, lastName in listConvert: print(firstName + ' ' + lastName)
import pygame from pygame import gfxdraw import sys,time, math pygame.init() screen = pygame.display.set_mode((600,480)) running = 1 blue = 0,0,255 white = 255, 255, 255 black = 0,0,0 while running: event = pygame.event.poll() if event.type == pygame.QUIT: running = 0 screen.fill(black) for i in range(20): print('Entered') pygame.draw.circle(screen, white, (250,120+(10*i)), 30+i,1) pygame.display.update() screen.fill(black) pygame.time.delay(50) for i in range(20): print('Entered') pygame.draw.circle(screen, white, (250,250-(10*i)), 45+i,1) pygame.display.update() screen.fill(black) pygame.time.delay(50) pygame.time.delay(100) for i in range(20): print('Entered') pygame.draw.circle(screen, white, (250,120+(10*i)), 60+i,1) pygame.display.update() screen.fill(black) pygame.time.delay(50) for i in range(20): print('Entered') pygame.draw.circle(screen, white, (250,250-(10*i)), 75+i,1) pygame.display.update() screen.fill(black) pygame.time.delay(50) pygame.time.delay(100) for i in range(20): print('Entered') pygame.draw.circle(screen, white, (250,120+(10*i)), 90+i,1) pygame.display.update() screen.fill(black) pygame.time.delay(50) for i in range(20): print('Entered') pygame.draw.circle(screen, white, (250,250-(10*i)), 105+i,1) pygame.display.update() screen.fill(black) pygame.time.delay(50)
#Considerações: o preço do produto sepre será positivo. from firebase import firebase firebase=firebase.FirebaseApplication('https://ep-design-software.firebaseio.com/', None) result=firebase.get('EP',None) loja=input('Nome da loja:') dicionario=result acao=int(input(''' Controle do estoque 0 - sair 1 - adicionar item 2 - remover item 3 - alterar item 4 - imprimir estoque Faça sua escolha: ''')) try: if loja not in dicionario['lojas']: dicionario['lojas'][loja]={'estoque':{},'Lista de produtos em falta':[]} except TypeError: dicionario={'lojas':{loja:{'estoque':{},'Lista de produtos em falta':[]}}} while acao!=0: if acao==1: produto=input('Nome do produto: ') if produto not in dicionario['lojas'][loja]['estoque']: quantidade=int(input('Quantidade inicial:')) while quantidade<0: print('A quantidade inicial não pode ser negativa.') quantidade=int(input('Quantidade inicial:')) preco=float(input('Preço do produto:')) while preco<0: print('O preço do produto não pode ser negativo') preco=float(input('Preço do produto:')) dicionario['lojas'][loja]['estoque'][produto]={'quantidade':quantidade, 'preço':preco} if dicionario['lojas'][loja]['estoque'][produto]['quantidade']==0: dicionario['lojas'][loja]['Lista de produtos em falta'].append(produto) else: print('Produto já cadastrado.') elif acao==2: produto=input('Nome do produto: ') if produto not in dicionario['lojas'][loja]['estoque']: print('Elemento não encontrado.') else: print('{0} removido com sucesso.'.format(produto)) del dicionario['lojas'][loja]['estoque'][produto] if produto in dicionario['lojas'][loja]['Lista de produtos em falta']: dicionario['lojas'][loja]['Lista de produtos em falta'].remove(produto) elif acao==3: produto=input('Nome do produto: ') if produto not in dicionario['lojas'][loja]['estoque']: print('Elemento não encontrado.') else: quantidade=int(input('Quantidade: ')) dicionario['lojas'][loja]['estoque'][produto]['quantidade']+=quantidade if dicionario['lojas'][loja]['estoque'][produto]['quantidade'] <= 0 : dicionario['lojas'][loja]['Lista de produtos em falta'].append(produto) else: if produto in dicionario['lojas'][loja]['Lista de produtos em falta']: dicionario['lojas'][loja]['Lista de produtos em falta'].remove(produto) pergunta=input('Alterar preco? 1 para sim e 0 para não.') if pergunta=='1': preco=float(input('Preço do produto:')) while preco<0: print('O preço do produto não pode ser negativo.') preco=float(input('Preço:')) dicionario['lojas'][loja]['estoque'][produto]['preço']=preco elif acao==4: soma = 0 for produto in dicionario['lojas'][loja]['estoque']: if dicionario['lojas'][loja]['estoque'][produto]['quantidade']>0: print('{0} : {1}'.format(produto, dicionario['lojas'][loja]['estoque'][produto]['quantidade'])) soma += dicionario['lojas'][loja]['estoque'][produto]['quantidade'] * dicionario['lojas'][loja]['estoque'][produto]['preço'] else: print(('{0} : {1}'.format(produto, 'Produto indisponível'))) print('O valor total do estoque é: {0} reais'.format(soma)) if len(dicionario['lojas'][loja]['Lista de produtos em falta']) > 0: print('Os produtos que estão em falta são: {0}'.format(dicionario['lojas'][loja]['Lista de produtos em falta'])) else: print('Não há produtos em falta.') else: print('Comando inválido.') acao=int(input(''' Controle do estoque 0 - sair 1 - adicionar item 2 - remover item 3 - alterar item 4 - imprimir estoque Faça sua escolha: ''')) firebase.put('https://ep-design-software.firebaseio.com/','EP',dicionario) print("Até mais!")
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'Emmanuel Barillot' # exemple pris ici : http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key import collections my_dict = {'carl': 40, 'alan': 2, 'bob': 1, 'danny': 3} my_items = my_dict.items() my_sorted_dict = sorted(my_items, key=lambda t : t[0]) od = collections.OrderedDict(my_sorted_dict) #od = collections.OrderedDict(sorted(my_dict.items())) print(">>> mydict:") for key,val in my_dict.items(): print("%s: %s" % (key, val)) print("") print(">>> od:") for key,val in od.items(): print("%s: %s" % (key, val)) od2 = collections.OrderedDict((('abc',10),('bcd',2))) print(">>> od2:") for key,val in od2.items(): print("%s: %s" % (key, val))
# -*- coding: utf-8 -*- import platform def polydiv(A,B): """ Calcul de la division de deux polynomes A / B Retourne [Q,R] le quotient et le reste de telle façon que A = B*Q+R """ Q = [0] # quotient R = A # reste while (polydegre(R) >= polydegre(B)): #print ("degre R = {}".format(polydegre(R))) #print ("degre B = {}".format(polydegre(B))) P = monome(R[polydegre(R)],polydegre(R)-polydegre(B)) #print ("P = {}".format(P)) R = polysomme(R,polyproduit(polymul(-1,P),B)) #print ("R = {}".format(R)) Q = polysomme(Q,P) #print ("Q = {}".format(Q)) #raw_input() return Q,R def polysomme(A,B): """ Somme de deux polynomes de degrés différents ou égaux """ degA = polydegre(A) degB = polydegre(B) plus_grand_degre = degA if (degA < degB): plus_grand_degre = degB C = [0]*(plus_grand_degre+1) for i in range(0,degA+1): C[i] = A[i] for i in range(0,degB+1): C[i] = C[i] + B[i] return C def polymul(c,P): """ Multiplication d'un polynome par un scalaire """ return [c*x for x in P] def monome(c,d): """ Construit un monome d'un degre donne et de coefficient donne """ P = [0]*(d+1) P[d] = c return P def polydegre(A): """ Degre d'un polynome """ deg = len(A)-1 while (A[deg] == 0 and deg >= 0): deg = deg -1 return deg def polyproduit(A,B): """ Produit de 2 polynomes """ C = [] for k in range(polydegre(A)+polydegre(B)+1): s = 0 for i in range(k+1): if (i <= polydegre(A)) and (k-i <= polydegre(B)): s = s + A[i]*B[k-i] C.append(s) return C if __name__ == "__main__" : pltf = platform.python_version() if '2.7' in pltf: print ("Plateforme python {} OK".format(pltf)) else: print("ATTENTION : ce script a été développé et testé pour python 2.7") print(" Il risque de ne pas fonctionner en python {}".format(pltf)) PA = [1,1,1,1,1] PB = [1,1,1,1] print "A = {}".format(PA) print "B = {}".format(PB) Q,R = polydiv(PA,PB) print "{} = {} x {} + {}".format(PA,PB,Q,R) Q,R = polydiv(PB,PA) print "{} = {} x {} + {}".format(PB,PA,Q,R) PA = [5,-4,3,2,-1] PB = [1,0,-1,1] Q,R = polydiv(PA,PB) print "{} = {} x {} + {}".format(PA,PB,Q,R)
import math as m from decimal import Decimal def develop_dyad(x, n=10): """ Calcul du développement dyadique propre à l'ordre n """ dd = [] x0 = 0. x1 = int(2.0*x) print (x0,x1) dd.append(x1) for i in range(1,n): x0 = x0 + x1 / (2.0**(i)) # attention, ne pas mettre i+1 ##print ("[{}] x0={}".format(i,x0)) x1 = int(2.0**(i+1)*(x-x0)) ##print ("[{}] x1={}".format(i,x1)) dd.append(x1) ##print (i,x0,x1) return dd def compose_dyad(dd): """ Compose un nombre x à partir de son développement dyadique propre à l'ordre n """ x = 0. for i in range(len(dd)): x = x + dd[i] / (2.0**(i+1)) # attention, ne pas mettre i+1 ##print ("[{}] x={}".format(i,x)) return x # x doit être dans [0,1[ x = Decimal(m.pi / 4.) ##x = 1./3. n = 50 print ("x = %f" % x) dd = develop_dyad(x, n) print (dd) print (compose_dyad(dd))
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'Emmanuel Barillot' """ Code expérimental pour tester les différentes façon de voir si un objet est iterable """ from traceback import print_exc # Duck typing def is_iterable(theElement): try: iterator = iter(theElement) except TypeError: # not iterable print_exc() pass else: # iterable pass # for obj in iterator: # pass # Type checking import collections def is_iterable(theElement): if isinstance(theElement, collections.Iterable): # iterable pass else: # not iterable pass def is_iterable(theElement): try: #treat object as iterable pass except TypeError, e: #object is not actually iterable print_exc() pass def iterable(a): try: (x for x in a) return True except TypeError: print_exc() return False isiterable = lambda obj: isinstance(obj, basestring) \ or getattr(obj, '__iter__', False)
def creat(user,password): with open('account.txt','a') as file: file.write(f'{user} {password}\n') def loginfunction(user,password): logininfo = f'{user} {password}' with open('account.txt','r') as file: users = file.readlines() loop = True f= 0 while loop: if logininfo in str(users[f]): print("login sucssesful") break f +=1 if f == users.__len__(): print("Try Again") loop = False choice = True while choice: print("1.creat") print('2.login') print('3.exit') var = int(input("select opetion:-")) if var == 1: name = input("Enter name :-") password = input("Enter the password:-") creat(name,password) elif var == 2: name = input("Enter name :-") password = input("Enter the password:-") loginfunction(name,password) elif var == 3: choice = False
#!/usr/bin/env python3 """ In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem. Here are data files describing three graphs: g1.txt g2.txt g3.txt The first line indicates the number of vertices and edges, respectively. Each subsequent line describes an edge (the first two numbers are its tail and head, respectively) and its length (the third number). NOTE: some of the edge lengths are negative. NOTE: These graphs may or may not have negative-cost cycles. Your task is to compute the "shortest shortest path". Precisely, you must first identify which, if any, of the three graphs have no negative cycles. For each such graph, you should compute all-pairs shortest paths and remember the smallest one (i.e., compute minu,v∈Vd(u,v), where d(u,v) denotes the shortest-path distance from u to v). If each of the three graphs has a negative-cost cycle, then enter "NULL" in the box below. If exactly one graph has no negative-cost cycles, then enter the length of its shortest shortest path in the box below. If two or more of the graphs have no negative-cost cycles, then enter the smallest of the lengths of their shortest shortest paths in the box below. """ import copy, time import numpy as np from multiprocessing import Pool from heapq import heappush, heappop class Solution: def __init__(self, fname): self.G = {} # The format of G should be in the dictionary form of # {tail_1: [(head_1, weight_1), head_2, weight_2), head_3, weight_3), ...], tail_2: [...], ....} # we also use 1-base index for vertices with open(fname, 'r') as f: self.n, self.m = list(map(int, f.readline().split())) for line in f.readlines(): tail, head, weight = list(map(int, line.split())) if tail not in self.G: self.G[tail] = [(head, weight)] else: self.G[tail].append((head, weight)) # one more pass to fill possible vertex with no out-edge for i in range(1, self.n+1): if i not in self.G: self.G[i] = [] def Bellman_Ford(self, s, G): """ implementation of Bellman-Ford algorithm to find shorted path between vertex s and all vertices, given the graph G. The format of G should be in the dictionary form of {tail_1: [(head_1, weight_1), head_2, weight_2), head_3, weight_3), ...], tail_2: [...], ....} """ # dp array, the shortest path from t to each vertex n = len(G.keys()) dp = {v: float('inf') for v in range(1, n+1)} dp[s] = 0 # init step # main loop, run for n-1 time # print('Running Bellman-Ford algorithm...') for i in range(n-1): print('Step {} of {}...'.format(i, n), end='\r') dp_last = dp.copy() # inner for-loop, looping through all vertices # I will 'push' the new values to the head vertex for v in G.keys(): for h, w in G[v]: dp[h] = min(dp[h], dp[v] + w) # check for early stop if dp == dp_last: print('\nEarly termination of Bellman-Ford.') return dp else: dp_last = dp.copy() # check for negative cost cycle for v in G.keys(): for h, w in G[v]: dp[h] = min(dp[h], dp[v] + w) if dp != dp_last: print('\nThere is a negative cost cycle. Exit the algorithm.') return None return dp def dijkstra_heap(self, start, G, weigths): # this is the implementation with heap, to get O(mlogn) time # modified from here: https://gist.github.com/kachayev/5990802 # modified for this purpose Q = [(0, start)] # this is the unvisited heap visited = set() # this is the visited nodes dist = {} # collect distances while Q: # as long as there are still unvisited nodes (cost, node) = heappop(Q) if node not in visited: dist[node] = cost visited.add(node) # put it in the visited list for child, weight in G[node]: if child not in visited: heappush(Q, (weight + cost, child)) res = float('inf') # get the un-weighted s-t path for t in dist: res = min(res, dist[t] - weigths[t] + weigths[start]) return res def APSP_1(self): """ vanilla implemenation of all-pair shortest path looping through all vertex, inovke Bellman-Ford at each vertex """ t_start = time.time() res = float('inf') for s in self.G.keys(): print('Working on node {} of total {} nodes... time elapsed: {:5.2f} minutes.'\ .format(s, self.n, (time.time() - t_start)/60)) dp = self.Bellman_Ford(s, self.G) if dp is None: print('\nThere is a negative cost cycle. Exit the algorithm.') return None res = min(res, min(dp.values())) return res def APSP_2(self): # Floyd-Warshall algorithm # n x n array, in dict form 0-based # A = [[float('inf') for _ in range(self.n)] for _ in range(self.n)] # n x n array, in dict form 0-based # A = {i: {j: float('inf') for j in range(self.n)} for i in range(self.n)} # 3D array A = np.full(shape=(self.n, self.n, self.n), fill_value=float('inf')) # first pass for i in self.G: # v is 1-based index A[0, i-1, i-1] = 0 for (j, c) in self.G[i]: A[0, i-1, j-1] = c # main loop, looping through k t_start = time.time() for k in range(1, self.n): print('Running step {} of total {}. Previous minimum: {}. Time elapsed: {:5.2f} minutes.'\ .format(k+1, self.n, A.min(), (time.time() - t_start)/60), end='\r') for i in range(self.n): for j in range(self.n): A[k, i, j] = min(A[k-1, i, j], (A[k-1, i, k] + A[k-1, k, j])) # check for negative cost cycle, also check for result for i in range(self.n): if A[k, i, i] < 0: print('\nThere is a negative cost cycle.') return None return A.min() def APSP_3(self): # Johnson's algorithm res = float('inf') # first pass, add a nominal vertex, and run Bellman Ford on it self.G[self.n + 1] = [(h, 0) for h in range(1, self.n + 1)] # get the dict of node weigths self.weights = self.Bellman_Ford(self.n+1, self.G) # 1-index based del self.G[self.n + 1] # rewegith all the edges, to get the new graph self.G_new = {} for tail in self.G: for h, w in self.G[tail]: if tail not in self.G_new: self.G_new[tail] = [(h, w + self.weights[tail] - self.weights[h])] else: self.G_new[tail].append((h, w + self.weights[tail] - self.weights[h])) # multi process run n_proc = 10 with Pool(processes=n_proc) as pool: res = pool.map(self.run_dijkstra, self.split_list(list(self.G_new.keys()), n_proc)) return res def run_dijkstra(self, start_list): t_start = time.time() res = float('inf') for i, s in enumerate(start_list): print('Running Dijkstra on node {} of total of {}... Time elapsed: {:5.1f} minutes.'\ .format(i+1, len(start_list), (time.time() - t_start)/60), end='\r') res = min(res, self.dijkstra_heap(s, self.G_new, self.weights)) return res def split_list(self, l, k): chunk_size = len(l)//k+1 list_of_lists = [l[i:i+chunk_size] for i in range(0,len(l),chunk_size)] return list_of_lists if __name__ == '__main__': fname = 'large.txt' # the answer is -6 (?) # fname = 'g3.txt' S = Solution(fname) res = S.APSP_3()
#!/usr/bin/env python3 """ This file describes an undirected graph with integer edge costs. It has the format [number_of_nodes] [number_of_edges] [one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost] [one_node_of_edge_2] [other_node_of_edge_2] [edge_2_cost] ... For example, the third line of the file is "2 3 -8874", indicating that there is an edge connecting vertex #2 and vertex #3 that has cost -8874. You should NOT assume that edge costs are positive, nor should you assume that they are distinct. Your task is to run Prim's minimum spanning tree algorithm on this graph. You should report the overall cost of a minimum spanning tree --- an integer, which may or may not be negative --- in the box below. IMPLEMENTATION NOTES: This graph is small enough that the straightforward O(mn) time implementation of Prim's algorithm should work fine. OPTIONAL: For those of you seeking an additional challenge, try implementing a heap-based version. The simpler approach, which should already give you a healthy speed-up, is to maintain relevant edges in a heap (with keys = edge costs). The superior approach stores the unprocessed vertices in the heap, as described in lecture. Note this requires a heap that supports deletions, and you'll probably need to maintain some kind of mapping between vertices and their positions in the heap. """ from heapq import heappush, heappop import time class Solution(object): def __init__(self, fname): self.G_1 = {} self.G_2 = {} # this is for the heap implementation self.E = [] # this will be a heap, with cost as the key with open(fname, 'r') as f: self.n, self.m = f.readline().split() for line in f.readlines(): n1, n2, cost = list(map(int, line.split())) # process n1 if n1 not in self.G_1: self.G_1[n1] = [(n2, cost)] else: self.G_1[n1].append((n2, cost)) # process n2 if n2 not in self.G_1: self.G_1[n2] = [(n1, cost)] else: self.G_1[n2].append((n1, cost)) # ===== below if for the heap implementation if n1 not in self.G_2: self.G_2[n1] = [(cost, n2)] else: heappush(self.G_2[n1], (cost, n2)) if n2 not in self.G_2: self.G_2[n2] = [(cost, n1)] else: heappush(self.G_2[n2], (cost, n1)) # to store edges as heap heappush(self.E, (cost, n1, n2)) def run1(self): # vanilla implementation of Prim's algorithm with O(mn) time visited = set() MST_cost = 0 # visit a random first node start = list(self.G_1.keys())[0] visited.add(start) # main loop while len(visited) < len(self.G_1): tmp_min = float('inf') candidate = -1 # find next node to absorbe for node in visited: for end, cost in self.G_1[node]: if end not in visited: if cost < tmp_min: tmp_min, candidate = cost, end visited.add(candidate) MST_cost += tmp_min return MST_cost def check_crossing(self, n1, n2, S1, S2): # return True is the edge (n1, n2) crosses the cut (S1, S2) if ((n1 in S1) and (n2 in S2)) or ((n1 in S2) and (n2 in S1)): return True else: return False def check_one_set(self, n1, n2, S): # return True if the edge (n1, n2) lies in the set S if (n1 in S) and (n2 in S): return True else: return False def run2(self): # fast implementation 1 with heap visited = set() unvisited = set(self.G_2.keys()) MST_cost = 0 # visit a random first node start = list(self.G_1.keys())[0] visited.add(start) unvisited.remove(start) # main loop while len(unvisited) > 0: # print('visited ', visited) # print('unvisited ', unvisited) tmp_list = [] cost, n1, n2 = heappop(self.E) while not self.check_crossing(n1, n2, visited, unvisited) and len(self.E) > 0: # not a crossing edge if self.check_one_set(n1, n2, unvisited): tmp_list.append((cost, n1, n2)) # we will push this back to the heap later cost, n1, n2 = heappop(self.E) # we will only exit if we have found a crossing edge # print(n1, n2) MST_cost += cost if n1 in visited: visited.add(n2) unvisited.remove(n2) else: visited.add(n1) unvisited.remove(n1) # we will push the edges lie in unvisited set back into the heap for x in tmp_list: heappush(self.E, x) return MST_cost if __name__ == '__main__': fname = 'hw1_3.txt' S = Solution(fname) t1 = time.time() print('MST cost with run 1 is: {}'.format(S.run1())) print('Time of run 1 is: {:3.6f} seconds'.format(time.time() - t1)) t2 = time.time() print('\nMST cost with run 2 is: {}'.format(S.run2())) print('Time of run 2 is: {:3.6f} seconds'.format(time.time() - t2))
import math start = input("Do you wanna know the volume of your theoretical ball? Yes (y) or no (n)?") b = "Bye." i = "Invalid answer." while start == "y": radius = input("Input the radius you wanna use.") volume = ((4/3)*(math.pi))*(int(radius)*int(radius)*int(radius)) print("The volume of your theoretical ball is " + str(volume)) again = input("Wanna play again? Yes (y) or no (n)") if again == "y": start = "y" if again == "n": start = "n" if start == "n": sure = input("You sure?") if sure == "y": print(b) if sure == "n": play = input("Do you wanna know the volume of your theoretical ball? Yes (y) or no (n)?") if play == "y": start == "y" if play == "no": start = "bitch" if start == "bitch": print(b) else: print(i)
num = float(input()) print('{0:.6f}'.format(num % 1))
hamlet = int(input()) dist1 = list(map(int, input().split())) shelter = int(input()) dist2 = list(map(int, input().split())) dist_ham = [] for i in range(dist1): list_hamlet = (dist1[i], i) dist_ham.append(list_hamlet) dist_shelt = [] for i in range(dist2): list_shelter = (dist2[i], i) dist_shelt.append(list_shelter) dist_ham.sort() dist_shelt.sort() print(dist_ham, dist_shelt)
def power(a, n): if n == 0: return 1 if a == 0: return 0 num = a if n % 2 == 1: num = num * power(a, n - 1) return num if n % 2 == 0: return power(a, n / 2) ** 2 a = float(input()) n = int(input()) print(power(a, n))
high = int(input()) dayDist = int(input()) nightDist = int(input()) generalDist = 0 days = 0 while True: # print("Dist is:", generalDist) generalDist = generalDist + dayDist days = days + 1 if generalDist < high: generalDist = generalDist - nightDist else: break print(days)
hour1 = int(input()) minute1 = int(input()) second1 = int(input()) hour2 = int(input()) minute2 = int(input()) second2 = int(input()) print((hour2-hour1)*3600 + (minute2-minute1)*60 + second2 - second1)
# Variable # autograd.Variable is the central class of the package. It wraps a Tensor, # and supports nearly all of operations defined on it. Once you finish your # computation you can call .backward() and have all the gradients computed automatically. # # You can access the raw tensor through the .data attribute, while the gradient w.r.t. # this variable is accumulated into .grad. # There's one more class which is very important for autograd implementation - a Function. # # Variable and Function are interconnected and build up an acyclic graph, # that encodes a complete history of computation. Each variable has a .grad_fn attribute # that references a Function that has created the Variable (except for Variables created by # the user - their grad_fn is None). # # If you want to compute the derivatives, you can call .backward() on a Variable. # If Variable is a scalar (i.e. it holds a one element data), you don't need to specify # any arguments to backward(), however if it has more elements, you need to specify a # gradient argument that is a tensor of matching shape. import torch from torch.autograd import Variable x = Variable(torch.ones(2, 2), requires_grad=True) print(x) y = 2 * x + 2 print(y) print(y.grad_fn) # grad can be implicitly created only for scalar outputs # so if y is not a scalar but an array, we cannot use y.backward() z = y * y * 3 out = z.mean() # out = z.max() all have the same gradient print("z and out: ", z, out) out.backward() print(x.grad) x = torch.randn(3) print(x) x = Variable(x, requires_grad=True) y = x * 2 print("data of y:", y.data) # data.norm is different from norm # http://pytorch.org/docs/stable/torch.html#torch.norm while y.data.norm() < 10: y = y * 3; print(y) grad = torch.FloatTensor([0.1, 1.0, 0.0001]) y.backward(grad) print(x.grad) # 3*3*2
# -*- coding: utf-8 -*- """ Created on Sun Sep 13 16:19:35 2020 @author: striver """ def heapify(tree, n, i): if i>=n: return c1 = 2*i+1 c2 = 2*i+2 max_=i if c1 < n and tree[c1] > tree[max_]: max_ = c1 if c2 < n and tree[c2] > tree[max_]: max_ = c2 if max_ != i: tree[i],tree[max_]=tree[max_],tree[i] heapify(tree, n, max_) def build_heap(tree, n): last_node=n-1 parent=(last_node-1)//2 for i in range(parent,-1,-1): heapify(tree,n,i) def heap_sort(tree, n): build_heap(tree,n) for i in range(n-1,-1,-1): tree[0],tree[i]=tree[i],tree[0] heapify(tree,i,0) tree=[4,10,3,5,1,2] n=6 #heapify(tree,n,0) #build_heap(tree,n) heap_sort(tree,n) for i in range(n): print(tree[i])
class XML_Validator(object): """ This class contains all the static methods necessary to check an XML file's validation. #XML documents must have the version number #and the language encoding on the first line #XML documents must have a root element #XML elements must have a closing tag #XML tags are case sensitive #XML elements must be properly nested #XML attribute values must be quoted """ #This static method checks the filename to see if it ends with a ".xml" exstension. #If True, then the file is supposed to be an XML file. #If False, then either the file's extension was not added or the file is not an XML file. def xml_file_check(self, filename):#Finished if filename[-4:] != ".xml": return False else: return True # def __init__(self, filename):#Finished if self.xml_file_check(filename): #This variable will hold the object that reads through the XML file. self.xml_file = open(filename, "r") #This variable will be used as a dictionary to store the element names. self.tag_list = {} #This variable will store the string name of the current tag that the file stream is on. self.current_tag = "" # self.version = "" # self.declaration = "" # self.encoding = "" #This method is used to fill the tag list with an element tag from the XML that we are #currently looking at. The tag list will be a ditionary that holds the name of the #element and its nest level in the XML file. def fill_tag_list(self, tag_name, level): self.tag_list[tag_name] = level #This method will be used to check to make sure that the first line in the XML file is #the version number and language encoding. def check_for_declaration(self):#Finished self.xml_file.seek(0) firstline = self.xml_file.readline() if firstline[:2] != "<?": return False num = firstline.find("?>", 0, len(firstline)) if num == -1: return False self.declaration = firstline[:num+2] return True # def get_version(self):#Finished test = self.declaration.find("\"", 2, len(self.declaration)) if test == -1: return False if self.declaration[test+1:test+3] != "1.": return False return self.declaration[test+1:self.declaration.find("\"", test+3, len(self.declaration))] # def print_file(self):#Finished #self.check_for_declaration() #print self.xml_file.seek(len(self.declaration)) for line in self.xml_file: print line # def xml_check_attrib(self): pass # def xml_check_nest(self): self.check_for_declaration() self.xml_file.seek(len(self.declaration)) firstline = self.xml_file.readline() #self.print_file() # def xml_close_check(self):#Finished if self.xml_file.closed(): True else: False # def xml_file_close(self):#Finished self.xml_file.close()
i = 1 while i < 9: print(i) i += 1 else: print("i is no longer less than 9")
balance=20000 card= input("enter the card") language= input("enter the language") account= input("enter the account") password=int(input("enter the password")) amount= int(input("enter the amount")) receipt= input("enter the receipt") if card=="debit card": if language=="enghish": if account== "saveing": if password== 123456: if amount > 0 and amount <=2000: print("your translete is comolet now your balance is",balance-amount) if receipt=="yes": print ("sucsful") else: print("a") else: print("b") else: print("c") else: print("account is current") else: print("hindi") else: print("card is correct")
print("AREA OF CIRCLE!!") r = input("Radius: ") r = float(r) def area(r): pi = 3.142 return pi*( r * r ) print("The area of the circle of radius {1} is {0}".format(area(r), r)) print("___________________________________") print("PRIME NUMBERS!!") p = input("Prime numbers upto: ") p = int(p) for i in range (1, p+1): if i > 1: for n in range(2, p): if (i%n)==0: break else : print(i) print("____________________________________") print("PATTERNS!!") n = input("Number of rows:") n = int(n) for i in range(0, n): for j in range(0, i+1): print("* ", end = "") print(" ") x = 1 for i in range(0, n): for j in range(0, i+1): print(x , end = "") x+=1 print(" ")
# coding: utf-8 def length_of_words(s): return [len(x.rstrip(",")) for x in s.split(" ")] if __name__ == "__main__": s = "Now I need a drink, alcoholic of course, " +"after the heavy lectures involving quantum mechanics." length_list = length_of_words(s) print(length_list)
# coding: utf-8 def pick_odd_chars(s): return s[::2] if __name__ == "__main__": s = "パタトクカシーー" print(pick_odd_chars(s))
def txt_reader(file_name): txt_lst = [] with open(file_name, 'r') as f: for line in f.readlines(): txt_lst.append(line.split('\t')) return txt_lst def get_most_played(file_name): txt = txt_reader(file_name) maxi = 0 game_name = '' for line in txt: if float(line[1]) > float(maxi): maxi = line[1] game_name = line[0] return game_name def sum_sold(file_name): txt = txt_reader(file_name) solded = 0 for line in txt: solded += float(line[1]) return solded def get_selling_avg(file_name): txt = txt_reader(file_name) counter = 0 solded = 0 for line in txt: solded += float(line[1]) counter += 1 avg_sell = solded / counter return avg_sell def count_longest_title(file_name): txt = txt_reader(file_name) longest_title = '' for line in txt: if len(line[0]) > len(longest_title): longest_title = line[0] return len(longest_title) def get_date_avg(file_name): txt = txt_reader(file_name) sum_year = 0 counter = 0 for line in txt: sum_year += int(line[2]) counter += 1 average_year = sum_year / counter return round(average_year) def get_game(file_name, title): txt = txt_reader(file_name) game_line = [] for line in txt: if title == line[0]: game_line = line game_line = [i.rstrip() for i in game_line] for item in game_line: game_line[1] = float(game_line[1]) game_line[2] = int(game_line[2]) return game_line def count_grouped_by_genre(file_name): txt = txt_reader(file_name) group = {} for line in txt: if not line[3] in group: group[line[3]] = 1 else: group[line[3]] += 1 return group def get_date_ordered(file_name): txt = txt_reader(file_name) txt.sort(key=lambda x: x[0]) txt.sort(key=lambda x: x[2], reverse=True) ordered = [] for line in txt: ordered.append(line[0]) return(ordered) print(get_date_ordered('game_stat.txt'))
import tensorflow as tf from tensorflow import keras ########################## #最简单的模型使用Sequential只有一个输入一个输出 model = keras.Sequential() # Adds a densely-connected layer with 64 units to the model: model.add(keras.layers.Dense(64, activation='relu')) # Add another: model.add(keras.layers.Dense(64, activation='relu')) # Add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) #配置训练的参数 model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) import numpy as np #拟合你的数据用fit data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) val_data = np.random.random((100, 32)) val_labels = np.random.random((100, 10)) model.fit(data, labels, epochs=10, batch_size=32, validation_data=(val_data, val_labels)) #评估模型 model.evaluate(x, y, batch_size=32) model.evaluate(dataset, steps=30) #预测数据 model.predict(x, batch_size=32) model.predict(dataset, steps=30) ############################ #使用函数式api构建模型,可以多输入多输出 inputs = keras.Input(shape=(32,)) # Returns a placeholder tensor # A layer instance is callable on a tensor, and returns a tensor. x = keras.layers.Dense(64, activation='relu')(inputs) x = keras.layers.Dense(64, activation='relu')(x) predictions = keras.layers.Dense(10, activation='softmax')(x) # Instantiate the model given inputs and outputs. model = keras.Model(inputs=inputs, outputs=predictions) # The compile step specifies the training configuration. model.compile(optimizer=tf.train.RMSPropOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) # Trains for 5 epochs model.fit(data, labels, batch_size=32, epochs=5) ########################## ########################## #构建子类模型 class MyModel(keras.Model): def __init__(self, num_classes=10): super(MyModel, self).__init__(name='my_model') self.num_classes = num_classes # Define your layers here. self.dense_1 = keras.layers.Dense(32, activation='relu') self.dense_2 = keras.layers.Dense(num_classes, activation='sigmoid') def call(self, inputs): # Define your forward pass here, # using layers you previously defined (in `__init__`). x = self.dense_1(inputs) return self.dense_2(x) def compute_output_shape(self, input_shape): # You need to override this function if you want to use the subclassed model # as part of a functional-style model. # Otherwise, this method is optional. shape = tf.TensorShape(input_shape).as_list() shape[-1] = self.num_classes return tf.TensorShape(shape) # Instantiates the subclassed model. model = MyModel(num_classes=10) # The compile step specifies the training configuration. model.compile(optimizer=tf.train.RMSPropOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) # Trains for 5 epochs. model.fit(data, labels, batch_size=32, epochs=5) ########################################## Keras Keras is a high-level API to build and train deep learning models. It's used for fast prototyping, advanced research, and production, with three key advantages: User friendly Keras has a simple, consistent interface optimized for common use cases. It provides clear and actionable feedback for user errors. Modular and composable Keras models are made by connecting configurable building blocks together, with few restrictions. Easy to extend Write custom building blocks to express new ideas for research. Create new layers, loss functions, and develop state-of-the-art models. Import tf.keras tf.keras is TensorFlow's implementation of the Keras API specification. This is a high-level API to build and train models that includes first-class support for TensorFlow-specific functionality, such as eager execution, tf.data pipelines, and Estimators. tf.keras makes TensorFlow easier to use without sacrificing flexibility and performance. To get started, import tf.keras as part of your TensorFlow program setup: import tensorflow as tf from tensorflow import keras tf.keras can run any Keras-compatible code, but keep in mind: The tf.keras version in the latest TensorFlow release might not be the same as the latest keras version from PyPI. Check tf.keras.version. When saving a model's weights, tf.keras defaults to the checkpoint format. Pass save_format='h5' to use HDF5. Build a simple model Sequential model In Keras, you assemble layers to build models. A model is (usually) a graph of layers. The most common type of model is a stack of layers: the tf.keras.Sequential model. To build a simple, fully-connected network (i.e. multi-layer perceptron): model = keras.Sequential() # Adds a densely-connected layer with 64 units to the model: model.add(keras.layers.Dense(64, activation='relu')) # Add another: model.add(keras.layers.Dense(64, activation='relu')) # Add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) Configure the layers There are many tf.keras.layers available with some common constructor parameters: activation: Set the activation function for the layer. This parameter is specified by the name of a built-in function or as a callable object. By default, no activation is applied. kernel_initializer and bias_initializer: The initialization schemes that create the layer's weights (kernel and bias). This parameter is a name or a callable object. This defaults to the "Glorot uniform" initializer. kernel_regularizer and bias_regularizer: The regularization schemes that apply the layer's weights (kernel and bias), such as L1 or L2 regularization. By default, no regularization is applied. The following instantiates tf.keras.layers.Dense layers using constructor arguments: # Create a sigmoid layer: layers.Dense(64, activation='sigmoid') # Or: layers.Dense(64, activation=tf.sigmoid) # A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix: layers.Dense(64, kernel_regularizer=keras.regularizers.l1(0.01)) # A linear layer with L2 regularization of factor 0.01 applied to the bias vector: layers.Dense(64, bias_regularizer=keras.regularizers.l2(0.01)) # A linear layer with a kernel initialized to a random orthogonal matrix: layers.Dense(64, kernel_initializer='orthogonal') # A linear layer with a bias vector initialized to 2.0s: layers.Dense(64, bias_initializer=keras.initializers.constant(2.0)) Train and evaluate Set up training After the model is constructed, configure its learning process by calling the compile method: model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) tf.keras.Model.compile takes three important arguments: optimizer: This object specifies the training procedure. Pass it optimizer instances from the tf.train module, such as AdamOptimizer, RMSPropOptimizer, or GradientDescentOptimizer. loss: The function to minimize during optimization. Common choices include mean square error (mse), categorical_crossentropy, and binary_crossentropy. Loss functions are specified by name or by passing a callable object from the tf.keras.losses module. metrics: Used to monitor training. These are string names or callables from the tf.keras.metrics module. The following shows a few examples of configuring a model for training: # Configure a model for mean-squared error regression. model.compile(optimizer=tf.train.AdamOptimizer(0.01), loss='mse', # mean squared error metrics=['mae']) # mean absolute error # Configure a model for categorical classification. model.compile(optimizer=tf.train.RMSPropOptimizer(0.01), loss=keras.losses.categorical_crossentropy, metrics=[keras.metrics.categorical_accuracy]) Input NumPy data For small datasets, use in-memory NumPy arrays to train and evaluate a model. The model is "fit" to the training data using the fit method: import numpy as np data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) model.fit(data, labels, epochs=10, batch_size=32) tf.keras.Model.fit takes three important arguments: epochs: Training is structured into epochs. An epoch is one iteration over the entire input data (this is done in smaller batches). batch_size: When passed NumPy data, the model slices the data into smaller batches and iterates over these batches during training. This integer specifies the size of each batch. Be aware that the last batch may be smaller if the total number of samples is not divisible by the batch size. validation_data: When prototyping a model, you want to easily monitor its performance on some validation data. Passing this argument—a tuple of inputs and labels—allows the model to display the loss and metrics in inference mode for the passed data, at the end of each epoch. Here's an example using validation_data: import numpy as np data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) val_data = np.random.random((100, 32)) val_labels = np.random.random((100, 10)) model.fit(data, labels, epochs=10, batch_size=32, validation_data=(val_data, val_labels)) Input tf.data datasets Use the Datasets API to scale to large datasets or multi-device training. Pass a tf.data.Dataset instance to the fit method: # Instantiates a toy dataset instance: dataset = tf.data.Dataset.from_tensor_slices((data, labels)) dataset = dataset.batch(32) dataset = dataset.repeat() # Don't forget to specify `steps_per_epoch` when calling `fit` on a dataset. model.fit(dataset, epochs=10, steps_per_epoch=30) Here, the fit method uses the steps_per_epoch argument—this is the number of training steps the model runs before it moves to the next epoch. Since the Dataset yields batches of data, this snippet does not require a batch_size. Datasets can also be used for validation: dataset = tf.data.Dataset.from_tensor_slices((data, labels)) dataset = dataset.batch(32).repeat() val_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_labels)) val_dataset = val_dataset.batch(32).repeat() model.fit(dataset, epochs=10, steps_per_epoch=30, validation_data=val_dataset, validation_steps=3) Evaluate and predict The tf.keras.Model.evaluate and tf.keras.Model.predict methods can use NumPy data and a tf.data.Dataset. To evaluate the inference-mode loss and metrics for the data provided: model.evaluate(x, y, batch_size=32) model.evaluate(dataset, steps=30) And to predict the output of the last layer in inference for the data provided, as a NumPy array: model.predict(x, batch_size=32) model.predict(dataset, steps=30) Build advanced models Functional API The tf.keras.Sequential model is a simple stack of layers that cannot represent arbitrary models. Use the Keras functional API to build complex model topologies such as: Multi-input models, Multi-output models, Models with shared layers (the same layer called several times), Models with non-sequential data flows (e.g. residual connections). Building a model with the functional API works like this: A layer instance is callable and returns a tensor. Input tensors and output tensors are used to define a tf.keras.Model instance. This model is trained just like the Sequential model. The following example uses the functional API to build a simple, fully-connected network: inputs = keras.Input(shape=(32,)) # Returns a placeholder tensor # A layer instance is callable on a tensor, and returns a tensor. x = keras.layers.Dense(64, activation='relu')(inputs) x = keras.layers.Dense(64, activation='relu')(x) predictions = keras.layers.Dense(10, activation='softmax')(x) # Instantiate the model given inputs and outputs. model = keras.Model(inputs=inputs, outputs=predictions) # The compile step specifies the training configuration. model.compile(optimizer=tf.train.RMSPropOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) # Trains for 5 epochs model.fit(data, labels, batch_size=32, epochs=5) Model subclassing Build a fully-customizable model by subclassing tf.keras.Model and defining your own forward pass. Create layers in the __init__ method and set them as attributes of the class instance. Define the forward pass in the call method. Model subclassing is particularly useful when eager execution is enabled since the forward pass can be written imperatively. Key Point: Use the right API for the job. While model subclassing offers flexibility, it comes at a cost of greater complexity and more opportunities for user errors. If possible, prefer the functional API. The following example shows a subclassed tf.keras.Model using a custom forward pass: class MyModel(keras.Model): def __init__(self, num_classes=10): super(MyModel, self).__init__(name='my_model') self.num_classes = num_classes # Define your layers here. self.dense_1 = keras.layers.Dense(32, activation='relu') self.dense_2 = keras.layers.Dense(num_classes, activation='sigmoid') def call(self, inputs): # Define your forward pass here, # using layers you previously defined (in `__init__`). x = self.dense_1(inputs) return self.dense_2(x) def compute_output_shape(self, input_shape): # You need to override this function if you want to use the subclassed model # as part of a functional-style model. # Otherwise, this method is optional. shape = tf.TensorShape(input_shape).as_list() shape[-1] = self.num_classes return tf.TensorShape(shape) # Instantiates the subclassed model. model = MyModel(num_classes=10) # The compile step specifies the training configuration. model.compile(optimizer=tf.train.RMSPropOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) # Trains for 5 epochs. model.fit(data, labels, batch_size=32, epochs=5) Custom layers Create a custom layer by subclassing tf.keras.layers.Layer and implementing the following methods: build: Create the weights of the layer. Add weights with the add_weight method. call: Define the forward pass. compute_output_shape: Specify how to compute the output shape of the layer given the input shape. Optionally, a layer can be serialized by implementing the get_config method and the from_config class method. Here's an example of a custom layer that implements a matmul of an input with a kernel matrix: class MyLayer(keras.layers.Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): shape = tf.TensorShape((input_shape[1], self.output_dim)) # Create a trainable weight variable for this layer. self.kernel = self.add_weight(name='kernel', shape=shape, initializer='uniform', trainable=True) # Be sure to call this at the end super(MyLayer, self).build(input_shape) def call(self, inputs): return tf.matmul(inputs, self.kernel) def compute_output_shape(self, input_shape): shape = tf.TensorShape(input_shape).as_list() shape[-1] = self.output_dim return tf.TensorShape(shape) def get_config(self): base_config = super(MyLayer, self).get_config() base_config['output_dim'] = self.output_dim @classmethod def from_config(cls, config): return cls(**config) # Create a model using the custom layer model = keras.Sequential([MyLayer(10), keras.layers.Activation('softmax')]) # The compile step specifies the training configuration model.compile(optimizer=tf.train.RMSPropOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) # Trains for 5 epochs. model.fit(data, targets, batch_size=32, epochs=5) #Callbacks #A callback is an object passed to a model to customize and extend its behavior during training. #You can write your own custom callback, or use the built-in tf.keras.callbacks that include: #1.tf.keras.callbacks.ModelCheckpoint: Save checkpoints of your model at regular intervals. #2.tf.keras.callbacks.LearningRateScheduler: Dynamically change the learning rate. #3.tf.keras.callbacks.EarlyStopping: Interrupt training when validation performance has stopped improving. #4.tf.keras.callbacks.TensorBoard: Monitor the model's behavior using TensorBoard. #To use a tf.keras.callbacks.Callback, pass it to the model's fit method: #使用callback可以调节你的训练过程 callbacks = [ # Interrupt training if `val_loss` stops improving for over 2 epochs keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'), # Write TensorBoard logs to `./logs` directory keras.callbacks.TensorBoard(log_dir='./logs') ] model.fit(data, labels, batch_size=32, epochs=5, callbacks=callbacks, validation_data=(val_data, val_targets))
import numpy as np a=np.array([1,3,2,4]) c=np.array([0,1,1,0]) b=np.argsort(a)#从小到大排序,并返还原来的索引 print(b) print(c[b])
n = int(input()) m = float(input()) print("%0.3f"%(n/m),"km/l")
while 1: n = int(input()) if (n==2002): print("Acesso Permitido") break else: print("Senha Invalida")
import pandas import argparse parser = argparse.ArgumentParser(description='Value count for columns.') parser.add_argument('file', metavar='F', help='source file') parser.add_argument('col', metavar='C', help='column to count values') args = parser.parse_args() data = pandas.read_csv(args.file) print(data[args.col].value_counts())
#!/usr/bin/python3 """ Here we have a class called rectangle which inherits our base class from our models.base module (this dicrectory) """ from models.base import Base def raise_exc(attribute="", error=""): """ raises an exception based on attribute and error information Args: attribute (str): what attr we are rasing for. Defaults to "". error (str): what error we are rasing. Defaults to "". - Error should be one of two type "Type" or "Raise" Raises: TypeError: Raises if "Type" is True for any attr ValueError(one): (raises if x or y) ValueError(two): raises for width or height """ if error == "Type": raise TypeError("{} must be an integer".format(attribute)) elif error == "Value": if attribute == "x" or attribute == "y": raise ValueError("{} must be >= 0".format(attribute)) else: raise ValueError("{} must be > 0".format(attribute)) class Rectangle(Base): """ In this class we intilize a new model from our superclass and setup a new rectangle class with attributes width, height, x, y, and id. ID is passed to the super class to initilize out model properly """ def __init__(self, width=None, height=None, x=0, y=0, id=None): """ inits our class with below arguments Args: width (int): width of the rectangle height (int): height of the rectangle x (int): X cordnate. Defaults to 0. y (int): Y cordnate. Defaults to 0. id (int): class Id of our model. Defaults to None. """ super().__init__(id) self.width = width self.height = height self.x = x self.y = y # ---------------------WIDTH---------------- @property def width(self): """ a getter for the width private attribute Returns: [int]: value of width private attribute """ return self.__width @width.setter def width(self, width): """ a setter for the width private attribute Args: width (int): the new width value for the attribute """ if type(width) is not int: raise_exc("width", "Type") elif width <= 0: raise_exc("width", "Value") self.__width = width # ---------------------HEIGHT---------------- @property def height(self): """ a getter for the height private attribute Returns: [int]: value of height private attribute """ return self.__height @height.setter def height(self, height): """ a setter for the height private attribute Args: height (int): the new height value for the attribute """ if type(height) is not int: raise_exc("height", "Type") elif height <= 0: raise_exc("height", "Value") self.__height = height # ---------------------X-CORDNATE---------------- @property def x(self): """ a getter for the X private attribute Returns: [int]: value of X private attribute """ return self.__x @x.setter def x(self, x): """ a setter for the X private attribute Args: x (int): the new X value for the attribute """ if type(x) is not int: raise_exc("x", "Type") elif x < 0: raise_exc("x", "Value") self.__x = x # ---------------------Y-CORDNATE---------------- @property def y(self): """ a getter for the Y private attribute Returns: [int]: value of Y private attribute """ return self.__y @y.setter def y(self, y): """ a setter for the Y private attribute Args: y (int): the new Y value for the attribute """ if type(y) is not int: raise_exc("y", "Type") elif y < 0: raise_exc("y", "Value") self.__y = y # -----------------AREA------------------ def area(self): """ calulates the area of the rectangle and returns it """ return self.width * self.height # -----------------DISPLAY---------------- def display(self): """ prints out a representation of a rectangle in stdout """ for space in range(self.y): print() for column in range(self.height): for space in range(self.x): print(' ', end="") for row in range(self.width): print('#', end="") print() # ------------------STR------------------ def __str__(self): """returns a printable string rep of our rectangle""" string = "[Rectangle] ({}) {}/{} - {}/{}" return string.format(self.id, self.x, self.y, self.width, self.height) # -----------------UPDATE---------------- def update(self, *args, **kwargs): """ updates our current attributes """ attrs = ["id", "width", "height", "x", "y"] if len(args) == 0: for key, value in kwargs.items(): setattr(self, key, value) return for index in range(len(args)): setattr(self, attrs[index], args[index]) # ---------------DICT-REP----------------- def to_dictionary(self): """ Returns a dictionary representation of a rectangle """ return {'x': self.x, 'y': self.y, 'id': self.id, 'height': self.height, 'width': self.width}
#!/usr/bin/python3 """prints a square""" def print_square(size=None): """prints out our square using size in stdout with #""" if isinstance(size, int) is not True: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for i in range(0, size): for j in range(0, size): print("#", end="") print()
#!/usr/bin/python3 """ module that contains a function using json encoding """ import json def save_to_json_file(my_obj, filename): """ writes an python Object to a text file, using a JSON representation """ with open(filename, mode="w+", encoding="utf-8") as file: json.dump(my_obj, file)
#!/usr/bin/python3 def common_elements(set_1, set_2): set_3 = list() for i in set_1: for x in set_2: if i == x: set_3.append(i) return set_3
#!/usr/bin/python3 """module contains a def to add new lines to a given text""" def text_indentation(text=None): """The def that adds the new lines""" new_string = "" print_string = "" if type(text) is not str: raise TypeError("text must be a string") for i in range(len(text)): new_string += text[i] if text[i] == '.' or text[i] == '?' or text[i] == ':': new_string += "\n\n" for i in range(len(new_string)): if new_string[i] == ' ' and new_string[i - 1] == '\n': continue print_string += new_string[i] print(print_string, end="")
#!/usr/bin/python3 """ module that contains a function using json encoding """ import json def from_json_string(my_str): """ returns the python representation of a JSON string """ return json.loads(my_str)
#!/usr/bin/python3 """ Description: Here we have a program that opens a MySQL database from arguments passed on exectution. Host name and port number are static to local host system. =================================================================== MySQL Execution: Will print results from query in ascending order by id of state entrys. Will only print entrys names that match given argument. =================================================================== USAGE: ./0-select_states.py (user)(password)(database name)(search name) """ import sys import MySQLdb if __name__ == "__main__": states_base = MySQLdb.connect(host="localhost", port=3306, user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) states_cur = states_base.cursor() states_cur.execute("SELECT * FROM states WHERE BINARY name='{}'\ ORDER BY id ASC".format(sys.argv[4])) rows = states_cur.fetchall() for row in rows: print(row) states_cur.close() states_base.close()
#print(3+6) #print("3+6") #被引号括起来的内容是字符串,原样输出 ''' 这是一段注释 这是一段注释 ''' """ 这也是一段注释 这也是一段注释 """ jay = ((3+6)/5) gay = (jay*5) print(gay*5)
counts=dict() line=input('enter a text') words=line.split() print(words) for word in words: counts[word]=counts.get(word,0)+1 print(counts)
# ============================================================================ # Name : day_3_part1.py # Author : PS # Date : 6.4.20 # Description : Day 3: Crossed Wires, part1 # Description : To fix the circuit, you need to find the intersection point # closest to the central port. Because the wires are on a grid, # use the Manhattan distance for this measurement. While the wires # do technically cross right at the central port where they both # start, this point does not count, nor does a wire count as # crossing with itself. # # For example, if the first wire's path is R8,U5,L5,D3, then starting # from the central port (o), it goes right 8, up 5, left 5, and finally # down 3. Then, if the second wire's path is U7,R6,D4,L4, it goes up 7, # right 6, down 4, and left 4. These wires cross at two locations # (marked X), but the lower-left one is closer to the central port: # its distance is 3 + 3 = 6. # # Here are a few more examples: # R75,D30,R83,U83,L12,D49,R71,U7,L72 # U62,R66,U55,R34,D71,R55,D58,R83 = distance 159 # R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51 # U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = distance 135 # What is the Manhattan distance from the central port to the # closest intersection? # ============================================================================ # Solution pseudocode # * 1. get array1 and array2 from input file # * 2. assign coordinates to each array vector # * 3. compare each set of coordinates between arrays (use strstr()?) # * if there's a match, store the coordinate # * 4. calculate distance from each matching coordinate # * 5. answer is shortest distance import csv outfile = open('readme.txt','w') def header( var ): msg = ["\n*****************************************************",var, "*****************************************************"] msg2 = ["\n\n*****************************************************\n",var, "\n*****************************************************\n"] for x in msg: print(x) for x in msg2: outfile.write(x) Day_Title = "Day 3: Crossed Wires, part 1" print("\n" + Day_Title) outfile.write( Day_Title ) header( "Wiring Solutions" ) # * 1. get array1 and array2 from input file readfile = open('test.txt', 'r') for line in readfile: wire1path = line wire2path = line print(wire1path) print(wire2path) outfile.close()
# oh soldier pretiffy my folder # input path as a input , file having the words that are not to be changed , format # captilize the first letter of all the folders # if the word is in the text file don't rename them # change the name of the files from the format then rename it with numbers import os def soldier(path,text_file,format): os.chdir(path) folders = os.listdir() count = 1 with open(text_file) as f: list_of_words = f.read().split(" ") for files in folders: if files in list_of_words: pass elif files.endswith(format): os.rename(files,f'{count}{format}') count = count + 1 else: os.rename(files,files.capitalize()) soldier("C:\\Users\\User\\Desktop\\Prac","g.txt",".jpg")
from collections import deque def is_equals(origin, inp_str): return origin == inp_str def is_valid_command(origin_type, input_type): if origin_type == "NUMBER": return input_type.isdigit() elif origin_type == "STRING": return input_type.isalpha() def solution(program, flag_rules, commands): answer = [] rules_dict = dict(tuple(i.split(" ") for i in flag_rules)) for command in commands: comm = deque(command.split(" ")) # program if not is_equals(program, comm.popleft()): answer.append(False) continue while comm: result = True flag = comm.popleft() if flag in rules_dict: if rules_dict[flag] == "NULL": continue if not is_valid_command(rules_dict[flag], comm.popleft()): result = False break else: result = False answer.append(result) return answer solution("line", ["-s STRING", "-n NUMBER", "-e NULL"], ["line -n 100 -s hi -e", "lien -s Bye"]) solution("line", ["-s STRING", "-n NUMBER", "-e NULL"], ["line -s 123 -n HI", "line fun"])
import math from itertools import permutations def is_prime_number(n): for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def solution(numbers): answer = [] numbers = list(numbers) for i in range(1, len(numbers) + 1): per = permutations(numbers, i) for p in per: number = int("".join(p)) if number == 0 or number == 1: continue if is_prime_number(number) and number not in answer: answer.append(number) return len(answer) solution("17") solution("011") solution("0001231")
def solution(nums): return len(nums) // 2 if len(set(nums)) >= len(nums) // 2 else len(set(nums)) solution([3, 1, 2, 3]) solution([3, 3, 3, 2, 2, 2]) solution([3, 3, 3, 3])
import turtle lenght = 300 a = [0, 0] b = [lenght, 0] c = [lenght/2, ((3*0.5)/2)*lenght] def middle_point(a, b): x = (a[0] + b[0])/2 y = (a[1] + b[1])/2 point = [x, y] return point def sierpinski (a, b, c, n): mid_a = middle_point(a, b) mid_b = middle_point(b, c) mid_c = middle_point(a, c) turtle.up() turtle.goto(mid_c) turtle.down() turtle.goto(mid_b) turtle.goto(mid_a) turtle.goto(mid_c) if n > 0 : sierpinski(c, mid_c, mid_b, n-1) sierpinski(b, mid_a, mid_b, n-1) sierpinski(a, mid_c, mid_a, n-1) def draw_triangle(a, b, c): turtle.up() turtle.goto(a) turtle.down() turtle.goto(b) turtle.goto(c) turtle.goto(a) draw_triangle(a, b, c) sierpinski(a, b, c, 5)
import unittest from string_calculator import StringCalculator class TestStringCalculator(unittest.TestCase): def test_empty_string(self): self.assertEqual(StringCalculator.add(''), 0) def test_single_number(self): self.assertEqual(StringCalculator.add('10'), 10) def test_if_separated_comma(self): self.assertEqual(StringCalculator.add('10,20'), 30) def test_if_separated_new_line(self): self.assertEqual(StringCalculator.add('1\n2'), 3) def test_more_two_numbers_with_diff_separate(self): self.assertEqual(StringCalculator.add('1\n2,3\n4'), 10) def test_negative_number(self): self.assertEqual(StringCalculator.add('-1,2,-3'), 'отрицательные числа запрещены: -1,-3') def test_ignore_number_more_1000(self): self.assertEqual(StringCalculator.add('1000, 2, 3'), 5) def test_one_char_separat(self): self.assertEqual(StringCalculator.add('//#\n1#2#3#1000'), 6) def test_multi_char_separat(self): self.assertEqual(StringCalculator.add('//###\n1###2###5'), 8)
import time class Clock(): def __init__(self): self.start_game = time.time() def duration_of_games(self): current_time = time.time() duration = time.strftime("%H:%M:%S", time.gmtime(current_time - self.start_game)) return duration def set_time(recharge): return time.time() + recharge def is_time(time_recharge): current_time = time.time() delta = current_time - time_recharge return True if delta >= 0 else False
class TV(): def __init__(self, volume=5, channel=""): self.volume=volume self.channel=channel def plus(self): zvp=int(input("На сколько вы хотите увеличить громкость телевизора?")) self.volume+=zvp if self.volume>30: print("Рекомендуется снизить громкость телевизора") print("Громкость была увеличена") print("Громкость стала равна:" + str(self.volume)) def minus(self): zvm=int(input("На сколько вы хотите уменьщить громкость телевизора?")) self.volume-=zvm if self.volume<0: self.volume=0 print("Громкость была уменьшена") print("Громкость стала равна:" + str(self.volume)) def change(self): print (""" 1-Новостной канал 2-Развлекательный канал 3-Спортивный канал 4-Канал с грустными фильмами """) change=int(input("На какой канал вы хотите переключиться?")) if change == 1: print("Вы переключились на новостной канал") elif change == 2: print("Вы переключились на развлекательный канал") elif change == 3: print("Вы переключились на спортивный канал") elif change == 4: print("Вы переключились на канал с грустными фильмами") else: print("Вы ввели неправильное значение") tv1=TV() choice= None while choice != "0": print \ (""" Мой телевизор 0 - Выйти 1 - Переключить канал 2 - Прибавить громкость 3 - Убавить громкость """) choice = input("Ваш выбор: ") print() if choice == "0": print("До свидания!") elif choice == "1": tv1.change() elif choice == "2": tv1.plus() elif choice == "3": tv1.minus() else: print("Извините, в меню игры нет такого пункта ", choice)
#user needs to type their name to start the game. print("IN ORDER FOR THIS GAME TO BEGIN...") name = input("Please type your name: ") def welcome():#Welcomes the User to the game print("Welcome to the Island Game!") print("Hello,", name,"! Welcome and now let's go to the customizing station!") def avatar1():#describes avatar 1 print("Avatar 1") print("They are an outgoing person. They love to talk and make friends. Their only pet peeve is silence!") def avatar2():#describes avatar 2 print("Avatar 2") print("They are a very quiet person. They love to keep to themsleves and have alone time daily. They would rather spend time reading than going out with friends!") def avatar3():#describes avatar 3 print("Avatar 3") print("They are a very adventurous person. They love to explore and discover new things about the nature around them.") def yesno():#asks the user if they are sure if they will continue with the avatar they chose print("Are you sure you would want to stay with your choice of avatar?") answer = input("Please type either yes or no: ") if answer == "yes": pregame() elif answer == "no": customizing2() else: print() print() print("That input you entered is not apart of the choices.") print("Please choose either yes or no") yesno() def customizing1(): #leads to the choices of what avatars are there print() print() print() print() print("Welcome to the Customizing Station!") print("In here, we will customize your very own character, by choosing which avatar your would like to be.") print("Choose the avatar you would like to be or relate to the most.") def customizing2(): #allows the user to enter which character they would like by entering the numbr that coressponds with the avatar print() print() avatar1() print() avatar2() print() avatar3() print() print("What is your choice?") print("1) Avatar 1") print("2) Avatar 2") print("3) Avatar 3") numbers = int(input("Enter the number for the avatar your would like: ")) print() print() if numbers == 1: print("You chose Avatar 1: You chose the avatar that is very outgoing and loves to hangout with other! ") yesno() elif numbers == 2: print("You chose Avatar 2: You chose the avatar that is a quiet type of person and loves to have alone time!") yesno() elif numbers == 3: print("You chose Avatar 3: You chose the avatar that is very adventurous and loves to explore the things around them!") yesno() else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") customizing2() def pregame(): #builds up to the game.Tells the user what happens and why they end up on a island stranded print() print() print() print() print("OK! Let's Begin!") print("Once upon a time,", name,"traveled everywhere!") print(name," went on trips where no one dared to go!") print("One day,", name,"boarded a ship to go to an exotic place.") print("However, this did not end well.") print("The ship collided with rocks and sunk!") print("Everyone else sunk and were never found again!") print("But", name,"survived!") print("You got washed up on an island!") print("You are all alone and no one else is there to help!") def basicinstructions():#this tells the user about how many lives they have and wishes them good luck print() print() print() print() print("Here are the instructions on how to survive!") print() print("You have infinite lives") print("But you will start with 3 lives.") print("Every decision you make is important!") print("GOOD LUCK!") print() print() def game1():#shows the time passing and sets up the game to go on to the food function for x in range(1,6): print(" Hour",x,"🕒") print() print("You have been on the island for about 5 hours now!") print("You are starting to get hungry") option1(hearts) hearts = 3 # this is how many hearts the user starts with, but they have infinite lives. def option1(hearts):#asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("What do you want to do?") print("1) Start looking for food") print("2) Lay there and cry") print("3) Throw a tantrum") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: food(hearts) elif options == 2: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option1(hearts) elif options == 3: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option1(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option1(hearts) def food(hearts):#In this function, it tells the user that they are going to get food, but they need to do specific things in order to get the food print ("You have " + str(hearts) + " hearts remaining.") print("You now get sticks to create an ax to obtain your food.") print("Please save some wood for future usage like creating a fire.") print() count = 0 while count<=30: print(count,"minutes") count = count + 5 else: print() print("After " +str(count),"minutes, you are finished gathering your sticks to create an ax to cut the vegetation.") print("You have now gathered your vegetables to eat.") option2(hearts) def option2(hearts): #asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("What do you want to do?") print("1) Go to the river to wash vegetables") print("2) Just eat it raw") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: river(hearts) elif options == 2: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option2(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option2(hearts) def river(hearts):#tells the user how many hearts they have left and that they are going to a river to cleanse the vegetables print ("You have " + str(hearts) + " hearts remaining.") print("You now are going to the river.") print("You are going to cleanse the vegetables.") print() for x in range(1,6): print(" Hour",x,"🕒") print() option3(hearts) def option3(hearts): #asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("After cleaning the vegetables...") print("What do you want to do?") print("1) Just eat it raw") print("2) Go and cook the vegetable first") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option3(hearts) elif options == 2: fire(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option3(hearts) def fire(hearts):#The user is then going to use the sticke they have collected to create a fire to cook the vegetables print("You now will use the saved sticks!") print("You will now create a fire to cook the vegetables") print() option4(hearts) def option4(hearts):#asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("What do you do?") print("1) Sit there and watch the fire") print("2) Cook the food and eat") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option4(hearts) elif options == 2: shelter(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option4(hearts) def shelter(hearts):#The user needs to build a house for their shelter print("You will now need to build a house.") print("You must get some wood for the house.") wood(hearts) def wood(hearts):#the user has finished chopping all the wood and the program shows that 3 hours have passed print("Chop, chop, chop") for x in range(1,3): print(" Hour",x,"🕒") print() print("After 3 hours, you have finished chopping and collecting all the wood you need.") food2(hearts) def food2(hearts):#In this function, it tells the user that they are going to get food, but they need to do specific things in order to get the food print ("You have " + str(hearts) + " hearts remaining.") print("You now get sticks to create an ax to obtain your food.") print("Please save some wood for future usage like creating a fire.") print() count = 0 while count<=30: print(count,"minutes") count = count + 5 else: print() print("After " +str(count),"minutes, you are finished gathering your sticks to create an ax to cut the vegetation.") print("You have now gathered your vegetables to eat.") option5(hearts) def option5(hearts):#asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("What do you want to do?") print("1) Go to the river to wash vegetables") print("2) Just eat it raw") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: river2(hearts) elif options == 2: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option5(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option5(hearts) def river2(hearts):#shows how many hearts the user has and the user now goes to the river to wash the vegetables, and shows that 6 hours have passed print ("You have " + str(hearts) + " hearts remaining.") print("You now are going to the river.") print("You are going to cleanse the vegetables.") print() for x in range(1,6): print(" Hour",x,"🕒") print() option6(hearts) def option6(hearts):#asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("After cleaning the vegetables...") print("What do you want to do?") print("1) Just eat it raw") print("2) Go and cook the vegetable first") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option3(hearts) elif options == 2: fire2(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option3(hearts) def fire2(hearts):#he user is then going to use the sticke they have collected to create a fire to cook the vegetables print("You now will use the saved sticks!") print("You will now create a fire to cook the vegetables") print() option7(hearts) def option7(hearts):#asks the user what they would want to do, and if they choose the wrong choice, they will lose a hearts print("What do you do?") print("1) Sit there and watch the fire") print("2) Cook the food and eat") options = int(input("Enter the number for the option you would like to do: ")) print() print() if options == 1: print("You lost 1 heart") hearts -= 1 print ("You have " + str(hearts) + " hearts remaining.") option7(hearts) elif options == 2: finishgame(hearts) else: print("That number you chose is not apart of the choices.") print("Please choose a number between 1 to 3") option7(hearts) def finishgame(hearts): #the user has finished eating and they continue to build the house. After 3 hours, they finish and then the game ends #The program prints the score/hearts the user has and they user can then compare the number of hearts they have with others who played the game before. print("You have now eaten and are ready to continuue.") print("You are now building your house.") for x in range(1,3): print(" Hour",x,"🕒") print() print("After 3 hours, you have finished your house!") print() print() print() print("THIS IS YOUR SCORE!") print ("You have " + str(hearts) + " hearts remaining.") print("You can compare your score with others outside of the game") print("Thank you for playing!") #calls the functions to start the game welcome() customizing1() customizing2() basicinstructions() game1()
#Vowel Counter #For large data files with open('vowel_count.txt') as f: c = f.readlines() # .read() statements breaks the line into words and here we want to calculate the vowels in a line. #for storing no. of vowels in each line count = [] for line in c: vowels = 0 #checking each letter for i in range(0, len(line)): if line[i] == 'a': vowels += 1 elif line[i] == 'e': vowels += 1 elif line[i] == 'i': vowels += 1 elif line[i] == 'o': vowels += 1 elif line[i] == 'u': vowels += 1 else: continue count.append(vowels) print(count)
"""This version is without the time filter and the other is with time filter, city filter.""" import csv import pandas as pd import time import datetime import collections from collections import Counter def get_city(): '''Asks the user for a city and returns the filename for that city's bike share data. Args: none. Returns: (str) Filename for a city's bikeshare data. ''' cityname = input('\nHello! Let\'s explore some US bikeshare data!\n' 'Would you like to see data for Chicago, New York, or Washington?\n') cityname=cityname.lower() city_verify=cityname if (cityname=='newyork'): filename='new_york_city.csv' city_df=pd.read_csv(filename) return city_df,city_verify elif (cityname=='washington'): filename='washington.csv' city_df=pd.read_csv(filename) return city_df,city_verify elif (cityname=='chicago'): filename='chicago.csv' city_df=pd.read_csv(filename) return city_df,city_verify else: print ("Enter only the above given names only") exit() def popular_month(city_file): '''This function calculates the month that occurs most often in the start time''' city_file["Start Time"] = pd.to_datetime(city_file["Start Time"]) months= city_file["Start Time"].dt.month countmonths= Counter(months) max_month=countmonths.most_common()[0:1] for x in max_month: if (x[0]==1): y= 'January' elif (x[0]==2): y='February' elif (x[0]==3): y='March' elif (x[0]==4): y='April' elif (x[0]==5): y='May' elif (x[0]==6): y='June' elif (x[0]==7): y='July' elif (x[0]==8): y='August' elif (x[0]==9): y='September' elif (x[0]==10): y='October' elif (x[0]==11): y='November' elif (x[0]==12): y='December' print ("Month often seen in start time is {} month and count is {}".format (y,x[1])) def popular_day(city_file): '''This function calculates the day that occurs most often in the start time It takes city dataframe as the argument''' city_file["Start Time"] = pd.to_datetime(city_file["Start Time"]) days= city_file["Start Time"].dt.weekday countdays= Counter(days) max_day=countdays.most_common()[0:1] for x in max_day: if (x[0]==0): y= 'Sunday' elif (x[0]==1): y='Monday' elif (x[0]==2): y='Tuesday' elif (x[0]==3): y='Wednesday' elif (x[0]==4): y='Thursday' elif (x[0]==5): y='Friday' elif (x[0]==6): y='Saturday' print ("Day often seen in start time is {} weekday and count is {}".format (y,x[1])) def popular_hour(city_file): '''This function calculates the hour that occurs most often in the start time It takes city dataframe as the argument''' city_file["Start Time"] = pd.to_datetime(city_file["Start Time"]) hours= city_file["Start Time"].dt.hour counthours= Counter(hours) max_hour=counthours.most_common()[0:1] for x in max_hour: print ("Day often seen in start time is {} th hour and count is {}".format (x[0],x[1])) def popular_stations(city_file): '''This function calculates the popular start station and the end station It takes city dataframe as the argument''' start_station=city_file.groupby(["Start Station"]).size() end_station=city_file.groupby(["End Station"]).size() print ("The most comon start staion is {} and its count is{} ".format(start_station.idxmax(),start_station.max())) print ("The most common end station is {} and its count is {}".format(end_station.idxmin(),end_station.max())) def popular_trip(city_file): '''This function calculates the popular trip between start station and the end station''' trip=city_file.groupby(["Start Station", "End Station"]).size() print ("The most common trip is between start station {} and end station {} and the count is {}".format(trip.idxmax()[0],trip.idxmax()[1],trip.max())) def users(city_file): '''This function gives the are the counts of each user type It takes city dataframe as the argument''' user=city_file['User Type'].tolist() coustomer=0 subscriber=0 for i in range(len(user)): if (user[i]=='Customer'): coustomer+=1 elif (user[i]=='Subscriber'): subscriber+=1 print ("Total number of coustomer users are {}".format(coustomer)) print ("Total number of subscriber users are {}".format(subscriber)) def genders(city_file): '''This function gives the counts of each gender type It takes city dataframe as the argument''' gender=city_file['Gender'].tolist() male=0 female=0 for i in range(len(gender)): if (gender[i]=='Male'): male+=1 elif (gender[i]=='Female'): female+=1 print ("Total number of male users {}".format(male)) print ("Total number of femlae users {}".format(female)) def trip_duration(city_file): '''This function gives the total and average duration of all the trips It takes city dataframe as the argument''' time_sec=city_file['Trip Duration'].sum() ave_time_sec=city_file['Trip Duration'].mean() print ("Total time for trip durations in minutes is {} and in hours is {} and seconds is {}".format((time_sec)/60,(time_sec)/(60*60),time_sec)) print ("Average time for trip durations in minutes is {} and in hours is {} and seconds is {}".format((ave_time_sec)/60,(ave_time_sec)/(60*60),ave_time_sec)) def birth_years(city_file): ''' This function gives the earliest birth year (when the oldest person was born), most recent birth year, and most common birth year? ''' age=city_file['Birth Year'] common_age=city_file.groupby(["Birth Year"]).size() print ("The earliest birth year was {}".format(int(age.max()))) print ("The recent birth year was {}".format(int(age.min()))) print ("The most comon birth year is {} and its count is{} ".format(common_age.idxmax(),common_age.max())) def statistics(): '''Calculates and prints out the descriptive statistics about a city and time period specified by the user via raw input. Args: nonegiven Returns: nonegiven ''' # Filter by city (Chicago, New York, Washington)7 city,city_verify = get_city() city["Start Time"] = pd.to_datetime(city["Start Time"]) start_time = time.time() popular_month(city) #TODO: call popular_month function and print the results print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is popular day...") start_time = time.time() popular_day(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is popular hour...") popular_hour(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is popular stations both start and end...") popular_stations(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is poplar trip between start and end station...") popular_trip(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is count of users...") users(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is the trip durations...") trip_duration(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is the genders count...") if (city_verify=='washington'): print ("The column was not there for the current dataset") restart = input('\nWould you like to restart? Type \'yes\' or \'no\'.\n') if restart.lower() == 'yes': statistics() else: print ("exit application done") exit() else: genders(city) print("That took %s seconds." % (time.time() - start_time)) print("Calculating the next statistic that is recent and old birth years...") birth_years(city) print("That took %s seconds." % (time.time() - start_time)) restart = input('\nWould you like to restart? Type \'yes\' or \'no\'.\n') if restart.lower() == 'yes': statistics() else: print ("Exit Application done") statistics()
import cv2 from matplotlib import pyplot as plt # reading the image img = cv2.imread(r'C:\Users\Jawhar\Downloads\einstein.jpg', 0) # displaying the original image plt.figure() plt.imshow(img, cmap = 'gray'),plt.title("Original Image"),plt.axis("off") # performing gaussian filtering with kernels of size 5 and 9 with different SDs. blur_gauss1 = cv2.GaussianBlur(img,(5,5),0) blur_gauss2 = cv2.GaussianBlur(img,(9,9),0.01) # subtracting the two filtered images sub = cv2.subtract(blur_gauss1,blur_gauss2) # passing the subtracted image to canny function canny = cv2.Canny(sub,100,75) # displaying the edge detected image plt.figure() plt.imshow(canny, cmap = 'gray'),plt.title("Edge detected image:"),plt.axis("off") plt.show()
#!/bin/python3 import sys def birthdayCakeCandles(n, ar): # Complete this function tallest = max(ar) # Generator expression return sum(1 for x in ar if x == tallest) # List comprehension #return len([1 for x in ar if x == tallest]) # List comprehension v2 #return len([x for x in ar if x == tallest]) n = int(input().strip()) ar = list(map(int, input().strip().split(' '))) result = birthdayCakeCandles(n, ar) print(result)
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0): self.val = val self.left = None self.right = None # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] class NestedInteger: """ This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation. """ def __init__(self, value=None): """ If value is not specified, initializes an empty list. Otherwise initializes a single integer equal to value. """ def isInteger(self): """ @return True if this NestedInteger holds a single integer, rather than a nested list. :rtype bool """ def add(self, elem): """ Set this NestedInteger to hold a nested list and adds a nested integer elem to it. :rtype void """ def setInteger(self, value): """ Set this NestedInteger to hold a single integer equal to value. :rtype void """ def getInteger(self): """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int """ def getList(self): """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer :rtype List[NestedInteger] """
def eightqueen(test): queen_x =[] for i in test: queen_x += i print(queen_x) #print(queen_x[0]) new_queen_x1 = [] for i in range(0,len(queen_x),2): #print(queen_x[i]) new_queen_x1.append(queen_x[i]) print(new_queen_x1) new_queen_x2 = [] for i in range(1,len(queen_x),2): #print(queen_x[i]) new_queen_x2.append(queen_x[i]) print(new_queen_x2) add = [a+b for a, b in zip(new_queen_x1,new_queen_x2)] less = [a+b for a, b in zip(new_queen_x1,new_queen_x2)] if len(set(new_queen_x1))!=8: print(False) elif len(set(new_queen_x2))!=8: print(False) elif len(set(add))!=8: return (False) elif len(set(less)))!=8: return (False) else: print(True) eightqueen([[0, 0], [1, 4], [2, 7], [3, 5], [4, 2], [5, 6], [6, 1], [7, 3]])
for i in range(1,51): if i==2: print(i,"是質數") for j in range(2,i): if (i%j)==0: break elif i%j!=0 and j+1==i : print(i,"是質數")
class Car: def __init__(self, name): self._speed_name_map = { "BMW": 250, "Mercedes": 350 } self._max_speed = self._define_max_speed(name) def _define_max_speed(self, name): return self._speed_name_map.get(name, 0) def distance_on_max_speed(self, distance): if self._max_speed == 0: print( "Speed = 0, select valid car brand: {}".format( list(self._speed_name_map.keys()) ) ) return 0 return distance / self._max_speed car1 = Car('BMW') car2 = Car('Mercedes') car3 = Car('ABC') print(car1.distance_on_max_speed(100)) print(car2.distance_on_max_speed(100)) print(car3.distance_on_max_speed(100)) class Animal: def __init__(self, name): self._name = name def voice(self): pass class Cat(Animal): def voice(self): print("Meow") class Dog(Animal): def voice(self): print("Bark") animal = Animal('?') animal.voice() cat = Cat('Sarah') cat.voice() dog = Dog('Rex') dog.voice() class Animal2: def __init__(self, name): self._name = name def voice(self): if self._name == 'cat': print('Meow') elif self._name == "dog": print('Bark') else: print("...") a1 = Animal2('cat') a2 = Animal2('dog') a3 = Animal2('dinosaur') a1.voice() a2.voice() a3.voice()
def replace(words, old_word, new_word): """ this function replace(words, old_word, new_word): that replaces all occurrences of old with new in a string :param words: :param old_word: :param new_word: :return: string """ return new_word.join(words.split(old_word)) print(replace("Mississippi", "i", "I")) print(replace("I love spom! Spom is my favorite food.Spom, spom, yum!", "o", "a"))
dict = {} # ---------------- ONE ---------------- # 1. Function to create the dictionary, the Function should ask for the length of the dictionary # According the length defined should ask to the user for the key and for the value. def askElementsIntoDictionary(): print("Insert the quantity of elements in the dictionary: ", end='') quantity = int(input()) global dict for x in range(0, quantity): print("Insert key: ", end='') key = input() print("Insert value: ", end='') value = input() dict.update({key: value}) askElementsIntoDictionary() # ---------------- TWO ---------------- # 2. Function to print the dictionary keys def printKeysOfDictionary(): print("Keys = ", end='') for key in dict: print("[{0}]".format(key), end='') print(end='\n') printKeysOfDictionary() # ---------------- THREE ---------------- # 3. Function to print the dictionary values def printValuesOfDictionary(): print("Values = ", end='') for key in dict: print("[{0}]".format(dict[key]), end='') print(end='\n') printValuesOfDictionary() # ---------------- FOUR ---------------- # 4. Function to print the dictionary def printDictionary(): print("Dictionary = {0}".format(dict)) printDictionary() # ---------------- FIVE ---------------- # 5. Function to define is a key inserted by the user, exists on the dictionary def validateKeyInDictionary(): print("Search key: ", end='') key = input() if key in dict.keys(): print("The key '{0}' exist in the dictinary".format(key)) else: print("The key '{0}' doesn't exist in the dictinary".format(key)) validateKeyInDictionary() # ---------------- SIX ---------------- # 6. Function to define is a value inserted by the user, exists on the dictionary. def validateValueInDictionary(): print("Search value: ", end='') value = input() if value in dict.values(): print("The value '{0}' exist in the dictinary".format(value)) else: print("The value '{0}' doesn't exist in the dictinary".format(value)) validateValueInDictionary() # ---------------- SEVEN ---------------- # 7. Use the dictionary as a Global variable to be used in all functions.
#The function replaces all occurrences of old with new in a string def replace(song, origen, after): varArr= song.split(origen) strfinal=after.join(varArr) print(strfinal) replace("Mississippi", "i", "I")
# OPERATOR == print('---------------- OPERATOR == ----------------') variableOne = 'circle' variableTwo = 'circle' if variableOne == variableTwo: result = 'EQUALS' else: result = 'NOT EQUALS' print("{0} == {1} ==> ARE {2}".format(variableOne, variableTwo, result)) # OPERATOR != print('---------------- OPERATOR != ----------------') if variableOne != variableTwo: result = 'DIFFERENT' else: result = 'NOT DIFFERENT' print("{0} != {1} ==> ARE {2}".format(variableOne, variableTwo, result)) # OPERATOR > print('---------------- OPERATOR > ----------------') variableOne = 43232 variableTwo = 3324 print("{0} > {1} ==> {2}".format(variableOne, variableTwo, variableOne > variableTwo)) variableOne = 'C#' variableTwo = 'Java' print("{0} > {1} ==> {2}".format(variableOne, variableTwo, variableOne > variableTwo)) # OPERATOR < print('---------------- OPERATOR < ----------------') variableOne = 482.25 variableTwo = -53.2 print("{0} < {1} ==> {2}".format(variableOne, variableTwo, variableOne < variableTwo)) variableOne = 'Python2' variableTwo = 'Python3' print("{0} < {1} ==> {2}".format(variableOne, variableTwo, variableOne < variableTwo)) # OPERATOR >= print('---------------- OPERATOR >= ----------------') variableOne = 'PHP4' variableTwo = 'PHP3' print("{0} >= {1} ==> {2}".format(variableOne, variableTwo, variableOne >= variableTwo)) variableOne = 526 variableTwo = 526.1 print("{0} >= {1} ==> {2}".format(variableOne, variableTwo, variableOne >= variableTwo)) # OPERATOR <= print('---------------- OPERATOR <= ----------------') variableOne = 'PHP4' variableTwo = 'PHP3' print("{0} <= {1} ==> {2}".format(variableOne, variableTwo, variableOne <= variableTwo)) variableOne = 526 variableTwo = 526.1 print("{0} <= {1} ==> {2}".format(variableOne, variableTwo, variableOne <= variableTwo)) # OPERATOR = print('---------------- OPERATOR = ----------------') variableOne = 'Manual' variableTwo = 'Automation' print("variableOne = '{0}'".format(variableOne)) print("variableTwo = '{0}'".format(variableTwo)) variableOne = variableTwo print("variableOne = variableTwo") print("variableOne = '{0}'".format(variableOne)) # OPERATOR += print('---------------- OPERATOR += ----------------') resultAdd = 0 index = 0 while index <= 5: resultAdd += index print('result =', resultAdd) index += 1 # OPERATOR -= print('---------------- OPERATOR -= ----------------') resultMin = 0 index = 5 while index <= 10: resultMin -= index print('result =', resultMin) index += 1 # OPERATOR *= print('---------------- OPERATOR *= ----------------') resultMul = 0 index = 11 while index <= 15: resultMul *= index print('result =', resultMul) index += 1 # OPERATOR /= print('---------------- OPERATOR /= ----------------') resultDiv = 0 index = 5 while index <= 10: resultDiv += index print('result =', resultDiv) index += 1 # OPERATOR in/not in print('---------------- OPERATOR in/not in ----------------') colorOne = 'red' colorTwo = 'white' listColors = ['blue', 'red', 'yellow', 'orange', 'gray', 'black'] if (colorOne in listColors): print(colorOne, " exists in list of colors") else: print(colorOne, " exists doesn't exit in list of colors") if (colorTwo not in listColors): print(colorTwo, " doesn't exist in list of colors") else: print(colorTwo, "exists in list of colors")
# ---------------- ONE ---------------- # 1. Function that will create a dictionary with a list of userID and userName, # the userID should be only numbers between 1 to 100. # Username should be only lowercase (nor more than 8 digits) def createDictionary(): dict = {} print("Insert the quantity of elements in the dictionary: ", end='') quantity = int(input()) for x in range(0, quantity): print("Enter user id: ", end='') userID = int(input()) print("Enter user name: ", end='') username = input() if userID > 0 and userID <= 100: if (len(username) <= 8 and username.islower()): dict[userID] = username else: print("Error with the username. Username should be only lowercase (nor more than 8 digits)") else: print("Error with the userID. Range of userID [0-100]") return dict users = createDictionary() # print(createDictionary()) # ---------------- TWO ---------------- # 2. Function that is going to request to the user for a number (only 1 number) # and need to return the amount of users that have their user ID starting with # the number inserted (E.g. if user inserted 1, then could count all users # with 1, 10,11,12,13..19 or 100), return and array with the user_ID that fulfilled this condition def requestUserID(dict, number): list = [] for key in dict: if (str(key).startswith(str(number))): list.append(key) return list print('UserIDs: ', requestUserID(users, 1)) # ---------------- THREE ---------------- # 3. Function that is going to request to the user for a character (only 1 char) # and need to return the amount of users that have their userName starting with the character inserted # (E.g. if user inserted a, then could count all users that start with a), # return and array with the list of userName that fulfilled this condition def requestUsername(dict, char): list = [] for key in dict: if dict[key].startswith(char): list.append(dict[key]) return list print('Usernames: ', requestUsername(users, 'a')) # ---------------- FOUR ---------------- # 4. Function to display a message considering : # UseID between 1-25 "User belong Group 1" # UseID between 26-50 "User belong Group 2" # UseID between 51-75 "User belong Group 3" # UseID between 76-100 "User belong Group 4" # Consider to use Case Equality def displayMessage(dict): for key in dict: if key >= 1 and key <=25: print("UserID[{0}] - User belong Group 1".format(key)) elif key >= 26 and key <=50: print("UserID[{0}] - User belong Group 2".format(key)) if key >= 51 and key <= 75: print("UserID[{0}] - User belong Group 3".format(key)) elif key >= 76 and key <= 100: print("UserID[{0}] - User belong Group 4".format(key)) displayMessage(users)
#Practice Operators #Create python script applying at least one time each one of the operators learned. #Print the values and the condition that give you the result obtained. print("Practice 3: Operators") print("1. Comparison operators") #Use of == print("Use of operator ==:") def equals(string1, string2): print(f"Comparing the length of word {string1} with {string2}") if(len(string1) == len(string2)): print(f"Result: {string1} has the same length as {string2}") else: print(f"Result: {string1} has not the same length as {string2}") equals("Automation","Manual") equals("Test","Case") print() #Use of < and > print("Use of operators < and >:") def compare(a, b): print(f"Comparing values {a} and {b}") if(a > b): print(f"Result: {a} is greater than {b}") elif(a < b): print(f"Result: {a} is less than {b}") else: print(f"Result: {a} is equal to {b}") compare(7, 5) compare(7, 17) compare(7, 7) print() #Use of >= and <= print("Use of operators >= and <=:") def is_in_range(x, lim_inf, lim_sup): print(f"Comparing if {x} is within the range [{lim_inf}, {lim_sup}]") if x >= lim_inf and x <= lim_sup: print(f"Result: {x} is within the range [{lim_inf}, {lim_sup}]") else: print(f"Result: {x} is not within the range [{lim_inf}, {lim_sup}]") is_in_range(7,3,10) is_in_range(8,12,22) print() #Use of != print("Use of operator !=:") def is_different_than(a,b): print(f"Is {a} different than {b}?") if(a != b): return True else: return False print(is_different_than(4.50,450)) print(is_different_than(50,50)) print() print("2. Assignment operators") #Use of =,+=, -=, *=, /=, %= print("Use of operators =,+=:") def hail_stone_sequence(x): count = 1 if x > 1: if x % 2 == 0: count += hail_stone_sequence(x / 2) print(count) else: count += hail_stone_sequence((x * 3) + 1) print(count) return count print("Hail stone sequence:") hail_stone_sequence(70) print() print("Use of operators -=, *=, /=, %=:") def function(a): print(f"Calculations using {a}") result = a result -= 2 result *= 3 result //= 4 result %= 2 print(f"Result = {result}") function(7) function(8) print() print("3. Membership operators") #Use of in, not in print("Use of operator in :") def is_number_in_range(x, lim_inf, lim_sup): print(f"Is {x} in range [{lim_inf},{lim_sup}]?") if x in range(lim_inf, lim_sup): return f"Result: {x} is within range [{lim_inf},{lim_sup}]" else: return f"Result: {x} is not within range [{lim_inf},{lim_sup}]" print(is_number_in_range(1,-22,44)) print(is_number_in_range(112,-22,44)) print() print("Use of operator not in:") def is_number_in_list(x, list): print(f"Is {x} in list {list}?") if x not in list: return "Result", False else: return "Result", True print(is_number_in_list(7,[4,6,2,5,1,5,33,2,5,33])) print(is_number_in_list(3,[343,21,35,73,23,453,3,32,1])) print() print("4. Identity operators") #Use of is, is not print("Use of operators is and is not:") str1 = "This" str2 = "This" if str1 is str2: print(f"str1={str1} and str2={str2} have same identity") str1 = "One" str2 = "0ne" if str1 is not str2: print(f"str1={str1} and str2={str2} have not same identity")
from tkinter import * import tkinter.messagebox as tmsg def getval(): tmsg.showinfo("Money Added",f"The Money {myslider.get()} has been added to Your account") root = Tk() root.geometry("720x720") root.title("Slider") Label(text="Get Free Dollars",font="timesnewroman 12 bold").pack() myslider = Scale(root,from_=0, to=200, orient=HORIZONTAL,tickinterval=100,length=200) myslider.pack() lb = Listbox(root) lb.insert(END,10) lb.pack() # print(lb.get()) Button(text="Get Dollars",command=getval).pack() root.mainloop()
# -*- coding: utf-8 -*- # @author Nathan Frazier from functions import * def kruskals(wG, showSteps): # Take a graph object V = wG.vertex_set() # Vertex set of subgraph is the same as the vertex set of main graph sortedE = sortEdges(wG.edge_set(), wG) # Sorts all edges by weight E = [] # Make an empty list of Edges T = (V, E) # Make a tuple containing the set of vertices and list of edges index = 0 # Index starts at the lowest weighted edge while len(E) != (len(V) - 1): # While we do not have a single tree if checkCycleUnconnected(sortedE[index], T): # Checks if adding the lowest edge create a cycle sortedE.remove(sortedE[index]) # If a cycle is made, remove that edge from the list of possible edges else: E.append(sortedE[index]) # If no cycle is made, add the edge to the list of edges in the subgraph index += 1 # Increase Index if showSteps: wG.draw_subgraph(T); # Shows each step print(f"Cost of graph after using Kruskals: {sum([cost(e, wG) for e in T[1]])}") # Print total cost of edges in subgraph return T #return the subgraph
import unittest from upper import StringMethod class TestStringMethod(unittest.TestCase): def setUp(self): foo = StringMethod('foo') def test_upper(self): self.assertEqual(foo.upper(), 'FOO') def test_isupper(self): if __name__ == '__main__': unittest.main()
""" Doubled """ # Create a method that decrypts the duplicated-chars.txt def decrypt_doubled(file_name): f = open(file_name, 'r') contents = f.readlines() new_contents = [] for j in range(len(contents)): temp = "" i = 0 while i < len(contents[j]) - 2: temp = temp + contents[j][i] i = i + 2 new_contents.append(temp) return new_contents decrypt_doubled('duplicated-chars.txt') # Create a method that decrypts reversed-lines.txt def decrypt_reversed(file_name): f = open(file_name, 'r') contents = f.readlines() new_contents = [] for i in range(len(contents)): new_contents.append(contents[i][:-1][::-1]) return new_contents decrypt_reversed('reversed-lines.txt') # Create a method that decrypts reversed-order.txt def decrypt_rordered(file_name): f = open(file_name, 'r') contents = f.readlines() n = len(contents) if n % 2 == 0: for i in range(n // 2): contents[i], contents[n-i-1] = contents[n-i-1], contents[i] else: for i in range((n-1) // 2): contents[i], contents[n-i-1] = contents[n-i-1], contents[i] return contents decrypt_rordered('reversed-order.txt')
#Quick sort original_quick = [4, 1, 3, 2, 8] def quicksort(array): if len(array) >= 2: left = [] right = [] value = array[len(array) // 2] array.remove(value) for i in array: if i > value: right.append(i) else: left.append(i) return quicksort(left) + [value] + quicksort(right) else: return array quicksort(original_quick)
import unittest from Animal import Animal class test_Animal(unittest.TestCase): def setUp(self): self.animal1 = Animal() def test_animal_hunger(self): self.assertEqual(self.animal1.hunger, 50) def test_animal_eat(self): self.assertEqual(self.animal1.eat(), 49) def test_animal_drink(self): self.assertEqual(self.animal1.drink(), 49) def test_animal_play(self): self.assertEqual(self.animal1.play(), "49 49") def test_animal_play2(self): self.assertEqual(self.animal1.play(), "51 51") if __name__ == "__main__": unittest.main()
""" Sorting Algorithm """ #Bubble sort original_bubble = [5, 1, 4, 2, 8] def bubble(array): for j in range(len(array) - 1): for i in range(len(array) - 1): if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i] return array bubble(original_bubble)
import unittest from Fibonacci import fibonacci class test_fibonacci(unittest.TestCase): def test_fibonacci_3(self): self.assertEqual(fibonacci(3), [0, 1, 1]) def test_fibonacci_2(self): self.assertEqual(fibonacci(2), [0, 1]) def test_fibonacci_error(self): self.assertEqual(fibonacci(0), "Error") if __name__ == "__main__": unittest.main()
class Counter: def __init__(self, value = 0): self.counter = value def add(self, number = 1): self.counter += number def get(self): print(f"The current value is {self.counter}") def reset(self): self.counter = 0
import random class DiceSet(object): def __init__(self): self.dices = [0, 0, 0, 0, 0, 0] def roll(self): for i in range(len(self.dices)): self.dices[i] = random.randint(1, 6) return self.dices def get_current(self, index = None): if index != None: return self.dices[index] else: return self.dices def reroll(self, index = None): if index != None: self.dices[index] = random.randint(1, 6) else: self.roll() dice_set = DiceSet() dice_set.roll() i = 0 while isinstance(i,int): if dice_set.get_current(i) == 6: i += 1 else: dice_set.reroll(i) dice_set.get_current(i) if i == 5 and dice_set.get_current(5) == 6: break dice_set.get_current()
""" You can find some posts and their comments in this file. Now you need to find the post which got the most popular comments. Most popular comments mean the sum of the likes on the comments. """ import json #Read file.json by using json #with open(filename, 'rb') as f #jsondata = json.loads(f.read()) def findpopularpost(filename): try: with open(filename, 'rb') as f_post: jsondata = json.loads(f_post.read()) sumlike_list = [] for i in range(len(jsondata)): temp = 0 if jsondata[i]['comments'] == None: sumlike_list.append(temp) else: for j in range(len(jsondata[i]['comments'])): temp = temp + jsondata[i]['comments'][j]['like_count'] sumlike_list.append(temp) popindex = sumlike_list.index(max(sumlike_list)) print(f"The most popular posts with maximum {max(sumlike_list)} like is ") return jsondata[popindex] except: print("Please enter a correct filename") findpopularpost('posts.json')
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 15:24:34 2019 @author: sridhar """ import math def cci(a,b,c): if (a+b)>c and (b+c)>a and (c+a)>b: s = (a+b+c)/2 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) cicr = (a*b*c)/(4*area) inr = (2*area)/(a+b+c) print("area of the circumscribed circle =",cicr) print("area of the inscribed circle =",inr) else: print("Circle cannot be formed by given parameters") cci(a = int(input("Enter the first side=")),b = int(input("Enter the first side=")),c = int(input("Enter the first side=")))
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gs import matplotlib.colors as mcolors class Engine(object): def __init__(self): #The context defines how far the agent can see self.context = 3 #set the range on how tall the map can be self.min_height = 5 self.max_height = 6 #set the ramge on how long the map can be self.min_width = 25 self.max_width = 25 : #The grace zone defines an area where there can be no walls #This makes it easier to ensure the agent/goal is not initialised in a wall self.grace_zone = 3 self.reset() def reset(self): self.gen_world() self.gen_walker() def gen_world(self): #dimensions of the map self.height = np.random.randint(self.min_height,self.max_height+1) self.width = np.random.randint(self.min_width,self.max_width+1) #Open spaces in the world are represented by zeros, walls as ones #We make the walls as thick as the agent can see self.world = np.zeros([self.width+2*self.context, self.height+2*self.context]) self.world[:,:self.context],self.world[:,-self.context:] = 1,1 self.world[:self.context,:],self.world[-self.context:,:] = 1,1 self.final_wall = self.width + self.context #distance value to the furthest wall counter = 1 #keeps track of how many columns have passed with no wall i = self.context+self.grace_zone #no walls in left-most area where the agent starts while i < self.final_wall-self.grace_zone: if np.random.power(counter) > 0.5: #a wall is more likely to be placed if there has not been one in a while counter = 0 length = np.random.randint(0,4) #length of the wall to be added start = np.random.randint(0,5) #grid-cell in which the first wallplacement will be self.world[i, np.arange(start, start+length)%self.height + self.context] = 1 i += 1#ensures there cannot two walls simultaneously which will likely create a block i += 1 counter += 1 #generate the position of the goal, the goal will be denoted as a negative one self.goal_pos = np.array([np.random.randint(self.final_wall - self.grace_zone, self.final_wall), np.random.randint(self.context,self.height+self.context)]) self.world[self.goal_pos[0], self.goal_pos[1]] = -1 def gen_walker(self): self.walker_pos = np.array([np.random.randint(self.context,self.context+3), np.random.randint(self.context,self.height+self.context)]) #returns only the area seen by agent def get_local(self): x,y = self.walker_pos local = np.copy(self.world[x-self.context:x+self.context+1, y-self.context:y+self.context+1]) local[self.context, self.context] = 2 #agent is defined as 2 in the world return local #returns entire world, including the outside walls def get_world(self): x,y = self.walker_pos world = np.copy(self.world) world[x, y] = 2 #agent is defined as 2 in the world return world def move_left(self): if self.world[self.walker_pos[0] -1, self.walker_pos[1]] < 1: self.walker_pos[0] -= 1 def move_right(self): if self.world[self.walker_pos[0] +1, self.walker_pos[1]] < 1: self.walker_pos[0] += 1 def move_down(self): if self.world[self.walker_pos[0], self.walker_pos[1] -1] < 1: self.walker_pos[1] -= 1 def move_up(self): if self.world[self.walker_pos[0], self.walker_pos[1] +1] < 1: self.walker_pos[1] += 1 def no_move(self): return def is_done(self): return np.array_equal(self.walker_pos, self.goal_pos) def display(self): grid = gs.GridSpec(2,1) fig = plt.figure() rgbarray = np.vstack([[1,1,1],[0.1,0,0.1],[0.15,0.15,1],[0.75,0.75,0]]) cmap = mcolors.ListedColormap(rgbarray) ax0 = fig.add_subplot(grid[0]) display = np.copy(self.world)%4 display[self.walker_pos[0], self.walker_pos[1]] = 2 display = display[self.context-1:-self.context+1 ,self.context-1:-self.context+1] ax0.imshow(display.T,vmin=0, vmax=3, origin = 'lower',cmap = cmap) ax0.set_xticks(np.arange(-.5, self.width+1, 1)) ax0.set_yticks(np.arange(-.5, self.height+1, 1)) ax0.set_xticklabels([]) ax0.set_yticklabels([]) ax0.grid(alpha=0.5) inner = gs.GridSpecFromSubplotSpec(1,2, subplot_spec=grid[1]) ax1 = fig.add_subplot(inner[0]) local = self.get_local()%4 ax1.imshow(local.T,vmin=0, vmax = 3,origin = 'lower', cmap=cmap) ax1.set_xticks(np.arange(-.5, self.context*2+1, 1)) ax1.set_yticks(np.arange(-.5, self.context*2+1, 1)) ax1.set_xticklabels([]) ax1.set_yticklabels([]) ax1.grid(alpha=0.5) ax2 = fig.add_subplot(inner[1]) ax2.axis('off') plt.show()
# -*- coding: utf-8 """String utilities""" __all__ = ('startswith_token', 'prefix') def startswith_token(s, prefix, sep=None): """Tests if a string is either equal to a given prefix or prefixed by it followed by a separator. """ if sep is None: return s == prefix prefix_len = len(prefix) return s.startswith(prefix) and ( not sep or len(s) == prefix_len or s.find(sep, prefix_len, prefix_len + len(sep)) == prefix_len) def prefix(s, *args, reverse=False): if reverse: pos = s.rfind(*args) else: pos = s.find(*args) return s[:pos] if pos >= 0 else s
# Declaring and initializing a variable. # Taking input from the user in floating point number. number = float(input("Enter a number:\n")) # Using an if statement to check if the number if positive. # If the number given by the user is greater than 0, then it is Positive. if number > 0: print("Positive number") # Using else if statement to check if the number is equal to zero. elif number == 0: print("Zero") # Using else statement to check if the number is negative. else: print("Negative number")
kolor = input('Jaki kolor lubisz?\n').lower() if kolor == 'czerwony': print('Ja też lubię czerwony') else: print(f'Nie lubie koloru {kolor}, wolę kolor czerwony') rainy = input("Is it raining?\n").lower() if rainy == 'yes': windy = input('Is it windy?\n').lower() if windy == 'yes': print('It`s too windy for umbrella.') elif windy == 'no': print('Take your umbrella.') elif rainy == 'no': print('Enjoy your day!') name = input("What`s your name?\n") print(len(name)) name = input("What`s your name?\n") surname = input("What`s your surname?\n") name_surname = name + ' ' + surname print(name_surname, len(name_surname)) name = input("What`s your name(in lower case)?\n").title() surname = input("What`s your surname(in lower case)?\n").title() name_surname = name + ' ' + surname print(name_surname) first_name = input('What`s your first name?') if len(first_name) < 5: surname = input('What`s your first name?') name = first_name + surname print(name.upper()) else: print(first_name.lower()) answer = input('Podaj jakiś tekst: ') answer_len = len(answer) start_num = int(input("Podaj liczbę od 1 do {}".format(answer_len + 1))) end_num = int(input("Podaj liczbę od {} do {}".format(start_num + 1, answer_len + 1))) print(answer[start_num - 1: end_num - 1]) word = input("say a word: ") vowel = ['a', 'e', 'o', 'u', 'i', 'y'] if word[0] in vowel: print(word + 'way') else: pig_word = word[1:len(word)] + word[0] + 'ay' print(pig_word) lista_miats = ['Wrocław', 'Warszawa', 'Londyn', 'Poznan'] wycinek1 = lista_miats[1:3] wycinek2 = lista_miats[1:] print(lista_miats) print(wycinek1) print(wycinek2) #a male_miasta = str(lista_miats) print(male_miasta.lower())
''' 1. Having a non-empty array of non-negative integers of length N, you need to return the maximum sum of subset of array elements such that you never take any two adjacent elements. 1 <= N <= 10^9 Example 1: input - [1,2,3,1], output - 4. You take 1st and 3rd elements Example 2: input - [2,7,9,3,1], output - 12. You take 1st, 3rd and 5th elements ''' def get_sum(arr: []) -> int: len_arr = len(arr) if len_arr == 2: return arr[0] if arr[0] > arr[1] else arr[1] if len_arr == 3: return arr[0] + arr[2] if arr[0] + arr[2] > arr[1] else arr[1] i = 0 if arr[0] + arr[2] > arr[1] + arr[3] else 1 cur_sum = arr[i] while i < len_arr: next_i = i + 2 if next_i >= len_arr: break if next_i+1 < len_arr and cur_sum + arr[next_i+1] > cur_sum + arr[next_i]: next_i += 1 cur_sum = cur_sum + arr[next_i] i = next_i return cur_sum print(get_sum([1,2,3,1])) # res: 4 print(get_sum([2,7,9,3,1])) # res: 12 print(get_sum([2,7,9,31,1])) # res: 38 print(get_sum([2,7,9,31,1, 2,7,9,311,1])) # res: 356 print(get_sum([2,1,1,2])) # res: 4
# buggy.py # silly program that does nothing to improve mankind!!! import random number1 = random.randint(1,10) number2 = random.randint(1,10) print('What is ' + str(number1) + ' + ' + str(number2) + ' ?') answer = int(input()) if answer == number1 + number2: print('Correct!') else: print('Nope!! The answer is ' + str(number1 + number2)) print('Hellllllllllllllllllllllllllooooooooooooo')
#!/usr/bin/python """ Program: getConcertInfo.py Author: Devin McGinty This pulls information from the WXPN concert calendar and displays it using in two windows (using ncurses). The left window displays the list of artists and the right window displays artist concert information. Uses: curses locale re urllib """ __author__ = "Devin McGinty" import curses import locale import re # import sys from urllib.request import urlopen def getMonth(n): """Return a month name for a given integer n.""" months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] return months[(int(n) - 1) % 12] def formatConcert(day,date,venue,cost): """Pack concert information into a dictionary""" date = date.split('-') m, d, y = range(3) # MM-DD-YYYY formatted day details = ["venue", "year", "month", "date", "day", "cost"] concert = [venue, date[y], date[m], date[d], day, cost] return dict(zip(details, concert)) def concertList(url): """Pull WXPN concert calendar to parse concert data. Return a library, with artist names as keys, corresponding to lists of libraries, each representing a concert. The structure is formatted below: { "Artist name": [ { Concert 1 Library }, { Concert 2 Library } ... ], ... } Requires: urllib.urlopen re Calls: formatConcert() """ site = urlopen(url) site_data = [] for line in site.readlines(): site_data.append(str(line, encoding='utf8')) site.close() # All concert information is denoted with table cell tags artist_tag = "<td " site_data = [l for l in site_data if artist_tag in l] # Regex's for components to parse artist_re = re.compile("(?<=<b>)[^<]+(?=<)") day_re = re.compile('(?<=-1">)[a-zA-Z]{3}(?=<)') date_re = re.compile('(?<=0">)[0-9\-]{10}') venue_re = re.compile('(?<=2">)[^<]*') cost_re = re.compile('(?<=3">)[^<]*') artists = {} for l in site_data: art = artist_re.search(l) if art: name = art.group() day = day_re.search(l).group() date = date_re.search(l).group() venue = venue_re.search(l).group() cost = cost_re.search(l).group() concert = formatConcert(day,date,venue,cost) if name not in artists: artists[name] = [concert] else: artists[name].append(concert) return artists def trimName(name,length): """Trim a string and append an ellipses (...) if the string exceeds a given length. """ if len(name) > length: name = name[:length] + "..." return name def populateListWin(win, names, offset, MID_Y, width): """Populate the artist list window. The active artist, given by names[offset] is highlighted and indented, in order to make it stand out, as shown: ____________________ |names[offset - 2] | |names[offset - 1] | | NAMES[offset] | |names[offset + 1] | |names[offset + 2] | |____________________| Parameters: win - Curses subwindow to be populated names - List of alphabetized artist names offset - Name to be highlighted MID_Y - vertical midpoint of win, position of names[offset] width - horizontal width of window, used to trim strings to fit Requires: curses Calls: trimName() """ win.clear() win.border() MARGIN = 1 width -= 7 SHIFT = 4 main_name = trimName(names[offset], width - SHIFT) # Add highlighted name win.addstr(MID_Y, MARGIN + SHIFT, main_name, curses.A_STANDOUT) # Add other names for row in range(1, MID_Y - MARGIN): if offset - row >= 0: # Above midpoint artist = trimName(names[offset - row], width) win.addstr(MID_Y - row, MARGIN, artist) if offset + row < len(names): # Below midpoint artist = trimName(names[offset + row], width) win.addstr(MID_Y + row, MARGIN, artist) win.refresh() def populateInfoWin(win, concerts, name): """Populate info window with artist and concert information. Parameters: win - curses subwindow to be populated concerts - List of dictionaries, each dictionary repesents a concert. name - Artist name Requires: curses """ win.clear() win.border() MARGIN = 4 win.addstr(MARGIN // 2, MARGIN // 2, name, curses.A_UNDERLINE) row = MARGIN for c in concerts: day = c["day"] + " " day += c["date"] + " " day += getMonth(c["month"]) + " " day += c["year"] win.addstr(row, MARGIN, c["venue"], curses.A_BOLD) win.addstr(row + 1, MARGIN * 2, day) win.addstr(row + 2, MARGIN * 2, c["cost"]) row += 4 win.refresh() def main(screen): """Initialize artist list and curses. Wait for user input and update subwindows accordingly, or quit. Requires connection to the internet to retrieve WXPN website Requires: curses Calls: concertList() populateInfoWin() populateListWin() """ # Load concert data URL = "http://www.xpn.org/events/concert-calendar" concerts = concertList(URL) # Initialize curses screen.leaveok(1) curses.curs_set(0) # Set up main screen, footer information. MAX_Y, MAX_X = screen.getmaxyx() MARGIN = 2 guide = "Scroll down/up using arrow keys or 'j'/'k'. Press 'q' to quit.\n" guide += " Fast scroll using 'J'/'K'." screen.addstr(MAX_Y - MARGIN,MARGIN,guide) info = "Devin McGinty 2014" screen.addstr(MAX_Y - MARGIN,MAX_X - (len(info) + 2 * MARGIN),info) # Create sub windows SUB_Y = MAX_Y - (2 * MARGIN) SUB_X = (MAX_X // 2) - (2 * MARGIN) LIST_WIN = screen.subwin(SUB_Y, SUB_X, MARGIN, MARGIN) LIST_MID = int((LIST_WIN.getmaxyx()[0]) / 2) INFO_WIN = screen.subwin(SUB_Y, SUB_X , MARGIN, (2 * MARGIN + SUB_X)) artists = list(sorted(concerts)) offset = 0 UP = curses.KEY_UP DN = curses.KEY_DOWN # Main loop while 1: populateListWin(LIST_WIN, artists, offset, LIST_MID, SUB_X) name = artists[offset] populateInfoWin(INFO_WIN, concerts[name], name) c = screen.getch() if c == ord('q') or c == ord('Q'): break elif (c == UP or c == ord('k')) and offset > 0: offset -= 1 elif (c == DN or c == ord('j')) and offset < len(artists): offset += 1 elif c == ord('K') and offset > 0: offset -= SUB_Y - (2 * MARGIN) elif c == ord('J') and offset < len(artists): offset += SUB_Y - (2 * MARGIN) # Safety resets for the offset if offset > len(artists) - 1: offset = len(artists) - 1 if offset < 0: offset = 0 if __name__ == "__main__": locale.setlocale(locale.LC_ALL,"") curses.wrapper(main)
name = input('Coloque seu nome: ') test1 = float(input('Coloque a nota da primeira prova: ')) test2 = float(input('Coloque a nota da segunda prova: ')) average = (test1 + test2)/2 print('Olá {} seja bem-vindo. A nota da sua primeira prova é {:.2f}'.format(name, test1), end=' ') print('A nota da sua segunda prova é {:.2f} e a sua média foi de {:.2f}'.format(test2, average))
def sum_list(p): sum = 0 for e in p: sum = sum + e return sum print sum_list([1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,0,0,8,67,5,5,4,3,3]) def has_duplicate_element(p): res = [] for i in range(0, len(p)): for j in range(0, len(p)): if i != j and p[i] == p[j]: return True return False print has_duplicate_element([1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,0,0,8,67,5,5,4,3,3]) def mystery(p): i = 0 while True: if i >= len(p): break if p[i] % 2: i = i + 2 else: i = i + 1 return i print mystery([1,1,5])
# def bigger(a,b): # if a > b: # return a # else: # return b # # def smaller(a,b): # if a < b: # return a # else: # return b # # def biggest(a,b,c): # return bigger(a,bigger(b,c)) # # def smallest(a,b,c): # return smaller(a,smaller(b,c)) # # def median(a,b,c): # max = biggest(a,b,c) # min = smallest(a,b,c) # return (min,max) # print (median(10,20,30)) # def find_last(string,str_string): # # position=string.find(str_string) # return position # print find_last("abcdefgh","i") # def test(): # test_cases = [ # ((2012,1,1,2012,2,28), 58), # ((2012,1,1,2012,3,1), 60), # ((2011,6,30,2012,6,30), 366), # ((2011,1,1,2012,8,8), 585 ), # ((1900,1,1,1999,12,31), 36523) # ] # # for (args, answer) in test_cases: # result = daysBetweenDates(*args) # if result != answer: # print "Test with data:", args, "failed", 'expected', answer, 'result', result # else: # print "Test case passed!", args, 'result', result # # test() p=[1,2] def proc1(p): q=[] while p: q.append(p.pop()) while q: p.append(q.pop()) print p print p proc1(p)
#!/usr/bin/python -tt import sys import httplib import HTMLParser import urllib,urllib2 from urllib2 import urlopen ''' Valid is a datastructure that stores a url together with a val parameter which is set to true or false depending on whether the url is a valid one or not ''' class Valid: ''' I suppose keeping a temperory repository of last 1000 links would speed up the process . Store here is that cache''' store = [] def __init__(self,the_url): if not the_url.startswith('http'): the_url = 'http://' + the_url self.url = the_url self.val = False ''' check function checks thevarious kinds of errors that may be associated with the url ''' def check(self): if self.url not in Valid.store: try: code = urlopen(self.url).code except ValueError: self.val = False except urllib2.HTTPError: self.val = False except urllib2.URLError: self.val = False except httplib.InvalidURL: self.val = False else: if code < 400: self.val = True Valid.store.append(self.url) if len(Valid.store)>=20: del Valid.store[0]
#!/usr/bin/env python3 """add duntion""" def add(a: float, b: float) -> float: """add Args: a (float): first numbre b (float): second number Returns: float: their sum as a float. """ return a + b
#!/usr/bin/env python3 """ basic async syntax""" import asyncio import random async def wait_random(max_delay: int = 10) -> float: """wait_random Args: max_delay (int, optional): integer. Defaults to 10. Returns: float: randon number between 0 and mas_dalay """ i = random.uniform(0, max_delay) await asyncio.sleep(i) return i