blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
7234a33a3295c694ce51d2719da4e096c818168f
arononeill/Python
/Sorting/selectionSort.py
440
3.640625
4
def selectionSort(list): for fillslot in range(length-1,0,-1): GreatestPosition = 0 for location in range(1,fillslot+1): if list[location]>list[GreatestPosition]: GreatestPosition = location temp = list[fillslot] list[fillslot] = list[GreatestPosition] list[GreatestPosition] = temp list = [54,26,93,17,77,31,44,55,20] length = len(list) selectionSort(list) print(list)
e54903690eceffc1bd7b49faa2db0f79d111f974
TheManyHatsClub/EveBot
/src/helpers/fileHelpers.py
711
4.125
4
# Take a file and read it into an array splitting on a given delimiter def parse_file_as_array(file, delimiter=None): # Open the file and get all lines that are not comments or blank with open(file, 'r') as fileHandler: read_data = [(line) for line in fileHandler.readlines() if is_blank_or_comment(line) == False] # If no delimiter is given, split on newlines, else we need to split on the delimiter if delimiter is None: file_array = read_data else: file_array = "".join(read_data).split(delimiter) return file_array # Determines whether a line is either blank or a comment def is_blank_or_comment(line): return line.strip() == '' or line[0:2] == "//"
e2fe6cea47113c933eb4202561d53411229b1240
MuhamadRamadan/Explore_US_Bikeshare_Data
/bikeshare.py
15,941
4.28125
4
import time import pandas as pd from tabulate import tabulate # Pretty-print tabular data in Python, a library and a command-line utility. #import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city and time filter to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') i = 0 # variable to limit number of wrong data entry if user is not serious city = "" # name of the city to analyze month = "" # name of the month to filter by, or "all" to apply no month filter day = "" # name of the day of week to filter by, or "all" to apply no day filter city_dict = {'chic.':'chicago', 'ny':'new york', 'wa':'washington' } # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs print("Whould you like to see data from Chicago, Washington or New York?") while (city not in city_dict.keys()) and (city not in city_dict.values()): # To have a case agnost input, convert the input to lower case regardless of the casing input by user city = input("Enter city name exactly as above. If you are lazy enter the abbr. as Chic., NY, WA respectively.\n").lower() i += 1 # limit the number of wrong data entry to 10 and warrning in between if i == 5: print("Are you serious? Please enter city name correctly") elif i == 10: print("Man up!! YOU ARE NOT SERIOUS..If you still interested, you have to restart") break #Check point when the user exceed the number of data entry limit. if city not in city_dict.values(): try: city = city_dict[city] except KeyError: city = "" # get user input to which time filter he wants to apply on data filter_list = ['month', 'day', 'both', 'none'] # a list of all time filter options that can be selected by user user_filter = "" # a str get user choice for the time filter i = 0 while (user_filter not in filter_list) and (city != ""): #don't continue as long as no vaild city entered from user # To have a case agnost input, convert the input to lower case regardless of the casing input by user user_filter = input('Whould you like to filter the data by month, day, both or not at all? Type "none" for no time filter\n').lower() i += 1 # limit the number of wrong data entry to 10 and warrning in between if i == 5: print("Are you serious? Please enter the filter correctly") elif i == 10: print("Man up!! YOU ARE NOT SERIOUS..If you still interested, you have to restart") break if user_filter == "none": month = "all" day = "all" elif user_filter == "month": month = get_month_filter() day = "all" elif user_filter == "day": month = "all" day = get_day_filter() elif user_filter == "both": month = get_month_filter() if month != "": #Check point when the user exceed the number of data entry limit. day = get_day_filter() print('-'*40) return city, month, day def get_month_filter(): """ Asks user to specify a month to analyze. Returns: (str) user_filter - name of the month to filter by """ # get user input for month (january, february, ... , june) months = ['january', 'february', 'march', 'april', 'may', 'june'] # A lit of months to be selected for filtering i = 0 # variable to limit number of wrong data entry if user is not serious user_filter = "" # a str get user choice for month filter while user_filter not in months: # To have a case agnost input, convert the input to lower case regardless of the casing input by user user_filter = input("Which month? January, February, March, April, May, or June?\n").lower() i += 1 # limit the number of wrong data entry to 10 and warrning in between if i == 5: print("Are you serious? Please enter the month correctly") elif i == 10: print("Man up!! YOU ARE NOT SERIOUS..If you still interested, you have to restart") user_filter = "" break return user_filter.lower() def get_day_filter(): """ Asks user to specify a day of week to analyze. Returns: (str) user_filter - name of the day to filter by """ # get user input for day of week (monday, tuesday, ... sunday) days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] # A lit of days to be selected for filtering i = 0 # variable to limit number of wrong data entry if user is not serious user_filter = "" # a str get user choice for day filter while user_filter not in days: # To have a case agnost input, convert the input to lower case regardless of the casing input by user user_filter = input("Which day? Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, or Saturday?\n").lower() i += 1 # limit the number of wrong data entry to 10 and warrning in between if i == 5: print("Are you serious? Please enter the day correctly") elif i == 10: print("Man up!! YOU ARE NOT SERIOUS..If you still interested, you have to restart") user_filter = "" break return user_filter.lower() def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # convert the Start Time & End Time columns to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) df['End Time'] = pd.to_datetime(df['End Time']) # extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.dayofweek # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) +1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] day = days.index(day) df = df[df['day_of_week'] == day] # extract hour from the Start Time column to create an hour column df['hour'] = df['Start Time'].dt.hour # Create a trip column from start station to end station df['trip'] = df['Start Station'] + "_" + df['End Station'] return df def time_stats(df, month, day): """ Displays statistics on the most frequent times of travel. Args: (Pandas DataFrame) df - Data set the function will apply the stats on (str) month - name of the month the user used as filter or 'all' (str) day - name of the day the user used as filter or 'all' """ print('\nCalculating The Most Frequent Times of Travel...') start_time = time.time() print('_'*60, '\n') # display the most common month popular_month = df['month'].mode()[0] months = ['january', 'february', 'march', 'april', 'may', 'june'] print("The most common month is:\n{}".format(months[popular_month-1].title())) # If the user filtered on month, print notification that common month stats is irrelevant if month != 'all': print("You filtered on that month so above stat is irrelevant") print('*'*60) # display the most common day of week popular_day = df['day_of_week'].mode()[0] days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] print("The most common day is:\n{}".format(days[popular_day].title())) # If the user filtered on day, print notification that common month stats is irrelevant if day != 'all': print("You filtered on that day so above stat is irrelevant") print('*'*60) # display the most common start hour popular_hour = df['hour'].mode()[0] print("The most common hour of the day is:\n", popular_hour ) print('*'*60) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """ Displays statistics on the most popular stations and trip. Args: (Pandas DataFrame) df - Data set the function will apply the stats on """ print('\nCalculating The Most Popular Stations and Trip...') start_time = time.time() print('_'*60, '\n') # display most commonly used start station popular_start_station = df['Start Station'].mode()[0] print("The most popluar start station is:\n ", popular_start_station.title()) print('*'*60) # display most commonly used end station popular_end_station = df['End Station'].mode()[0] print("The most popluar end station is:\n ", popular_end_station.title()) print('*'*60) # display most frequent combination of start station and end station trip popular_trip = df['trip'].mode()[0] popular_trip_st_a = popular_trip.split("_")[0] popular_trip_st_b = popular_trip.split("_")[1] print("The most popular trip is:") print(" Start Station:", popular_trip_st_a) print(" End Station:", popular_trip_st_b) print('*'*60) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """ Displays statistics on the total and average trip duration. Args: (Pandas DataFrame) df - Data set the function will apply the stats on """ print('\nCalculating Trip Duration...') start_time = time.time() print('_'*60, '\n') # Calculate trip time from start & end time columns and create a trip_time column df['trip_time'] = df['End Time'] - df['Start Time'] # display total travel time calculated total_travel_time_calc = df['trip_time'].sum() print("The total traveling time done for 2017 through June (calculated):\n", total_travel_time_calc) print('*'*60) # display mean travel time calculated average_travel_time_calc = df['trip_time'].mean() print("The average time spent for each trip (calculated):\n", average_travel_time_calc) print('*'*60) # display total travel time from Trip Duration column total_travel_time = df['Trip Duration'].sum() print("The total traveling time done for 2017 through June (Dataset):\n", total_travel_time) print('*'*60) # display total travel time from Trip Duration column average_travel_time = df['Trip Duration'].mean() print("The average time spent for each trip (Dataset):\n", average_travel_time) print('*'*60) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """ Displays statistics on bikeshare users. Args: (Pandas DataFrame) df - Data set the function will apply the stats on """ print('\nCalculating User Stats...') start_time = time.time() print('_'*60, '\n') # Display counts of user types # This has been excluded for longer execution time # user_types = df.groupby(['User Type'])['User Type'].count() user_types = df['User Type'].value_counts() print("The counts of user types are:") #use reset_index & to_string to suppress Name & dtype from the output print((user_types.reset_index()).to_string(header=None, index=None)) print('*'*60) # Use try-except clause to skip Gender/Birth year stats in case of Washington try: # Display counts of gender user_gender = df['Gender'].value_counts() print("The counts of each gender are:") #use reset_index & to_string to suppress Name & dtype from the output print((user_gender.reset_index()).to_string(header=None, index=None)) print('*'*60) # Display earliest, most recent, and most common year of birth earliest_birth_year = df['Birth Year'].min() most_recent_birth_year = df['Birth Year'].max() most_common_birth_year = df['Birth Year'].mode()[0] print("The earlies Birth Year is:", earliest_birth_year) print('#'*40) print("The most recent Birth Year is:", most_recent_birth_year) print('#'*40) print("The most common Birth Year is:", most_common_birth_year) print('*'*60) except KeyError: print('No gender/year of birth data to share for Washington') print('*'*60) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def main(): while True: city, month, day = get_filters() #Check point when the user exceed the number of data entry limit, he need to restart if he still interested try: df = load_data(city, month, day) except KeyError: break except ValueError: break # Check which stats the user is interested in and display stats one by one upon his needs if input("'\nWould you like to see time stats? Enter yes or press any key if no.\n").lower() == 'yes': time_stats(df, month, day) if input("'\nWould you like to see station stats? Enter yes or press any key if no.\n").lower() == 'yes': station_stats(df) if input("'\nWould you like to see trip stats? Enter yes or press any key if no.\n").lower() == 'yes': trip_duration_stats(df) if input("'\nWould you like to see user stats? Enter yes or press any key if no.\n").lower() == 'yes': user_stats(df) # cleaning up Data Frame by deleting all added columns and keep the original ones to be displayed to user upon request df.drop(columns = ['month', 'day_of_week', 'hour', 'trip', 'trip_time'], errors = 'ignore', inplace = True) # Displaying individual trips in groups of 5 rows untill the user says no print("We came to the end of stats show. We hope you liked it!") display_data = input('\nWould you like to view 5 rows of individual trip data? Enter yes or press any key if no\n').lower() pointer_loc = 0 # A variable used as a pointer to the row/s need to be diplayed while display_data == 'yes': pd.set_option("display.max_columns", None) # the maximum number of columns to display to unlimited. (Hint. this can be used for rows as well) print(tabulate(df.iloc[pointer_loc : pointer_loc + 5], headers='keys', tablefmt='pretty', showindex = False)) # use tabulate to diplay rows in a pretty table display_data = input('\nWould you like to continue? Enter yes or press any key if no\n').lower() pointer_loc += 5 restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
c70566c6b0a4e05b9278373b358c14e21e6ac103
Natan10/ProjetoAquario
/Classes/luz.py
941
3.828125
4
#Classe Portao # Nome_Luz : # Ligada: Ligada / Desligada # Ativar: Liga / Desliga a Luz # Potencia: Ajusta a potência da luz, se possível... Como fazer um método opcional? acho melhor não fazer kkk import random import time class Luz: def __init__(self,nome, ligada = 0, tempo_ligada = 0): self.nome = nome self.ligada = ligada self.tempo_ligada = tempo_ligada def get_nome(self): return self.nome def get_estado_luz(self): if self.ligada == 1: return "Ligada" else: return "Desligada" def set_estado_luz(self): if self.ligada == 1: self.ligada = 0 self.tempo_ligada = int(time.time() - self.tempo_ligada) return "Luz desligada!" else: self.ligada = 1 self.tempo_ligada = time.time() return "Luz ligada!" def get_tempo_ligada(self): if(self.ligada): return int(time.time() - self.tempo_ligada) return self.tempo_ligada
07a84d9a07ae1be948cb524f53a03a866f62ade7
hmercado237/hmercado237.github.io
/chatbot2.py
1,232
4.09375
4
# --- Define your functions below! --- def intro(): print("HELLO, I AM CHATBORT") print("LET'S TALK!") print("[INSTRUCTIONS FOR USE]") # RPS # Different bort personalities def choosePersonality(): print("Choose a personality to talk to. You can choose:") choice = input("Mean, Nice, or Nervous") return choice # --- Put your main program below! --- def main(): mean = ("Hi" : "CAN YOU LEAVE", "What's up" : " DON'T SPEAK TO ME FOOL!", "How are you?" : "TERRIBLE, NOW THAT I AM TALKING TO YOU." ) nice = ("Hi :""HI, IT'S SO NICE TO MEET YOU!", "What's up" : "OH I'M JUST TALKING TO THE MOST INTERESTING PERSON IN THE WORLD.", "How are you?" : "OH I'M JUST LOVELY!") nervous = ( "Hi" : "", "What's up" : "...UM, HI.", "How are you?" : "NERVOUS!") userChoice = choosePersonality() intro() while True: answer = input("(What will you say?)") if userchoice = "Nice": print(userChoice[answer]) elif userchoice = "Mean": print(userChoicer[answer]) elif userChoice = "Nervous": print(userChoice[answer]) # DON'T TOUCH! Setup code that runs your main() function. if __name__ == "__main__": main()
a37e4d06363f8ead6644dff84add4cf30cd8bbd3
taucsrec/recitations
/2018a/Michal/rec1/tester_example.py
284
3.8125
4
print ("hi") def check_parity(n): if n % 2 == 0: return "even" else: return "odd" def test(): if check_parity(0) == "odd": print("error in function check_parity") if check_parity(1) == "even": print("error in function check_parity")
2c60fa8bde0253965de757c32599fc6be923d46e
rajatmann100/rosalind-bioinformatics-stronghold
/p3-revc.py
398
3.59375
4
# read file file = open("./data/rosalind_revc.txt", "r") input_str = file.read() print(input_str) reverse_str = input_str[::-1] def getComplement(bp): switcher = { "A": "T", "T": "A", "C": "G", "G": "C" } return switcher.get(bp, "nothing") COMP_STR = '' for x in reverse_str: if(x != "\n"): COMP_STR += getComplement(x) print(COMP_STR)
6af6841b7adc41f77845bb13eeee3bd855bc388e
pviktoria/Python
/biggest.py
287
3.875
4
def multinumber(): list=[] for i in range(0,5): number=int(input("Szám: ")) list.append(number) multiplenum=multiple(list) print("A szorzat: {:^10}".format(multiplenum)) def multiple(list ): sum= 1 for i in list: sum*=i return sum multinumber()
18e427e8cf326d2e04699da0a321443d1a5b9ba1
pviktoria/Python
/harmadik2_nehez.py
805
3.53125
4
Név= 'Pap Viktória, ' Osztály= 'Szoftverfejlesztő-esti, ' Dátum= '2020-12-16, 15m' Feladat='Állatok nevét és súlyát adja meg' print(Név, Dátum) print(Feladat) import allat állatfajok = [] for _ in range(3): fajnév = input('Add meg egy állatfaj nevét! ') tömeg = input('Hány kilogramm a tömege egy példánynak? ') állatfaj = allat.Állatfaj(fajnév, tömeg) állatfajok.append(állatfaj) legnehezebb_állat = állatfajok[0] for állatfaj in állatfajok: print('A(z) ', állatfaj.fajnév, ' tömege ', állatfaj.tömeg, ' kg.', sep='') if állatfaj.tömeg > legnehezebb_állat.tömeg: legnehezebb_állat = állatfaj célfájl = open('legnehezebb.txt', 'w') print('A(z)', legnehezebb_állat.fajnév, 'a legnehezebb.', file=célfájl) célfájl.close()
0c861151d4f8fb374ae5a766dab0a25567722099
yauheni-sarokin/for_tests
/tests/test006/main3.py
423
3.640625
4
class Property: def __init__(self) -> None: self._my_value = None @property def my_value(self) -> int: return self._my_value*5 @my_value.setter def my_value(self, my_value: int) -> None: self._my_value = my_value*3 if __name__ == '__main__': _property = Property() _property.my_value = 4 print(_property.my_value) print(_property.my_value)
0b62cb1c19d6b1ab85cd314d407acc390dd4812c
yauheni-sarokin/for_tests
/tests/test044/main5.py
360
3.84375
4
# Generators def repeater(value): while True: yield value def repeat_three_times(value): yield value yield value yield value if __name__ == '__main__': # for x in repeater('Hi'): # print(x) obj = repeater('hey') print(obj.__next__()) print(next(obj)) for x in repeat_three_times('hou'): print(x)
2a153ef02f9ea6ef69af466991f5e91f4052712e
yauheni-sarokin/for_tests
/tests/test040/main3.py
499
3.890625
4
# Instance, Class, and Static Methods # Demystified1 class MyClass: def method(self): return 'instance method called', self @classmethod def class_method(cls): return 'class method called', cls @staticmethod def staticmethod(): return 'static method called' if __name__ == '__main__': my_class = MyClass() print(my_class.method()) print(my_class.class_method()) print(MyClass.method(my_class)) print(my_class.class_method())
b196230fec17e6b74df20eb28ba2adb05525b3ab
yauheni-sarokin/for_tests
/tests/test038/main.py
426
3.84375
4
# abstract base classes from abc import ABCMeta, abstractmethod class Base(metaclass=ABCMeta): @abstractmethod def foo(self): pass @abstractmethod def bar(self): pass class Concrete(Base): def bar(self): pass def foo(self): pass if __name__ == '__main__': concrete = Concrete() print(issubclass(concrete.__class__, Base)) c = concrete.__class__()
53ee9c32a16ed0788b8bc85fd7c656f7f78e0620
cvpe/Pythonista-scripts
/Map for RocketBlaster05.py
20,119
3.578125
4
''' NOTE: This requires the latest beta of Pythonista 1.6 (build 160022) Demo of a custom ui.View subclass that embeds a native map view using MapKit (via objc_util). Tap and hold the map to drop a pin. The MapView class is designed to be reusable, but it doesn't implement *everything* you might need. I hope that the existing methods give you a basic idea of how to add new capabilities though. For reference, here's Apple's documentation about the underlying MKMapView class: http://developer.apple.com/library/ios/documentation/MapKit/reference/MKMapView_Class/index.html If you make any changes to the OMMapViewDelegate class, you need to restart the app. Because this requires creating a new Objective-C class, the code can basically only run once per session (it's not safe to delete an Objective-C class at runtime as long as instances of the class potentially exist). ''' from objc_util import * import ast import ctypes import ui import location from math import cos, sin, radians, sqrt, atan2, pi import os import time import weakref radius = 6371000 # earth radius in meters close_distance = 10 # maximum 10 meters between 2 close pin's close_number = 3 # minimum pin's number to set as a close area MKPointAnnotation = ObjCClass('MKPointAnnotation') MKPinAnnotationView = ObjCClass('MKPinAnnotationView') MKAnnotationView = ObjCClass('MKAnnotationView') # for photo as pin UIColor = ObjCClass('UIColor') # used to set pin color def haversine(lat1,lon1,lat2,lon2): dlat = radians(lat2 - lat1) dlon = radians(lon2 - lon1) # Haversine for.ula: https://en.wikipedia.org/wiki/Haversine_formula a = (sin(dlat / 2) * sin(dlat / 2) + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) * sin(dlon / 2)) c = 2 * atan2(sqrt(a), sqrt(1 - a)) d = radius * c return d def mapView_annotationView_calloutAccessoryControlTapped_(self,cmd,mk_mapview, mk_annotationView,mk_calloutAccessoryControlTapped): global locs pinView = ObjCInstance(mk_annotationView) mapView = ObjCInstance(mk_mapview) annotation = pinView.annotation() title = str(annotation.title()) lat = annotation.coordinate().a lon = annotation.coordinate().b if title == 'Current Location': # change lat,lon to differentiate user pin of trash pin lat += 0.00000001 lon += 0.00000001 mapView.ui_view.add_pin(lat, lon, 'deleted user point', str((lat, lon))) locs[(lat,lon)] = 'trash' # add (if was current) or updte (if user) record with open(path,mode='wt') as f: content = str(locs) f.write(content) # if user location, append a line in file with (lat,lon) if title == 'Current Location': mapView.deselectAnnotation_animated_(annotation, True) else: # delete old pin only if not the current location pin mapView.removeAnnotation_(annotation) # =========== special process for trying to center trash pin's: begin # loop on all pin's' locs_update = False for annotation1 in mapView.annotations(): if str(annotation1.title()) == 'deleted user point': # trash pin lat1 = annotation1.coordinate().a lon1 = annotation1.coordinate().b close_pins = [(lat1,lon1)] close_annots = [annotation1] # loop on all pin's for annotation2 in mapView.annotations(): if annotation2 == annotation1: continue # same, skip if str(annotation2.title()) == 'deleted user point': # compute haversine distance (on a sphere) between 2 points lat2 = annotation2.coordinate().a lon2 = annotation2.coordinate().b all_close = True for annotation3 in close_annots: lat3 = annotation3.coordinate().a lon3 = annotation3.coordinate().b d = haversine(lat3,lon3,lat2,lon2) if d > close_distance: all_close = False break if all_close: # pin 2 close to all pin's already in group close_pins.append((lat2,lon2)) close_annots.append(annotation2) if len(close_pins) >= close_number: # needed minimum number of pin's form a close area around pin 1 # get their center min_lat,min_lon,max_lat,max_lon,d_lat,d_lon = compute_region_param(close_pins) latc = (min_lat+max_lat)/2 lonc = (min_lon+max_lon)/2 # remove close pin's for annot in close_annots: latd = annot.coordinate().a lond = annot.coordinate().b mapView.removeAnnotation_(annot) del locs[(latd,lond)] # remove in locs locs_update = True del close_annots # create the center pin subtit = '' for lat,lon in close_pins: if subtit: subtit += '\n' subtit += str((lat,lon)) mapView.ui_view.add_pin(latc, lonc, 'deleted group', subtit) locs[(latc,lonc)] = close_pins if locs_update: with open(path,mode='wt') as f: content = str(locs) f.write(content) # ========== special process for trying to center trash pin's: end def mapView_viewForAnnotation_(self,cmd,mk_mapview,mk_annotation): global own_ui_image, del_ui_image, grp_ui_image try: # not specially called in the same sequence as pins created # should have one MK(Pin)AnnotationView by type (ex: pin color) annotation = ObjCInstance(mk_annotation) mapView = ObjCInstance(mk_mapview) if annotation.isKindOfClass_(MKPointAnnotation): tit = str(annotation.title()) subtit = str(annotation.subtitle()) id = tit pinView = mapView.dequeueReusableAnnotationViewWithIdentifier_(id) if not pinView: if tit == 'Current Location': # Show a photo instead of a pin: use MKAnnotationView pinView = MKAnnotationView.alloc().initWithAnnotation_reuseIdentifier_(annotation,id) pinView.setImage_(own_ui_image.objc_instance) elif tit == 'deleted user point': # Show a photo instead of a pin: use MKAnnotationView pinView = MKAnnotationView.alloc().initWithAnnotation_reuseIdentifier_(annotation,id) pinView.setImage_(del_ui_image.objc_instance) elif tit == 'deleted group': # Show a photo instead of a pin: use MKAnnotationView pinView = MKAnnotationView.alloc().initWithAnnotation_reuseIdentifier_(annotation,id) pinView.setImage_(grp_ui_image.objc_instance) l_title = ui.Label() l_title.font = ('Menlo',12) # police echappement fixe l_title.text = subtit lo = ObjCInstance(l_title) lo.setNumberOfLines_(0) pinView.setDetailCalloutAccessoryView_(lo) else: # Modify pin color: use MKPinAnnotationView pinView = MKPinAnnotationView.alloc().initWithAnnotation_reuseIdentifier_(annotation,id) pinView.animatesDrop = True # Animated pin falls like a drop if tit == 'Dropped Pin': pinView.pinColor = 0 # 0=red 1=green 2=purple elif tit == 'Current Location': pinView.pinColor = 2 # 0=red 1=green 2=purple else: pinView.pinColor = 1 # 0=red 1=green 2=purple pinView.canShowCallout = True # tap-> show title if tit in ['user point', 'Current Location']: # RightCalloutAccessoryView for trash button bo = ObjCClass('UIButton').alloc().init() bo.setTitle_forState_('🗑',0) bo.setFrame_(CGRect(CGPoint(0,0), CGSize(40,40))) pinView.setRightCalloutAccessoryView_(bo) else: pinView.annotation = annotation return pinView.ptr return None except Exception as e: print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e) # Build method of MKMapView Delegate methods = [mapView_annotationView_calloutAccessoryControlTapped_, mapView_viewForAnnotation_] protocols = ['MKMapViewDelegate'] try: MyMapViewDelegate = ObjCClass('MyMapViewDelegate') except Exception as e: MyMapViewDelegate = create_objc_class('MyMapViewDelegate', methods=methods, protocols=protocols) # _map_delegate_cache is used to get a reference to the MapView from the (Objective-C) delegate callback. The keys are memory addresses of `OMMapViewDelegate` (Obj-C) objects, the values are `ObjCInstance` (Python) objects. This mapping is necessary because `ObjCInstance` doesn't guarantee that you get the same object every time when you instantiate it with a pointer (this may change in future betas). MapView stores a weak reference to itself in the specific `ObjCInstance` that it creates for its delegate. _map_delegate_cache = weakref.WeakValueDictionary() class CLLocationCoordinate2D (Structure): _fields_ = [('latitude', c_double), ('longitude', c_double)] class MKCoordinateSpan (Structure): _fields_ = [('d_lat', c_double), ('d_lon', c_double)] class MKCoordinateRegion (Structure): _fields_ = [('center', CLLocationCoordinate2D), ('span', MKCoordinateSpan)] class MapView (ui.View): @on_main_thread def __init__(self, *args, **kwargs): ui.View.__init__(self, *args, **kwargs) MKMapView = ObjCClass('MKMapView') frame = CGRect(CGPoint(0, 0), CGSize(self.width, self.height)) self.mk_map_view = MKMapView.alloc().initWithFrame_(frame) self.mk_map_view.ui_view = self #print(dir(self.mk_map_view.region())) flex_width, flex_height = (1<<1), (1<<4) self.mk_map_view.setAutoresizingMask_(flex_width|flex_height) self_objc = ObjCInstance(self) self_objc.addSubview_(self.mk_map_view) self.mk_map_view.release() self.long_press_action = None self.scroll_action = None #NOTE: The button is only used as a convenient action target for the gesture recognizer. While this isn't documented, the underlying UIButton object has an `-invokeAction:` method that takes care of calling the associated Python action. self.gesture_recognizer_target = ui.Button() self.gesture_recognizer_target.action = self.long_press UILongPressGestureRecognizer = ObjCClass('UILongPressGestureRecognizer') self.recognizer = UILongPressGestureRecognizer.alloc().initWithTarget_action_(self.gesture_recognizer_target, sel('invokeAction:')).autorelease() self.mk_map_view.addGestureRecognizer_(self.recognizer) self.long_press_location = ui.Point(0, 0) self.map_delegate = MyMapViewDelegate.alloc().init()#.autorelease() self.mk_map_view.setDelegate_(self.map_delegate) self.map_delegate.map_view_ref = weakref.ref(self) _map_delegate_cache[self.map_delegate.ptr] = self.map_delegate # Add a map type button maptype_button = ui.Button() maptype_button.frame = (self.width-82,2,80,20) maptype_button.border_width = 1 maptype_button.corner_radius = 5 maptype_button.border_color = 'red' maptype_button.background_color = (1,0,0,0.8) maptype_button.tint_color = 'black' maptype_button.title = 'map type' maptype_button.action = self.maptype_button_action self.add_subview(maptype_button) self.mk_map_view.mapType = 0 camera_button = ui.Button() camera_button.frame = (maptype_button.x-40-2,2,40,20) camera_button.border_width = 1 camera_button.corner_radius = 5 camera_button.border_color = 'red' camera_button.background_color = (1,0,0,0.8) self.add_subview(camera_button) camera_button.tint_color = 'black' camera_button.title = '3D' camera_button.action = self.camera_button_action self.update_interval = 2 # call update each 2 seconds def update(self): location.start_updates() time.sleep(0.1) loc = location.get_location() location.stop_updates() if loc: lat, lon = loc['latitude'], loc['longitude'] # update face pin location coord = CLLocationCoordinate2D(lat, lon) self.user_annotation.setCoordinate_(coord, restype=None, argtypes=[CLLocationCoordinate2D]) def maptype_button_action(self,sender): x = self.x + sender.x + sender.width/2 y = 70 + self.y + sender.y + sender.height sub_menu_dict = {'standard':0, 'hybrid':2} #sub_menu_dict = {'standard':0, 'satellite':1, 'hybrid':2, 'satelliteFlyover':3, 'hybridFlyover':4, 'mutedStandard':5} sub_menu = [] for k in [*sub_menu_dict]: sub_menu.append(k) tv = ui.TableView() tv.frame = (0,0,180,85) #tv.frame = (0,0,180,280) tv.data_source = ui.ListDataSource(items=sub_menu) tv.allows_multiple_selection = False #tv.selected_row = (0,self.mk_map_view.mapType()) tv.delegate = self tv.present('popover',popover_location=(x,y),hide_title_bar=True) tv.wait_modal() map_type = sub_menu_dict[sub_menu[tv.selected_row[1]]] #print(map_type) if map_type != self.mk_map_view.mapType(): self.mk_map_view.mapType = map_type def camera_button_action(self,sender): # tests have shown that mkmapview has a default mkcamera if sender.title == '3D': self.mk_map_view.camera().setPitch_(45) self.mk_map_view.camera().setAltitude_(500) self.mk_map_view.camera().setHeading_(45) self.mk_map_view.setShowsBuildings_(True) sender.title = '2D' else: self.mk_map_view.camera().setPitch_(0) sender.title = '3D' def tableview_did_select(self, tableview, section, row): tableview.close() def long_press(self, sender): #NOTE: The `sender` argument will always be the dummy ui.Button that's used as the gesture recognizer's target, just ignore it... gesture_state = self.recognizer.state() if gesture_state == 1 and callable(self.long_press_action): loc = self.recognizer.locationInView_(self.mk_map_view) self.long_press_location = ui.Point(loc.x, loc.y) self.long_press_action(self) @on_main_thread def add_pin(self, lat, lon, title, subtitle=None, select=False): '''Add a pin annotation to the map''' MKPointAnnotation = ObjCClass('MKPointAnnotation') coord = CLLocationCoordinate2D(lat, lon) annotation = MKPointAnnotation.alloc().init().autorelease() annotation.setTitle_(title) if subtitle: annotation.setSubtitle_(subtitle) annotation.setCoordinate_(coord, restype=None, argtypes=[CLLocationCoordinate2D]) self.mk_map_view.addAnnotation_(annotation) if select: self.mk_map_view.selectAnnotation_animated_(annotation, True) return annotation @on_main_thread def remove_all_pins(self): '''Remove all annotations (pins) from the map''' self.mk_map_view.removeAnnotations_(self.mk_map_view.annotations()) @on_main_thread def set_region(self, lat, lon, d_lat, d_lon, animated=False): '''Set latitude/longitude of the view's center and the zoom level (specified implicitly as a latitude/longitude delta)''' region = MKCoordinateRegion(CLLocationCoordinate2D(lat, lon), MKCoordinateSpan(d_lat, d_lon)) self.mk_map_view.setRegion_animated_(region, animated, restype=None, argtypes=[MKCoordinateRegion, c_bool]) @on_main_thread def set_center_coordinate(self, lat, lon, animated=False): '''Set latitude/longitude without changing the zoom level''' coordinate = CLLocationCoordinate2D(lat, lon) self.mk_map_view.setCenterCoordinate_animated_(coordinate, animated, restype=None, argtypes=[CLLocationCoordinate2D, c_bool]) @on_main_thread def get_center_coordinate(self): '''Return the current center coordinate as a (latitude, longitude) tuple''' coordinate = self.mk_map_view.centerCoordinate(restype=CLLocationCoordinate2D, argtypes=[]) return coordinate.latitude, coordinate.longitude @on_main_thread def point_to_coordinate(self, point): '''Convert from a point in the view (e.g. touch location) to a latitude/longitude''' coordinate = self.mk_map_view.convertPoint_toCoordinateFromView_(CGPoint(*point), self._objc_ptr, restype=CLLocationCoordinate2D, argtypes=[CGPoint, c_void_p]) return coordinate.latitude, coordinate.longitude def _notify_region_changed(self): if callable(self.scroll_action): self.scroll_action(self) # -------------------------------------- # DEMO: def long_press_action(sender): global locs,path # Add a pin when the MapView recognizes a long-press c = sender.point_to_coordinate(sender.long_press_location) # this of only to special process asked in forum # https://forum.omz-software.com/topic/7077/removing-custom-pins-with-map-api for annotation in sender.mk_map_view.annotations(): if str(annotation.title()) == 'Dropped Pin': lat = annotation.coordinate().a lon = annotation.coordinate().b sender.mk_map_view.removeAnnotation_(annotation) sender.add_pin(lat, lon, 'user point', str((lat, lon))) break sender.add_pin(c[0], c[1], 'Dropped Pin', str(c), select=True) sender.set_center_coordinate(c[0], c[1], animated=True) # add dropped pin as 'user' to file locs[(c[0], c[1])] = 'user' with open(path,mode='wt') as f: content = str(locs) f.write(content) def scroll_action(sender): # Show the current center coordinate in the title bar after the map is scrolled/zoomed: sender.name = 'lat/long: %.2f, %.2f' % sender.get_center_coordinate() def compute_region_param(l): # Compute min and max of latitude and longitude min_lat = min(l,key = lambda x:x[0])[0] max_lat = max(l,key = lambda x:x[0])[0] min_lon = min(l,key = lambda x:x[1])[1] max_lon = max(l,key = lambda x:x[1])[1] d_lat = 1.2*(max_lat-min_lat) d_lon = 1.2*(max_lon-min_lon) return min_lat,min_lon,max_lat,max_lon,d_lat,d_lon def build_pin(path): my_ui_image = ui.Image.named(path) dx,dy = 28,86 v = ui.View(frame=(0,0,dx,dx),corner_radius=dx/2) iv = ui.ImageView(frame=(0,0,dx,dx)) iv.image = my_ui_image v.add_subview(iv) with ui.ImageContext(dx,dx) as ctx: v.draw_snapshot() # if circular cropped my_ui_image = ctx.get_image() # image with pin and its foot, coloured circle replaced by the photo) with ui.ImageContext(dx,dy) as ctx: foot = ui.Path.oval(dx/2-2,dy/2-1,4,2) ui.set_color((0,0,0,1)) foot.fill() pin = ui.Path.rounded_rect(dx/2-1,dx/2,2,dy/2-dx/2,1) ui.set_color((0.6,0.6,0.6,1)) pin.fill() my_ui_image.draw(0,0,dx,dx) my_ui_image = ctx.get_image() # circular image without foot not pin #d = 28 #v = ui.View(frame=(0,0,d,d),corner_radius=d/2) #iv = ui.ImageView(frame=(0,0,d,d)) #v.add_subview(iv) #iv.image = my_ui_image #with ui.ImageContext(d,d) as ctx: # v.draw_snapshot() # if circular cropped # my_ui_image = ctx.get_image() return my_ui_image def crosshair_pin(): dx = 28 with ui.ImageContext(dx,dx) as ctx: cross = ui.Path() cross.line_width = 1 ui.set_color('black') cross.move_to(dx-4,dx/2) cross.add_arc(dx/2,dx/2,dx/2-4,0,2*pi) ui.set_color('red') cross.line_width = 2 cross.move_to(0,dx/2) cross.line_to(dx,dx/2) cross.move_to(dx/2,0) cross.line_to(dx/2,dx) cross.stroke() my_ui_image = ctx.get_image() return my_ui_image def main(): global locs, path global own_ui_image,del_ui_image, grp_ui_image own_ui_image = build_pin('emj:Man') del_ui_image = build_pin('iob:ios7_trash_outline_32') grp_ui_image = crosshair_pin() # create main view mv = ui.View() mv.name = 'Map for RocketBlaster05' mv.background_color = 'white' mv.present('fullscreen') w,h = ui.get_screen_size() # Create and present a MapView: v = MapView(frame=(0,0,w,h-76)) mv.add_subview(v) v.long_press_action = long_press_action v.scroll_action = scroll_action path = 'locations.txt' locs = {} if os.path.exists(path): with open(path,mode='rt') as f: aux = {} content = f.read() locs = ast.literal_eval(content) # file content is {(lat,lon):data} # where data is - 'user' # - 'trash' # - [(lat,lon),(lat,lon),...] for pt in locs.keys(): lat,lon = pt if locs[pt] == 'user': v.add_pin(lat, lon, 'user point', str((lat, lon))) elif locs[pt] == 'trash': v.add_pin(lat, lon, 'deleted user point', str((lat, lon))) else: subtit = '' for latg,long in locs[pt]: if subtit: subtit += '\n' subtit += str((latg,long)) v.add_pin(lat, lon, 'deleted group', subtit) # center on user location import location location.start_updates() time.sleep(0.1) loc = location.get_location() location.stop_updates() if loc: lat, lon = loc['latitude'], loc['longitude'] # add a purple pin for user's location v.user_annotation = v.add_pin(lat, lon, 'Current Location', str((lat, lon))) l = [(lat,lon)] # include user location but not in locs for pt in locs.keys(): lat,lon = pt l.append((lat,lon)) min_lat,min_lon,max_lat,max_lon,d_lat,d_lon = compute_region_param(l) v.set_region((min_lat+max_lat)/2, (min_lon+max_lon)/2,1.2*(max_lat-min_lat), 1.2*(max_lon-min_lon), animated=True) if __name__ == '__main__': main()
10ee46c1b8740ec9456a4e84a74669f0dc7b91c3
cacquani/mastermind_py
/mastermind.py
1,339
3.796875
4
import random print('Create secret code!') colours = [ 'R', 'Y', 'G', 'B', 'K', 'W' ] def create_code(): return random.choices(colours, k=4) def calculate_score(code, guess): correct = 0 included = 0 indexes = [] for index, element in enumerate(guess): if code[index] == element: correct = correct + 1 indexes.append(index) indexes.reverse() for index in indexes: code.pop(index) guess.pop(index) for element in guess: try: index = code.index(element) code.pop(index) included = included + 1 except ValueError: print return [correct, included] # code = ['G', 'W', 'B', 'K'] code = create_code() print('Code: ', code) # guess = ['K', 'K', 'W', 'B'] # guess = create_code() print("Enter four colours separated by spaces. Possible colours are: R, Y, G, B, K, W:") guess_string = '' while 1: guess_string = input('> ') if guess_string == 'exit': break guess = guess_string.split() print('Guess: ', guess) score = calculate_score(code.copy(), guess) if score[0] == 4: print('You won!') break else: print('Correct pegs: ', score[0]) print('Right colour, wrong position: ', score[1]) print
9861031db8acdcc1aad8164d7ff8c3464ede2745
Jaminy/Email-Mining
/Snippets/PN.py
784
3.546875
4
>>> y=re.findall(r'\d+', 'hello +94716772265') >>> y ['94716772265'] >>> print y ['94716772265'] >>> z=phonenumbers.parse("+" + y[0]) >>> print z Country Code: 94 National Number: 716772265 >>> z=phonenumbers.parse("+", "US") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.linux-x86_64/egg/phonenumbers/phonenumberutil.py", line 2576, in parse phonenumbers.phonenumberutil.NumberParseException: (1) The string supplied did not seem to be a phone number. >>> z PhoneNumber(country_code=94, national_number=716772265, extension=None, italian_leading_zero=None, number_of_leading_zeros=None, country_code_source=None, preferred_domestic_carrier_code=None) >>> phonenumbers.is_possible_number(z) True >>> phonenumbers.is_valid_number(z) True
52b7f866a0a7e7169857af6d225cefcd3b059214
Kamali29/OpenCV
/2.Basic Functions/Erosion and Dilation.py
786
3.640625
4
# Dilation adds pixels to the boundaries of objects in an image, # while erosion removes pixels on object boundaries. # It is normally performed on binary images. import cv2 import numpy as np # Reading the input image img = cv2.imread(r'C:\Users\Lovely\Desktop\Open_CV\Resources\lena.png', 0) # Taking a matrix of size 5 as the kernel kernel = np.ones((5, 5), np.uint8) imgCanny = cv2.Canny(img,150,200) img_dilation = cv2.dilate(imgCanny, kernel, iterations=1) img_erosion = cv2.erode(img_dilation, kernel, iterations=1) cv2.imshow('Input', img) cv2.waitKey(0) cv2.imshow('Canny Image', imgCanny) cv2.waitKey(0) cv2.imshow('Eroded Image', img_erosion) cv2.waitKey(0) cv2.imshow('Dilated Image', img_dilation) cv2.waitKey(0) cv2.destroyAllWindows()
4bd955a7d74e3c3c6979549222551c99eeab73e1
oscar510/built-by-titan
/oscar01.py
897
3.640625
4
import turtle def draw_square(): square_size = 100 turtle.forward(square_size) turtle.right(90) turtle.forward(square_size) turtle.right(90) turtle.forward(square_size) turtle.right(90) turtle.forward(square_size) def draw_circles(): turtle.back(60) turtle.left(90) turtle.left(90) turtle.left(90) turtle.pu() turtle.forward(50) turtle.pd() turtle.circle(10) turtle.pu() turtle.back(50) turtle.right(90) turtle.forward(20) turtle.left(90) turtle.forward(25) turtle.pd() turtle.circle(10) turtle.pu() turtle.back(25) turtle.left(90) turtle.forward(80) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(20) turtle.right(90) turtle.forward(25) turtle.pd() turtle.circle(10) draw_square() draw_circles()
1db81f19b60305fcc9da2fb4244037e095647b1b
HeizerSpider/Reinforcement_Learning
/mountaincar.py
1,134
3.578125
4
import gym import numpy as np env = gym.make("MountainCar-v0") env.reset() print(env.observation_space.high) # sometimes we engage in some environments in which we dont know these values and hence we have to learn for awhile before we actually get to know these values print(env.observation_space.low) print(env.action_space.n) #how many actions we can actually take #OS == obervation space DISCRETE_OS_SIZE = [20] * len(env.observation_space.high) #observation space table size discrete_os_win_size = (env.observation_space.high-env.observation_space.low) / DISCRETE_OS_SIZE print(discrete_os_win_size) q_table = np.random.uniform(low = -2, high = 0, size = (DISCRETE_OS_SIZE + [env.action_space.n])) # gives every combination space and velocity , 20 by 20 by 3 actions that can be taken, with values between -2 and 0, and the values should be slowly tweaked and optimized over time print(q_table.shape) print(q_table) ''' done = False while not done: action = 2 new_state, reward, done, _ = env.step(action) #state in this case is position and velocity print(reward, new_state) env.render() env.close() '''
63d84a0ec7ecdcff9c8bed3ad6f50888e9cfb664
ameya-ganchha/python-challenge
/PyBank/main.py
1,991
3.640625
4
import csv budget_csv = 'budget_data.csv' def print_file(statement, file_pointer) : print (statement) file_pointer.write(str(statement) + "\n") with open('myfile.txt',"w") as f : with open(budget_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') # Prompt the user for what wrestler they would like to search for next(csvreader) # Loop through the data sum_of_profitloss = 0 num_months = 0 change = 0 max_val = -999999999999 min_val = 999999999999 for row in csvreader: sum_of_profitloss = sum_of_profitloss + int(row[1]) num_months = num_months + 1 if num_months == 1 : prev_val = int(row[1]) continue if num_months >= 2 : diff = int(row[1]) - prev_val change = change + diff #print (row[0]) #print ( "nw : " + str(row[1]) + " prev_Val :" + str(prev_val) + " change : " + str(change)) prev_val = int(row[1]) if max_val < diff : max_val = diff max_month = row[0] #print ( "Value : " + str(max_val)) if min_val > diff : min_val = diff min_month = row[0] print_file ('Financial Analysis ',f) print_file ('---------------------------',f) print_file (str(' Total Months : ' + str(num_months)),f) print_file (str(' Total amount : $' + str(sum_of_profitloss)),f) roundval =format((float((change)/(num_months-1))) , ".2f" ) print_file (str(' Average change : $ ' + str(roundval)),f) print_file (str(' Greatest Increase : ' + str(max_month) + ' : $ ' + str(max_val) ),f) print_file (str(' Greatest Decrease : ' + str(min_month) + ' : $ ' +str(min_val)),f)
66b628fb453b1704150bd027fe966a9835f15b2f
davidjanghoonlee/python-exercise-files
/ex43.py
11,398
3.9375
4
# from python import exit and radom integer generator modules from sys import exit from random import randint # class that has-a function "enter" that takes self parameter class Scene(object): def enter(self): print "Unconfigured scene. Subclass it and implement enter()." exit(1) # class with: class Engine(object): # has-a _init_ that takes self and scene_map parameters; def __init__(self, scene_map): self.scene_map = scene_map # has-a function "play" that takes self as a parameter def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) # print this out the last scene current_scene.enter() # make a class "Death" that is-a "Scene" with "enter" with self parameter class Death(Scene): end = [ "The scythe of death has reached you. Adios...", "Do better next time!", "You can do better than that! Come on!", "Our highly esteemed hero...Please try again and save the world!", "The icy cold clammy hand from underground dragged you to death..." "Bye...", "Hades has invited you to his kingdom where no one can escape..", "Welcome to eternal Tartarus...." ] def enter(self): print Death.end[randint(0, len(self.end)-1)] exit(1) # make a class "CentralCorridor" that is-a "Scene" that has a function "enter" class CentralCorridor(Scene): def enter(self): print "Hey Hercules!" print "The Titans of the Tartarus have invaded the Olympus!" print "Other gods have been killed or escaped. Even taken captive!" print "You are the chosen one to save the Olympus and your" print "mission is to get the 'Lightning Bolt' from Zeus's room," print "strike the Titans with it," print "and rescue the helpless gods and goddesses to the " print "top of the Olympus." print "\n" print "You are running down the streets of Oedipus" print "to head toward Mount Olympus." print "On the way to Olympus, you meet a one-eyed Cyclops." print "He approached you with green slimy skin, grinding his teeth," print "drooling, and one eye." print "He's blocking the way to the Olympus. What would you do?" print "You have a sword and a shield that Athena gave you as gifts." print "Will you [fight him] or [run away] or [tell a joke] ?" action = raw_input("> ") if "run" in action: print "With your fastest run, you tried to escape!" print "You ran as hard as you can!" print "The hungry Cyclops's not gonna miss you cuz he's huggrryy." print "While you ran a yard he ran a mile." print "Within a single blink of your eyes" print "he's in front of you.\n" print "'Hey, boy,' said he.\n" print "'Wut, wut is it!? What do you want from me!?,'" print "said Hercules.\n" print "'I'm going to eat you like a piece of cake." print "Yum,' replied the Cyclops.\n" print "Without letting you reply, he eats you. You are dead. " return 'death' elif "fight" in action: print "Like the world's strongest demi-god, you fight." print "You draw your sword and dash toward him," print "THUMP! You got his back." print "You first blind him with your sword." print "The cool blade creates an intersection with his neck." print "PSHSHSHSH." print "The spring of blood soaks you." print "The big nuisance is down! You can proceed to Mount Olympus" return 'laser_weapon_armory' elif "tell" in action: print "You try to tell the Cyclops joke you know:" print "" print "'Wait, what languages does he speak?...hmmm...'\n " print "While you were thinking, a humongous hand reached you." print "Grabbbb!!!!Squeeze!!!Too strong!!!!!" print "You can't move. Then, he swallowed you.\nDeath." return 'death' else: print "NO OTHER CHOICE. TRY AGAIN" return 'central_corridor' # make a class "LaserWeaponArmory" that is-a "Scene" with a function "enter" class LaserWeaponArmory(Scene): def enter(self): print "Here you are at the Mount Olympus." print "You see no one in the Counicl Square of the Olympus." print "You see no one in the room of Zeus." print "However, you see a golden chest." print "What will you do?" print "Will you [strike the chest] or [open the chest] or [move on]" do_what = raw_input("> ") if "strike" in do_what: print "Clang!....Nothing happened. Maybe too weak!" print "You got mad and striked the chest multiple times" print "Clang!"*4 print "You striked the chest %d times." % (randint(1, 10000)) print "You were too loud." print "The furious Titans came and dragged you to Tartarus." return 'death' elif "open" in do_what: print "All you had to do was just simply open!" print "You grabbed Zeus's Lightning Bolt" print "Now...." print "Hercules on the RESCUE!!!!" return 'the_bridge' elif "move" in do_what: print "When you came out, the Titans were walking by Zeus's room." print "They saw you and came after you." print "The cold blade of them went through your tummy." print "You DIED." return 'death' else: print "What you gonna do? Try again." return 'laser_weapon_armory' # make a class "TheBridge" that is-a "Scene" with function "enter" class TheBridge(Scene): def enter(self): print "Now with your Lightning Bolt, you came out of the room." print "You see those evil Titans trying to swallow the Olympus gods." print "You are so mad right now." print "What action do you take now?!" print "Will you [strike Titans with Lightning] or [strike the gods] or" print "[run away] ?" action = raw_input("> ") if "Titan" in action or "titan" in action: print "With your Pikachu Lightning Bolt, you strike the Titans!\n" print "'Pikachu, bolt attack!' roared Hercules.\n" print "The Titans fell down. They died because of electric shock" print "The cloaks of the gods and the goddesses" print "were made of rubber (inductor)" print "so they survived from the flowing electricity.\n" return 'escape_pod' elif "god" in action: print "The cloaks of the gods and the goddesses" print "were made of rubber (inductor)" print "so they survived from the flowing electricity.\n" print "Because you were foolish to attack your allies" print "instead of attacking the enemies," print "your enemies swallowed your allies.\n" print "Now, they are coming after you" print "THUMP " * 8 print "\nROOOOOOOOAAAAAAAAR\n" print "They got you! (Smiley Face)" return 'death' elif "run" in action: print "You abandoned the gods and the Olympus" print "You such a coward." print "The Titans killed every gods." print "Since the ferocious Titans are ruling the world as gods," print "The earth committed suicide" print "by destroying itself with its own" print "gravitational force." print "It became a blackhole, and everyone died." return 'death' else: print "NO OTHER CHOICE. TRY AGAIN!" return "the_bridge" # make a class "EscapePod" that is-a "Scene" with function "enter" class EscapePod(Scene): def enter(self): print "Now that all gods are saved," print "you have go to the gate of Tartarus and close it again." print "You rush down the mountain desperately trying to make it to" print "the gate of Tartarus before the Titans regenerate" print "and reappear on Olympus. You reach down to" print "the gate of Tartarus. When you were about to shut the gate," print "you saw your mom in Tartarus." print "\nYou can hardly believe that she's in there," print "and you start to weep." print "What would you do?" print "Would you [shut the gate] for the world's sake? or" print "Would you [go in to meet your mom] for your sake?" hesitate = raw_input("> ") if "shut" in hesitate: print "You ignored your mom and shut the gate" print "You hear her cry," print "but that's okay because you are such a nice son." print "GOOD JOB shutting your own mom off for the world's sake." print "Wheeeee~~~~You saved the world!" return 'finished' else: print "You jump into pod and met your mom." print "You approached her to hug her...." print "......" print "BUT THEN!!" print "She suddenly disappeared!" print "Oh man! It was a hallucination!" print "Since you failed to shut the gate," print "the Titans conquered the world." print "Plus, you died." return 'death' # make a class "running" that is-a "Scene" class Running(Scene): def enter(self): print "You are being chased!" print "You are running!" print "Running" * (randint(1, 9)) print "But eventually you were caught." print "You died" return 'death' # make a class "Finished" that is-a "Scene" class Finished(Scene): def enter(self): print "You saved the world!" print "Hurray! Victory is yours!" return 'finished' # make a class "Map" that has-a: class Map(object): # attribute scenes = { 'central_corridor': CentralCorridor(), 'laser_weapon_armory': LaserWeaponArmory(), 'the_bridge': TheBridge(), 'escape_pod': EscapePod(), 'death': Death(), 'finished': Finished(), 'running': Running() } # _init_ with self and start_scene parameters def __init__(self, start_scene): self.start_scene = start_scene # function "next_scene" that takes self and scene_name parameters def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val # function "opening_scene" with self def opening_scene(self): return self.next_scene(self.start_scene) # set "a_map" to an instance of class "Map" with central_corridor parameter a_map = Map('central_corridor') # set "a_game" to an instance of class "Engine" with "a_map" parameter a_game = Engine(a_map) # from class "a_game" get function "play" and run it! a_game.play()
97c80a0bc24deb72d908c283df28b314454bcfc5
KHilse/Python-Stacks-Queues
/Queue.py
2,139
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None def isEmpty(self): """Returns True if Queue is empty, False otherwise""" if self.head: return False return True def enqueue(self, item): """Adds an item to the back of queue""" if self.head: current_node = self.head while current_node.next != None: current_node = current_node.next new_node = Node(item) current_node.next = new_node else: new_node = Node(item) self.head = new_node def dequeue(self): """Removes the item from the front of queue. Returns the removed item""" if self.head: popped = self.head self.head = self.head.next return popped.data return False def peek(self): """Returns the first item in the queue, but doesn't remove it""" if self.head: return self.head.data return None def size(self): """Returns the (int) size of the queue""" current_node = self.head index = 0 while current_node: current_node = current_node.next index += 1 return index def __str__(self): """Returns a string representation of all items in queue""" current_node = self.head result = "" while current_node: if result != "": result = result + ", " result = result + current_node.data current_node = current_node.next return result my_queue = Queue() print('Is Queue empty?', my_queue.isEmpty()) my_queue.enqueue('A') my_queue.enqueue('B') my_queue.enqueue('C') my_queue.enqueue('D') print("queue state:", my_queue) print('Dequeued item:', my_queue.dequeue()) print('First item:', my_queue.peek()) print('Here are all the items in the queue:', my_queue) print('The size of my stack is:', my_queue.size()) # BONUS - Implement the Queue with a Linked List
efb28bd3bedf010ba4cc3fc2692df19968d6f24c
rohit-nair/neuralist
/scripts/mapping.py
1,080
3.53125
4
#!/usr/bin/env python import json import sqlite3 DUPE_FILE = "lastfm_duplicates.txt" DB_FILE = "data/lastfm_similars.db" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("""Select * from top100_similars;""") all_data = cursor.fetchall() print "all_data", len(all_data) cursor.execute("""CREATE TABLE IF NOT EXISTS top100_similars_mapped (tid TEXT, target TEXT, similarity REAL)""") count = 0 rows = 0 for single_data in all_data: countries = single_data[1].split(",") #print "length countries", len(countries), countries for i in range(0,len(countries)/2): #print "inserting {} {} {}".format(single_data[0],countries[i*2], float(countries[i*2+1])) cursor.execute("INSERT INTO top100_similars_mapped (tid, target, similarity) VALUES(?,?,?)",[single_data[0],countries[i*2], float(countries[i*2+1])]) conn.commit() rows += len(countries)/2 count += 1 print "##### {} rows processed and {} inserted \r".format(count, rows), print "" cursor.close()
8e889b7bcf53c0d9704df68b21bdbc25e70335ae
alpha-martinez/scripting-with-python
/my-script.py
1,047
3.875
4
# # open a file # alpha_file = open('alpha-text', 'r') # numbers = [1, 2, 3] # for i in range(len(numbers)): # num = numbers[i] # alpha_file.write("{}\n".format(num)) # alpha_file.close() # # close a file # print(alpha_file.read()) # alpha_file.close() # open a file rome_file = open('rome.txt', 'a') numbers = [1,2,3] for i in range(len(numbers)): num = numbers[i] rome_file.write("{}\n".format(num)) # write to the file # rome_file.write('\nHello\n') # close a file rome_file.close() # read a file # print(rome_file.read()) # If file is not found, one will be created adam_file = open('adam.txt', 'w') adam_file.write('Adam') # adam_file.write('Adam') adam_file.close() # Look up how to read lines from a file in python new_file = open('new_file.txt') file_items = new_file.readlines() for i in range(len(file_items)): each_item = file_items[i] print('Before: {}'.format(each_item)) print(each_item[0:-1]) file_items[i] = each_item[0:-1] print(file_items) # print(file_items) new_file.close()
485458ce7505e832f81aab7520d9fa16db630e89
kalstoykov/Python-Coding
/isPalindrome.py
1,094
4.375
4
import string def isPalindrome(aString): ''' aString: a string Returns True if aString is a Palindrome String strips punctuation Returns False otherwise. ''' alphabetStr = "abcdefghijklmnopqrstuvwxyz" newStr = "" # converting string to lower case and stripped of extra non alphabet characters aString = aString.lower() for letter in aString: if letter in alphabetStr: newStr += letter # if string is one letter or empty, it is a Palindrome if len(newStr) <= 1: return True # if string has more than 1 letter else: # reversing the string revStr = '' for i in range(len(newStr), 0, -1): revStr += newStr[i-1] # if string equals to reversed string, it is a Palindrome if list(newStr) == list(revStr): return True return False # Test cases print isPalindrome("Madam") # returns True print isPalindrome("Hello World") # returns False print isPalindrome(" Madam") # returns True print isPalindrome("1") # returns True
40a293a5218de8b7594049e1f06a4c0d18988b14
Freemont7/dat119spr19
/Campbell_Week_8.py
4,115
4.53125
5
# -*- coding: utf-8 -*- """ Chris Campbell 3/27/19 Python 1 - Dat 119 - Spring 2019 Week 8 "We’re going to create an application to track a user’s todo list! Our application will maintain at least two lists: 1) items that need to be done and 2) items that have already been completed." """ #create todo list and completed tasks list with nothing in them todo_list = ["run", "eat", "breathe"] completed_tasks = [] #greeting print("Welcome to the ToDo list tracker: ") print("") #main function to run loop def main(): #while loop to make sure user selects an item (1-5) from the menu #if not, ask again choice = 0 while choice != 5: main_menu() choice = input("Enter your choice: ") print("") #if elif statements to correspond user's choice to running the #function that relates to that choice #IE if they choose 1, then run function to display todo list if choice == "1": display_todo_list() elif choice == "2": display_completed_list() elif choice == "3": add_item_todo_list() elif choice == "4": mark_completed() elif choice == "5": print("Thank you. Program exitting.") break else: print("Invalid selection. Please choose a choice between 1 and 5: ") print("") #function to define menu def main_menu(): print(" Menu ") print("1 View ToDo list") print("2 View completed tasks") print("3 Add item to ToDo list") print("4 Mark item as completed") print("5 Exit") #function to display todo list def display_todo_list(): for object in todo_list: #print list as numbered list of items print(todo_list.index(object) +1, object) #if todo list is empty, do not proceed and give this message and return to menu if todo_list == []: print("There is nothing on the ToDo list.") print("") #completed list function def display_completed_list(): for object in completed_tasks: print(completed_tasks.index(object) +1, object) if completed_tasks == []: print("There are no completed items.") print("") #function to add item to todo list def add_item_todo_list(): additem = input("Type in a task to add to ToDo list: ") todo_list.append(additem) #function to add item to completed list and remove from todo list def mark_completed(): display_todo_list() #do not proceed if todo list is empty if todo_list == []: print("There is nothing to mark as completed. ") print("") #main_menu() #if todo has an item, then: if todo_list != []: #while loop and then if else statements to check that input #is first a number and second not greater than the amount of items #which are on the todo list while True: #get length of todo list length = len(todo_list) completed = input("Select number of item to mark as completed: ") try: #make sure user input is an integer val = int(completed) completed = int(completed) #if user input is not a number on the list, print error #and ask again if completed > length: print("Invalid, number is not on list") if completed <= 0: print("Choose a number greater than 0") else: completed_value = todo_list[completed-1] todo_list.remove(completed_value) completed_tasks.append(completed_value) print("") break #if not an integer, give this error and ask for another input except ValueError: print("Input invalid. Please select a number corresponding to an item on the list") #if completed != 1 to len(todo_list): #completed = input("Please select the number of an item on the todo list: ") #run main main()
fb471f247f81c03e3cd90bf680e9b2d0646c27e1
minsau/hacker-rank
/algorithms/kangaroo.py
352
3.875
4
def kangaroo(x1, v1, x2, v2): # Write your code here start_diff = x1 - x2 velocity_diff = v2 - v1 if (v2 > v1 or velocity_diff == 0): return 'NO' if((start_diff % velocity_diff) == 0): return 'YES' else: return 'NO' print(kangaroo(0, 2, 5, 3)) print(kangaroo(0, 3, 4, 2)) print(kangaroo(43, 2, 70, 2))
06007fc223dccb013f734a94f408a4260e7de7c5
annash2005/python_1
/natural#1-n.py
170
3.765625
4
command = input ("Put in the number") #Let's convert cool to interger com_int = int(command) import time num = 1 while(num <= com_int ): print(num) num = num +1
7f3f92769c490f23ade030172f02e0e0ce102774
annash2005/python_1
/while.py
86
3.703125
4
import time num = 1 while(num <= 10 ): print(num) num = num +1 print("Anna Is AMAZING")
fac8d1383134a37e65843b3b83ac424d1d7e277c
maxgamesNL/lessonup.app_Bot
/main.py
1,260
4.0625
4
import time #This is the main file of the project. #On editing write documentation for easy editing. Running = True #Explains what the program is to the user. def Intro(): print("Welcome to LessonUp Bot!!!") time.sleep(1.5) print("This bot is able to perform") time.sleep(1.5) print("A lot of actions realy fast") time.sleep(1.5) print("It is able to answer randomly.") time.sleep(1.5) print("And give custom answers") time.sleep(2.5) print("Start-Up Complete") time.sleep(1) print("This is a list of all the commands.") time.sleep(1) print("Type the number of your command.") time.sleep(1) print("And you will go to the menu of your command!") print("") def CommandList(): print("1. Flooder(Fills the Lesson-Up with bots that give random answers.)") print("") print("") print("") print("") print("To stop type stop.") #This is where the user is shown all the options of the program. def MainMenu(): CommandList() UserInput = input("Enter the number of your command: ") if(UserInput == "stop" or "Stop"): Running = False else: UserInputNum = int(UserInput) Intro() time.sleep(3) while(Running): MainMenu()
875a71a620c74bec5b2772ca0e8be779b4b7a52a
JeffCalvert01P/fullstack-nanodegree-vm
/vagrant/tournament/tournament_ec.py
6,400
3.59375
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 import tournament_dbsql_ec def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all the match records from the database.""" connection = connect() cursor = connection.cursor() cursor.execute(tournament_dbsql_ec.deleteMatchesSQL()) connection.commit() connection.close def deletePlayers(): """Remove all the player records from the database. """ connection = connect() cursor = connection.cursor() cursor.execute(tournament_dbsql_ec.deletePlayersSQL()) connection.commit() connection.close def countPlayers(tournament): """Returns the number of players currently registered. Args: tournament: the tournament number """ connection = connect() cursor = connection.cursor() data = (tournament,) cursor.execute(tournament_dbsql_ec.selectAllPlayersSQL(), data) row_count = cursor.rowcount connection.close return row_count def registerPlayer(tournament, name): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ connection = connect() cursor = connection.cursor() data = (tournament, name) cursor.execute(tournament_dbsql_ec.registerPlayerSQL(), data) connection.commit() connection.close def playerStandings(tournament): """Reurns a list of the players in order of their standings Args: tournament: the tournament number Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by the database) name: the player's full name (as registered) wins: the number of matches the player has won matches: the number of matches the player has played """ connection = connect() cursor = connection.cursor() # Query player standings cursor.execute(tournament_dbsql_ec.playerStandingsSQL(), (tournament,)) rows = cursor.fetchall() connection.close return rows def reportMatch(tournament, winner, loser, round_num, tie_ind): """Records the outcome of a single match between two players. Args: tournament: the tournament number winner: the id number of the player who won loser: the id number of the player who lost round_num: the current round of matches tie_ind: indicates whether the match was a tie """ """ I always put the lesser player id in the player 1 id to limit the number of rows and keep the data cleaner """ if winner > loser: player1 = loser player2 = winner else: player2 = loser player1 = winner # Insert record for matches table connection = connect() cursor = connection.cursor() data = (tournament, player1, player2, round_num, tie_ind) cursor.execute(tournament_dbsql_ec.reportMatchInsertSQL(), data) """ Insert a record in the matches table when there is a tie to give the second player credit """ if tie_ind == "Y": data = (tournament, player2, player1, round_num, tie_ind) cursor.execute(tournament_dbsql_ec.reportMatchInsertSQL(), data) connection.commit() connection.close def swissPairings(tournament, round_num): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standings. Args: tournament: the tournament number round_num: the current round of matches Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first player's name id2: the second player's unique id name2: the second player's name """ connection = connect() cursor = connection.cursor() cursor.execute(tournament_dbsql_ec.playerOrderSQL(), (tournament,)) count = 0 row_count = 0 pairing = () pairing_list = [] matchq_connection = connect() match_connection = connect() for row in cursor: count += 1 row_count += 1 if count < 2: # Hold the first of each pair for later matching player1 = row else: # Make sure the smaller value is in first position if player1[0] < row[0]: player1_id_h = player1 player2_id_h = row else: player2_id_h = player1 player1_id_h = row # check for duplicates - Extra Credit 1 - I also put # constraints on the database. matchq_cursor = connection.cursor() data = (tournament, player1_id_h[0], player2_id_h[0]) matchq_cursor.execute(tournament_dbsql_ec.checkMatchExistsSQL(), data) matchq_connection.commit() count = 0; # if no match found, pair the players if matchq_cursor.rowcount == 0: pairing = player1_id_h + player2_id_h pairing_list.append(pairing) pairing = () # Insert the matched players into the match table matchq_connection.close connection.close """ Append last player with a dummy negative record so they get credit for a win, but do not appear in a match. I removed the table contraint to allow for -1 """ if (round_num == 0 and cursor.rowcount % 2 > 0 and row_count == cursor.rowcount): pairing = player1 + (-1, ' ') pairing_list.append(pairing) # print pairing_list return pairing_list
cd019d3abb62ba7430aefe5042069ba838d787ec
lfbessegato/Treinamento_Python_Udemy
/Exercicio05.py
274
3.828125
4
print('Exercício05 - Dicionário de Cores') cores={'verde':'Green','amarelo':'Yellow','azul':'Blue','vermelho':'Red','preto':'Black'} cor=input('Digite a Cor para traduzir: ').lower() traducao = cores.get(cor,'Esta informação não consta no dicionário') print(traducao)
7047450bb38b74d3df8f0544b5ca789b0c3a73c6
Takkarpool/Proyecto-Formales
/Habitacion.py
1,055
4.03125
4
class Habitacion: """ Clase que representa una habitación """ def __init__(self, xInicial, yInicial ,ancho, alto, numero): """ Constructor de una habitacion :param xInicial: posición x inicial del Habitación :param yFinal: posición y inicial del Habitación :param width: anchura del Habitación :param height: altura del Habitación :param numero: número de la habitación """ self.x = xInicial self.y = yInicial self.alto = alto self.ancho = ancho self.numero = numero def __eq__(self, other): """ Comparador de Habitaciones :param other: otra habitación :return: True si sin iguales y false si no lo son, ademas de la excepción NotImplemented si other no es una habitación """ if not isinstance(other, Habitacion): return NotImplemented return self.x == other.x and self.y == other.y and self.alto == other.alto and self.ancho == other.ancho
df1c2b27258ba4d3c57f79cd45d680527027ed5e
onelieV/neorl
/neorl/evolu/bat.py
15,736
3.5
4
# -*- coding: utf-8 -*- #""" #Created on Fri Jun 18 19:45:06 2021 # #@author: Devin Seyler and Majdi Radaideh #""" import random import numpy as np import math import joblib from neorl.evolu.discrete import mutate_discrete, encode_grid_to_discrete, decode_discrete_to_grid #Main reference of the BAT algorithm: #Xie, J., Zhou, Y., & Chen, H. (2013). A novel bat algorithm based on #differential operator and Levy flights trajectory. #Computational intelligence and neuroscience, 2013. class BAT(object): """ BAT Algorithm :param mode: (str) problem type, either ``min`` for minimization problem or ``max`` for maximization :param bounds: (dict) input parameter type and lower/upper bounds in dictionary form. Example: ``bounds={'x1': ['float', 0.1, 0.8], 'x2': ['float', 2.2, 6.2]}`` :param fit: (function) the fitness function :param nbats: (int): number of bats in the population :param fmin: (float): minimum value of the pulse frequency :param fmax: (float): maximum value of the pulse frequency :param A: (float) initial value of the loudness rate :param r0: (float) asymptotic value of the pulse rate :param alpha: (float) decay factor of loudness ``A``, i.e. A approaches 0 by the end of evolution if ``alpha < 1`` :param gamma: (float) exponential factor of the pulse rate ``r``, i.e. ``r`` increases abruptly at the beginning and then converges to ``r0`` by the end of evolution :param levy: (bool): a flag to activate Levy flight steps of the bat to increase bat diversity :param int_transform: (str): method of handling int/discrete variables, choose from: ``nearest_int``, ``sigmoid``, ``minmax``. :param ncores: (int) number of parallel processors (must be ``<= nbats``) :param seed: (int) random seed for sampling """ def __init__(self, mode, bounds, fit, nbats=50, fmin=0, fmax=1, A=0.5, r0=0.5, alpha=1.0, gamma=0.9, levy='False', int_transform='nearest_int', ncores=1, seed=None): if seed: random.seed(seed) np.random.seed(seed) assert ncores <= nbats, '--error: ncores ({}) must be less than or equal to nbats ({})'.format(ncores, nbats) assert nbats >= 5, '--error: number of bats must be more than 5 for this algorithm' #--mir self.mode=mode if mode == 'min': self.fit=fit elif mode == 'max': def fitness_wrapper(*args, **kwargs): return -fit(*args, **kwargs) self.fit=fitness_wrapper else: raise ValueError('--error: The mode entered by user is invalid, use either `min` or `max`') self.int_transform=int_transform if int_transform not in ["nearest_int", "sigmoid", "minmax"]: raise ValueError('--error: int_transform entered by user is invalid, must be `nearest_int`, `sigmoid`, or `minmax`') self.bounds=bounds self.ncores = ncores self.nbats=nbats self.fmax=fmax self.fmin=fmin self.A=A self.alpha=alpha self.gamma=gamma self.r0=r0 self.levy_flight=levy #infer variable types self.var_type = np.array([bounds[item][0] for item in bounds]) #mir-grid if "grid" in self.var_type: self.grid_flag=True self.orig_bounds=bounds #keep original bounds for decoding print('--debug: grid parameter type is found in the space') self.bounds, self.bounds_map=encode_grid_to_discrete(self.bounds) #encoding grid to int #define var_types again by converting grid to int self.var_type = np.array([self.bounds[item][0] for item in self.bounds]) else: self.grid_flag=False self.bounds = bounds self.dim = len(bounds) self.lb=np.array([self.bounds[item][1] for item in self.bounds]) self.ub=np.array([self.bounds[item][2] for item in self.bounds]) def init_sample(self, bounds): #sample initializer indv=[] for key in bounds: if bounds[key][0] == 'int': indv.append(random.randint(bounds[key][1], bounds[key][2])) elif bounds[key][0] == 'float': indv.append(random.uniform(bounds[key][1], bounds[key][2])) # elif bounds[key][0] == 'grid': # indv.append(random.sample(bounds[key][1],1)[0]) else: raise Exception ('unknown data type is given, either int, float, or grid are allowed for parameter bounds') return np.array(indv) def eval_bats(self, position_array): #--------------------- # Fitness calcs #--------------------- core_lst=[] for case in range (0, position_array.shape[0]): core_lst.append(position_array[case, :]) if self.ncores > 1: with joblib.Parallel(n_jobs=self.ncores) as parallel: fitness_lst=parallel(joblib.delayed(self.fit_worker)(item) for item in core_lst) else: fitness_lst=[] for item in core_lst: fitness_lst.append(self.fit_worker(item)) return fitness_lst def select(self, pos, fit): #this function selects the best fitness and position in a population best_fit=np.min(fit) min_idx=np.argmin(fit) best_pos=pos[min_idx,:] return best_pos, best_fit def ensure_bounds(self, vec, bounds): vec_new = [] # cycle through each variable in vector for i, (key, val) in enumerate(bounds.items()): # variable exceedes the minimum boundary if vec[i] < bounds[key][1]: vec_new.append(bounds[key][1]) # variable exceedes the maximum boundary if vec[i] > bounds[key][2]: vec_new.append(bounds[key][2]) # the variable is fine if bounds[key][1] <= vec[i] <= bounds[key][2]: vec_new.append(vec[i]) return vec_new def fit_worker(self, x): #This worker is for parallel calculations # Clip the bat with position outside the lower/upper bounds and return same position x=self.ensure_bounds(x,self.bounds) if self.grid_flag: #decode the individual back to the int/float/grid mixed space x=decode_discrete_to_grid(x,self.orig_bounds,self.bounds_map) # Calculate objective function for each search agent fitness = self.fit(x) return fitness def ensure_discrete(self, vec): #""" #to mutate a vector if discrete variables exist #handy function to be used three times within BAT phases #Params: #vec - bat position in vector/list form #Return: #vec - updated bat position vector with discrete values #""" for dim in range(self.dim): if self.var_type[dim] == 'int': vec[dim] = mutate_discrete(x_ij=vec[dim], x_min=min(vec), x_max=max(vec), lb=self.lb[dim], ub=self.ub[dim], alpha=self.a, method=self.int_transform, ) return vec def Levy(self, dim): #function to return levy step beta = 1.5 sigma = ( math.gamma(1 + beta) * math.sin(math.pi * beta / 2) / (math.gamma((1 + beta) / 2) * beta * 2 ** ((beta - 1) / 2)) ) ** (1 / beta) u = 0.01 * np.random.randn(dim) * sigma v = np.random.randn(dim) zz = np.power(np.absolute(v), (1 / beta)) step = np.divide(u, zz) return step def evolute(self, ngen, x0=None, verbose=True): """ This function evolutes the BAT algorithm for number of generations. :param ngen: (int) number of generations to evolute :param x0: (list of lists) initial position of the bats (must be of same size as ``nbats``) :param verbose: (bool) print statistics to screen :return: (dict) dictionary containing major BAT search results """ self.history = {'local_fitness':[], 'global_fitness':[], 'A': [], 'r': []} self.fbest=float("inf") self.verbose=verbose self.Positions = np.zeros((self.nbats, self.dim)) self.r=self.r0 if x0: assert len(x0) == self.nbats, '--error: the length of x0 ({}) MUST equal the number of bats in the group ({})'.format(len(x0), self.nbats) for i in range(self.nbats): self.Positions[i,:] = x0[i] else: # Initialize the positions of bats for i in range(self.nbats): self.Positions[i,:]=self.init_sample(self.bounds) #Initialize and evaluate the first bat population fitness0=self.eval_bats(position_array=self.Positions) x0, f0=self.select(pos=self.Positions,fit=fitness0) self.xbest=np.copy(x0) # Main BAT loop for l in range(0, ngen): self.a= 1 - l * ((1) / ngen) #mir: a decreases linearly between 1 to 0, for discrete mutation #------------------------------------------------------ # Stage 1A: Loop over all bats to update the positions #------------------------------------------------------ for i in range(0, self.nbats): if self.levy_flight: #Eq.(11) make a levy flight jump to increase population diversity self.Positions[i,:]=self.Positions[i,:]+np.multiply(np.random.randn(self.dim), self.Levy(self.dim)) #Eq.(8)-(10) f1=((self.fmin-self.fmax)*l/ngen+self.fmax)*random.random() f2=((self.fmax-self.fmin)*l/ngen+self.fmin)*random.random() betas=random.sample(list(range(0,self.nbats)),4) self.Positions[i, :]=self.xbest+f1*(self.Positions[betas[0],:]-self.Positions[betas[1],:]) +f2*(self.Positions[betas[2],:]-self.Positions[betas[3],:]) self.Positions[i, :] = self.ensure_bounds(self.Positions[i , :], self.bounds) self.Positions[i, :] = self.ensure_discrete(self.Positions[i , :]) #----------------------- #Stage 1B: evaluation #----------------------- fitness1=self.eval_bats(position_array=self.Positions) x1, f1=self.select(pos=self.Positions,fit=fitness1) if f1 <= self.fbest: self.fbest=f1 self.xbest=x1.copy() #--------------------------------- #Stage 2A: Generate new positions #--------------------------------- for i in range(0, self.nbats): # Pulse rate if random.random() > self.r: self.Positions[i, :] = self.xbest + self.A * np.random.uniform(-1,1,self.dim) self.Positions[i, :] = self.ensure_bounds(self.Positions[i , :], self.bounds) self.Positions[i, :] = self.ensure_discrete(self.Positions[i , :]) #----------------------- #Stage 2B: evaluation #----------------------- fitness2=self.eval_bats(position_array=self.Positions) x2, f2=self.select(pos=self.Positions,fit=fitness2) if f2 <= self.fbest: self.fbest=f2 self.xbest=x2.copy() #--------------------------------- #Stage 3A: Generate new positions #--------------------------------- for i in range(0, self.nbats): # loudness effect if random.random() < self.A: self.Positions[i, :] = self.xbest + self.r * np.random.uniform(-1,1,self.dim) self.Positions[i, :] = self.ensure_bounds(self.Positions[i , :], self.bounds) self.Positions[i, :] = self.ensure_discrete(self.Positions[i , :]) #----------------------- #Stage 3B: evaluation #----------------------- fitness3=self.eval_bats(position_array=self.Positions) x3, f3=self.select(pos=self.Positions,fit=fitness3) if f3 <= self.fbest: self.fbest=f3 self.xbest=x3.copy() #--------------------------------- #Stage 4: Check and update A/r #--------------------------------- if min(f1, f2, f3) <= self.fbest: #update A self.A = self.alpha*self.A #update r self.r = self.r0*(1-math.exp(-self.gamma*l)) #--------------------------------- #Stage 5: post-processing #--------------------------------- #--mir if self.mode=='max': self.fitness_best_correct=-self.fbest self.local_fitness = -min(f1 , f2 , f3) else: self.fitness_best_correct=self.fbest self.local_fitness = min(f1 , f2 , f3) self.best_position=self.xbest.copy() self.history['local_fitness'].append(self.local_fitness) self.history['global_fitness'].append(self.fitness_best_correct) self.history['A'].append(self.A) self.history['r'].append(self.r) # Print statistics if self.verbose and i % self.nbats: print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^') print('BAT step {}/{}, nbats={}, Ncores={}'.format((l+1)*self.nbats, ngen*self.nbats, self.nbats, self.ncores)) print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^') print('Best Bat Fitness:', np.round(self.fitness_best_correct,6)) if self.grid_flag: self.bat_decoded = decode_discrete_to_grid(self.best_position, self.orig_bounds, self.bounds_map) print('Best Bat Position:', np.round(self.bat_decoded,6)) else: print('Best Bat Position:', np.round(self.best_position,6)) print('Loudness A:', self.A) print('Pulse rate r:', self.r) print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^') #mir-grid if self.grid_flag: self.bat_correct = decode_discrete_to_grid(self.best_position, self.orig_bounds, self.bounds_map) else: self.bat_correct = self.best_position if self.verbose: print('------------------------ BAT Summary --------------------------') print('Best fitness (y) found:', self.fitness_best_correct) print('Best individual (x) found:', self.bat_correct) print('--------------------------------------------------------------') return self.bat_correct, self.fitness_best_correct, self.history
e8681b0161825b2dbadf5c906eb1488fc94f5553
onelieV/neorl
/build/lib/neorl/parsers/TuneChecker.py
3,810
3.609375
4
""" This class parses the TUNE block and returns a checked dictionary containing all TUNE user parameters """ import numpy as np import os class TuneChecker(): """ This class checks the input for any errors/typos and then overwrites the default inputs by user ones Inputs: master_parser: are the parsed paramters from class InputParser master_paramdict: are the default values given from the class ParamList.py """ def __init__(self, parsed, default): self.default=default self.parsed=parsed self.tune_dict={} for key in self.default: self.tune_dict[key] = self.default[key][0] self.tune_dict=self.check_input(self.parsed, self.default, 'TUNE') def check_input (self, parser, paramdict, card): """ This function loops through any data list and check if data structure and types are correct Inputs: parser: is a parsed dict from the user for any block paramdict: is a default dict by neorl for any block card: is the block/card name Returns: this function does not return, but overwrites the default values in self.gen_dict, self.dqn_dict, ... """ for item in parser: if '{' in item or '}' in item: continue if item not in paramdict: print('--error: {} is NOT found in neorl input variable names'.format(item)) raise(ValueError) try: if paramdict[item][2] == "str": parser[item] = str(parser[item]).strip() elif paramdict[item][2] == "int": parser[item] = int(float(parser[item])) elif paramdict[item][2] == "float": parser[item] = float(parser[item]) elif paramdict[item][2] == "bool": parser[item] = bool(parser[item]) elif paramdict[item][2] == "strvec": parser[item] = [str(element.strip()) for element in parser[item].split(",")] elif paramdict[item][2] == "vec": parser[item] = np.array([float(element.strip()) for element in parser[item].split(",")]) except: print('--error: the data structure for parameter {} in card {} must be {}, but something else is used'.format(item, card, paramdict[item][2])) raise(ValueError) for item in paramdict: if paramdict[item][1] == "r" and item not in parser.keys(): raise Exception ('--error: parameter {} in card {} is required for neorl but it is not given in the input'.format(item, card)) if paramdict[item][1] == "o" and item not in parser.keys(): if item not in ['flag']: print ('--warning: parameter {} in card {} is missed, Default is used ---> {}'.format(item,card, paramdict[item][0])) for item in parser: #final checked dictionary self.tune_dict[item] = parser[item] if 'extfiles' in parser.keys(): for item in self.tune_dict['extfiles']: if not os.path.exists(item): raise Exception('--error: User provided {} as external file/directory to be copied by TUNE, such file does not exist in the working directory'.format(item)) self.tune_dict={k: v for k, v in self.tune_dict.items() if v is not None} self.tune_dict['flag'] = True return self.tune_dict
e19cdf1f2a6f0c8bcca403c8071f2901117cdc08
Leona-qy/machine-learning-web-applications
/punctuation/punctuation/removePunctuations.py
178
3.90625
4
def Punctuation(string): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' for x in string.lower(): if x in punctuations: string = string.replace(x, "") return string
55d24682fa25a8836fec14d71db36ff268ec3420
DroidFreak32/7th_semester
/Python/college_notes/tkinter/1-window/1-window.py
277
3.890625
4
Example:1a import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3 window = tkinter.Tk() # Code to add widgets will go here... window.mainloop() Example:1b import tkinter window=tkinter.Tk() window.title("First tkinter") window.mainloop()
13776998dc9b97cf329928fa2a5632f4be87d37a
Crowiant/learn-homework-1
/2_if2.py
1,196
4.3125
4
""" Домашнее задание №1 Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки * Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая строка 'learn', возвращает 3 * Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты """ def main(first_str: str, second_str: str): if type(first_str) is not str and type(second_str) is not str: return print(0) elif first_str is not second_str and second_str == 'learn': return print(3) elif first_str is not second_str and len(first_str) > len(second_str): return print(2) if __name__ == "__main__": main(1,2) main('gun', 'gun') main('easy', 'learn')
3851d7501e886dfc0ea0ce0e7ff601cdc4703e06
alihasan13/python_hackerrank
/find_second_largest_num.py
183
3.5
4
n = int(input()) arr=[] for i in range(n): x = list( map(int, input().split())) arr.append(x) print (arr) larger= max(num for num in arr if num!=max(arr)) print (larger)
f09de8f722be2cd8818e4547e4c083547c3521d0
AleksanderMako/Algorithms
/src/pythonSamples/isPalindrome.py
589
3.59375
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) < 1: return True alphanumeric = "".join(c.lower() for c in s if c.isalnum()) # print(alphanumeric) return self.isPalindromeHelper(0,len(alphanumeric)-1,alphanumeric) def isPalindromeHelper(self,left,right,cleanStr): if left > right: return True if cleanStr[left] == cleanStr[right] and self.isPalindromeHelper(left+1,right-1,cleanStr): return True return False
a735b44f27614aa4681b18f84473c3ba4b6c5558
QiongWangUSCEE/EE511-Simulation-Methods-for-Stochastic-Systems
/project1/Q1a.py
1,237
3.59375
4
import random as rd import matplotlib.pyplot as plt def main(): # get the dataset for different number times of Bernoulli trial (n=50, p=0.5) result20 = experiment(20) result100 = experiment(100) result200 = experiment(200) result1000 = experiment(1000) result2000 = experiment(2000) result10000 = experiment(10000) # set the size of the figure, and plot 6 histograms plt.rcParams['figure.figsize'] = (24, 18) plt.rcParams['savefig.dpi'] = 300 plt.figure() result = [result20, result100, result200, result1000, result2000, result10000] times = [20, 100, 200, 1000, 2000, 10000] for i in range(1, 7): plt.subplot(3, 2, i) plt.hist(result[i - 1], bins=range(50), rwidth=1, edgecolor='black', align='left') plt.title(str(times[i - 1]) + ' times') plt.xlabel('Number of Heads') plt.ylabel('Frequency') plt.show() # return the number of heads for each Bernoulli trial (n=50, p=0.5) def experiment(times: int) -> list: result = [] for j in range(times): head = 0 for i in range(50): head += int(rd.random() + 0.5) result.append(head) return result if __name__ == '__main__': main()
879b6bbe39b82003cc3a61fade57d33c592d8907
lunar-r/sword-to-offer-python
/剑指offer/40 数组中只出现一次的数字.py
2,067
3.5625
4
# -*- coding: utf-8 -*- """ File Name: 40 数组中只出现一次的数字 Description : Author : simon date: 19-3-3 """ # -*- coding:utf-8 -*- class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): if array == None or len(array) <= 0: return [] resultExclusiveOr = 0 # 定义为ab异或的结果 因为不相同 必然不是1 for num in array: resultExclusiveOr ^= num indexOf1 = self.FindFirstBitIs1(resultExclusiveOr) num1, num2 = 0, 0 for num in array: if self.IsBit1(num, indexOf1): # 对于数据进行分组 将两个出现一次的数字转换成一个出现次数为1的问题 num1 ^= num else: num2 ^= num return [num1, num2] # 最右边为1的那一位 def FindFirstBitIs1(self, num): indexBit = 0 while num & 1 == 0 and indexBit <= 32: indexBit += 1 num = num >> 1 return indexBit # 某一位是不是1 def IsBit1(self, num, indexBit): num = num >> indexBit return num & 1 # -*- coding:utf-8 -*- class mySolution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): if not array: return [] temp = 0 for num in array: temp ^= num right = self.rightEstIndex1(temp) num1, num2 = 0, 0 for num in array: if self.isBit1(num, right): num1 ^= num else: num2 ^= num return [num1, num2] def rightEstIndex1(self, num): indexBit = 0 while not num & 1: indexBit += 1 num = num >> 1 return indexBit def isBit1(self, num, indexBit): num = num >> indexBit return num & 1 if __name__ == '__main__': aList = [2, 4, 3, 6, 3, 2, 5, 5] s = mySolution() print(s.FindNumsAppearOnce(aList))
a845790ab300d3bfb4705d36be4457de66638692
lunar-r/sword-to-offer-python
/剑指offer/41 和为s的两个数字.py
793
3.609375
4
# -*- coding: utf-8 -*- """ File Name: 41 和为s的两个数字 Description : Author : simon date: 19-3-4 """ # -*- coding:utf-8 -*- class Solution: def FindNumbersWithSum(self, array, tsum): # write code here if not array: return [] left, right = 0, len(array)-1 while left < right: sum_ = array[left] + array[right] if sum_ == tsum: return [array[left], array[right]] while array[left] + array[right] > tsum: right -= 1 while array[left] + array[right] < tsum: left += 1 return [] if __name__ == '__main__': test = [1,2,4,7,11,15] solu = Solution() print(solu.FindNumbersWithSum(test, 5))
6368eaed261b57e7e599ff846e2886491878a052
lunar-r/sword-to-offer-python
/剑指offer/19 二叉树的镜像.py
2,902
3.578125
4
# -*- coding: utf-8 -*- """ File Name: 19 二叉树的镜像 Description : Author : YYJ date: 2019-02-16 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回镜像树的根节点 def Mirror(self, root): # 先修改子树 再交换本级的左右节点 # write code here if root == None: return root.left, root.right = self.Mirror(root.right), self.Mirror(root.left) return root def Mirror0(self, root): # 先交换本级的左右节点 再修改子树 if not root: return root.left, root.right = root.right, root.left # self.Mirror(root.left) self.Mirror(root.right) return root def Mirror_bug(self, root): root.right = self.Mirror(root.left) # 没有分析明白为什么错 root.left = self.Mirror(root.right) # 低级错误 先对root.right进行修改 后一句实际上想要的是未修改之前的值 # 正确写法 root.left, root.right = self.Mirror(root.right), self.Mirror(root.left) # 非递归实现 def Mirror2(self, root): if root == None: return stackNode = [] stackNode.append(root) while len(stackNode) > 0: nodeNum = len(stackNode) - 1 tree = stackNode[nodeNum] stackNode.pop() nodeNum -= 1 if tree.left != None or tree.right != None: tree.left, tree.right = tree.right, tree.left if tree.left: stackNode.append(tree.left) nodeNum += 1 if tree.right: stackNode.append(tree.right) nodeNum += 1 # 非递归实现 def MirrorNoRecursion(self, root): if root == None: return nodeQue = [root] while len(nodeQue) > 0: curLevel, count = len(nodeQue), 0 while count < curLevel: count += 1 pRoot = nodeQue.pop(0) pRoot.left, pRoot.right = pRoot.right, pRoot.left if pRoot.left: nodeQue.append(pRoot.left) if pRoot.right: nodeQue.append(pRoot.right) if __name__ == '__main__': pRoot1 = TreeNode(8) pRoot2 = TreeNode(8) pRoot3 = TreeNode(7) pRoot4 = TreeNode(9) pRoot5 = TreeNode(2) pRoot6 = TreeNode(4) pRoot7 = TreeNode(7) pRoot1.left = pRoot2 pRoot1.right = pRoot3 pRoot2.left = pRoot4 pRoot2.right = pRoot5 pRoot5.left = pRoot6 pRoot5.right = pRoot7 pRoot8 = TreeNode(8) pRoot9 = TreeNode(9) pRoot10 = TreeNode(2) pRoot8.left = pRoot9 pRoot8.right = pRoot10 S = Solution() print(S.Mirror(pRoot1).left.val)
48e6d207932f6c208bcfa879c18d826344b0343f
lunar-r/sword-to-offer-python
/leetcode/200. Number of Islands.py
1,705
3.5625
4
# -*- coding: utf-8 -*- """ File Name: 200. Number of Islands Description : Author : simon date: 19-3-31 """ """ DFS 这道题其实和之前的剑指offer最后补充的回溯问题很相似 机器人的运动范围 每次找到一个运动范围之后 将这个范围全部清成0 """ class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not grid: return 0 rows = len(grid) cols = len(grid[0]) self.cnt = 0 def DFS(i, j): if 0 <= i < rows and 0 <= j < cols and grid[i][j] == '1': grid[i][j] = '0' DFS(i + 1, j) DFS(i - 1, j) DFS(i, j + 1) DFS(i, j - 1) for i in range(rows): for j in range(cols): if grid[i][j] == '1': self.cnt += 1 DFS(i, j) return self.cnt """ 简洁写法 """ class Solution_(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ def sink(i, j): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == '1': grid[i][j] = '0' map(sink, (i+1, i-1, i, i), (j, j, j+1, j-1)) # 使用map函数直接调用四个方向 return 1 return 0 return sum(sink(i, j) for i in range(len(grid)) for j in range(len(grid[0]))) if __name__ == '__main__': print(Solution().numIslands([["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]))
463aaa4cc99d5a573bec3d34e0fa3e87c6709988
lunar-r/sword-to-offer-python
/leetcode/283. Move Zeroes.py
1,488
3.859375
4
# -*- coding: utf-8 -*- """ File Name: 283. Move Zeroes Description : Author : simon date: 19-3-12 """ """ 直接考虑每个非零数字最终需要移动的次数 使用一个List存放每一个元素需要移动的距离 """ class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ N = len(nums) move = [0] * N cnt = 0 for i in range(N): move[i] = cnt if not nums[i]: cnt += 1 for i in range(N): nums[i - move[i]] = nums[i] for i in range(N - cnt, N): nums[i] = 0 class Solution1(object): def sao(self, nums): nums.sort(key=bool, reverse=True) nums.sort(key=lambda x: 1 if not x else 0) class Solution0(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ last0 = 0 # 可以分成第一个数字为0 和第一个数字不为0两种情况讨论 #如果第一个数字不为 last0将跟着不为零的数字一直往前走 知道找到一个0 for i in range(0, len(nums)): if (nums[i] != 0): nums[i], nums[last0] = nums[last0], nums[i] last0 += 1 # 每发生一次交换 0 都会岁之后移
2ccd24c820e0218f7f3f5a637d9b4d7fc418efa6
lunar-r/sword-to-offer-python
/剑指offer/17 合并两个排序的链表.py
2,153
3.71875
4
# -*- coding: utf-8 -*- """ File Name: 17 合并两个排序的链表 Description : Author : YYJ date: 2019-02-16 """ # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: #返回合并后列表 def Merge(self, pHead1, pHead2): # write code here if pHead1 == None: return pHead2 elif pHead2 == None: return pHead1 p1, p2 = pHead1, pHead2 dummy = ListNode(0) # 新建链表必须有头节点 p3 = dummy while p1 and p2: if p1.val <= p2.val: p3.next = p1 # 链表的链接 p1 = p1.next else: p3.next = p2 p2 = p2.next p3 = p3.next # 指针移动 if p1: p3.next = p1 elif p2: p3.next = p2 return dummy.next def Merge0(self, pHead1, pHead2): if pHead1 == None: return pHead2 elif pHead2 == None: return pHead1 if pHead1.val < pHead2.val: # 不断拆解问题 pM = pHead1 # 只是为了记住头节点 pHead1.next = self.Merge(pHead1.next, pHead2) else: pM = pHead2 pHead2.next = self.Merge(pHead1, pHead2.next) return pM def Merge1(self, pHead1, pHead2): # write code here dummy = ListNode(0) pHead = dummy while pHead1 and pHead2: if pHead1.val >= pHead2.val: dummy.next = pHead2 pHead2 = pHead2.next else: dummy.next = pHead1 pHead1 = pHead1.next dummy = dummy.next if pHead1: dummy.next = pHead1 elif pHead2: dummy.next = pHead2 return pHead.next node1 = ListNode(1) node2 = ListNode(3) node3 = ListNode(5) node1.next = node2 node2.next = node3 node4 = ListNode(2) node5 = ListNode(4) node6 = ListNode(6) node4.next = node5 node5.next = node6 S = Solution() print(S.Merge(node1, node4).next.val)
cafda8e5ff27c14b82cbcf19b1bbc617759a4b94
lunar-r/sword-to-offer-python
/leetcode/647. Palindromic Substrings.py
786
3.65625
4
# -*- coding: utf-8 -*- """ File Name: 647. Palindromic Substrings Description : Author : simon date: 19-3-12 """ """ 考虑每一个可能的对称轴 共有2N-1个可能的点(包含两个index的中点) """ class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ if not s: return 0 cnt = 0 s = list(s) N = len(s) for i in range(2 * N - 1): p1 = i // 2 p2 = p1 + i % 2 while (p1 >= 0 and p2 < len(s)): if s[p1] == s[p2]: cnt += 1 p1 -= 1 p2 += 1 else: break return cnt
13c7be410caaf9a5b9f81baf58c97b9751d72d52
lunar-r/sword-to-offer-python
/剑指offer/41 和为S的连续正数序列.py
858
3.828125
4
# -*- coding: utf-8 -*- """ File Name: 41 和为S的连续正数序列 Description : Author : simon date: 19-3-4 """ # -*- coding:utf-8 -*- class Solution: def FindContinuousSequence(self, tsum): # write code here if tsum <= 0: return small, big = 1, 2 curSum = 3 res = [] while small <= (tsum-1)/2: if curSum == tsum: res.append([x for x in range(small, big+1)]) big += 1 curSum += big while curSum < tsum: big += 1 curSum += big while curSum > tsum: small += 1 curSum -= small - 1 return res if __name__ == '__main__': test = 9 solu = Solution() print(solu.FindContinuousSequence(test))
20bf6a7fedd28c550879813689ca58832f89f5b8
lunar-r/sword-to-offer-python
/leetcode/10. Regular Expression Matching.py
2,325
3.921875
4
# -*- coding: utf-8 -*- """ File Name: 10. Regular Expression Matching Description : Author : simon date: 19-4-12 """ """ 递归 + memo 爽的一批 自顶向下 为什么是自顶向下 因为当前的解依赖于未来的解 dp(i,j)意味着 s[i:] 和 p[j:] 之间的匹配情况 """ class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ memo = {} def dp(i, j): if i == len(s) and j == len(p): # 00 res = True elif i != len(s) and j == len(p): # 10 res = False else: # 01 11 if (i, j) in memo: res = memo[(i, j)] else: if j < len(p) - 1 and p[j + 1] == '*': if i < len(s) and p[j] in ['.', s[i]]: res = dp(i, j + 2) or dp(i + 1, j) else: res = dp(i, j + 2) elif i < len(s) and p[j] in ['.', s[i]]: res = dp(i + 1, j + 1) else: res = False memo[(i, j)] = res return res return dp(0, 0) class Solution_(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ memo = {} def dp(i, j): if (i, j) not in memo: if i == len(s) and j == len(p): # 00 res = True elif i != len(s) and j == len(p): # 10 res = False else: # 01 11 if j < len(p) - 1 and p[j + 1] == '*': if i < len(s) and p[j] in ['.', s[i]]: res = dp(i, j + 2) or dp(i + 1, j) else: res = dp(i, j + 2) elif i < len(s) and p[j] in ['.', s[i]]: res = dp(i + 1, j + 1) else: res = False memo[(i, j)] = res return memo[(i, j)] return dp(0, 0) if __name__ == '__main__': print(Solution().isMatch("aab", "c*a*b"))
522959faa58ad93ac77d5ef590bd61f197eea45e
lunar-r/sword-to-offer-python
/剑指offer/01 二维数组查找.py
1,208
3.765625
4
# -*- coding: utf-8 -*- """ File Name: 01 二维数组查找 Description : Author : YYJ date: 2019-02-12 """ # test """ 二刷记录 """ # -*- coding:utf-8 -*- class Solution2: # array 二维列表 def Find(self, target, array): # write code here rows = len(array) cols = len(array[0]) if array else 0 i, j = rows - 1, 0 while i >= 0 and j < cols: if array[i][j] == target: return True elif array[i][j] < target: j += 1 else: i -= 1 return False class Solution: # array 二维列表 def Find(self, target, array): # write code here if array == []: return False M, N = len(array), len(array[0]) # 从右上角开始 i, j = 0, N - 1 while i < M and j >= 0: if array[i][j] == target: return True if array[i][j] > target: j -= 1 else: i += 1 return False if __name__ == '__main__': testArr = [[1, 2], [3, 4]] solu = Solution() print(solu.Find(3, testArr))
8269465b2b495fd82b23c2861c8d1cb9a1e988ae
lunar-r/sword-to-offer-python
/剑指offer/33 把数组排成最小的数.py
1,087
3.90625
4
# -*- coding: utf-8 -*- """ File Name: 33 把数组排成最小的数 Description : Author : simon date: 19-2-24 """ from functools import cmp_to_key # -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here if not numbers: return # numstr = list(map(lambda x: str(x), numbers)) # 定义变换F 输入x numstr = list(map(str, numbers)) # 定义变换F 以及输入x numstr.sort(key=cmp_to_key(lambda x,y: int(x+y) - int(y+x))) # 使用Python内置函数实现排序 # for i in range(len(numstr)): # 因为这是利用两两比较进行排序的算法 所以冒泡排序很适合 # for j in range(len(numstr)-i-1): # if self.cmp(numstr[j], numstr[j+1]): # numstr[j], numstr[j+1] = numstr[j+1], numstr[j] return ''.join(numstr) def cmp(self, x, y): return int(x+y) - int(y+x) if __name__ == '__main__': test = [3, 32, 321] solu = Solution() print(solu.PrintMinNumber(test))
508d420c1004b216125d3f50247d29e9a5deba68
lunar-r/sword-to-offer-python
/leetcode/572. Subtree of Another Tree.py
2,326
3.75
4
# -*- coding: utf-8 -*- """ File Name: 572. Subtree of Another Tree Description : Author : simon date: 19-3-24 """ """ Naive approach, O(|s| * |t|) """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def helper(s, t): if not s and not t: return True if not s and t: return False if not t and s: return False if s.val == t.val: return helper(s.left, t) or helper(s.right, t) or (same(s.left, t.left) and same(s.right, t.right)) else: return helper(s.left, t) or helper(s.right, t) def same(s, t): if not s and not t: return True if not s and t: return False if not t and s: return False if s.val == t.val: return same(s.left, s.left) and same(s.right, t.right) else: return False return helper(s, t) """ 思路清晰版 代码 """ class Solution_(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def isSameTree(p, q): if not p and not q: return True if (p and not q) or (not p and q): return False return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right) if not t: return True if not s and t: return False if isSameTree(s, t): return True return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) def isMatch(self, s, t): if not(s and t): return s is t return (s.val == t.val and self.isMatch(s.left, t.left) and self.isMatch(s.right, t.right)) def isSubtree(self, s, t): if self.isMatch(s, t): return True if not s: return False return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
9dfa5f7bea5cac3228715bf6b83ad731fddbdee3
lunar-r/sword-to-offer-python
/剑指offer/22 从上往下打印二叉树.py
1,259
3.8125
4
# -*- coding: utf-8 -*- """ File Name: 22 从上往下打印二叉树 Description : Author : YYJ date: 2019-02-17 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here if not root: return [] queue = [] out = [] queue.append(root) while queue: curNode = queue.pop(0) out.append(curNode.val) # list.pop() return and remove item if curNode.left: queue.append(curNode.left) if curNode.right: queue.append(curNode.right) return out if __name__ == '__main__': pNode1 = TreeNode(8) pNode2 = TreeNode(6) pNode3 = TreeNode(10) pNode4 = TreeNode(5) pNode5 = TreeNode(7) pNode6 = TreeNode(9) pNode7 = TreeNode(11) pNode1.left = pNode2 pNode1.right = pNode3 pNode2.left = pNode4 pNode2.right = pNode5 pNode3.left = pNode6 pNode3.right = pNode7 S = Solution() print(S.PrintFromTopToBottom(pNode1))
b049e855fb873027a24ac6e3f022b675788d4ad9
lunar-r/sword-to-offer-python
/剑指offer/把字符串转换成整数.py
1,435
3.75
4
# -*- coding: utf-8 -*- """ File Name: 把字符串转换成整数 Description : Author : simon date: 19-3-19 """ # -*- coding:utf-8 -*- class Solution: def StrToInt(self, s): # write code here if not s: return 0 s = list(s) for i in s: if i not in ['+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: return 0 def makenum(s): res = 0 i = 1 while s: tp = s.pop() res += i * int(tp) # 使用哈希表实现比较靠谱 i *= 10 return res if s[0] in ['-', '+']: res = 1 if s[0] == '+' else -1 res *= makenum(s[1:]) else: res = makenum(s) return res """ 改进 """ class Solution_: def StrToInt(self, s): # write code here if not s: return 0 nums = [] numbers = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} for i, n in enumerate(s): if n in numbers.keys(): nums.append(n) elif i == 0 and n in ['+', '-']: continue else: return 0 res = 0 for i in nums: res = res * 10 + numbers[i] if s[0] == '-': return -1 * res return res
e733b066911f5ebafa1a8a01c37d9cf69ef3870f
amanlalpuria/go-python-over
/Using Python to Access Web Data/02. Assignment.py
272
3.5625
4
import re def getNumbers(str,sum): array = re.findall(r'[0-9]+', str) for i in array: sum+=int(i) return sum sum = 0 file = "regex_sum_702801.txt" fh = open(file) for line in fh: result = getNumbers(line,sum) sum = result print(sum)
f3d2913606a2b0536ceb12a9b469762cd9d86fc3
giant-xf/python
/untitled/4.0-数据结构/4.02-栈和队列/4.2.2-队列的实现.py
945
4.4375
4
class Queue(object): #创建一个空的队列 def __init__(self): #存储列表的容器 self.__list = [] def enqueue(self,item): #往队列中添加一个item元素 self.__list.append(item) #头插入,头出来,时间复杂度 O(n) #self.__list.insert(0,item) def dequeue(self): #从队列尾部删除一个元素 #return self.__list.pop() #头删除 时间复杂度 O(n) return self.__list.pop(0) def is_empty(self): #判断一个队列是否为空 return not self.__list def size(self): #返回队列的大小 return len(self.__list) if __name__ == '__main__': s = Queue() print(s.is_empty()) s.enqueue(1) s.enqueue(2) s.enqueue(3) print(s.is_empty()) print(s.size()) print(s.dequeue()) print(s.dequeue()) print(s.dequeue())
5e68926d8fb2ab4328840045fbf9b330f983445b
giant-xf/python
/untitled/1.01-小白成长记/复习篇/函数--匿名函数.py
437
3.6875
4
def fun(a,b): sum =a+b return sum print("result =",fun(1,2)) t=lambda x,y:x+y print("result =",t(1,2)) #应用场景: #函数作为参数传递 #1.自定义函数 def f(a,b,opt): print("result =",opt(a,b)) f(1,2,lambda x,y:x+y) #2.作为内置函数的参数 stus =[{"name":'老王','age':15}, {'name':"老李",'age':16}, {'name':"老陈",'age':17}] stus.sort()
15d307f0a9d26df337c7fe941d2c4fcf28c9d9d6
giant-xf/python
/untitled/4.0-数据结构/eg.py
1,816
4
4
class Node(object): """单链表的节点""" def __init__(self,elem): self.elem = elem self.next = None class SingleLinkList(object): """单链表的实现""" def __init__(self): self.__head =None def is_empty(self): """判断是否为空""" return self.__head == None def length(self): '''链表的长度''' #指针/游标指向表头 cur = self.__head #计数 count = 0 while cur != None: count +=1 cur = cur.next return count def travel(self): """链表的遍历""" cur = self.__head while cur != None: print(cur.elem, end=" ") cur = cur.next def add(self,item): """链表表头添加数据""" node = Node(item) if self.__head == Node: self.__head = node else: node.next = self.__head self.__head = node def append(self,item): """链表尾部添加数据""" node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node if __name__ == '__main__': ll =SingleLinkList() ll.add(1) ll.add(2) ll.add(3) ll.add(4) #ll.travel() ll.append(5) ll.append(6) ll.append(7) ll.append(8) ll.travel() # print(ll.is_empty()) # print(ll.length()) # # ll.append(1) # print(ll.is_empty()) # print(ll.length()) # # ll.append(2) # ll.append(3) # ll.append(4) # ll.append(5) # ll.append(6) # ll.travel()
1212457649585f24add77cd3ed4c18e543d14a6e
giant-xf/python
/untitled/2.0-小白进阶篇/2.01-核心编程/1.01.3-生成器应用于协程.py
1,605
4.03125
4
#生成器中 send用法 next()用法 __next__()用法 以及 yield 用法 '''1.next(xx)用法: 调用一次生成一个值,最后生成完了会异常 2.__next__用法: 与next用法相同 3.send()的用法: 第一次不能传入非空数据,要么不用seed(),要么传入None, 传入temp参数,传一次更新一次,否则下次不传就默认传入了None 可以用条件判断使其一直保持最初传入的值 def f(): i=0 while i<5: if i==0: temp =yield i else : print(temp) yield i i+=1 4.yield 用法: 函数中可以参入多个yield ,变成生成器,暂停一次 ''' ''' 生成器分两种 :1.生成器a =(i for i in rang(10)) 2.函数中含有yield,变成了对象,而不是函数了, 遇到yield会暂停,下一次调用继续运行 作用:协程 ''' def Num(): i =0 while i<5: temp =yield i print(temp) i +=1 t=Num() #next(t) #print(t.send('ooooo')) #第一次传入数据会异常 print(t.send(None)) #第一次可以传空值 print(t.__next__()) print(t.send('hah')) print(t.__next__()) def Num_1(): while True: print('----1----') yield None def Num_2(): while True: print('----2----') yield None t1=Num_1() t2=Num_2() #while True: #t1.__next__() #t2.__next__()
4fb432f7762c778f8efd0de0e14031b004a27f2b
Resinchen/CG-course-Urfu
/draw_func_ghrafic.py
1,635
3.875
4
from math import * from tkinter import * screen_width = 700 screen_height = 600 is_show_X_axis = True is_show_Y_axis = True # входные данные a = -10 b = 10 func = lambda x: sin(x)+cos(x/2) # доп. переменные x0 = 0 ymin = ymax = y0 = func(a) axis_y_x = axis_x_y = 0 # будем ли рисовать вертикльную ось if a > 0 and b > 0 or a < 0 and b < 0: is_show_Y_axis = False print('Not show Y_axis') root = Tk() root.geometry('650x650') canvas = Canvas(root, width=screen_width, height=screen_height+10, bg="white") canvas.pack(side=LEFT) # ищем минимум и максимум функции for xx in range(screen_width): x = a + xx * (b - a) / screen_width y = func(x) if y < ymin: ymin = y if y > ymax: ymax = y # будем ли рисовать горизонтальную ось if ymin > 0 or ymax < 0: is_show_X_axis = False print('Not show X_axis') # рисуем график for x_scaled in range(screen_width): x = a + x_scaled * (b - a) / screen_width y = func(x) y_scaled = (y - ymax) * screen_height / (ymin - ymax) + 5 if y > 0 and axis_y_x < y_scaled: axis_y_x = y_scaled if x == 0: axis_x_y = x_scaled # рисуем график canvas.create_line(x0, y0, x_scaled, y_scaled) x0 = x_scaled y0 = y_scaled # рисуем оси if is_show_Y_axis: canvas.create_line(axis_x_y, screen_height, axis_x_y, 0, width=1, arrow=LAST) if is_show_X_axis: canvas.create_line(0, axis_y_x, screen_width, axis_y_x, width=1, arrow=LAST) root.mainloop()
0ad4b40d559778b1b9623427de20cb10b5c20f2d
aitsc/interesting-algorithm
/上楼梯问题.py
300
3.609375
4
def 上楼梯(层数,次数=[0]): if 层数>=3: 上楼梯(层数-1, 次数) 上楼梯(层数-2, 次数) 上楼梯(层数-3, 次数) elif 层数==2: 次数[0] = 次数[0] + 2 else: 次数[0] = 次数[0] + 1 return 次数[0] print(上楼梯(4))
4785c91aa4570236396e5628a71b14c7bc3d1c36
arung-agamani/tubes-tbfo-cyk
/grammarConverter.py
1,707
3.59375
4
RULE_DICT = {} def read_grammar(grammar_file): with open(grammar_file) as cfg: lines = cfg.readlines() return [x.replace("->", "").split() for x in lines] def add_rule(rule): global RULE_DICT if rule[0] not in RULE_DICT: RULE_DICT[rule[0]] = [] RULE_DICT[rule[0]].append(rule[1:]) def convert_grammar(grammar): global RULE_DICT unit_productions, result = [], [] res_append = result.append index = 0 for rule in grammar: new_rules = [] if len(rule) == 2 and rule[1][0] != "'": unit_productions.append(rule) add_rule(rule) continue elif len(rule) > 2: terminals = [(item, i) for i, item in enumerate(rule) if item[0] == "'"] if terminals: for item in terminals: rule[item[1]] = f"{rule[0]}{str(index)}" new_rules += [f"{rule[0]}{str(index)}", item[0]] index += 1 while len(rule) > 3: new_rules += [f"{rule[0]}{str(index)}", rule[1], rule[2]] rule = [rule[0]] + [f"{rule[0]}{str(index)}"] + rule[3:] index += 1 add_rule(rule) res_append(rule) if new_rules: res_append(new_rules) while unit_productions: rule = unit_productions.pop() if rule[1] in RULE_DICT: for item in RULE_DICT[rule[1]]: new_rule = [rule[0]] + item if len(new_rule) > 2 or new_rule[1][0] == "'": res_append(new_rule) else: unit_productions.append(new_rule) add_rule(new_rule) return result
77df69304204d14fbcf444cb65e18c7d9bfb2f3f
arung-agamani/tubes-tbfo-cyk
/inputFile4.py
260
4
4
def greet(name): """ This function greets to the person passed in as parameter """ print("Hello, " + name + ". Good morning!") while(True): name = input("Input your name : ") if (name != ""): greet(name) else: break
1b0dbc67c509a73b2482d2424987e284c5dbd063
kevinliu2019/CP1404practicals
/prac_05/hex_colours.py
758
4.4375
4
CODE_TO_COlOUR = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7", "AntiqueWhite1": "#ffefdb", "AntiqueWhite2": "#eedfcc", "DodgerBlue3": "#1874cd", "gray": "#bebebe", "aquamarine1": "#7fffd4", "OldLace": "#fdf5e6", "aquamarine4": "#458b74", "azure1": "#f0ffff", "azure2": "#e0eeee", "LightCoral": "#f08080", "MediumPurple": "#9370db", "beige": "#f5f5dc", "DarkSalmon": "#e9967a"} print(CODE_TO_COlOUR) colour_name = input("Enter a colour name: ") while colour_name != "": print("The code for \"{}\" is {}".format(colour_name, CODE_TO_COlOUR.get(colour_name))) colour_name = input("Enter a colour name: ")
c67732237f85176b80ae8a8a6691c7e10c71e41c
marcoacarvalho/marco-carvalho
/Connection.py
1,074
3.5
4
###################################################### # Exemplos de uso do sqlobject ###################################################### import sqlobject from sqlobject.mysql import builder conn = 'mysql://dbuser:dbpassword@localhost/sqlobject_demo?debug=1' """ Database Connections Examples: MySQL conn = MySQLConnection(user='test', passwd='pwd', db='testdb') [this method is now deprecated. Use the URI method below] conn = 'mysql://test:pwd@localhost/testdb' conn = 'mysql://test:pwd@localhost/testdb?debug=1' [To allow debugging, shows sql queries] PostgreSQL conn = PostgresConnection('user=test passwd=pwd dbname=testdb') [this method is now deprecated. Use the URI method below] conn = 'postgres://test:pwd@localhost/testdb' SQLite conn = SQLiteConnect('database.db') conn = 'sqlite://path/to/database.db' DBM conn = DBMConnection('database/') conn = 'dbm://path/to/database/' ... (then assign using:) class Person(SQLObject): _connection = conn """
bd8def2a1686e8c48fc77f68009bc8a292db6cba
DilrajS/TD-Learning-Black-Jack
/wordBased.py
6,297
3.921875
4
import Card import Dealer import Player import random # import time # IMPORTANT VARIABLES AND DICTIONARIES current_player = 0 # Keeps track of who is playing. numOfPlayers = 0 # Number of players user wants. playerDictionary = {} # Keeps players (& dealer) in a dictionary. cardDict = {} # This stores cards that are created. suitList = ["clubs", "diamonds", "hearts", "spades"] # List of suits. valueDictionary = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 10, 12: 10, 13: 10, 14: 11} # How much each card is worth. # Need to make A worth 11 points (or 14 in list) automatically unless score > 21. # Add bust counter, if all players bust, no need for dealer to play. # CREATING PLAYER(S). inputCheck = False while not inputCheck: # Asks user how many players will play. try: numOfPlayers = int((input("How many players are going to play (0 - 3)? : \n"))) if type(numOfPlayers) == int: inputCheck = True except ValueError: print("Incorrect input, try again.") # Caps number of players. if numOfPlayers > 3: numOfPlayers = 3 # Generate and store players in a dictionary. for _ in range(numOfPlayers): newPlayer = Player.Player(0) playerDictionary[_] = newPlayer # print(playerDictionary) # GENERATE CARDS. deckCount = int(input("Enter a number for how many decks you want to play with: ")) # How many decks to use. def generate_card(): # Generating values for a card object name = random.randint(1, 13) suit = random.randint(1, 4) count = 0 value = int(valueDictionary[name]) c = Card.Card() c.__int__(name, suit, count, value) # Push the values into the object. card_key = str(name) + suitList[suit - 1] # Creates a card ID to store the card in the dictionary. if card_key in cardDict.keys(): # Check if card already exists in the dictionary by searching for the card ID. if cardDict[card_key].count < deckCount: # If found in dictionary, checks if possible to create another card. cardDict[card_key].count += 1 print("The card drawn is: " + str(c.value)) playerDictionary[current_player].update_score(c.value) # Updates player score. else: generate_card() # If found in dictionary, but not possible to create another card, generates a new card. else: c.count = 1 # If card not in dictionary, adds it and increases card count. cardDict[card_key] = c print("The card drawn is: " + str(c.value)) playerDictionary[current_player].update_score(c.value) # Updates player score. # HIT FUNCTION. def hit(): generate_card() # Calls generate function to generate a new card and updates player score. # HOLD FUNCTION. def hold(): global current_player if current_player + 1 < numOfPlayers: # If there is another player after the current player do this. current_player += 1 # Switches to the next player hit_check_helper() # Calls hit_check_helper so next player can hit/hold. else: # If the last player chose to hold, do the following. current_player += 1 # Switches to dealer (in the player library) # COMPARE SCORES FUNCTION. def compare_scores(): # If you bust or have a lower score than dealer, you lose. score_list = [] for i in range(numOfPlayers + 1): if i <= numOfPlayers - 1: if playerDictionary[i].score == 0: score_list.append("Player " + str(i + 1) + ": Loss") elif playerDictionary[i].score >= 22: score_list.append("Player " + str(i + 1) + ": Loss") else: if playerDictionary[_].score >= dealer.score: score_list.append("Player " + str(_ + 1) + ": Win") else: score_list.append("Player " + str(_ + 1) + ": Loss") else: # Add if dealer score is lower than player scores. if playerDictionary[i].score == 0: score_list.append("Dealer Loss") elif playerDictionary[i].score >= 22: score_list.append("Dealer Loss") else: score_list.append("Dealer Win") print(score_list) # GAME CODE. # Create a dealer, give him 1 card (update score with 1 card.) dealer = Dealer.Dealer(0) # Creates a dealer object playerDictionary[len(playerDictionary)] = dealer # Puts the dealer last int he player dictionary # print(playerDictionary) # Give all players 2 cards (update points/score using 2 cards.) for x in range(numOfPlayers): generate_card() generate_card() print("Current score of Player " + str(x + 1) + " is: " + str(playerDictionary[x].score)) print("------------------------------------------------") current_player += 1 print("All players have been dealt cards! Switching to Hit/Hold phase... \n") # Set current player back to 0 so we can go to Hit / Hold phase. current_player = 0 hit_check = True def hit_check_helper(): global hit_check global current_player print("Current Player: " + str(current_player + 1) + " | Current Score: " + str(playerDictionary[current_player].get_score())) print("Enter 1 to hit and 0 to hold.") check_for_hit = int(input()) if check_for_hit == 1: hit() if playerDictionary[current_player].get_score() > 21: print("New score is: " + str(playerDictionary[current_player].get_score())) print("Bust. Switching player...") playerDictionary[current_player].bust() hold() elif check_for_hit == 0: if current_player == len(playerDictionary): hit_check = False else: hold() else: print("Error: Only values of 1 and 0 are accepted.") hit_check_helper() while hit_check and current_player < numOfPlayers: hit_check_helper() # Dealer part while dealer.get_score() <= 17: # Code for how the Dealer plays, if his score is < 17, heep hitting. hit() print("Dealer's score is: " + str(dealer.get_score())) if dealer.score > 21: # If dealer hits over 21, it prints out Dealer busted. dealer.bust() print("Dealer bust.") compare_scores() # Compares all the scores by calling the compare scores method # GUI.
42d8d3d8105a71924d5a391eef15d9cfc7f66aa2
Danielacvd/Py3
/Funciones/funciones.py
4,613
4.375
4
""" Funciones en python3 Definicion o llamada: Syntax Basica: def nombre_funcion(): codigo.... return codigo #llamo desde el cuerpo del programa nombre_funcion() Dentro de la funcion puedo declarar variables, inicializarlas, etc Pero para que estan variables puedan vivir fuera de la funcion, las tengo que retornar Las variables solo viven dentro de la funcion, si declaro una variable dentro de una funcion y la llamo desde fuera de la funcion dara un error, por eso se escapan o retornan usando el return o print. Retorno: Lo importante del return es que con el puedo sacar devolver valores, al momento de devolver valores la ejecucion de la funcion termina. Puedo devolver multiples valores, separandolos por comas. Pero estos valores se trataran en conjunto como su fueran una tupla, inmutables, pero se pueden reasignar a otras variables. Envio de valores Ademas de devolver valores, puedo recibir valores Syntax: def nombre_funcion(a, b): resultado = a+b return resultado nombre_funcion(a, b) #No necesariamente el nombre de la variable que entrego tiene que ser el que recibo en los parametros de la funcion. def suma(a, b): return a+b resultado = suma(5,5) print(resultado) Arqumentos y parametros Los valores que recibo en la funcion, se llaman parametros, pero cuando yo estoy enviando datos a una funcion, estos se llaman argumentos Argumentos por posicion Cuando envio un argumento, estos son recibidos por la funcion que yo estoy llamando, y se reciben por orden en los parametros recibidos. def suma(a, b): return a+b resultado = suma(5,7) # 5 seria tomara el primer lugar de los parametros, 7 el segundo (a = 5, b = 7) Sin embargo, puede evadir este orden, si al momento de llamar la funcion y enviar los argumentos a estos les asigno el nombre del parametro resta(b=30, a=10) Tambien esta la llamada sin argumentos Si llamamos a un funcion que tiene definidos parametros y al llamarla no le entregamos los argumentos necesarios, dara un error. def suma(a,b): return a+b suma()#Error La funcion suma estara esperando que entreguemos argumentos para los parametros a y b. Para lidiar con estos, podemos usar parametros por defecto. def resta(a=None, b=None): if a == None or b == None: print("Faltaron los numeros para la ejecucion de la funcione") return return a-b #En caso de que lleguen los 2 argumentos realizo la operacion. resta() Paso por valor y referencia Depende del tipo de dato que enviamos a la funcion, podemos diferenciar 2 comportamientos: - Paso por valor: Se crea una copia local de la variable dentro de la funcion. - Paso por referencia: Se maneja directamente la variable, lo cambios realizados dentro de la funcicon la afectara tambien afuera de esta. - Los tipos simples se pasan por valor: Enteros, flotantes, cadenas, logicos(int, float, str, bool) - Los tipos compuestos se pasan por referencia: Listas, diccionarios, conjuntos(list, dicc, set) Paso por valor Los numeros se pasan por valor, crean una copia dentro de la funcion, por lo que no les afecta lo que se haga con ellos dentro de una funcion def doble(numero): numero *= 2 return numero n = 10 print(doble(n)) print(n) Paso por referencia Las listas y otras colecciones son datos compuestos por lo que se pasan por referencia, por lo que se los modifico desde la funcion lo modificare tambien afuera. lista_n = [1,2,3] print(lista_n) def altera_lista(lista): lista.append(4) print(lista) altera_lista(lista_n) print(lista_n Tambien se pueden modificar los tipos simples, los devolvemos modificados y se los reasignamos a su variable def doble(numero): return numero * 2 n = 10 n = doble(n) print(n) En el caso de los tipos de datos compuestos, podemos evitar la modificacion enviando una copia def doblar_valores(numeros): for i,n in enumerate(numeros): numeros[i] *= 2 ns = [10,50,100] doblar_valores(ns[:]) # Una copia al vuelo de una lista con [:] print(ns) """ def nombre_funcion(parametro): return f"Hola {parametro}" print(nombre_funcion("Daniel")) def sin_parametro(): n1 = 10 n2 = 20 print(f"Suma: {n1 + n2}") sin_parametro() def parametro_por_defecto(nombre = "Daniel"): return f"Hola {nombre}" print(parametro_por_defecto("Feña")) def suma(a, b): return a+b resultado = suma(5,5) print(resultado) print("asd") def doble(numero): numero *= 2 return numero n = 10 print(doble(n)) print(n) print("\nASD") lista_n = [1,2,3] print(lista_n) def altera_lista(lista): lista.append(4) print(lista) altera_lista(lista_n) print(lista_n
faf5e2e6b7a1df320d4dd5124041cbf0ccf19692
Danielacvd/Py3
/Estructura_de_control/ciclo_while.py
460
4.03125
4
""" Ciclo While inicializo variable while condicion: instrucciones actualizar variable else: print("Fin ciclo") Si uso el break en el while, no se ejecutara el else, ya que el ciclo no finaliza su iteracion, si no que se interrumpe Instrucción continue Sirve para "saltarse" la iteración actual sin romper el bucle. Hacer menus, dentro de un while van las opciones, como el do while de C """ i = 0 while i <= 10: print(i) i += 1
69c90196bf5f5b97440c574eef6df4d6c70bf04c
Danielacvd/Py3
/Errores_y_excepciones/excepciones.py
2,764
4.1875
4
""" Errores y Excepciones en Python Excepciones Son bloques de codigo que nos permiten seguir con la ejecucion del codigo a pesar de que tengamos un error. Bloque Try-Except Para prevenir fallos/errores tenemos que poner el bloque propenso a errores en un bloque TRY, y luego encadenar un bloque except para tratar la situacion excepcional, mostrando que ocurrio un fallo/error try: n = float(input("Introduce un número decimal: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") De esta forma se controlar situaciones excepcionales que generan errores y en vez de que se muestre el error mostramos un mensaje o ejecutamos una pieza de codigo diferente. Tambien al usar excepciones se puede forzar al usuario a introducir un numero valida usando un while, haciendo que introduzca el dato solicitado hasta que lo haga bien, y romper el ciclo con un break. while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) break except: print("Ha ocurrido un error, introduce bien el número") Bloque else: Puedo encadenar un bloque else despues del except (similar al else de un ciclo) para comprobar el caso en que todo salio bien.(Si todo funciona bien, no se ejecuta la excepcion). while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break Bloque Finally: Este bloque se ejecutara al final del codigo, ocurra o no un error while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break finally: print("Fin de la iteración") """ try: n = float(input("Introduce un número decimal: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) break except: print("Ha ocurrido un error, introduce bien el número") while(True): try: n = float(input("Introduce un número: ")) m = 4 print("{}/{} = {}".format(n,m,n/m)) except: print("Ha ocurrido un error, introduce bien el número") else: print("Todo ha funcionado correctamente") break
db1eedd2b2ea011786f6b26d58a1f72e5349fceb
mirarifhasan/PythonLearn
/function.py
440
4.15625
4
#Function # Printing the round value print(round(3.024)) print(round(-3.024)) print(min(1, 2, 3)) #If we call the function without parameter, it uses the default value def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() #Array passing in function def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)
d8a7bf8f88456c702dc0ad06f88a7aa6cfcac0a9
MadsRasted/pythonExam
/ListLoops.py
1,451
4.0625
4
#List loops animalList = ['Hamster', 'Tiger', 'Gnu', 'Lion'] #For loop #Loop thru for i in animalList: print(i) print('') #Loop thru for i in range(len(animalList)): print(animalList[i]) print('') #Break at position for i in animalList: print(i) if i == 'Tiger': break print('') #___________________________________________________________________________________# #While loop i = 0 while i < len(animalList): print(animalList[i]) i += 1 print('') j = 0 while True: print(animalList[j]) j += 1 if j == 4: break print('') #List comprehension x = 0 [print(x) for x in animalList] print('') newAnimalList3 = [] animalList3 = [x for x in animalList] #Almindeligt for loop til at tage dyr med H i ny liste newAnimalList = [] for x in animalList: if "H" in x: newAnimalList.append(x) print(newAnimalList) #Samme funktion som for loopet, men lavet som list comprehension, så meget kortere syntax print('Kun dyr der starter med T') newAnimalList2 = [x for x in animalList if 'T' in x] print(newAnimalList2) print('Upper case') newAnimalList = [x.upper() for x in animalList] print(newAnimalList) print('Nick er dum erstatter alle positions i listen') newAnimalList = ['Nick er dum' for x in animalList] print(newAnimalList) #Replace en position print("Erstatter hamster med Great ape") newAnimalList = [x if x != "Hamster" else "Great Ape" for x in animalList] print(newAnimalList)
e2667a1f65600f84b0f1892372f22ae131a859bd
ruiwancheng/test
/test_list_and_dictionary.py
2,060
4.09375
4
list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list[2:-2])# 从第二个开始(包含),到倒数第二个(不包含) length = len(list) # 容量 max_data = max(list) # 最大值 min_data = min(list) # 最小值 # list(tuple) print(list) list.append(11) # 添加元素 print(list) print(list.count(3)) # 计算元素出现次数 list.extend([12, 13, 14, 15]) # 添加列表 print(list) list.insert(8, 89) # insert(idex, element) 在指定位置添加元素 print(list) list.pop(-1) # pop(index) 移除指定位置元素,默认最后一个, print(list) list.remove(12) # 移除指定元素 print(list) list.reverse() # 反转 print(list) list.sort() # 排序 print(list) new_list = list.copy() list.clear() # 清空 print(list) print("""--------------------------dictionary----------------------------------""") dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} dict2 = dict.copy() # 复制 del dict["Name"] print(f"删除Name元素之后是{dict}") dict.clear() print(f"清空所有元素之后是{dict}") print(f"字典的元素数量为{len(dict2)}") print(f"将字段转换为字符串{str(dict2)}") print(f"字典的类型是{type(dict2)}") tup1 = (1, 2, 3,) dict3 = {} dict3.fromkeys(tup1, 10) print(f"使用元组创建字段并提供默认值结果是:{dict3}") print(f"获取Name对应的值{dict2.get('Name')}") print(f"判断Age键是不是在字典里{'Age' in dict2}") print(f"返回字典中的键值对视图{dict2.items()}") print(f"返回字典中的键视图{dict2.keys()}") print(f"返回字段中的值视图{dict2.values()}") dict2.setdefault("Rui") print(f"甚至字典中的键值对,如果键不存在则直接添加,值为默认值,比如设置一个不存在的Rui键之后{dict2}") dict2.update({"Ye":1, "Su":2}) print(f"添加其他字段的键值对之后:{dict2}") dict2.pop("Class") print(f"删除字段中的键为class的键值对之后:{dict2}") print(f"什么叫随机返回并删除最后一个键值对?:{dict2.popitem()}") print(f"删除并返回之后的字典是{dict2}")
69199e5f988a159992b12ba048712c86f9d14032
kimmoahola/neural
/app.py
5,872
4.03125
4
from numpy import random from numpy.ma import exp, array, dot class NeuralNetwork: def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. random.seed(1) # We model a single neuron, with 3 input connections and 1 output connection. # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1 # and mean 0. self.synaptic_weights = 2 * random.random((3, 5)) - 1 # The Sigmoid function, which describes an S shaped curve. # We pass the weighted sum of the inputs through this function to # normalise them between 0 and 1. def __sigmoid(self, x): return 1 / (1 + exp(-x)) # The derivative of the Sigmoid function. # This is the gradient of the Sigmoid curve. # It indicates how confident we are about the existing weight. def __sigmoid_derivative(self, x): return x * (1 - x) # We train the neural network through a process of trial and error. # Adjusting the synaptic weights each time. def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in range(number_of_training_iterations): # Pass the training set through our neural network (a single neuron). output = self.think(training_set_inputs) # Calculate the error (The difference between the desired output # and the predicted output). # print(training_set_outputs) # print(output) error = training_set_outputs - output # print(error) # print('----') # Multiply the error by the input and again by the gradient of the Sigmoid curve. # This means less confident weights are adjusted more. # This means inputs, which are zero, do not cause changes to the weights. adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output)) # Adjust the weights. self.synaptic_weights += adjustment # The neural network thinks. def think(self, inputs): # Pass inputs through our neural network (our single neuron). return self.__sigmoid(dot(inputs, self.synaptic_weights)) mode_off = [1, 0, 0, 0, 0] mode_heat8 = [0, 1, 0, 0, 0] mode_heat10 = [0, 0, 1, 0, 0] mode_heat16 = [0, 0, 0, 1, 0] mode_heat20 = [0, 0, 0, 0, 1] output_groups = ['off', 'heat8', 'heat10', 'heat16', 'heat20'] # tavoite # virhe # virhe muutosnopeus # sisä miinus ulko # sisä miinus 12h ulkolämpötilaennuste # PID-säätimen i-termi # oliko edellinen komento lämmitys training_set_inputs = array([ [5, 1, 0], [5, 1, 1], [8, 0, 0], [5, -1.5, 0], # [5, 2, 0, 10, 10, 0, 1], # [5, 1.2, 0, 10, 10, 0, 1], # [5, 0.5, 0, 10, 10, 0, 1], # [5, 0.5, -0.1, 10, 10, 0, 1], # [5, -1, 0, 10, 10, 0, 1], # [7, 0, 0, 20, 18, 0, 1], # [7, 1, 0, 20, 18, 1, 1], # [5, -0.9, 0, 11, 7, -1, 1], # [5, -1.2, 0, 11, 7, -1.5, 1], # [5, -0.1, 0, 11, 7, -0.5, 0], ]) # training_set_outputs = array([[1, 1, 0]]).T training_set_outputs = array([ mode_heat8, mode_heat16, mode_heat10, mode_off, # mode_heat16, # mode_heat10, # mode_heat8, # mode_off, # mode_heat16, # mode_heat20, # mode_heat8, # mode_off, # mode_off, ]) def test(neural_network): test_sets = [ ([4, 0.5, 0.1], mode_heat8), # ([6, 0, 0.5, 15, 10, 1, 1], mode_heat16), # ([5, 2, 0, 10, 10, 0, 1], mode_heat16), # ([5, -1.2, 0, 11, 7, -1.5, 1], mode_off), # ([5, -0.1, 0, 11, 7, -0.5, 0], mode_off), # ([5, -0.9, 0, 11, 7, -1, 1], mode_heat8), ] failed_count = 0 def run_test(i, c): result = neural_network.think(array(i)) max_result = max(result) output_group_index = result.tolist().index(max_result) test_output = output_groups[output_group_index] correct_output_text = output_groups[c.index(max(c))] if test_output != correct_output_text: print('\ntest did not pass') print('test_input', test_input) print('test output', test_output) print('correct', correct_output_text) print('result', result) return 1 return 0 for test_input, correct_output in zip(training_set_inputs.tolist(), training_set_outputs.tolist()): failed_count += run_test(test_input, correct_output) for test_input, correct_output in test_sets: failed_count += run_test(test_input, correct_output) total_count = len(test_sets) + len(training_set_inputs) success_count = total_count - failed_count print(f'Accuracy {success_count}/{total_count} {success_count / total_count * 100} %') def main(): # Intialise a single neuron neural network. neural_network = NeuralNetwork() print("Random starting synaptic weights: ") print(neural_network.synaptic_weights) # Train the neural network using a training set. # Do it 10,000 times and make small adjustments each time. neural_network.train(training_set_inputs, training_set_outputs, 1000) print("New synaptic weights after training: ") print(neural_network.synaptic_weights) test(neural_network) if __name__ == "__main__": main() # # # Test the neural network with a new situation. # print("Considering new situation -> ?: ") # # result = neural_network.think(array([6, 0, 0.5, 15, 10, 1, 1])) # # print(result) # max_result = max(result) # output_group_index = result.tolist().index(max_result) # print(output_groups[output_group_index]) # # # if result[0] < 0.5: # # print('no heat') # # else: # # print('heat')
2ac79f13fc4c1c6616184d5c4c1327bbc593daf3
daivikvennela/python-udemy
/Math.py
434
4.09375
4
print("math") number_1 = eval(input("number1: ")) operation = input("operation - +,-,*,/: ") number_2 = eval(input("number2: ")) if operation == "+": result = number_1 + number_2 elif operation == "-": result = number_1 - number_2 elif operation == "*": result = number_1 * number_2 elif operation == "/": result = number_1 / number_2 print(number_1, operation, number_2,"=",result) x = 1+10 y = x+1 print(y)
856f9202d749b87a551fc014dc3a481018fcd564
rishi23root/Password-Strength-Checker
/run.py
13,545
3.765625
4
from tkinter import * class password_strength_checker: def __init__(self,password): self.password =rf'{password}' # saving empty variables self.digits_count = 0 self.small_letters_count = 0 self.big_letters_count = 0 self.special_count = 0 # possibilities self.digit_possibility = 10 self.letter_possibility = 26 self.special_possibility = 33 def counter(self): # clearing the whitespace from password password = self.password.strip() # looping in password for i in password: if i.isdigit() : # if it is a number [0-9] # possiblity = 10 self.digits_count +=1 elif i.isalpha() : # if is in [a-zA-Z] # possiblity = 26 if i.isupper(): self.big_letters_count += 1 else : self.small_letters_count += 1 else: # """ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" # possiblity = 33 self.special_count += 1 def total_possibitities(self): # to calculate the possible password of this format dig = self.digit_possibility**self.digits_count if self.digits_count != 0 else 1 small_alfa = self.letter_possibility**self.small_letters_count if self.small_letters_count != 0 else 1 big_alfa = self.letter_possibility**self.big_letters_count if self.big_letters_count != 0 else 1 spe = self.special_possibility**self.special_count if self.special_count != 0 else 1 # total possibility self.tp = (dig*small_alfa*big_alfa*spe) return self.tp def time_converter(self,time_in_sec): # convert the second time in readable format result = '' centurie = 60*60*24*365*100 year = 60*60*24*365 month =60*60*24*30 week =60*60*24*7 day =60*60*24 hour = 60*60 minute = 60 def func(centuries): if len(str(centuries)) > 2 and centuries > 20: centuries = str(centuries)[:2] + f'x10^{len(str(centuries))-2}' else : centuries = str(int(centuries)) return centuries # centuries if time_in_sec >= centurie: centuries = time_in_sec//centurie result += f'{func(centuries)} c., ' time_in_sec = time_in_sec%centurie else: centuries = 0 # year if time_in_sec >= year : # convert in years years = time_in_sec//year result += f'{func(years)} y, ' time_in_sec = time_in_sec%year else: years = 0 # month if time_in_sec >= month: # convert in months months = time_in_sec//month result += f'{func(months)} M, ' time_in_sec = time_in_sec%month else: months = 0 # week if time_in_sec >= week: # convert in weaks weeks = time_in_sec//week result += f'{func(weeks)} w, ' time_in_sec = time_in_sec%week else: weeks = 0 # day if time_in_sec >= day: # convert into days days = time_in_sec//day result += f'{func(days)} d, ' time_in_sec = time_in_sec%day else: days = 0 # hour if time_in_sec >= hour: # convert into hours hours = time_in_sec//hour result += f'{func(hours)} h, ' time_in_sec = time_in_sec%hour else: hours = 0 # minute if time_in_sec >= minute : # convet into min minutes = time_in_sec//minute result += f'{func(minutes)} m, ' time_in_sec = time_in_sec%minute else: minutes = 0 result += f'{round(time_in_sec)} s' # print(result) return result,[centuries ,years , months, weeks, days, hours, minutes,time_in_sec] def brute_force_time(self) : self.total_possibitities() print('total_possibitities :',self.tp) print() # Online Attack Scenario: # (Assuming one thousand guesses per second) — print('Online Attack Scenario: Assuming one thousand guesses per second\n',self.time_converter(self.tp/1_000)[0]) print() # Offline Fast Attack Scenario: # (Assuming one hundred billion guesses per second) — print('Offline Fast Attack Scenario :Assuming one hundred billion guesses per second\n',self.time_converter(self.tp/1_000_000_000)[0]) print() # Massive Cracking Array Scenario: # (Assuming one hundred trillion guesses per second) print('Massive Cracking Array Scenario :Assuming one hundred trillion guesses per second\n',self.time_converter(self.tp/1_000_000_000_000)[0]) print() # self.time_converter(self.tp/1_000) # self.time_converter(self.tp/1_000_000_000) # self.time_converter(self.tp/1_000_000_000_000) @classmethod def runner(cls,password): psc= cls(password) # run the counter psc.counter() # count total possibilities # psc.total_possibitities() # find brute_force runtime psc.brute_force_time() class Gui(password_strength_checker): """Gui for the password strength generaotor""" def __init__(self,master): # showing the tk window self.root = master master.title('Password Strength Checking.') # hwight of the windows self.height = 700 self.width = 1000 self.root.geometry(f"{self.width}x{self.height}") self.root.configure(bg ='#34495E') self.head() self.input() self.calculation_filed() def head(self): # heading head = Label(self.root,text='Password Strength Checker',font=('arial',30,'bold'),fg ='white',bg ='#34495E') head.place(relheight=0.15,relwidth=1) def input(self): password = Entry(self.root,bd=5,font=('arial',20),relief=GROOVE ,exportselection=0,justify=CENTER) password.place(relx=0.1,rely=0.15,relheight=0.075,relwidth=0.8) # giving placeholder password.insert(0, 'Enter your password here') # add eventlistener password.bind("<FocusIn>", lambda _ : password.delete('0','end')) # press enter events execute commends # self.update_cal() password.bind("<Return>",lambda _:self.update_cal(password.get())) def update_cal(self,password): calculations = password_strength_checker(password) calculations.counter() # character counts self.digits.set(calculations.digits_count) self.upppercase.set(calculations.big_letters_count) self.lowercase.set(calculations.small_letters_count) self.special.set(calculations.special_count) # saveign total possibility calculations.total_possibitities() # time calculations one = calculations.time_converter(calculations.tp/1_000)[0] self.online.set(one) two = calculations.time_converter(calculations.tp/1_000_000_000)[0] self.offline.set(two) three =calculations.time_converter(calculations.tp/1_000_000_000_000)[0] self.massive.set(three) def calculation_filed(self): # calculations of the password # character counts digits ,upppercase,lowercase,special Label(self.root,text='Digits',font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.05,rely=0.3,relheight=0.075) Label(self.root,text='Upppercase',font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.3,rely=0.3,relheight=0.075) Label(self.root,text='Lowercase',font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.55,rely=0.3,relheight=0.075) Label(self.root,text='Special',borderwidth = 4,width = 10, relief="ridge",font=('arial',20),fg ='white',bg ='#34495E').place(relx=0.8,rely=0.3,relheight=0.075) # values self.digits = StringVar() self.upppercase = StringVar() self.lowercase = StringVar() self.special = StringVar() # self.digits.set(500) Label(self.root,textvariable= self.digits,font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.05,rely=0.38,relheight=0.075) Label(self.root,textvariable= self.upppercase,font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.3,rely=0.38,relheight=0.075) Label(self.root,textvariable= self.lowercase,font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.55,rely=0.38,relheight=0.075) Label(self.root,textvariable= self.special,font=('arial',20),borderwidth = 4,width = 10, relief="ridge",fg ='white',bg ='#34495E').place(relx=0.8,rely=0.38,relheight=0.075) # time taken by 3 methods # 1. 1_000 Online Attack Scenario: Assuming one thousand guesses per second # 1. 1_000_000 Offline Fast Attack Scenario :Assuming one hundred billion guesses per second # 1. 1_000_000_000 Massive Cracking Array Scenario :Assuming one hundred trillion guesses per second Label(self.root,borderwidth = 4,width = 10, relief="ridge",text=" Online Attack Scenario: Assuming one thousand guesses per second",font=('arial',14,'bold'),wraplength=500,fg ='white',bg ='#34495E').place(rely=0.5,relheight=0.1, relwidth=0.5) Label(self.root,borderwidth = 4,width = 10, relief="ridge",text=" Offline Fast Attack Scenario :Assuming one hundred billion guesses per second",font=('arial',14,'bold'),wraplength=500,fg ='white',bg ='#34495E').place(rely=0.67,relheight=0.1, relwidth=0.5) Label(self.root,borderwidth = 4,width = 10, relief="ridge",text=" Massive Cracking Array Scenario :Assuming one hundred trillion guesses per second",font=('arial',14,'bold'),wraplength=500,fg ='white',bg ='#34495E').place(rely=0.85,relheight=0.1, relwidth=0.5) self.online = StringVar() self.offline = StringVar() self.massive = StringVar() # self.massive.set(10) Label(self.root,borderwidth = 4,width = 10, relief="ridge",textvariable=self.online,font=('arial',14),wraplength=300,fg ='white',bg ='#34495E').place(relx=0.55,rely=0.459,relheight=0.17,relwidth=0.45) Label(self.root,borderwidth = 4,width = 10, relief="ridge",textvariable=self.offline,font=('arial',14),wraplength=300,fg ='white',bg ='#34495E').place(relx=0.55,rely=0.64,relheight=0.17,relwidth=0.45) Label(self.root,borderwidth = 4,width = 10, relief="ridge",textvariable=self.massive,font=('arial',14),wraplength=300,fg ='white',bg ='#34495E').place(relx=0.55,rely=0.82,relheight=0.17,relwidth=0.45) @classmethod def run(cls): root = Tk() func = cls(root) root.mainloop() Gui.run()
35b74584f9373c2bb54020d55702df1ca61aa47b
Samsabal/public-library-system
/Book.py
2,662
3.53125
4
import json import BookItemCSV import LoanItem import PersonCSV CURRENTUSER = 0 class Book(): """This is a book class""" def __init__(self, author, country, imageLink, language, link, pages, title, year): self.author = author self.country = country self.imageLink = imageLink self.language = language self.link = link self.pages = pages self.title = title self.year = year def writeToDatabase(self, book): with open('BookDatabase.json') as json_file: data = json.load(json_file) book_data = { "author": self.author, "country": self.country, "imageLink": self.imageLink, "language": self.language, "link": self.link, "pages": self.pages, "title": self.title, "year": self.year } data.append(book_data) self.writeToJson(data) def writeToJson(self, data): with open("BookDatabase.json", 'w',) as f: json.dump(data, f, indent=4) def showBook(self): print("[Book] Author: " + self.author) print("[Book] Country: " + self.country) print("[Book] Image Link: " + self.imageLink) print("[Book] Language: " + self.language) print("[Book] Link: " + self.link) print("[Book] Pages: " + str(self.pages)) print("[Book] Title: " + self.title) print("[Book] Year: " + str(self.year)) if LoanItem.loanAvailabilityCheck(self.findISBN(), self.author, self.title): while True: print("[Book]") userInput = input("[Book] Would you like loan this book (y/n): ") if userInput == "y": loanItem = LoanItem.LoanItem(CURRENTUSER, 14, self.findISBN()) loanItem.writeToDatabase() print("[Book] Loan successfully administrated.") print("[Book]") break if userInput == "n": break print("[Book] Invalid input, please try again. ") else: input("[Book] No book available, press any key to go back!") def findISBN(self): bookItemList = BookItemCSV.readFromBookItemCSV() for bookItem in bookItemList: if bookItem.author == self.author and bookItem.title == self.title: return bookItem.ISBN def setCurrentUses(usernumber): global CURRENTUSER CURRENTUSER = usernumber
4235ddfb49c4281b0ecbb62fa93c9098ca025273
davisrao/ds-structures-practice
/06_single_letter_count.py
638
4.28125
4
def single_letter_count(word, letter): """How many times does letter appear in word (case-insensitively)? >>> single_letter_count('Hello World', 'h') 1 >>> single_letter_count('Hello World', 'z') 0 >>> single_letter_count("Hello World", 'l') 3 """ # we need to make the whole string lowercase # normal ltr of word + if statement lowercase_word = word.lower() counter = 0 for ltr in lowercase_word: if ltr == letter: counter +=1 return counter # look into the count method here - this makes thsi a lot easier
2d0b03210a1804efc091fd08d2424e39d3485798
Bernardo-MR/EjercicioPrueba
/EjercicioCoche.py
241
3.71875
4
# Autor: Bernardo Mondragon Ramirez # Calcula velocidad promedio, dado el tiempo y la distancia d = int(input("Teclea la distancia en km. enteros: ")) t = int(input("Teclea el tiempo en hrs. enteros: ")) v = d*t print("Velocidad promedio:",v, "km/h")
45861e4c7821d123a4e97685286dabb27b83f6b3
wolf5885/agendaPy
/menu.py
1,585
3.6875
4
from os import system def mainMenu(): system("clear") print("Menú Principal") print("==== =========") print() print(" a) Alta de Personas") print(" b) Búsqueda de Personas") print(" m) Modificación de Personas") print(" e) Eliminación de Personas") print(" s) Salir del sistema") print() print() def hightMenu(): system("clear") print("Alta de Personas") print("==== == ========") print() print(" a) Alta de Persona") print(" v) Volver al menú anterior") print() print() def searchMenu(): system("clear") print("Busqueda de Persona") print("======== == =======") print() print(" a) Busqueda por apellido") print(" d) Busqueda por Dni") print(" v) Volver al menu principal") print() print() def removeMenu(): system("clear") print("Eliminación de Persona") print("=========== == =======") print() print(" d) Buscar por Dni y eliminar") print(" v) Volver al menu principal") print() print() def changeMenu(): system("clear") print("Modificacion de Persona") print("============ == =======") print() print(" d) Busqueda por Dni") print(" v) Volver al menu principal") print() print() def modificationMenu(): system("clear") print("Opciones de Modificacion de Persona") print("======== == ============ == =======") print() print(" d) Cambiar Direccion") print(" e) Cambiar correo electronico ") print(" t) Cambiar Telefono ") print(" v) Volver a menu de busqueda ") print()
c98dd8cc4843b8458b0838636f624d8129cfc0fe
itspawanbhardwaj/python-examples
/com/bdu/chapter/four/Conditions.py
184
3.8125
4
album_year = 1983 if album_year > 1980: print "Album year is greater than 1980" elif (album_year > 1990): print "greater than 1990" else: print "album is less than 1980"
b3ac0fbaf398833737607940fede0714d6f6d41d
duanyiting2018/learning_python
/bounce_ball_game.py
1,418
3.6875
4
from tkinter import * import time,random tk=Tk() tk.title("Bounce ball game") tk.resizable(0,0) tk.wm_attributes("-topmost",1) c=Canvas(tk,width=500,height=450,bd=0,highlightthickness=0) c.pack() tk.update() class ball: def __init__(self,ca,co): self.ca=ca self.id=ca.create_oval(10,10,30,30,fill=co) self.ca.move(self.id,245,100) starts=[-3,-2,-1,1,2,3] random.shuffle(starts) self.x=starts[0] self.y=-3 self.c_h=self.ca.winfo_height() self.c_w=self.ca.winfo_width() def draw(self): self.ca.move(self.id,self.x,self.y) pos=self.ca.coords(self.id) if pos[1]<=0: self.y=3 #print(self.y,"y") if pos[3]>=self.c_h: self.y=-3 #print(self.y,"y") if pos[0]<=0: self.x=3 #print(self.x,"x") if pos[2]>=self.c_w: self.x=-3 #print(self.x,"x") class paddle: def __init__(s,ca,co): self.id=ca.create_rectangle(0,0,100,20,fill=co) self.ca.move(self.id,200,300) def draw(self): pass ball=ball(c,"green") paddle=paddle(c,"orange") while True: ball.draw() paddle.draw() tk.update_idletasks() tk.update() time.sleep(0.03)
c2d84cef1ee24526239102c834c5db617c28e1aa
duanyiting2018/learning_python
/selection_sort.py
695
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 16:08:57 2020 @author: duanyiting """ def showdata(data): for i in range(len(data)): print('%5d'%data[i],end=" ") print() return "" def select(data): for i in range(len(data)-1): for j in range(i+1,len(data)): if data[i]>data[j]: data[i],data[j]=data[j],data[i] print("i:",i," ",data[i]," ","j:",j," ",data[j]) showdata(data) print() data=[438,829,73725,35,5,94,23,77] print("初始数组为:",end="") showdata(data) print("\n--------------------------------------------------") select(data) print("排序后的数组为:",end="") showdata(data)
afddf0f66e7ff4df3edb9ca64c32ade9c095070e
duanyiting2018/learning_python
/learning_python/turtle_eight.py
243
3.90625
4
import turtle t = turtle.Pen() def draw_star(size, points): angle = 360 / points for x in range(0, points): t.forward(size) t.left(180 - angle) t.forward(size) t.right(180-(angle * 2)) #draw_star(50,50)
8dac9d53df8a0d280a5a2b95987e5b5ba6c9ffbb
duanyiting2018/learning_python
/money.py
334
3.96875
4
# -*- coding: utf-8 -*- def money(fiveNumber,twoNumber,oneNumber): total=5*fiveNumber+2*twoNumber+oneNumber return total fiveNumber=int(input("Enter a number of five:")) twoNumber=int(input("Enter a number of two:")) oneNumber=int(input("Enter a number of one:")) print("total money is:",money(fiveNumber,twoNumber,oneNumber))
644d944cab96f8cbae9d53d2939433ece24bf839
duanyiting2018/learning_python
/beachball.py
590
3.53125
4
# -*- coding: utf-8 -*- import pygame pygame.init() screen=pygame.display.set_mode([700,500]) screen.fill([255,255,255]) my_ball=pygame.image.load("beach_ball.png") screen.blit(my_ball,[60,60]) pygame.display.flip() x=60 y=60 for i in range(1,100): pygame.time.delay(1000) pygame.draw.rect(screen,[255,255,255],[x,y,90,90],0) x+=200 screen.blit(my_ball,[x,y]) pygame.display.flip() #pygame.time.delay(1000) #pygame.display.flip() running=True while running: for event in pygame.event.get(): if event.type==pygame.QUIT: running=False pygame.quit()
08823f540327149c6d4de3749d5d2317cdbd0e34
duanyiting2018/learning_python
/student_list1.py
694
3.5625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 18:56:32 2020 @author: duanyiting """ class student: def __init__(self): self.name="" self.score=0 self.next=None head=student() head.next=None ptr=head select=0 while select !=2: print("输入1添加数据,输入2离开:") select=int(input()) if select==1: new_data=student() new_data.name=input("学生姓名:") new_data.no=input("学生学号:") new_data.Math=input("数学成绩:") new_data.English=input("英语成绩:") ptr.next=new_data#指针设置为新元素的位置 new_data.next=None#下一个元素先指向None ptr=ptr.next
bd9fb8875f07565de13167b981c1baf97c9c4ec4
duanyiting2018/learning_python
/class_account.py
494
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 20:12:07 2020 @author: duanyiting """ class account: #def __init__(self): #self.account_name=input() #self.account_money=int(input()) def see_account(self): print(self.account_name,",",self.account_money) def change_account(self): name=input() money=int(input()) self.account_name=name self.account_money=money account=account() account.change_account() account.see_account()
e56884fd026ee0541d964544fe138b855269e1b8
duanyiting2018/learning_python
/class_employee2.py
1,316
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 4 19:37:40 2020 @author: duanyiting """ class employee: #__init__==setting def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex #__str__==getting def __str__(self): return "name:"+self.name+"\t age:"+str(self.age)+"\t sex:"+self.sex class employee1(employee): def __init__(self,name,age,sex,level,salary1): super().__init__(name,age,sex) self.level=level self.salary1=salary1 def __str__(self): return "name:"+self.name+"\t age:"+str(self.age)+"\t sex:"+self.sex+ \ "level:"+self.level+"salary1:"+str(self.salary1) class employee2(employee): def __init__(self,name,age,sex,depart,salary2): super().__init__(name,age,sex) self.depart=depart self.salary2=salary2 def __str__(self): return "name:"+self.name+" \t age:"+str(self.age)+"\t sex:"+self.sex+ \ "\n depart:"+self.depart+"\t salary2:"+str(self.salary2) employee1=employee1("老八",22,"男","3级",300000) employee2=employee2("老八秘制小汉堡",21,"生物","生物部",10000) print(employee1) print(employee2) '''employee------------------- | | | | employee1 employee2'''
f4f1319bebc4e5edfcdc8edd8cff987158994391
duanyiting2018/learning_python
/class_person_student.py
1,452
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 3 20:age3:33 2020 @author: duanyiting """ class Person: def __init__(self,name,addr,sex,age): self.name=name self.addr=addr self.sex=sex self.age=age def output1(self,name,addr,sex,age): print("name:",name,"addr:",addr,"sex:",sex,"age:",age) def output2(self,name,sex,age): print("name:",name,"sex:",sex,"age:",age) def output3(self,age): print("age:",age) class Student(Person): def __init__(self,math,english): self.math=math self.english=english def output1(self,name,addr,sex,age,math,english): print("name:",name,"addr:",addr,"sex:",sex,"age:",age,"math:"\ ,str(math),"english",str(english)) def output2(self,addr,sex,age,english): print("addr:",addr,"sex:",sex,"age:",age,"english",str(english)) def output3(self,math): print("math:",str(math)) person=Person("1","2","3",4) student=Student(5,6) name,addr,sex,age,math,english="1","2","3",4,5,6 person.output1(name,addr,sex,age) person.output2(name,sex,age) person.output3(age) student.output1(name,addr,sex,age,math,english) student.output2(addr,sex,age,english) student.output3(math) #也可以不用输入参数,可以调用内部参数( \ #就是把参数(除self以外)都去掉,print()里面输出的参数都加self.xxx( \ #可以参考class_employee2.py)) #记得把123456改成对应的属性哦~
ba547c8e6d073237cb6330c2a2b38b0829913e31
kniewohner1/mystuff
/hello.py
116
3.671875
4
#!/usr/bin/python if __name__ == '__main__': n = 5 for i in range(n): if i >= 3: print(i)
2cbc5e2ac30e8625e7b9ebbe6f900c5742ca8716
jlm200065/SoftWareImprovement
/test/test.py
1,202
3.65625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """code_info @Time : 2021 2021/4/2 13:48 @Author : jiangliming @File : test.py """ from selenium import webdriver # (1) browser = webdriver.Chrome() # (2) # Edith has heard about a cool new online to-do app. She goes # to check out its homepage browser.get('http://localhost:8000') # (3) # She notices the page title and header mention to-do lists assert 'Django' in browser.title # (4) # She is invited to enter a to-do item staright away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # when she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an item in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both item on her list # Edith wonder whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep #browser.quit()
26a80b1e87230fd2d097ed1d3d04a63f21711b66
DanielSCrouch/basic-algorithms
/binary_tree/test_traversal.py
2,136
3.734375
4
import unittest from binary_tree.binary_tree import BinaryTree class TestBinaryTree(unittest.TestCase): def test_breadth_first_traversal(self): bt = BinaryTree() bt.insert(9) bt.insert(4) bt.insert(6) bt.insert(20) bt.insert(170) bt.insert(15) bt.insert(1) ordered = [9, 4, 20, 1, 6, 15, 170] traversal = bt.breadth_first_traversal() for item in ordered: self.assertEqual(item, traversal.__next__()) def test_breadth_first_traversal2(self): bt = BinaryTree() bt.insert(9) bt.insert(4) bt.insert(6) bt.insert(20) bt.insert(170) bt.insert(15) bt.insert(2) bt.insert(1) bt.insert(3) bt.insert(5) bt.insert(7) bt.insert(14) bt.insert(16) bt.insert(150) bt.insert(171) ordered = [9, 4, 20, 2, 6, 15, 170, 1, 3, 5, 7, 14, 16, 150, 171] traversal = bt.breadth_first_traversal() for item in ordered: self.assertEqual(item, traversal.__next__()) def test_depth_first_traversal_preorder(self): bt = BinaryTree() bt.insert(9) bt.insert(4) bt.insert(6) bt.insert(20) bt.insert(170) bt.insert(15) bt.insert(1) ordered = [9, 4, 1, 6, 20, 15, 170] traversal = bt.depth_first_traversal(order="preorder") for item in ordered: self.assertEqual(item, traversal.__next__()) def test_depth_first_traversal_inorder(self): bt = BinaryTree() bt.insert(9) bt.insert(4) bt.insert(6) bt.insert(20) bt.insert(170) bt.insert(15) bt.insert(1) ordered = [1, 4, 6, 9, 15, 20, 170] traversal = bt.depth_first_traversal(order="inorder") for item in ordered: self.assertEqual(item, traversal.__next__()) # def test_depth_first_traversal_postorder(self): # bt = BinaryTree() # bt.insert(9) # bt.insert(4) # bt.insert(6) # bt.insert(20) # bt.insert(170) # bt.insert(15) # bt.insert(1) # ordered = [1, 6, 4, 15, 170, 20, 9] # traversal = bt.depth_first_traversal(order="postorder") # for item in ordered: # self.assertEqual(item, traversal.__next__())
163539325a65d9dca176df7cb23fda6c6d8869b4
Lyzw57/Dice-roller
/dice_roll.py
774
3.84375
4
# def roll_the_dice(dice: str): # """ # non bonus version. # """ # from random import randint # amount, size = dice.split("d") # result = 0 # for i in range(1, int(amount) + 1): # result += randint(1, int(size)) # return result def roll_the_dice(dice: str): """ bonus version. """ from random import randint amount, size = dice.split("d") results = [] print for i in range(1, int(amount) + 1): results.append(randint(1, int(size))) result = str(sum(results)) + ":" for each in results: result += " " result += str(each) return result if __name__ == "__main__": for example in ('3d6', '4d12', '1d10', '5d4'): print(example, roll_the_dice(example))
b2234ad8314af231120f2fca6ea427ef2fee5362
jonmaxgreenberg/AnagramsSolver
/anagramssolver.py
2,635
4.03125
4
def main(base_word, added_letters): __author__ = "Jonathan Greenberg" import pandas as pd import collections import pprint import pickle alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] two_letter_combos = [] three_letter_combos = [] pp = pprint.PrettyPrinter(indent=4) def get_unique_combos(combos): # get the word frequency of this word + the added letter unique_two_letter_combos = [] for combo in combos: unique_two_letter_combos.append(''.join(sorted(combo))) unique_two_letter_combos = set(unique_two_letter_combos) return unique_two_letter_combos for letter in alphabet: for letter2 in alphabet: combo = letter + letter2 two_letter_combos.append(combo) two_letter_combos = get_unique_combos(two_letter_combos) for letter in alphabet: for letter2 in alphabet: for letter3 in alphabet: combo = letter + letter2 + letter3 three_letter_combos.append(combo) three_letter_combos = get_unique_combos(three_letter_combos) result_set = {} # upload frequency dictionary from pickle file all_words_frequencies = {} with open('frequency_dict.pickle', 'rb') as handle: all_words_frequencies = pickle.load(handle) def find_anagrams(base_word, added_letters): # get the word frequency of this word + the added letter freq = {} word_plus = base_word + added_letters for letter in word_plus: if letter in freq: freq[letter] += 1 else: freq[letter] = 1 # make sure the dict is ordered alphabetically, bc then the strings/keys will be equatable freq = collections.OrderedDict(sorted(freq.items())) key = str(freq) # if this anagram is in all_words_frequencies then add to the result_set if key in all_words_frequencies: result_set[added_letters] = all_words_frequencies[key] def anagram_steal(base_word, num_letters_to_add): for letter in alphabet: find_anagrams(base_word, letter) if num_letters_to_add > 1: for combo in two_letter_combos: find_anagrams(base_word, combo) if num_letters_to_add > 2: for combo in three_letter_combos: find_anagrams(base_word, combo) pp.pprint(result_set) return result_set return anagram_steal(base_word, int(added_letters))
0ad445d7ae58a5b1a89ee2681003379f429e220a
MaxToyberman/Enigma
/Rotor.py
1,880
3.5
4
from Translator import Translator ''' Author:Maxim Toyberman Date:18.11.2015 ''' class Rotor(Translator): def __init__(self, ringOffset, ringSetting, permutation, notch): super(self.__class__, self).__init__(permutation) self.ringOffset = ringOffset self.ringSetting = ringSetting self.notch = notch def encryptedLetter(self, letter): ''' using the formula P(A+B+C)-B+C :param letter-receiving plain text letter and convert it to cipher text: :return: cipher text letter ''' rightShifted = self.rightCircularShift(self.letterToIndex(letter),self.ringOffset-1) print( chr(ord('A')+rightShifted)); leftShifted = self.leftCircularShift(rightShifted,self.ringSetting - 1) translated = self.forwardTranslataion(chr(ord('A')+leftShifted)) result = self.rightCircularShift(self.letterToIndex(translated), self.ringSetting - 1 - (self.ringOffset - 1)) return result def decryptLetter(self, letter): ''' using the formula P(A+B+C)-B+C :param letter-receiving cipher text letter and convert it to plain text: (the only difference is the direction (forward or reverse permutation) :return: cipher text letter ''' rightShifted = self.rightCircularShift(self.letterToIndex(letter),self.ringOffset-1) leftShifted = self.leftCircularShift(rightShifted,self.ringSetting - 1) translated = self.reverseTranslataion(chr(ord('A')+leftShifted)) result = self.rightCircularShift(self.letterToIndex(translated), self.ringSetting - 1 - (self.ringOffset - 1)) return result def IsTurnOverNotch(self): return self.ringOffset == self.notch def advanceOffSet(self): #advance rotor by one each key press self.ringOffset=self.rightCircularShift(self.ringOffset,1)
16a9dbae2999b30e78c1b5bf460c0b8614a44fb1
mattcpfannenstiel/feudalismSim
/LandUnit.py
2,808
3.859375
4
from Climate import Climate from Location import Location class LandUnit: """ The basic unit that produces grain and houses serfs """ SERF_MAX = 10 PRODUCTION_VALUE = 50 SERF_UPKEEP_COST = 5 def __init__(self, x, y, fief): """ Makes a new land unit :param x: the x location of the land unit on the map :param y: the y location of the land unit on the map :param fief: the fief that the land unit belongs to """ self.farmable = True self.serfs = 0 self.WEATHER = Climate() self.owner = fief self.full = False self.GRID_LOCATION = Location(x, y) def changeowner(self, newowner): """ Changes the current owner of the land unit to the new owner """ self.owner = newowner def getlandunit(self, x, y, fmap): """ Returns the land unit from the x, y location from the map :return: sends back the landunit at that location """ return fmap[x][y][2] def getproduction(self): """ Return the production of the land unit :return: the production of the landunit """ return self.PRODUCTION_VALUE * self.serfs def getupkeep(self): """ Returns the upkeep of the landunit :return: the upkeep from multiplying number of serfs by their upkeep cost """ return self.serfs * self.SERF_UPKEEP_COST def getvonneumann(self, fmap): """ Looks in the land unit's Von Neumann Neighborhood and returns cells inside the map grid :param fmap: the map grid to reference from :return: the list of cells around the cell """ c = [] if (len(fmap) > self.GRID_LOCATION.xloc + 1 >= 0) and (0 <= self.GRID_LOCATION.yloc < len(fmap)): c.append(self.getlandunit(self.GRID_LOCATION.xloc + 1, self.GRID_LOCATION.yloc, fmap)) if (len(fmap) > self.GRID_LOCATION.xloc >= 0) and (0 <= self.GRID_LOCATION.yloc + 1 < len(fmap)): c.append(self.getlandunit(self.GRID_LOCATION.xloc, self.GRID_LOCATION.yloc + 1, fmap)) if (len(fmap) > self.GRID_LOCATION.xloc - 1 >= 0) and (0 <= self.GRID_LOCATION.yloc < len(fmap)): c.append(self.getlandunit(self.GRID_LOCATION.xloc - 1, self.GRID_LOCATION.yloc, fmap)) if (len(fmap) > self.GRID_LOCATION.xloc >= 0) and (0 <= self.GRID_LOCATION.yloc - 1 < len(fmap)): c.append(self.getlandunit(self.GRID_LOCATION.xloc, self.GRID_LOCATION.yloc - 1, fmap)) return c def addserf(self): """ Adds a serf to the land unit unless the land unit is full """ if self.serfs < self.SERF_MAX: self.serfs += 1 else: self.full = True
99db5d93dd6673b1afa97701b1fb8d09294223c0
timseymore/py-scripts
/Scripts/set.py
485
4.125
4
# -*- coding: utf-8 -*- """ Sets numerical sets and operations on them Created on Tue May 19 20:08:17 2020 @author: Tim """ test_set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # returns a set of numbers in given range (inclusive) # that are divisible by either 2 or 3 def set_mod_2_3(size): temp = {} index = 0 for i in range(1, size + 1): if (i % 2 == 0) or (i % 3 == 0): temp[index] = i index += 1 return temp set1000 = set_mod_2_3(1000)
fea0c7cd509f4f9e059fcefb37218a380cd25b2d
timseymore/py-scripts
/Scripts/hanoi.py
307
3.75
4
# -*- coding: utf-8 -*- """ Hanoi Towers how many turns to solve a Hanoi towers puzzle with n discs Created on Wed Apr 8 16:54:52 2020 @author: Tim """ def turns_to_solve(n): if n == 1: return 1 elif n == 2: return 3 else: return (turns_to_solve(n-1) * 2) + 1
4bdf487e4600dfd927e4419f0c25391cfbfb721c
timseymore/py-scripts
/Scripts/counting.py
2,285
4.5
4
# -*- coding: utf-8 -*- """ Counting examples of counting and recursive counting used in cominatorics We will be implementing a graph consisting of nodes and then use recursive counting to find the number of possible paths from the start node to any given node in the graph. The number of possible paths to any given node is the sum of the possible paths to all of its sub-nodes. Created on Wed May 20 17:58:07 2020 @author: Tim """ # We start by defining a simple node class. class Node: def __init__(self, name: str, subs: list): self.name = name self.subs = subs # We will now create nodes that will # represent the structure of our graph. # It is a one-directional graph, where each sub-node (child) # has an arrow pointing to the parent node (self). # Note that any given node may have any number of parent nodes. N1 = Node("N1", []) N2 = Node("N2", [N1]) N3 = Node("N3", [N1]) N4 = Node("N4", [N2, N3]) N5 = Node("N5", [N2, N4]) N6 = Node("N6", [N3]) N7 = Node("N7", [N5]) N8 = Node("N8", [N5, N7]) N9 = Node("N9", [N6, N7]) N10 = Node("N10", [N8, N9]) # Let's create a function to recursively count # the number of possible paths from start (N1) to any given node n. # This is poor style however, the function should be an inner method of Node. def num_paths(n: Node): # We define a local helper-function to recursively count the paths. # Calling num_paths will be simpler without the need # to pass an accumulator, this will help avoid errors # by ensuring the accumulator is always called starting at 0 def aux(node, acc): if node.subs == []: # This is our base case: a node with no subs has one possible path return acc + 1 else: # Sum the number of paths to each sub and return the result for sub in node.subs: acc += aux(sub, 0) return acc return aux(n, 0) # Some test cases to check that it works correctly print(num_paths(N1) == 1) print(num_paths(N2) == 1) print(num_paths(N3) == 1) print(num_paths(N4) == 2) print(num_paths(N5) == 3) print(num_paths(N6) == 1) print(num_paths(N7) == 3) print(num_paths(N8) == 6) print(num_paths(N9) == 4) print(num_paths(N10) == 10)