blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
15ca8c6d3f87e3d9ba08751f0a736d7ab8de8a1c
jeongmingang/python_study
/chap04/answer_01.py
441
3.59375
4
print("# 확인문제 2") # 1~100 사이에 있는 숫자 중 2진수로 변환했을 때 0이 하나만 포함된 숫자를 찾고, # 그 숫자들의 합을 구하는 코드를 만들어 보세요. # 리스트 내포를 사용해본 코드입니다. output = [i for i in range(1, 100 + 1) if "{:b}".format(i).count("0") == 1] for i in output: print("{} : {}".format(i, "{:b}".format(i))) print("합계 :", sum(output)) print()
5e2f9a70a704ef41ce95dca53d4a73d57d81852c
DEEPESH98/Basic_Python_Programs
/problem2.py
1,963
3.71875
4
'''write a code using that will take user input from and search on google and store top 10 url in the list. conditions : i ) URL must be stored permanently as well ii) user can give input using keyboard and voice both''' import pyttsx3 import webbrowser import speech_recognition as sr import datetime import time engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) def speak(audio): print('Computer: ' + audio) engine.say(audio) engine.runAndWait() def greetMe(): currentH = int(datetime.datetime.now().hour) if currentH >= 0 and currentH < 12: speak('Good Morning! sir') if currentH >= 12 and currentH < 18: speak('Good Afternoon! sir') if currentH >= 18 and currentH !=0: speak('Good Evening! sir') greetMe() from googlesearch import search speak(' plz speck topic your search topic') url=[] def myCommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try: web = r.recognize_google(audio, language='en-in') print('User: ' + web + '\n') except sr.UnknownValueError: speak('Sorry sir! I didn\'t get that! Try typing the command!') web = str(input('Command: ')) return web if __name__ == '__main__': while True: web = myCommand(); web = web.lower() for i in search(web,stop=10): print(i) # i will only print url time.sleep(1) url.append(i) print(url)
c6af04a8defbaf4435f00930ea00d1883d36624a
beer-garden/brewtils
/brewtils/rest/__init__.py
1,028
4.125
4
# -*- coding: utf-8 -*- def normalize_url_prefix(url_prefix): """Enforce a consistent URL representation The normalized prefix will begin and end with '/'. If there is no prefix the normalized form will be '/'. Examples: =========== ============ INPUT NORMALIZED =========== ============ None '/' '' '/' '/' '/' 'example' '/example/' '/example' '/example/' 'example/' '/example/' '/example/' '/example/' =========== ============ Args: url_prefix (str): The prefix Returns: str: The normalized prefix """ if url_prefix in (None, "/", ""): return "/" new_url_prefix = "" # Make string begin with / if not url_prefix.startswith("/"): new_url_prefix += "/" new_url_prefix += url_prefix # Make string end with / if not url_prefix.endswith("/"): new_url_prefix += "/" return new_url_prefix
74573f25ff0f21be4dfd4e01fb27164ea8fe124a
jamesliao2016/HCDR2018
/LT2018/top_problems/4_BinarySearch/240. Search a 2D Matrix II.py
3,857
4.09375
4
#!/usr/bin/env python2 # coding:utf-8 class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0]: return False i,j = len(matrix)-1,0 while i>=0 and i<len(matrix) and j>=0 and j<len(matrix[0]): if matrix[i][j] == target: return True else: if matrix[i][j] > target: i-=1 else: j+=1 return False if __name__ == '__main__': ipt = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] # nn=20 nn=5 print(Solution().searchMatrix(ipt,nn)) ''' Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following matrix: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true. Given target = 20, return false. # 4 apr, 2019 if not matrix or not matrix[0]: return False i,j = 0,len(matrix[0])-1 while i>=0 and i<len(matrix) and j>=0 and j<len(matrix[0]): if matrix[i][j] == target: return True else: if matrix[i][j] > target: j-=1 else: i+=1 return False # 3 apr, 2019 l,r = 0,len(matrix[0])-1 while l>=0 and l<len(matrix) and r>=0 and r<len(matrix[0]): if matrix[l][r] == target: return True else: if matrix[l][r] > target: r-=1 else: l+=1 return False # 19 mar, 2019 if len(matrix)==0: return False l,r = 0,len(matrix[0]) - 1 while l>=0 and l<len(matrix) and r>=0 and r<len(matrix[0]): if matrix[l][r] == target: return True elif matrix[l][r] > target: r -= 1 else: l += 1 return False # 6 jan, 2019 if len(matrix)==0: return False l,r = 0,len(matrix[0])-1 while l>=0 and l<len(matrix) and r>=0 and r<len(matrix[0]): if matrix[l][r]==target: return True # else: elif matrix[l][r]<target: l+=1 else: r-=1 return False # 5 jan, 2019 if not max(matrix): return False l, r = 0, len(matrix[0]) - 1 while l>=0 and l<len(matrix) and r>=0 and r<len(matrix[0]): if matrix[l][r] == target: return True elif matrix[l][r] > target: r -= 1 else: l+=1 return False # 4 jan, 2019 if len(matrix)==0: return False if len(matrix)==1: return target in matrix[0] l,r = 0,len(matrix[0])-1 while l>=0 and l<len(matrix) and r>=0 and r<len(matrix[0]): if matrix[l][r]==target: return True if matrix[l][r] > target: r -= 1 else: l += 1 return False # 12 dec m,n=0,len(matrix[0])-1 while m<len(matrix) and n>=0: if matrix[m][n] == target: return True if matrix[m][n] > target: n-=1 else: m+=1 return False '''
17848cb4bcb168680c8626e95fcaf58b685e9a70
Tarun-Sharma9168/Python-Programming-Tutorial
/gfg23.py
1,211
3.84375
4
''' ###### # ##### # ### ### ##### # # # ### # ##### #### ##### ###### ### # # #### # ##### #### # Author name : Tarun Sharma Problem Statement: Finding the Product of all elements in a list... ''' #library section from collections import Counter import sys import numpy as np from functools import reduce from time import perf_counter import math sys.stdin =open('input.txt','r') sys.stdout=open('output.txt','w') #Code Section def prod1(arr): mul=1 for i in arr: mul=mul*i return mul def prod2(arr): return np.prod(arr) def prod3(arr): return reduce(lambda x,y : x * y , arr) ''' def prod4(arr): return math.prod(arr) #available in python 3.8 ''' #Input Output Section t1_start=perf_counter() n=int(input()) arr=list(map(int,input().split())) #element=int(input('enter the element to search')) #Calling of the functions that are there in the code section print(prod1(arr)) print(prod2(arr)) print(prod3(arr)) #print(prod4(arr)) t1_end=perf_counter() print('total elapsed time',t1_start-t1_end)
f7cf2b4ad020ce119f5151fa598dca7b706cb641
AndyMender/pyrpg
/pyrpg_mapper.py
7,200
3.65625
4
def mapGenerator(dimension,**coord_dict): '''Generates and populates a map matrix in-place with coordinates of map markers. dimension - the dimension of the generated unidimensional map matrix **coord_dict - dictionary or sequence of map_marker = (x,y) assignments to populate the map matrix ''' map_matrix= [dimension * [0] for i in range(dimension)] for map_marker,coords in coord_dict.items(): x,y = coords map_matrix[x][y] = map_marker return map_matrix class Move(): '''Handles player movement across a matrix-based map. Takes 2 arguments: map_array - matrix defining map dimensions and containing special map markers pc_loc - player location coordinates if they're known (optional tuple argument) ''' def __init__(self, map_array, pc_loc = None): self.map_array = map_array self.map_marker = None # needs to be tracked internally to link # different movement directions self.x = 0 # same reason as above self.y = 0 if pc_loc is None: for row in map_array: if 'e' in row: self.y = row.index('e') self.x = map_array.index(row) break # prevents exhaustive searches self.pc_loc = (self.x,self.y) self.map_marker = self.map_array[self.x][self.y] self.map_array[self.x][self.y] = 1 # player arrives at map 'exit' - saved map marker and noted player # position as 1 afterwards else: self.pc_loc = pc_loc self.x,self.y = self.pc_loc # unpacking player location into # individual coordinates try: if self.map_array[self.x][self.y] not in (0, 1): self.map_marker = self.map_array[self.x][self.y] # saving map marker - literal value, other than 0 or 1, # hence map marker position except IndexError: print('Illegal player location or out of map bounds') return # exits function call if given player location coordinates are # outside of the map self.map_array[self.x][self.y] = 1 # noted player position as 1 def __showmap__(self): for row in self.map_array: print(row) def __north__(self): self.map_array[self.x][self.y] = self.map_marker if self.map_marker else 0 # reinstating map marker to current player position if exists, # if no map marker, default 0 is reinstated if 0 > self.x-1: print('Illegal player location or out of map bounds') self.map_array[self.x][self.y] = 1 # restoring player position after out-of-bounds movement return # cancelling move via 'return' - no other option exists elif self.map_array[self.x-1][self.y] != 0: self.map_marker = self.map_array[self.x-1][self.y] # checking if next movement position is a map marker; save if yes else: self.map_marker = None # clearing map marker information, otherwise first movement # condition will fail for all subsequent movements self.x -= 1 self.map_array[self.x][self.y] = 1 def __west__(self): self.map_array[self.x][self.y] = self.map_marker if self.map_marker else 0 if 0 > self.y-1: print('Illegal player location or out of map bounds') self.map_array[self.x][self.y] = 1 return elif self.map_array[self.x][self.y-1] != 0: self.map_marker = self.map_array[self.x][self.y-1] else: self.map_marker = None self.y -= 1 self.map_array[self.x][self.y] = 1 def __south__(self): self.map_array[self.x][self.y] = self.map_marker if self.map_marker else 0 try: if self.map_array[self.x+1][self.y] != 0: self.map_marker = self.map_array[self.x+1][self.y] else: self.map_marker = None except IndexError: print('Illegal player location or out of map bounds') self.map_array[self.x][self.y] = 1 return self.x += 1 self.map_array[self.x][self.y] = 1 def __east__(self): self.map_array[self.x][self.y] = self.map_marker if self.map_marker else 0 try: if self.map_array[self.x][self.y+1] != 0: self.map_marker = self.map_array[self.x][self.y+1] else: self.map_marker = None except IndexError: print('Illegal player location or out of map bounds') self.map_array[self.x][self.y] = 1 return self.y += 1 self.map_array[self.x][self.y] = 1 def __toloc__(self): self.map_array[self.x][self.y] = self.map_marker if self.map_marker else 0 self.x, self.y = input('State the coordinates, separated with a comma: ').split(',') try: if self.map_array[self.x][self.y] != 0: self.map_marker = self.map_array[self.x][self.y] else: self.map_marker = None except IndexError: print('Illegal player location or out of map bounds') self.map_array[self.x][self.y] = 1 return self.map_array[self.x][self.y] = 1 def __toplace__(self): self.map_array[self.x][self.y] = self.map_marker if self.map_marker else 0 next_loc = input('Where would you like to go? ') for row in self.map_array: if next_loc in row: self.y = row.index(next_loc) self.x = self.map_array.index(row) break else: print('I am afraid this city does not have that facility.') try: if self.map_array[self.x][self.y] != 0: self.map_marker = self.map_array[self.x][self.y] else: self.map_marker = None except IndexError: print('Illegal player location or out of map bounds') self.map_array[self.x][self.y] = 1 return self.map_array[self.x][self.y] = 1 if __name__ == '__main__': # Generating a 5x5 map using list comprehensions: molag_ker = [5 * [0] for i in range(5)] # Placing items on the map by directly addressing x,y coordinates: molag_ker[0][1] = 'b' # b - blacksmith molag_ker[0][4] = 'g' # g - general store molag_ker[4][4] = 'e' # e - village/town/city exit # For procedurally generated maps, markers will be placed randomly within map # bounds (try...except: raise IndexError for handling?) # Drawing map for checking: for row in molag_ker: print(row) molag_ker_map = Move(molag_ker) for i in range(6): molag_ker_map.__showmap__() molag_ker_map.__east__() molag_ker_map.__south__() molag_ker_map.__north__()
6bae261a57d4c1b986f300c4960b14804ac07c6c
EricCWWong/2048AI
/class_2048_helper.py
3,516
4.15625
4
import numpy as np def merge_row(row): ''' This function merges a given row to the right. It is same as swiping right in the game 2048. Example: >>> # our input... >>> row = [2,0,2,0] >>> new_row = merge_row(row) >>> new_row >>> # our output... >>> [0,0,0,4] ''' no_zero_row = [] for el in row: if el != 0: no_zero_row.append(el) new_row = [] if len(no_zero_row) == 2: if no_zero_row[0] == no_zero_row[1]: new_row.append(no_zero_row[0] + no_zero_row[1]) else: new_row = no_zero_row elif len(no_zero_row) == 3: if no_zero_row[0] == no_zero_row[1]: new_row.append(no_zero_row[0] + no_zero_row[1]) new_row.append(no_zero_row[2]) elif no_zero_row[1] == no_zero_row[2]: new_row.append(no_zero_row[0]) new_row.append(no_zero_row[1] + no_zero_row[2]) else: new_row = no_zero_row elif len(no_zero_row) == 4: if no_zero_row[0] == no_zero_row[1]: new_row.append(no_zero_row[0] + no_zero_row[1]) if no_zero_row[2] == no_zero_row[3]: new_row.append(no_zero_row[2] + no_zero_row[3]) else: new_row.append(no_zero_row[2]) new_row.append(no_zero_row[3]) elif no_zero_row[1] == no_zero_row[2]: new_row.append(no_zero_row[0]) new_row.append(no_zero_row[1] + no_zero_row[2]) new_row.append(no_zero_row[3]) elif no_zero_row[2] == no_zero_row[3]: new_row.append(no_zero_row[0]) new_row.append(no_zero_row[1]) new_row.append(no_zero_row[2] + no_zero_row[3]) else: new_row = no_zero_row else: new_row = no_zero_row if len(new_row) != 4: no_empty = 4 - len(new_row) for _ in range(no_empty): new_row = [0] + new_row return new_row def merge(grid): ''' This uses the merge row function above and calculate the new grid after merging. Example: >>> # our input... >>> grid = [[2,0,2,0] [0,0,4,0] [4,4,0,0] [2,8,0,2]] >>> new_grid = merge(grid) >>> new_grid >>> # our output... >>> [[0,0,0,4] [0,0,0,4] [0,0,0,8] [0,2,8,2]] ''' tiles = grid new_grid = [] for row in tiles: new_tiles = merge_row(row) new_grid.append(new_tiles) return np.array(new_grid) def neighbour_difference(grid, axis=None): ''' This calculates the differences between neighbouring tiles. Example: >>> # our input... >>> grid = [[2,0,2,0] [0,0,4,0] [4,4,0,0] [2,8,0,2]] >>> neig_diff = neighbour_difference(grid) >>> neig_diff >>> [2,-2, 2, 0,-4, 4, 0, 4, 0, -6, 8, -2] ''' hor_diff = [] vert_diff = [] for row in grid: for i in range(3): hor_diff.append(row[i] - row[i + 1]) for row in np.transpose(grid): for i in range(3): vert_diff.append(row[i] - row[i + 1]) if axis == 0: return np.array(hor_diff) elif axis == 1: return np.array(vert_diff) else: return np.insert(hor_diff, len(hor_diff), vert_diff)
4339d4e0a505286a54e12bc177e971bd9e6935b2
tisaconundrum2/Aivery
/chatter/util/BasicFunctionality.py
2,735
3.78125
4
import sys from Qtickle import Qtickle class Basics: """ This class is a scaffolding class, it holds global functionality for all classes inheriting from it. It is here to simplify and globalize certain variables and functionalities to each of the UI classes. *Note: Rigorous prototyping is still occurring So, naturally, assume that something in this class is always getting changed or added to better serve all cases in each UI class. ... Since `Basics` is shared among all the UI classes it would make sense that we would have some variables, that are necessary among all these classes, be put here in a high place where they can be referenced often. """ def __init__(self): self.qt = Qtickle.Qtickle(self) def setupUi(self, Form): """ Get the Ui_Form, it is like the HTML of the UI It will show the styling of the UI. But buttons and widgets have no function. connectWidgets fixes this :param Form: :return: """ sys.exit('Error: Application closed unexpectedly\n' 'The method "SetupUI()" was not found in this module ') def get_widget(self): """ This function specifies the variable that holds the styling. Use this function to get the variable :return: """ sys.exit('Error: Application closed unexpectedly\n' 'The method "get_widget()" was not found in this module') def connectWidgets(self): """ Connect the necessary widgets. :return: """ sys.exit('Error: Application closed unexpectedly\n' 'The method "connectWidgets()" was not found in this module') def function(self): """ Each Module's functionality will be ran in this function. You will define what will happen to the data and parameters in here :return: """ sys.exit('Error: Application closed unexpectedly\n' 'The method "function()" was not found in this module') def isEnabled(self): """ Checks to see if current widget isEnabled or not :return: """ sys.exit('Error: Application closed unexpectedly\n' 'The method "isEnabled()" was not found in this module') def setDisabled(self, bool): """ After every execution we want to prevent the user from changing something. So, disable the layout by greying it out :param bool: :return: """ sys.exit('Error: Application closed unexpectedly\n' 'The method "setDisabled()" was not found in this module')
ee178c1e36fd937bb7b7c6173a08bede41da9729
fajarg/Machine-learning
/tugas 1/sa.py
177
3.71875
4
#masukan = [] a = list() while True : masukan = str(input("Silahkan masukan nama barang : ")) a.append(masukan) if masukan == "b" : break print (a)
d50e0c0b02845ae749fd15ffb70a672cbcbe8f20
soyalextreme/python-course-intermediate
/lists_and_dic.py
957
4.125
4
def main(): """ Working with the list and dictionary on the same structure """ my_list = [1, "Hello", True, 4.5] my_dic = {"firstname": "Alejandro", "lastname": "Andrade"} super_list = [ {"firstname": "Alejandro", "lastname": "Andrade"}, {"firstname": "Miguel", "lastname": "Martinez"}, {"firstname": "Tomas", "lastname": "Hernandez"} ] super_dict = { "natural_nums": [1, 2, 3, 4, 5], "integer_nums": [-1, -2, 0, 1, 2], "floating_nums": [1.1, 4.5, 6.43] } print("PRINTING THE SUPER DICTIONARY") for key, value in super_dict.items(): print(key, "-", value) print("PRINTING THE SUPER DICTIONARY") for i in super_list: for key, value in i.items(): print(key, "-", value, end=" | ") print("\n") if __name__ == "__main__": """ Main Entry """ main()
19426a28dc587126c9cc288571f59b4e48c75301
PavelBabko/Project-1
/project_1.py
852
3.609375
4
import urllib.request from bs4 import BeautifulSoup year=input('Введите интересующий год (не ранее 2000):') month=input('Введите месяц в числовом эквиваленте:') year1=str(year) month1=str(month) address=("https://www.kinopoisk.ru/premiere/ru/%s/month/%s/" % (year1,month1)) def get_html(url): response = urllib.request.urlopen(url) return response.read() def extraction(html): soup = BeautifulSoup(html,"html.parser") table = soup.find('div', class_ = 'block_left') filmoteka = [] for film in table.find_all('span', class_ = 'name'): filmoteka.append(film.a.text) for i in filmoteka: print(i) def main(): extraction(get_html(address)) if __name__ == '__main__': main()
511ea0acf7ef8f6e0f0c66f68634fcb8ebe62982
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/terrance_jones/lesson4/dict_lab.py
282
3.859375
4
#Dictionaries 1 def dictionaries1(): d = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} print(d) d.pop('cake') print(d) d['fruit']= 'Mango' print(d) print(d.keys()) print(d.values()) print('cake' in d) print('Mango' in d.values())
03b5a9a303de8250faaadcdd2706eb29e3074ebd
williamgarner/cs491-HW2
/Driver.py
650
3.5625
4
from Game import Game game = Game() print(f"Welcome to Blackjack you have ${game.account}") print('The dealer will now shuffle the cards') game.shuffle_deck() print("Place your bet: ") game.bet = int(input()) game.deal_first_cards() choice = 'h' while not game.game_over and choice != 's': print(f"Here are your cards: {game.get_player_cards()}") print("Would you like to hit or stand(h or s)?") choice = str(input()) if choice == 'h' or choice == "H": game.deal_player_a_card() game.dealers_turn() print("Game over!") print(f"Your hand {game.get_player_cards()}") print(f"Dealer's hand: {game.get_dealer_cards()}") print(game.get_winner())
5f1e9decc3a5531c4db40f05b6e9dd59928040f0
bhuvaneshwari02/Cloud
/N EvenNumbers.py
109
3.921875
4
num = int(input("Enter a number")) num1 = num+num lst = [i for i in range (num1+1) if (i%2 == 0)] print(lst)
bdc51bd6121e05ea0a9a4ecbedbf6abce6343969
bhainesva/Challenge
/Levenshtein.py
2,571
3.5625
4
import sys from datetime import datetime # Returns a boolean indicating whether the two strings # a and b are within thresh steps of each other def isClose(a, b, thresh): #Storing these values in variables to avoid repeated len() calls magA = len(a) magB = len(b) # There's no point computing the distance if we know it # has to be over the threshold if (abs(magA-magB) > thresh): return False # Initializes the two dimensional array where the work is done D = [[0 for x in range(magB+1)]for x in range(2)] # To turn an empty string into one of length j requires j edits for j in range(1, magB+1): D[0][j] = j for i in range(magA): D[1][0] = i+1 for j in range(1, magB+1): # Substitution m1 = D[0][j-1] # If we're substituting 'x' for 'x' it doesn't count if (a[i] != b[j-1]): m1 += 1 # Deletion m2 = D[0][j] + 1 # Insertion m3 = D[1][j-1] + 1 # Determines which path is the most efficient D[1][j] = min(m1, m2, m3) # If we've already taken more steps than the threshold # there's no point in continuing if min(*D[1]) > thresh: return False # Resets the working matrix D[0] = D[1] D[1] = [0 for x in range(magB+1)] return D[0][magB] <= thresh def extract(inList, exclude): out = [] for word in inList: if word not in exclude: for a in exclude: if word not in out and isClose(a, word, 1): out.append(word) return out if __name__ == "__main__": startTime = datetime.now() # Array to contain the resulting friend network tiers = [[] for x in range(3)] # User input word to create a network for a = sys.argv[1] # Array to hold candidates for being added to the network cands = [] # Reads in contents of wordlist and determines candidates with open('randomlist.txt', 'r') as f: for word in f: word = word.strip() if isClose(a, word, 3): cands.append(word) # Extracts the tiers from the possible candidates tiers[0] = extract(cands, [a]) tiers[1] = extract(cands, tiers[0]) tiers[2] = extract(cands, tiers[1]) # Outputs running time print datetime.now() - startTime # Displays results print "INPUT: ", a print "TIER1: ", tiers[0] print "TIER2: ", tiers[1] print "TIER3: ", tiers[2]
91e6074aed261328b63890c7629737ed07cd8031
daniel-reich/ubiquitous-fiesta
/e5S2DtfJafpybGhKc_23.py
938
3.59375
4
def rotate(mat): class Grid: def __init__(self, grid): self.grid = grid self.cols = {} for n in range(len(grid[0])): col = [] for row in grid: col.append(row[n]) self.cols[n] = col self.rows = {} for n in range(len(grid)): self.rows[n] = grid[n] def rotate(self, deg): if deg == 90: new_rows = [] for n in sorted(list(self.cols.keys())): new_rows.append(list(reversed(self.cols[n]))) elif deg == 180: new_rows = list(reversed(self.grid)) elif deg == 270: new_rows = [] for n in reversed(sorted(list(self.cols.keys()))): new_rows.append(self.cols[n]) elif deg == 360: new_rows = self.grid else: return 'Incorrect Angle: {}'.format(deg) return new_rows grid = Grid(mat) return grid.rotate(90)
62deddb842ce09946f9f0eecb02b146380ea3fa1
Nedashkivskyy/NedashkivskyyV
/Лб 5 Завдання 2-3(варіант 10).py
259
3.578125
4
with open('Probne.txt') as file: words=0 characters=0 for line in file: wordslist=line.split() words=words+len(wordslist) characters += sum(len(word) for word in wordslist) print(words) print(characters)
8f177aece906cbab0caa53f0632374a5bfd67c4a
why1679158278/python-stu
/python资料/day8.4/day04/demo03.py
426
4.34375
4
""" for + range range 范围 产生一个范围的整数 """ # 写法1: range(开始,结束,间隔) # 注意:不包含结束值 # for number in range(1,11,2): # print(number)# 1 3 5 7 9 # 写法2: range(开始,结束) # 注意:间隔默认为1 # for number in range(1,5):# 1 2 3 4 # print(number) # 写法3: range(结束) # 注意:开始默认为1 for number in range(5):#0 1 2 3 4 print(number)
b96e21d7e8a15df561909e941a9485329417f73b
sprawin/Python_Docs
/class_with_kwargs.py
578
3.8125
4
class Student: def __init__(self,**data): for i,j in data.items(): if(i == "name"): self.name = j if(i=="age"): self.name = j if(i=="mobile"): self.mobile = j if i not in {"name","age","mobile"}: print("contact your developer. Only name, age and mobile are available.") def show(self): print(self.name, self.mobile) s1 = Student(name = "Praveen", age = 23, mobile = "9486185751") s1.show()
5d594df38638a8f78c9c05362c1e2a8c47d74f9f
shirapahmer/Treap
/treap.py
7,977
3.90625
4
import random class Node(object): # create a binary tree node consisting of a key/data pair #code taken and modified from slides for binary tree def __init__(self, k, p): self.key = k self.priority = p self.leftChild = None self.rightChild = None self.occurenceCount = 0 #taken from slides for binary tree def __str__(self): return "{" + str(self.key) + " , " + str(self.priority) + "}" class Treap(object): def __init__(self): self.__root = None self.__nElems = 0 ##modified from code given for BST #prints the nodes in readable format displaying tree-like node relationships def printTreap(self): self.pTreap(self.__root, "ROOT: ", "") print() ##modified from code given for BST def pTreap(self, n, kind, indent): print("\n" + indent + kind, end="") if n: print(n, end="") if n.leftChild: self.pTreap(n.leftChild, "LEFT: ", indent + " ") if n.rightChild: self.pTreap(n.rightChild, "RIGHT: ", indent + " ") ##code modified from code for AVL tree. #rotates cur node to the right. Its leftChild becomes its parent and cur #takes on the rightChild of its previous leftChild. Cur's previous parent #now points to the leftChild node because it replaced cur def rotateRight(self, cur, insert = True): temp = cur.leftChild tempRight = temp.rightChild temp.rightChild = cur cur.leftChild = tempRight if not insert: parent = self.getParent(cur.key) if cur == self.__root: self.__root = temp elif cur.key < parent.key: parent.leftChild = temp elif cur.key > parent.key: parent.rightChild = temp return temp if insert else cur ##code modified from code for AVL tree #rotates cur node to the left. Its rightChild becomes its parent and cur #takes on the leftChild of its previous rightChild. Cur's previous parent #now points to the leftChild node because it replaces cur def rotateLeft(self, cur, insert = True): temp = cur.rightChild tempLeft = temp.leftChild temp.leftChild = cur cur.rightChild = tempLeft if not insert: parent = self.getParent(cur.key) if cur == self.__root: self.__root = temp if cur.key < parent.key: parent.leftChild = temp if cur.key > parent.key: parent.rightChild = temp return temp if insert else cur ##modified from code given for BST. #insert a new node. Calls the private insert function def insert(self, k): # remember nElems to see if it changed due to insert temp = self.__nElems #generate random number for priority randNum = random.random() self.__root = self.__insert(self.__root, k, randNum) # if the insert failed, # then nElems will not have changed return temp != self.__nElems ##modified from code given for BST. def __insert(self, cur, k, randNum): # empty tree, so just insert the node, increment the num of elements #in the tree, and increment amount of nodes with that key if not cur: self.__nElems += 1 newNode = Node(k, randNum) newNode.occurenceCount += 1 return newNode #if the key is already in the node, just increment tally of that node #increment the num of elems in the tree if cur.key == k: cur.occurenceCount += 1 self.__nElems += 1 # insert k in the left or right branch as appropriate elif k < cur.key: cur.leftChild = self.__insert(cur.leftChild, k, randNum) #make sure the priority of the new key is not bigger than its parent if cur.priority < cur.leftChild.priority: cur = self.rotateRight(cur) elif k > cur.key: cur.rightChild = self.__insert(cur.rightChild, k, randNum) #make sure the priority of the new key is not bigger than its parent if cur.priority < cur.rightChild.priority: cur = self.rotateLeft(cur) # at this point, k was inserted into the correct branch, # or it wasn't inserted since the key k was already there return cur #the calling function to find if theres node with the given key in the tree def find(self, k): key = self.__find(k) if key: occurs = self.getOccurenceCount(k) print("Found node with key:", k,"\nOccurs ",occurs, "times.") return True else: print("No node found with key: "+ k) return False ##modified from code given for BST #recursively find the node with the given key k. returns the node if found. #if the key is the root node, return the root node itself def __find(self, k, cur = "start"): if cur == "start": cur = self.__root #if node isn't found, return None if not cur: return None if k == cur.key: return cur elif k < cur.key: return self.__find(k, cur.leftChild) else: return self.__find(k, cur.rightChild) #get the number of times a key appears in the tree def getOccurenceCount(self, k): k = self.__find(k) return k.occurenceCount #get the parent node of a node with a given key def getParent(self, k, cur = "start"): if cur == "start": cur = self.__root if cur.key == k: return cur #if cur's right child exists and it is the key, return cur. Same with #the left node if (cur.rightChild and cur.rightChild.key == k) or \ (cur.leftChild and cur.leftChild.key == k):return cur #if not, move on to the next key in the correct side of the tree elif k < cur.key: return self.getParent(k, cur.leftChild) else: return self.getParent(k, cur.rightChild) #remove a node with given key def remove(self, k, cur = "start"): if cur == "start": cur = self.__find(k) #if the node doesn't exist, return none if not cur: return False #if there is more than one of the key, just decrement the count if self.getOccurenceCount(cur.key) >1: cur.occurenceCount -= 1 return #if its a leaf node if not cur.rightChild and not cur.leftChild: #if it is the root node, set root to none if cur == self.__root: self.__root = None #find the parent node of cur, set it to None else: parent = self.getParent(cur.key) if parent.rightChild == cur: parent.rightChild = None elif parent.leftChild == cur: parent.leftChild = None self.__nElems -= 1 return True #if cur is not a leaf node else: #if it has two children, rotate with the child who has a higher #priority of the two nodes if cur.leftChild and cur.rightChild: if cur.leftChild.priority > cur.rightChild.priority: self.rotateRight(cur, insert = False) else: self.rotateLeft(cur, insert = False) #if it only has one child node, rotate with that node elif not cur.leftChild and cur.rightChild: self.rotateLeft(cur, insert = False) else: self.rotateRight(cur, insert = False) #keep going until it is a leaf node and deleted cur = self.remove(k, cur)
88c647aaa35c48d2ed50c787469d87ab284aa0ba
pgmabv99/pyproblems
/av24_tree_no_recur.py
2,935
3.6875
4
class stk_t: def __init__(self,node,dir,lev,par): self.node=node self.dir=dir self.lev=lev self.par=par class node_t: hh=0 def __init__(self, pv): self.v=pv self.children=[] def copy(self): node2=node_t("") node2.v=self.v+"_copy" return node2 class test_t: #pre-order with stack def trav_nr_pre(self, root): print(" ") print("++++pre-order++++++") stk_list=[] dir=0 lev=0 node=root stk_p=stk_t(node,dir,lev,None) stk_list.append(stk_p) while len(stk_list)>0: stk_p=stk_list.pop() node_p=stk_p.node lev=stk_p.lev par=stk_p.par print("popped from stack value", node_p.v, "lev", lev ) node_p1=node_p.copy() if(par!=None): par.children.append(node_p1) else: root1=node_p1 #push children and remember current as thier parent for child in reversed(node_p.children): stk_p=stk_t(child,dir,lev+1,node_p1) stk_list.append(stk_p) #end loop return root1 #post order with stack and copy def trav_nr_post(self,root): print(" ") print("++++post-order++++++") stk_list=[] dir="down" lev=0 node=root stk_p=stk_t(node,dir,lev,None) stk_list.append(stk_p) while len(stk_list)>0: stk_p=stk_list.pop() node_p=stk_p.node dir=stk_p.dir lev=stk_p.lev # print("popped from stack value", node_p.v, "lev", lev, "dir ", dir) if (len(node_p.children)==0): print("Leaf lev" , lev, "value ",node_p.v ) else: if dir=="down": #down #reappend(push) current with dir=up stk_p=stk_t(node_p,"up",lev,None) stk_list.append(stk_p) for child_p in reversed(node_p.children): stk_p=stk_t(child_p,"down",lev+1,None) stk_list.append(stk_p) else: #print and skip print("up lev" , lev, "value ",node_p.v ) #end loop return root=node_t("a") c1=node_t("c1") c2=node_t("c2") c3=node_t("c3") root.children.append(c1) root.children.append(c2) root.children.append(c3) g11=node_t("g11") g12=node_t("g12") c1.children.append(g11) c1.children.append(g12) g21=node_t("g21") c2.children.append(g21) gg211=node_t("g211") g21.children.append(gg211) test_p=test_t() root1=test_p.trav_nr_pre(root) root2=test_p.trav_nr_pre(root1) test_p.trav_nr_post(root2)
59599a08d2331650413c3236903559768e70e8e5
dankoo97/EulerProjects1-50
/Euler_18_MaximumPathSum1.py
2,250
3.578125
4
# By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. # # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23. # # Find the maximum total from top to bottom of the triangle below: # # 75 # 95 64 # 17 47 82 # 18 35 87 10 # 20 04 82 47 65 # 19 01 23 75 03 34 # 88 02 77 73 07 63 67 # 99 65 04 28 06 16 70 92 # 41 41 26 56 83 40 80 70 33 # 41 48 72 33 47 32 37 16 94 29 # 53 71 44 65 25 43 91 52 97 51 14 # 70 11 33 28 77 73 17 78 39 68 17 57 # 91 71 52 38 17 14 91 43 58 50 27 29 48 # 63 66 04 68 89 53 67 30 73 16 69 87 40 31 # 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 # # NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. # However, Problem 67, is the same challenge with a triangle containing one-hundred rows; # it cannot be solved by brute force, and requires a clever method! ;o) def path_sum(file_path): def get_greatest_sum(x=0, y=0): pos = (str(x) + ',' + str(y)) if pos in sums: return sums[pos] # prevent extra calculations l_sum = get_greatest_sum(x + 1, y) # triangle is left adjusted, so going down the left path from the top is triangle[x][0] r_sum = get_greatest_sum(x + 1, y + 1) # and the right path is triangle [x][len(triangle[x] - 1] sums[pos] = (l_sum if l_sum > r_sum else r_sum) + triangle[x][y] # we compare the sum of the left path and right path, return the greater and add the val of our position return sums[pos] triangle = [] with open(file_path) as tx: for i in tx: i = i.strip('\n') triangle += [i.split(' ')] for i in range(len(triangle)): triangle[i] = [int(j) for j in triangle[i]] # turning our text into a 2d list of int sums = {} # storing found sums for positions for j in range(len(triangle[-1])): sums[str(len(triangle) - 1) + ',' + str(j)] = triangle[-1][j] # the bottom row is inputted into our sums so we have a base return get_greatest_sum() def __main__(): print(path_sum('triangle1.txt')) # 1074 if __name__ == '__main__': # we will use the same method for problem 67 __main__()
93849794cad8ad2d1198f31e832096176b401a62
mooba/jianzhi_offer
/ch03/14/reOrderArray.py
1,044
3.765625
4
# -*- coding:utf-8 -*- ''' 调整数组顺序使奇数位于偶数前面 ''' class Solution: def reOrderArray(self, array): # write code here array_len = len(array) if array_len == 0 or array_len == 1: return array odd_num = 0 for num in array: if num & 0x1 == 1: odd_num += 1 odd_point = 0 while odd_point < odd_num: if array[odd_point] & 0x1 == 1: odd_point += 1 else: next_point = odd_point tmp1 = array[next_point] while tmp1 & 0x1 != 1 and next_point + 1 < array_len: tmp2 = array[next_point + 1] array[next_point + 1] = tmp1 tmp1 = tmp2 next_point += 1 array[odd_point] = tmp1 odd_point += 1 return array if __name__ == "__main__": s = Solution() lst = [1,2,3,4,5,6,7] print s.reOrderArray(lst)
2acef48cf47791d973d9df124f25d512eb0e6307
canwe/python3-course-advanced
/30_concurrent_futures/deadlock_demo.py
837
3.921875
4
from concurrent.futures import ThreadPoolExecutor def wait_forever(): """ This function will wait forever if there's only one thread assigned to the pool """ my_future = executor.submit(zip, [1, 2, 3], [4, 5, 6]) # Creates a deadlock # result = my_future.result() # print (result) # Works return my_future # returns the inner future from this if __name__ == '__main__': # Creates a deadlock # executor = ThreadPoolExecutor(max_workers=1) # won't work because there is only one worker at max # # We’ve just created a deadlock! The reason is that we are having one Future wait for another Future to finish. # executor.submit(wait_forever) # Works executor = ThreadPoolExecutor(max_workers=3) fut = executor.submit(wait_forever) result = fut.result() print (list(result.result())) # [(1, 4), (2, 5), (3, 6)]
1ad6ed8d46b9fafb28f7cc0317c9447045405f26
Enstore-org/enstore
/src/Cache.py
1,539
3.90625
4
""" Implementation of a simple cache that holds certain number of elements and removes excess based on LRU """ import collections import threading DEFAULT_CAPACITY=200 class Cache: """ simple lru cache """ def __init__(self, capacity=DEFAULT_CAPACITY): """ :type capacity: :obj:`int` :arg capacity: cache size """ self.capacity = capacity self.cache = collections.OrderedDict() self.lock = threading.Lock() def get(self,key): """ :type key: :obj:`obj` """ with self.lock: try: value = self.cache.pop(key) self.cache[key]=value return value except KeyError: return None def put(self,key,value): """ :type key: :obj:`obj` :arg kay: key :type value: :obj:`obj` :arg kay: value """ with self.lock: try: self.cache.pop(key) except KeyError: if len(self.cache) >= self.capacity: """ remove first (oldest) item: """ self.cache.popitem(last=False) self.cache[key]=value def __repr__(self): return self.cache.__repr__() if __name__ == "__main__": # pragma: no cover cache = Cache(3) cache.put("a",1) cache.put("b",1) cache.put("c",1) print cache cache.put("d",1) print cache
2f40bfce7d4a3a50863fac31fce9dfa03cca4bed
Joshua-fosu/Hello_world
/Congratulations.py
1,796
3.59375
4
import pygame.ftfont class CongratulatoryMessage: """Congratulate user on playing the game...""" def __init__(self, screen, stats, ai_settings): #Attributing values self.screen = screen self.stats = stats self.ai_settings = ai_settings #Get rect of screen... self.screen_rect = self.screen.get_rect() self.font = pygame.font.SysFont(None, 50) self.color = 0, 0, 0 self.prep_message_high() self.prep_message_low() def prep_message_high(self): """Print this message if user had higher than high score""" self.msg = "Congratulations!!!" + "\n" self.msg += "You have beat the current high score..." self.msg += f"The new high score is {self.stats.high_score}." self.msg_image = self.font.render(self.msg, True, self.color, self.ai_settings.bg_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.centerx = self.screen_rect.centerx self.msg_image_rect.top = 200 def prep_message_low(self): """Print this message if user had lower than the high score""" self.info = "That was a good performance" self.info += "Try to beat the high score next time..." self.info_image = self.font.render(self.info, True, self.color, self.ai_settings.bg_color) self.info_rect = self.info_image.get_rect() self.info_rect.centerx = self.screen_rect.centerx self.info_rect.top = 200 def show_higher(self): self.screen.blit(self.msg_image, self.msg_image_rect) def show_lower(self): self.screen.blit(self.info_image, self.info_rect)
32c2173a44292b3ca4f51da79cd1ae2862d7a74f
ItsLogical/LetsLearnIP-ProgrammingForEconomists
/solutions/othello1.py
829
4.09375
4
NUMBER_OF_SQUARES = 64 no_white_pieces = int(raw_input("Enter the number of white pieces on the board: ")) no_black_pieces = int(raw_input("Enter the number of black pieces on the board: ")) total_pieces = no_white_pieces + no_black_pieces # We need to cast either the dividend or divisor to a float to prevent incorrect # values due to integer division # (We could have also just cast the raw_input values to floats right away, buuut # they're supposed to be ints ya know... So I thought this was nicer) pct_black_board = no_black_pieces / float(NUMBER_OF_SQUARES) * 100 pct_black_all_pieces = no_black_pieces / float(total_pieces) * 100 print "The percentage of black pieces on the board is: %0.2f%%" % pct_black_board print "The percentage of black pieces of all the pieces on the board is: %0.2f%%" % pct_black_all_pieces
d726375fcaaf9746d88d3dd235fb3a6056d9e1d1
homeworkprod/utilities
/biggestfiles.py
2,989
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """List the biggest files. :Copyright: 2008-2014 Jochen Kupperschmidt :Date: 10-Jul-2014 (original release: 20-Apr-2008) :License: MIT """ from __future__ import print_function from argparse import ArgumentParser from collections import namedtuple try: reduce # Python 2 except NameError: from functools import reduce # Python 3 from pathlib import Path from operator import attrgetter import os FileInfo = namedtuple('FileInfo', ['path', 'size']) def parse_args(): """Parse command line arguments.""" parser = ArgumentParser(description='List the biggest files.') parser.add_argument( 'path', metavar='PATH') parser.add_argument( '-m', '--max-files', dest='max_files', type=int, default=10, help='maximum number of files to show (default: 10)') parser.add_argument( '-p', '--pattern', dest='pattern', default='*', help='a pattern to narrow down the search, e.g. "*.txt"\n' ' NOTE: The pattern might need to be escaped, possibly ' 'using quotes or backslashes, depending on your shell.') return parser.parse_args() def collect_file_infos(search_path, pattern): """Yield information on each file along the path.""" file_paths = collect_file_paths(search_path, pattern) return map(create_file_info, file_paths) def collect_file_paths(search_path, pattern): """List all files along the path.""" for directory, subdirectories, files in os.walk(search_path): for file_path in Path(directory).glob(pattern): yield file_path def create_file_info(file_path): """Collect information on a file (i.e. its size).""" size = file_path.stat().st_size return FileInfo(file_path, size) def collect_biggest_files(file_infos, limit): """Determine the biggest files.""" return collect_highest(file_infos, attrgetter('size'), limit) def collect_highest(iterable, sort_key, limit): """Return the highest elements from the iterable, considering the value returned by the sort key function ``sort_key``, but no more than ``limit``. """ def update_with_item(items, item): return sorted(items + [item], key=sort_key, reverse=True)[:limit] return reduce(update_with_item, iterable, []) def format_results(file_infos): """Format the file information objects.""" if file_infos: highest_size_digits = len(str(file_infos[0].size)) tmpl = ' {{0.size:>{}d}} {{0.path}}'.format(highest_size_digits) for file_info in file_infos: yield tmpl.format(file_info) else: yield 'No files were found.' def main(): args = parse_args() file_infos = collect_file_infos(args.path, args.pattern) biggest_files = collect_biggest_files(file_infos, args.max_files) for line in format_results(biggest_files): print(line) if __name__ == '__main__': main()
fd1f9cc2bf32537583286cf316d2992137276a1c
sfa119f/tugas4-kriptografi
/function.py
3,086
3.515625
4
def isPrime(n): # Mengetahui apakah n adalah bilangan prima if n == 2 or n == 3: return True elif n < 2 or n % 2 == 0: return False elif n < 9: return True elif n % 3 == 0: return False else: maxVal = int(n**0.5) temp = 5 while temp <= maxVal: if n % temp == 0: return False if n % (temp + 2) == 0: return False temp += 6 return True def gcd(x, y): # Menghitung fpb dari x dan y if(y == 0): return x else: return gcd(y, x % y) def lcm(x, y): # Menghitung kpk dari x dan y return x * y // gcd(x, y) def invMod(val1, val2): # Menghitung invers modulo a, b, x, y, u, v = val1, val2, 0, 1, 1, 0 while a != 0: q = b // a r = b % a m = x - u * q n = y - v * q b, a, x, y, u, v = a, r, u, v, m, n if b != 1: return None return x % val2 def blockMessage(n): # Value block message dengan panjang n if n == 0: return 0 if n == 1: return 10 else: return blockMessage(n - 2) * 100 + 25 def lenValCipher(n): # Menghitung panjang hasil dari cipher text if n < 25: lenVal = 1 else: lenVal = 2 while blockMessage(lenVal + 2) < n: lenVal += 2 return lenVal def makeBlockMessage(lenVal, text): # Membuat block message dari text dengan panjang lenVal if len(text) % (lenVal // 2) != 0: text += 'X' * ((lenVal // 2) - (len(text) % (lenVal // 2))) res = [] for i in range(0, len(text), (lenVal // 2)): if lenVal == 1: res.append(ord(text[i]) - ord('A') // 10) res.append(ord(text[i]) - ord('A') % 10) else: blockDigit = 0 for j in range(i, i + (lenVal // 2)): blockDigit = blockDigit * 100 + (ord(text[j]) - ord('A')) res.append(blockDigit) return res def blockMessageToText(lenVal, mArray): # Convert block message to text res = '' i = 0 while i < len(mArray): if lenVal == 1: res += chr(mArray[i] * 10 + mArray[i+1]) i += 2 else: tres1 = '' if mArray[i] // (10 ** (lenVal - 2)) == 0: tres2 = 'A' else: tres2 = '' while mArray[i] != 0: tres1 = chr(mArray[i] % 100 + ord('A')) + tres1 mArray[i] //= 100 res += (tres2 + tres1) i += 1 return res def blockCipherToStr(lenVal, cArray): # Membuat semua panjang dari blok cipher menjadi sama panjang res = '' for i in range(len(cArray)): temp = '' for j in range(lenVal - len(str(cArray[i]))): temp += '0' res += (temp + str(cArray[i])) return res def strToBlockCipher(lenVal, strNum): # Mengembalikan panjang dari masing-masing blok cipher ke semula temp = 10 ** lenVal res = [] while len(strNum) != 0: val = int(strNum[:lenVal]) strNum = strNum[lenVal:] res.append(val) return res def makePlain(plainText): # Membuat plainText sesuai dengan format yang diinginkan yakni # menghilangkan angka dan symbol serta membuat huruf menjadi uppercase p = [] plainText = plainText.upper() plain = list(plainText) for char in plain: if (char.isalpha()): p.append(char) newP = "".join(p) return newP
01d666c33339019838a410d8a72634383c91e5bd
linjorejoy/Calulating-the-digits-of-pi
/Nilakantha Series.py
529
3.890625
4
"""This is from the Nilakantha Series [Referance:https://www.mathscareers.org.uk/article/calculating-pi/] pi = 3 + 4 4 4 4 ____ - ____ + ____ - ____ + ..... 2*3*4 4*5*6 6*7*8 8*9*10 """ import math def getPi(noOfIter): pivalue = 3 for i in range(1, noOfIter+3): pivalue += 4/(2*i*(2*i+1)*(2*i+2))*((-1)**(i+1)) return pivalue piVal = getPi(10) print("{0:.50f} and diff is {1}".format(piVal, piVal- math.pi))
ef7bee16df5945b8743b68600797e7cf5324a09f
theadamsacademy/python_tutorial_for_beginners
/19_tuples/1_access.py
212
3.890625
4
person_record = ("Mike", 1996, "Atlanta, Georgia") print(person_record[2]) print(person_record[-1]) print(person_record[0:3]) print(person_record[-3:-2]) for person_data in person_record: print(person_data)
b9857d21bc882b44cad96c6cf00ea2e302fd706d
doomnonius/codeclass
/daily-probs/day2.py
689
4.0625
4
"""Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? """ import operator from functools import reduce from copy import deepcopy L = [3, 2, 1] def array(L): newList = [] for x in L: L2 = deepcopy(L) del L2[L.index(x)] x = reduce(lambda x,y: (x*y), L2) newList.append(int(x)) return newList print(array(L))
7db80e861ca96a6ecb02f832f44b89f64df5b368
saravananprakash1997/Python_Logical_Programs
/merge_sort_two_lists.py
445
4.0625
4
# merge two lists and sort them limit1=int(input("enter the limit of the list1 :")) list1=[] for i in range(1, limit1+1): input1=int(input("enter the list values :")) list1.append(input1) print(list1) limit2=int(input("enter the limit of list2 :")) list2=[] for j in range(1, limit2+1): input2=int(input("enter the list values :")) list2.append(input2) print(list2) for k in list2: list1.append(k) print(list1) list1.sort() print(list1)
01aa6e10fa3031ab705e17cb23401c119dbe22bc
dreops/second_py_train
/py-revision.py
521
3.640625
4
#lists training frontrow = ['osman', 'paul', 'mark', 'mike', 'alex', 'julie'] for name in frontrow: print(name) #re-assign Tim replacing Mike # frontrow[3]="Tim" #adding Tim to the front row frontrow.append("tim") frontrow.remove("osman") # replacing Osman with Tim # you can use .replace with care #portal tut. cool_cows = ["Winnie the Moo", "Moolan", "Milkshake", "Mooana"] cool_sheep = ["Baaaart", "Baaaarnaby"] cool_pigs = ["Chris P. Bacon", "Hamlet", "Hogwarts"] cool_animals = [cool_cows, cool_sheep, cool_pigs]
1808f4ff7318e4cac3be6e653c18d5e60e0bad97
dvagal/ML_engineer_homework_assignment
/cognoa_ds_lib/plotting_tools.py
14,800
3.71875
4
import matplotlib.pyplot as plt import matplotlib ### Importing matplotlib both ways because there are a mix of functions below that use different interfaces. ### Would be good to clean this up at some point. import numpy as np import pandas as pd def _get_list_of_unique_x_values(list_of_x_data_lists): ''' Helper function for functions below. Intended for overlaying bar charts where a list of lists or arrays represent the x-values of each dataset that will be overlayed. This functions determines the list of the x-values that should be displayed on the x-axis ''' list_of_unique_lists = [np.unique(dataset) for dataset in list_of_x_data_lists] combined_list_with_duplicates = [item for sublist in list_of_unique_lists for item in sublist] list_of_unique_x_values = np.unique(combined_list_with_duplicates) return list_of_unique_x_values def overlay_bar_charts_from_numeric_arrays(list_of_x_data_lists, legend_label_list, plot_options_dict): ''' Intended for situations where there is a small number of often repeated values that most of the data might have and you want to compare distributions without them obscuring one another x_values_list: a list of data lists or arrays ''' list_of_unique_x_values = _get_list_of_unique_x_values(list_of_x_data_lists) list_of_x_data_bars = [] list_of_y_data_bars = [] for dataset in list_of_x_data_lists: x_data_bars = [] y_data_bars = [] for x_value in list_of_unique_x_values: y_value = len(dataset[dataset==x_value]) x_data_bars.append(x_value) y_data_bars.append(y_value) list_of_x_data_bars.append(np.array(x_data_bars)) list_of_y_data_bars.append(np.array(y_data_bars)) overlay_bar_charts(list_of_x_data_bars, list_of_y_data_bars, legend_label_list, x_values_are_categorical=False, plot_options_dict=plot_options_dict) def overlay_bar_charts(list_of_x_data_bars, list_of_y_data_bars, legend_label_list=[''], x_values_are_categorical=True, plot_options_dict=None): ''' Overlay some number of bar charts with values (or categories) list_of_x_data_bars, and y_values list_of_y_data_bars ... This can run on categorical or numeric data. If numeric x-axis becomes the value of the numbers, and the bars will probably not be equally spaced. The chart can easily get overwhelmed with many bins. This function is mostly useful if only a small number of often repeated numeric values are present in the data. ... If your x data is categorical then you should have it remapped to equally spaced bars: set x_values_are_categorical to True ... The overlaying of many different data bars is accomplished by injecting coordinated offsets into the x-values of different elements of the x lists so that they can be seen side-by-side. When interpreting the results (especially if the x-data is numerical rather than categorical) it should be remembered that this offset is a necessary artifact of plotting in an understandable way and not indicative of a true numerical offset in the data. ''' def get_bar_width(n_bars, x_range): bar_density = float(n_bars) / float(x_range[1] - x_range[0]) bar_width = 0.5 / bar_density ### want roughly this percent of visual screen to be taken up by bars return bar_width if 'figshape' in plot_options_dict.keys(): plt.figure(figsize=plot_options_dict['figshape']) else: plt.figure(figsize=(12,8)) if 'grid' in plot_options_dict.keys() and plot_options_dict['grid']==True: plt.grid(True) n_datasets = len(list_of_x_data_bars) assert n_datasets == len(list_of_y_data_bars) assert n_datasets == len(legend_label_list) xtick_labels = None if x_values_are_categorical: #### In this case x-values need to be identical in every array, otherwise #### Plotted bins will not match up for x_values_case in list_of_x_data_bars: assert np.array_equal(list_of_x_data_bars[0], x_values_case) xtick_labels = list_of_x_data_bars[0] x_range = [0, len(xtick_labels)] list_of_x_values_for_plotting = [np.arange(len(xtick_labels))]*n_datasets else: x_range = [min([min(x_data) for x_data in list_of_x_data_bars]), max([max(x_data) for x_data in list_of_x_data_bars])] list_of_x_values_for_plotting = list_of_x_data_bars n_bars = sum([len(x_data) for x_data in list_of_x_data_bars]) bar_width = get_bar_width(n_bars, x_range) if 'color_ordering' in plot_options_dict: colors_list = plot_options_dict['color_ordering'] else: colors_list = ['black', 'red', 'blue', 'yellow', 'green', 'purple', 'orange'] for plot_index, (x_data_bars, y_data_bars, legend_label, color) in enumerate(zip(list_of_x_values_for_plotting, list_of_y_data_bars, legend_label_list, colors_list)): x_offset = bar_width * ((float(plot_index) ) - (0.5 * (n_datasets))) this_legend_label = legend_label if 'means_in_legend' in plot_options_dict.keys() and plot_options_dict['means_in_legend']==True: this_legend_label += ', mean='+str(round(np.average(list_of_x_data_bars[plot_index], weights=list_of_y_data_bars[plot_index]), 3)) #plt.bar(left=x_data_bars+x_offset, height=y_data_bars, width=bar_width, color=color, alpha=0.5, label=this_legend_label) plt.bar(left=x_data_bars+x_offset, height=y_data_bars, width=bar_width, color=color, alpha=0.5, label=this_legend_label) if legend_label_list != ['']: plt.legend(fontsize=plot_options_dict['legend_fontsize']) plt.xlabel(plot_options_dict['xlabel'], fontsize=plot_options_dict['xlabel_fontsize']) plt.ylabel(plot_options_dict['ylabel'], fontsize=plot_options_dict['ylabel_fontsize']) plt.title(plot_options_dict['title'], fontsize=plot_options_dict['title_fontsize']) if x_values_are_categorical: ### Increase bottom margin for readability plt.xticks(np.arange(len(xtick_labels)), xtick_labels, rotation=50, fontsize=8) plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2) #handy function to plot some histograms of DataFrame columns def plot_histogram(df, column_name, sort=False): histo = df[column_name].value_counts() if(sort): histo = histo.sort_index() X = np.array(histo.keys()) Y = histo.values plt.bar(np.arange(len(X)), Y, align='center') plt.xticks(np.arange(len(X)), X) plt.title("Histogram of "+column_name+" values") plt.xlabel(column_name) plt.ylabel('Frequency') fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5, forward=True) plt.show() #plot correlation of categorical feature with outcome variable def plot_feature_correlation(df, feature_column_name, sort=False): c = 1.0 - df.groupby(feature_column_name)['outcome'].mean() if (sort): c = c.sort_index() X = np.array(c.keys()) Y = c.values plt.bar(np.arange(len(X)), Y, align='center') plt.xticks(np.arange(len(X)), X) plt.title("Correlation of outcome variable with "+feature_column_name+" categories") plt.xlabel(feature_column_name) plt.ylabel('Percent non spectrum') fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5, forward=True) plt.show() def plot_classifier_profiles(bunch_of_classifier_data, plot_title, default_coverage_to_plot = 0.0, specificity_bin_width = 0.025, ylim=(0., 1.), legend_font_size=16, shaded_sensitivity_zones=True): import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap fig = plt.figure(figsize=(20, 6)) #setup axes plt.xlabel('specificity', fontsize=28) plt.xticks(np.arange(0.0, 1.1, 0.05), fontsize=16) plt.xlim(0.0, 1.0) plt.ylabel('sensitivity', fontsize=28) plt.yticks(np.arange(0.0, 1.1, 0.05), fontsize=16) plt.ylim(ylim) #add shaded sensitivity zones if required if (shaded_sensitivity_zones): plt.axhspan(0.7, 0.8, edgecolor='none', facecolor='lightyellow', alpha=1.0, zorder=1) plt.axhspan(0.8, 0.9, edgecolor='none', facecolor='orange', alpha=0.3, zorder=1) #plot data for (classifier_info, sensitivity_specificity_dataframe) in bunch_of_classifier_data: print 'Plot for classifier info: ', classifier_info #if we're being asked to plot the optimal point only (as opposed to an ROC curve) if ('type' in classifier_info and classifier_info['type'] == 'optimal_point'): label = classifier_info['label'] if 'label' in classifier_info else 'unnamed classifier' if sensitivity_specificity_dataframe['coverage']<1.0: label = label + ' @ '+"{0:.0f}%".format(100*sensitivity_specificity_dataframe['coverage'])+' coverage' size = classifier_info['size'] if 'size' in classifier_info else 400 linestyle = classifier_info['linestyle'] if 'linestyle' in classifier_info else '-' alpha = classifier_info['alpha'] if 'alpha' in classifier_info else 0.75 fill = classifier_info['fill'] if 'fill' in classifier_info else True edgecolors = classifier_info['color'] if 'color' in classifier_info else None if (fill): facecolors = classifier_info['color'] if 'color' in classifier_info else None else: facecolors = 'none' label = label + " [ {0:.0f}%".format(100*sensitivity_specificity_dataframe['sensitivity'])+' sens, ' label = label + "{0:.0f}%".format(100*sensitivity_specificity_dataframe['specificity'])+' spec]' plt.scatter([sensitivity_specificity_dataframe['specificity']],[sensitivity_specificity_dataframe['sensitivity']], s=size, alpha=alpha, facecolors=facecolors, edgecolors=edgecolors, label=label, zorder=10) #we default to plotting curves else: min_acceptable_coverage = classifier_info['coverage'] if 'coverage' in classifier_info else default_coverage_to_plot specificity_sensitivity_values = [(spec, sen) for spec, sen in zip(sensitivity_specificity_dataframe['specificity'].values, sensitivity_specificity_dataframe['sensitivity'].values)] plot_color = classifier_info['color'] if 'color' in classifier_info else None label = classifier_info['label'] if 'label' in classifier_info else 'unnamed classifier' linewidth = classifier_info['linewidth'] if 'linewidth' in classifier_info else 3 linestyle = classifier_info['linestyle'] if 'linestyle' in classifier_info else '-' if 'coverage' not in sensitivity_specificity_dataframe: plt.plot(sensitivity_specificity_dataframe['specificity'], sensitivity_specificity_dataframe['sensitivity'], marker=None, linewidth=linewidth, label=label, color = plot_color, linestyle=linestyle) else: sensitivity_specificity_dataframe['rounded_specificity'] = sensitivity_specificity_dataframe['specificity'].apply(lambda x: 0 if np.isnan(x) else specificity_bin_width*(int(x/specificity_bin_width)) ) acceptable_coverage_sensitivity_specificity_dataframe = sensitivity_specificity_dataframe[sensitivity_specificity_dataframe.coverage>=min_acceptable_coverage] min_sensitivity = acceptable_coverage_sensitivity_specificity_dataframe.groupby('rounded_specificity')['sensitivity'].min() max_sensitivity = acceptable_coverage_sensitivity_specificity_dataframe.groupby('rounded_specificity')['sensitivity'].max() specificity = acceptable_coverage_sensitivity_specificity_dataframe.groupby('rounded_specificity')['rounded_specificity'].max() plt.plot(specificity, max_sensitivity, linewidth=linewidth, label=label, color = plot_color, linestyle=linestyle) #add legend plt.legend(loc="lower left", prop={'size':legend_font_size}) #add title plt.title(plot_title, fontsize=20, fontweight='bold') #let's do it! plt.show() return plt,fig #same as above but plots a simple bar chart instead of complicated ROC curves def barplot_classifier_profiles(bunch_of_classifier_data, plot_title, sensitivity_low=0.75, sensitivity_high=0.85, min_coverage=0.7): barplot_data = [] for (classifier_info, sensitivity_specificity_dataframe) in bunch_of_classifier_data: label = classifier_info['label'] if 'label' in classifier_info else 'unnamed classifier' if 'coverage' in sensitivity_specificity_dataframe.columns: sensitivity_specificity_dataframe = sensitivity_specificity_dataframe[(sensitivity_specificity_dataframe['coverage']>=min_coverage) ] sensitivity = sensitivity_specificity_dataframe.groupby('rounded_specificity')['sensitivity'].max() specificity = sensitivity_specificity_dataframe.groupby('rounded_specificity')['rounded_specificity'].max() else: sensitivity = sensitivity_specificity_dataframe.groupby('specificity')['sensitivity'].max() specificity = sensitivity_specificity_dataframe.groupby('specificity')['specificity'].max() temp = pd.DataFrame(zip(specificity,sensitivity), columns=['specificity', 'sensitivity']) temp2 = temp[(temp['sensitivity']>=sensitivity_low) & (temp['sensitivity']<=sensitivity_high)] bar_height = temp2['specificity'].mean() barplot_data += [ (classifier_info['label'],bar_height) ] fig = plt.figure(figsize=(20, 10)) barlist = plt.barh( range(len(barplot_data)), [x[1] for x in barplot_data] , align='center', edgecolor = "black", alpha=0.8 ) plt.yticks(range(len(barplot_data)), [x[0] for x in barplot_data]) #setup value labels for i, v in enumerate( [x[1] for x in barplot_data] ): plt.text(v - 0.05, i-0.1, "{0:.0f}%".format(100*v), color='black', fontsize=24) #setup name labels for i,v in enumerate ( [x[0]['label'] for x in bunch_of_classifier_data] ): plt.text(0.02, i-0.1, v, color='black', fontsize=18) #setup colors for i in range(0, len(barlist)): classifier_info = bunch_of_classifier_data[i][0] color = classifier_info['color'] if 'color' in classifier_info else None barlist[i].set(facecolor=color) #setup axes plt.ylabel('algorithm', fontsize=28) plt.yticks([]) plt.xlabel('specificity', fontsize=28) plt.xticks(np.arange(0.0, 1.1, 0.05), fontsize=16) plt.xlim(0.0, 1.0) #add title plt.title(plot_title, fontsize=20, fontweight='bold') #let's do it! print 'show figure with title ', plot_title plt.show() return plt,fig
95772d21e233d0ec6bbd9d5e3998362eaa0da20b
louishu17/tree_color_coding_task
/automorphisms.py
1,822
3.578125
4
""" Created on 6/7/21 @author: louishu17, fayfayning, kieranlele """ import math """ checks if L1 and L2 are equal """ def checkL1L2(tree): if tree == tuple([0, 1]) or tree == [0, 1]: return True ind_1 = tree.index(1) m = tree.index(1, ind_1 + 1) L1 = [tree[i] - 1 for i in range(1, m)] L2 = [tree[i] for i in range(m, len(tree))] L2.insert(0, tree[0]) if L1 == L2: return True return False """ Gets the label of the rth node of the tree """ def get_label(r, tree): lr = tree[r] r1 = len(tree) for i in range(r + 1, len(tree)): if tree[i] <= lr: r1 = i - 1 break for j in range(r - 1, -1, -1): if tree[j] == lr - 1: r2 = j + 1 break label = [r2] label.extend(tree[r:r1 + 1]) return label """ Iterates through the tree to get all the labels """ def all_labels(tree): labels = [] for r in range(1, len(tree)): label = get_label(r, tree) labels.append(label) return labels """ Calculates the number of automorphisms using the labels """ def calc_aut(labels): dict = {} num = 1 for i in labels: tup = tuple(i) if tup not in dict: dict[tup] = 0 dict[tup] += 1 for i in dict.values(): num *= math.factorial(i) return num """ calculates automorphisms based on a given tree """ def aut(tree): if tree == tuple([0, 1]) or tree == [0, 1]: return 2 if not checkL1L2(tree): labels = all_labels(tree) num = calc_aut(labels) else: ind_1 = tree.index(1) m = tree.index(1, ind_1 + 1) L1 = [tree[i] - 1 for i in range(1, m)] labels = all_labels(L1) aut_L1 = calc_aut(labels) num = aut_L1 * aut_L1 * 2 return num
13fe5166a6dfcea17d28efe16f24eda5ca5634b9
SeckMohameth/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,135
4.125
4
#!/usr/bin/python3 """ a function that divides all elements of a matrix. """ def matrix_divided(matrix, div): """divide elements in matrix Args: matrix: list in a list div: int or float dividing byt Returns: Nothing Raises: TypeError: matrix must be a 27 matrix (list of lists) of integers/floats TypeError: div must be a number ZeroDivisionError: division by zero """ new_list = [] second_list = [] for eachList in matrix: for eachNumber in matrix: if not len(eachList) len(matrix[0]): raise TypeError("Each row of the matrix must have the\ same size") second_list.append(eachNumber/div) new_list.append(second_list) second_list = [] if float not in matrix and int not in matrix: raise TypeError("matrix must be a matrix (list of\ lists) of integers/floats") if type(div) != int and type(div) != float: raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") return new_list
7c290e483421caf1f0987201a0af04dffc3cba20
hyl404/HTML
/python练习/2月5日python练习/列表和字典.py
1,888
4
4
'''inventory = ["sword","armor","shield","healing potion"] print("Your items:") for item in inventory: print(item) print("You have",len(inventory),"in your ass") #对列表进行检索 index = int((input("选择你想要的角色:"))) print("这是你选择的角色:",inventory[index]) #对列表进行切片 start = int(input("选择你的角色从:")) finish = int(input("到这里结束:")) print("你的角色从",start,"开始","在",finish,"结束") print(inventory[start:finish]) #对列表进行连接 chest =["gold","gems"] print("你又发现两个ass") print("你想要把他加入到你的队伍当中") inventory= inventory+chest print("现在你的队伍为:",inventory) #通过切片对列表进行赋值 print("现在你需要对一些队员进行更改") inventory[4:6] = ["you fire"] print("现在你的队伍已经改变了:") print(inventory) #删除列表元素,其列表长度会减一,元素都会往前走 #[del与remove不一样,del是根据位置来删除元素而remove是根据值] print("需要移除一些队员:") # del inventory[2] # print("你已经成功移除2号") print(inventory) #删除切片 删除的元素后,列表长度会缩短,剩下的元素会形成一个连续的、从零开始的列表 del inventory[:2] print(inventory) #创建字典 geek={ "404":"fuck q assoul", "Googling":"you batter don't do that", "Link rot":"the process by web whinch lins is ok ", } print("获得键值是:",geek["404"]) test=input("你想访问的键值是:") if test in geek: print(geek[test]) else: print("FUCK Q ,I DONT KONW WHAT IS FACK WITH THAT") ''' inventory = ["sword","armor","shield","healing potion"] start = int(input("选择你的角色从:")) finish = int(input("到这里结束:")) print("你的角色从",start,"开始","在",finish,"结束") print(inventory[start:finish])
06c92413844eeb31d1a811c6248250346c0a6654
pmlandwehr/flo
/examples/model-correlations/src/correlation.py
860
3.734375
4
"""Visualize the scatter plot of x, y """ import sys import math # use headless matplotlib # http://stackoverflow.com/a/3054314/564709 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plot import loaders tsv_filename = sys.argv[1] x, y = loaders.data_from_tsv(tsv_filename) # # print out the scatter plot. writing PNGs does not do very well for # # functional tests, so we'll comment it out for now. # scatter = plot.scatter(x, y) # plot.setp(scatter, color='r', linewidth=0.0, alpha=0.05) # plot.savefig(sys.argv[2]) # calculate the correlation xave = sum(x) / len(x) yave = sum(y) / len(y) xsig = math.sqrt(sum((i - xave)*(i - xave) for i in x) / (len(x) - 1)) ysig = math.sqrt(sum((i - yave)*(i - yave) for i in y) / (len(y) - 1)) r = 0.0 for i, j in zip(x, y): r += (i - xave)/xsig * (j - yave)/ysig r /= len(x) - 1 print(r)
3e60eaf0d625945860cb76fbd0fd6967f74c9975
rafaelperazzo/programacao-web
/moodledata/vpl_data/380/usersdata/313/84249/submittedfiles/testes.py
119
3.75
4
n = input (' valor de n: ') i = 1 cont = 0 while i<n: if i%2 ==1: cont= cont + i print( cont )
dbcfc3e63beb8922b6fb1d7b85077b33263700c3
shivampandey7241/PPT_maker
/waandaa.py
384
3.515625
4
from wand.image import Image img = input("Image name\t") logo = input("logo name\t") naam = input("file name\t") with Image(filename= img) as image: with Image(filename= logo) as water: water.resize(1700, 600) with image.clone() as watermark: watermark.watermark(water, 0.1, 10, 20) watermark.save(filename= naam)
1baf750dbced00367c56b530dd2dc96d2a8cb3d2
marielme/Basic-for-arduino-board
/run_bas_in_arduino.py
803
3.84375
4
""" run_bas_in_arduino >> python run_bas_in_arduino.py demo.abp The extencion .abp means arduino Basic program, it doesn't be use .bas, although it is Basic, because finally the code will be parse to be interpreted in python for an arduino. Parameters ---------- arg1 : file with Basic code """ import sys from arduino_basic import * if __name__ == "__main__": file_name = sys.argv[1] # file_name = "demo.abp", demo.abp is a file with basic commands if not file_name: print('You need a input file with basic') exit(0) # creating an instance of the class ArBasProgram. program = ArBasProgram() # call an instance load_file with basic code. program.load_file(file_name) # call an instance run. program.run()
4eed803bc8d4072bf7d46404abb4d2e77d414e41
jamesliao2016/TIPMAX
/datacleaning/checktext.py
389
3.625
4
import sys # to check if each line has consistent number of row. hd = open(sys.argv[1]) for line in hd: line = line.rstrip().split(',') column = len(line) print line, len(line) break for line in hd: line = line.rstrip().split(',') if len(line) != column: print 'something is wrong' print line, len(line) exit() print 'No problem!'
1a6df4dc4c001c84e5a291d2b2db447d6036a4bf
hpellis/learnpythonthehardway
/harriet_ex12.py
258
3.71875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 28 17:07:28 2018 @author: 612383249 """ age=input("How old are you?") height=input("How tall are you?") weight=input("How much do you weigh?") print(f"So, you're {age} old, {height} tall and {weight} heavy.")
9f7cfe2f869ee71acb74b787f8e86655191e9e12
sriduth/netlab-socket-programming
/Send-File/client.py
842
3.90625
4
#including libraries import socket #creating and configuring the socket my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) #connecting to server's welcome socket my_socket.connect(("127.0.0.1",12345)) #get a file-interface for message.txt #open message.txt in read mode : "r" #other modes are "w" - write mode, "a" - append "r+" read/write message = open("message.txt","r") #read the data inside the textfile and close message_content = message.read() message.close() #send the data to server my_socket.send(message_content) #receive reply from server server_reply = my_socket.recv(1024) #printing server_reply print server_reply #reopen file in write mode and APPEND server-reply to file message = open("message.txt","a") message.write(server_reply) message.close() #close client socket my_socket.close() #program ends
d1c5829ffc3b1bb24999b0722821040da99f9226
DavidtheDJ/DSW-11-24
/Radio-Buttons/Sheep_Class.py
1,217
4.125
4
#David Justice #11-23-16 #Sheep Override from New_Animals import * class Sheep(Animal): """A sheep animal""" #construtor def __init__(self): #call the parent class constructor with default values for cow #growth rate = 1; light need = 2; water need = 5 super().__init__(1,3,6,"") self._type = "Sheep" #override frow method for subclass def grow(self,food,water): if food >= self._food_need and water >= self._water_need: if self._status == "New Born" and water > self._water_need: self._weight += self._growth_rate * 1.6 elif self._status == "Baby" and water > self._water_need: self._weight += self._growth_rate + 1.3 else: self._weight += self._growth_rate #increament day growing self._days_growing += 1 #update the status self._update_status() def main(): #create a new potato crop sheep_animal = Sheep() print(sheep_animal.report()) #manually grow the crop manual_grow(sheep_animal) print(sheep_animal.report()) manual_grow(sheep_animal) print(sheep_animal.report()) if __name__ == "__main__": main()
2562dd3d0bcbe45c06f862afac16865b2157c1d8
rdiverdi/HExBOTS
/hexbot_pkg/nodes/HExBOT_move.py
4,178
3.5625
4
""" Move function for hexbot. """ from numpy import * from Leg import * class Hexbot: def __init__(self, runrate): # lookup tables # index of array is the timestep # element of array is [x, y, z] position of leg relative to leg origin # for legs touching ground (repeats because some legs will do things on 1st timestep and some will do on the 25th.) self.runrate = runrate ''' self.walkdown = [None] * 48 self.walkup = [None] * 48 for i in range(0, 24): walkdown[i] = [6, 1.8 - (i * 3.6 / 23), -4] walkdown[i + 24] = walkdown[i] walkup[i] = ([6, -1.8 + (i * 3.6 / 23), -abs(i - 11) / 3.0]) walkup[i + 24] = walkup[i] ''' self.even_down = True self.legs = self.init_legs() self.t = 1 self.legpositions = [] # start even legs off the ground for leg in self.legs: if leg.even: leg.z = 0 leg.onground = 1 self.legpositions.extend(leg.returnangles()) def init_legs(self): legs = [] for i in range(0, 6): legs.append(Leg(i + 1)) return legs def movebot(self, command): """ Executes command. Meant to be run every timestep. Timesteps should be from 1 to 48 legs is a list of instances of legs (0-5) Returns 16-element array of servo positions. """ if command == 'walkforward': return walkforward() elif command == 'turn': print "Hahaha good one no." else: print "That's not a command I know." def walkforward(self): """ takes in the timestep (1-48) and a list of instances of the legs check the lookup tables and output the x, y, z positions of each foot with respect to its leg origin in the form of a list of 18 angles """ anglelist = [] # check which legs should be down on this step for leg in self.legs: if leg.even == evensturn: # find the x y z position for this timestep [x, y, z] = walkup[timestep] # mirror across the y axis for legs on the left else: [x, y, z] = walkdown[timestep] if leg.index < 4: x = -1 * x angles = leg.findangles(x, y, z) for (i, angle) in enumerate(angles): if leg.even != evensturn and i % 3 == 1: # find servo 1 of all legs that are down angle = angle - 18 # move servo 1 an extra 18 degrees down to account for angle loss due to holding weight anglelist.append((angle + 180) % 360 - 180) # convert angle to -180 to 180 return anglelist def walkrate(self, dx, dy, runrate): """ takes in a list of the leg instances walks in dx, dy direction (rates given in inches per second) returns the list of 18 angles for the current time """ anglelist = [] switching = False for leg in self.legs: switching = switching or leg.check_limit() print switching for leg in self.legs: if switching and leg.even: angles = leg.movespeed(dx, dy, -2, runrate) elif switching and not leg.even: angles = leg.movespeed(dx, dy, 2, runrate) else: angles = leg.movespeed(dx, dy, 0, runrate) # add 18 degrees down to servo 1 if the leg should be on the ground # maybe we should move this to findangles if leg.even: angles[1] -= 0 anglelist.extend(angles) return anglelist # create leg instances for testing. In use, these will be created in ROS_coms file if __name__=='__main__': legs = [] for i in range(0, 6): legs.append(Leg(i)) # for i in range(48): # movebot('walkforward', i, legs) # print len(walkdown) # for i in range(len(walkdown)): # print walkdown[i] # print len(walkforward(7, legs))
a2e0a2552faf1a9370eea468fd7e591e85023aa3
VitamintK/AlgorithmProblems
/hackerrank/celebrate_neurodiversity_2021/a.py
878
3.6875
4
# Autism Screening Questionnaire #!/bin/python3 import math import os import random import re import sys # # Complete the 'findOdd' function below. # # The function is expected to return a STRING. # The function accepts STRING_ARRAY series as parameter. # from collections import defaultdict def findOdd(series): seqs = defaultdict(int) for serie in series: ls = [ord(x) for x in serie] diffs = [] for i in range(1,len(ls)): diff = ls[i] - ls[i-1] diffs.append(diff) seqs[''.join(str(d) for d in diffs)] += 1 for serie in series: ls = [ord(x) for x in serie] diffs = [] for i in range(1,len(ls)): diff = ls[i] - ls[i-1] diffs.append(diff) if seqs[''.join(str(d) for d in diffs)] == 1: return serie if __name__ == '__main__':
18f40325fd55f41812b39011ff99986519493f85
cloxnu/AlgorithmLandingPlan
/CodingInterviews/13. 机器人的运动范围.py
683
3.5625
4
def movingCount(m: int, n: int, k: int) -> int: def digitsum(x: int) -> int: res = 0 while x != 0: res += x % 10 x //= 10 return res queue = [(0, 0)] res = 0 visit = {} while queue: x, y = queue.pop(0) if x >= m or y >= n or x < 0 or y < 0: continue if (x, y) in visit: continue if digitsum(x) + digitsum(y) > k: continue visit[(x, y)] = True res += 1 queue.append((x + 1, y)) queue.append((x - 1, y)) queue.append((x, y + 1)) queue.append((x, y - 1)) return res print(movingCount(2, 3, 1))
5cb0d824cf8b144719c3160791e8bda002fd7933
RyanHankss/PRG105_HoursWorked
/hoursWorked.py
315
3.546875
4
#define a function that accepts hours worked and pay rate def payment(hours, rate): my_pay = hours * rate #convert to string str_payment = str(my_pay) print("I've made $" + str_payment + " in one day.") my_hours = 6.5 my_wage = 60 # call function payment(3, 8.25) payment(my_hours, my_wage)
d1967a65b2dff05374fc2f132ab446f4adb43fec
Radu1990/Python-Exercises
/think python/src_samples_2/writting_a file.py
320
3.96875
4
#to write a file you have to open with w a second parameter fout = open('letswrite.txt', 'w') print(fout) line_0 = 'This is our first attempt to write something in a file using Python' fout.write(line_0) line_1 = '000' fout.write(line_1) line_2 = '\nNow we start to write using the new line character' fout.write(line_2)
378447137c063049f2a055b4cf760c84441ed987
dkeech/Xiangqi
/XiangqiGame.py
19,757
3.703125
4
# Author: Dan Keech # CS 162 Portfolio Project # This program defines and operates a game of Xiangqi, or Chinese chess. # Static variables for conversion from letter to number and back alpha_to_index = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9} index_to_alpha = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i'} def no_flying_general(test_board): '''Checks to make sure that a move doesn't expose a flying general''' # Create a set of generals, find the two generals in the board and insert them. generals = [] gen_set = set() # check for flying general for key, value in test_board.items(): if value.lower() == 'g': generals.append(key) # Order generals in the set by coordinates generals.sort(key=lambda x: int(x[1])) # If generals are on the same column, make a set of the items between them. If the set only has 1 item (' '), # they are flying generals. if generals[0][0] == generals[1][0]: for i in range(int(generals[0][1]) + 1, int(generals[1][1])): gen_set.add(test_board[(generals[0][0], str(i))]) if len(gen_set) == 1: return False return True class XiangqiGame: """This class contains all functions in a game of Xiangqi""" def __init__(self): # Set game state to 'UNFINISHED', initialize dict of pieces, using lower() for red and upper() for black # The board is a dict with coords: item, the item is either an empty space, an uppercase # letter, or a lowercase letter. self._board = {('a', '1'): 'R', ('a', '2'): ' ', ('a', '3'): ' ', ('a', '4'): 'P', ('a', '5'): ' ', ('a', '6'): ' ', ('a', '7'): 'p', ('a', '8'): ' ', ('a', '9'): ' ', ('a', '10'): 'r', ('b', '1'): 'K', ('b', '2'): ' ', ('b', '3'): 'C', ('b', '4'): ' ', ('b', '5'): ' ', ('b', '6'): ' ', ('b', '7'): ' ', ('b', '8'): 'c', ('b', '9'): ' ', ('b', '10'): 'k', ('c', '1'): 'E', ('c', '2'): ' ', ('c', '3'): ' ', ('c', '4'): 'P', ('c', '5'): ' ', ('c', '6'): ' ', ('c', '7'): 'p', ('c', '8'): ' ', ('c', '9'): ' ', ('c', '10'): 'e', ('d', '1'): 'A', ('d', '2'): ' ', ('d', '3'): ' ', ('d', '4'): ' ', ('d', '5'): ' ', ('d', '6'): ' ', ('d', '7'): ' ', ('d', '8'): ' ', ('d', '9'): ' ', ('d', '10'): 'a', ('e', '1'): 'G', ('e', '2'): ' ', ('e', '3'): ' ', ('e', '4'): 'P', ('e', '5'): ' ', ('e', '6'): ' ', ('e', '7'): 'p', ('e', '8'): ' ', ('e', '9'): ' ', ('e', '10'): 'g', ('f', '1'): 'A', ('f', '2'): ' ', ('f', '3'): ' ', ('f', '4'): ' ', ('f', '5'): ' ', ('f', '6'): ' ', ('f', '7'): ' ', ('f', '8'): ' ', ('f', '9'): ' ', ('f', '10'): 'a', ('g', '1'): 'E', ('g', '2'): ' ', ('g', '3'): ' ', ('g', '4'): 'P', ('g', '5'): ' ', ('g', '6'): ' ', ('g', '7'): 'p', ('g', '8'): ' ', ('g', '9'): ' ', ('g', '10'): 'e', ('h', '1'): 'K', ('h', '2'): ' ', ('h', '3'): 'C', ('h', '4'): ' ', ('h', '5'): ' ', ('h', '6'): ' ', ('h', '7'): ' ', ('h', '8'): 'c', ('h', '9'): ' ', ('h', '10'): 'k', ('i', '1'): 'R', ('i', '2'): ' ', ('i', '3'): ' ', ('i', '4'): 'P', ('i', '5'): ' ', ('i', '6'): ' ', ('i', '7'): 'p', ('i', '8'): ' ', ('i', '9'): ' ', ('i', '10'): 'r'} self._game_state = 'UNFINISHED' # RED_WON, BLACK_WON self._turn = 0 self._color = 'red' if self._turn % 2 == 0 else 'black' self._test_board = dict self._checker = None # Getter and setter for the board @property def board(self): return self._board @board.setter def board(self, d): self._board = d def print_board(self): '''Print the board as it currently stands''' board_string = ' ' for l in 'abcdefghi': board_string += f"{l} " board_string += '\n' for i in range(1, 11): for a in 'abcdefghi': board_string += f"[{self._board[(a, str(i))]}]-" board_string += f' {i}\n' if i != 5 and i != 10: for j in range(1, 10): board_string += ' | ' board_string += '\n' print(board_string) def get_game_state(self): """Returns the game state""" return self._game_state def is_in_check(self, color, check_board=None): """Tells you if a piece is in check""" general = None # Set board either to self._board or a test board to test the next move if check_board is None: board = self.board else: board = check_board # If red, find upper() G, if color.lower() == 'red': for key, value in board.items(): if value == 'G': general = key break # if a lowercase piece can move to the general's spot, return True for key in self.board: if self.board[key].islower(): if self.move_helper(key, general, board): return True # If black, find lower() g if color.lower() == 'black': for key, value in board.items(): if value == 'g': general = key break # if an uppercase piece can move to the general's spot, return True for key in self.board: if self.board[key].isupper(): if self.move_helper(key, general, board): return True return False def opposite_color(self): """Returns the opposite color to the active one""" if self._color == 'red': return 'black' else: return 'red' def count_pieces(self): """Returns a tuple of red pieces and black pieces""" # This information helps with the simplest stalemate case, where the general is the only piece left. red_pieces = 0 black_pieces = 0 for key in self.board: if self.board[key].isupper(): red_pieces += 1 elif self.board[key].islower(): black_pieces += 1 return red_pieces, black_pieces def locate_generals(self): """Find generals' location for checkmate testing""" for key, value in self.board.items(): if value == 'G': self._red_general = key if value == 'g': self._black_general = key def make_move(self, fr, to): """Moves pieces as instructed from one space to another, updates board""" # Handles universal situations: to an open space, space occupied by opponent, space occupied by same side board = self.board from_space = (fr[0], fr[1:]) to_space = (to[0], to[1:]) # False if space not on board or origin is empty if True in [to_space not in board, from_space not in board, board[from_space] == ' ']: return False # False if wrong color if True in [self._turn % 2 == 0 and self._color == 'black', self._turn % 2 != 0 and self._color == 'red']: return False if self._color == 'red' and self.board[from_space].islower(): return False if self._color == 'black' and self.board[from_space].isupper(): return False # Gets approval from move_helper, which handles individual piece cases valid = self.move_helper(from_space, to_space, self._board) # if move is not valid, return False if not valid: return False # Handle move: first test to see if it puts piece in check else: test_board = dict(self.board) test_board[to_space] = test_board[from_space] test_board[from_space] = ' ' # Use the test board to see if the move creates a flying general or puts the piece in check if no_flying_general(test_board) and not self.is_in_check(self._color, test_board): # Add to turn count, put piece in destination, make origin empty self._turn += 1 self._board[to_space] = self._board[from_space] self._board[from_space] = ' ' self.locate_generals() self._checker = to_space # After deciding that the move is valid, check to see if other color is in check # Even if piece is not in check, run checkmate() to see if game is won # check to see if solitary General can't move if self._color == 'red': if self.is_in_check('black') or self.count_pieces()[1] == 1: if self.checkmate(self._black_general): self._game_state = 'RED_WON' else: if self.is_in_check('red') or self.count_pieces()[0] == 1: if self.checkmate(self._red_general): self._game_state = 'BLACK_WON' self._color = 'red' if self._turn % 2 == 0 else 'black' return True return False def move_helper(self, fr, to, board=None): """Helps the move function by determining if move is valid""" # Handles specific piece cases if board is None: board = self.board else: board = board from_space = fr to_space = to piece = board[fr] knight_count = 0 # this keeps track of the knight's move mid-turn # if from is empty, return False. If destination has a piece, validate it as opponent. if board[from_space] == ' ': return False if board[to_space] != ' ': # Test capture to see if pieces are on the same team if board[from_space].islower() == board[to_space].islower(): return False # Test Rook, that the move is on the same row or column. if piece.lower() == 'r': if to_space[0] == from_space[0] or to_space[1] == from_space[1]: # Check to ensure there are no pieces between start and finish if self.check_between_orthogonal(from_space, to_space) > 0: return False else: return True return False # Test Cannon if piece.lower() == 'c': if to_space[0] == from_space[0] or to_space[1] == from_space[1]: # If capturing, ensure that there is exactly one piece between. if board[to_space] is not ' ': if self.check_between_orthogonal(from_space, to_space) != 1: return False elif self.check_between_orthogonal(from_space, to_space) == 1: return True if self.check_between_orthogonal(from_space, to_space) > 0: return False return True return False # Test Pawn if piece.lower() == 'p': # Move only forward until past the river, then forward or sideways. if piece.isupper(): if int(to_space[1]) == int(from_space[1]) + 1: return True if int(to_space[1]) == int(from_space[1]) - 1: return False if int(from_space[1]) >= 6 and board[to_space] == ' ' and to_space in \ [(index_to_alpha.get(alpha_to_index[fr[0]] + 1), fr[1]), (index_to_alpha.get(alpha_to_index[fr[0]] - 1), fr[1])]: return True if piece.islower(): if int(to_space[1]) == int(from_space[1]) - 1: return True if int(to_space[1]) == int(from_space[1]) + 1: return False if int(from_space[1]) <= 5 and board[to_space] == ' ' and to_space in \ [(index_to_alpha.get(alpha_to_index[fr[0]] + 1), fr[1]), (index_to_alpha.get(alpha_to_index[fr[0]] - 1), fr[1])]: return True return False # General/Advisor boundary: make sure General and Advisor only move within their area. if piece.lower() == 'g' or piece.lower() == 'a': if piece.isupper(): # set boundary if False in [alpha_to_index[to_space[0]] <= 6, alpha_to_index[to_space[0]] >= 4, int(to_space[1]) <= 3]: return False if piece.islower(): if False in [alpha_to_index[to_space[0]] <= 6, alpha_to_index[to_space[0]] >= 4, int(to_space[1]) >= 8]: return False # Test General: 1 space forward or one sideways if piece.lower() == 'g': if True not in [to_space[0] == from_space[0], to_space[1] == from_space[1]]: return False if True not in [alpha_to_index.get(to_space[0]) == alpha_to_index.get(from_space[0]) + 1, int(to_space[1]) == int(from_space[1]) + 1, alpha_to_index.get(to_space[0]) == alpha_to_index.get(from_space[0]) - 1, int(to_space[1]) == int(from_space[1]) - 1]: return False return True # Test Advisor: one space diagonal if piece.lower() == 'a': if True in [to_space[0] == from_space[0], to_space[1] == from_space[1], abs(int(to_space[1]) - int(from_space[1])) != 1]: return False # Test Elephant: two spaces diagonal, only on its side of the river. if piece.lower() == 'e': if True in [piece.isupper() and int(to_space[1]) > 5, piece.islower() and int(to_space[1]) < 6]: return False if True in [to_space[0] == from_space[0], to_space[1] == from_space[1], abs(int(to_space[1]) - int(from_space[1])) != 2, abs(alpha_to_index[to_space[0]] - alpha_to_index[from_space[0]]) != 2]: return False middle_piece = (index_to_alpha[int((int(alpha_to_index[from_space[0]]) + int(alpha_to_index[to_space[0]])) / 2)], str(int((int(from_space[1]) + int(to_space[1])) / 2))) if board[middle_piece] != ' ': return False # Test knight: check that there is no piece on the orthogonal leg or the diagonal leg of the move. if piece.lower() == 'k' and knight_count == 0: forward_gap = int(to_space[1]) - int(from_space[1]) side_gap = alpha_to_index[to_space[0]] - alpha_to_index[from_space[0]] if abs(forward_gap) == 2 and abs(side_gap) == 1: first_step = (from_space[0], str(int(from_space[1]) + int(forward_gap / 2))) if board[first_step] == ' ': return True return False elif abs(side_gap) == 2 and abs(forward_gap) == 1: first_step = ( index_to_alpha[alpha_to_index[from_space[0]] + int(side_gap / 2)], from_space[1]) if board[first_step] == ' ': return True return False return True def check_between_orthogonal(self, fr, to): '''Counts pieces between start and destination on a row or column''' fr0, fr1, to0, to1 = alpha_to_index[fr[0]], int(fr[1]), alpha_to_index[to[0]], int(to[1]) occupied_spaces = set() if fr0 == to0: if fr1 < to1: for i in range(fr1 + 1, to1): if self._board[index_to_alpha[fr0], str(i)] != ' ': occupied_spaces.add((index_to_alpha[fr0], str(i))) else: for i in range(to1 + 1, fr1): if self._board[index_to_alpha[fr0], str(i)] != ' ': occupied_spaces.add((index_to_alpha[fr0], str(i))) if fr1 == to1: if fr0 < to0: for i in range(fr0 + 1, to0): if self._board[index_to_alpha[i], str(fr1)] != ' ': occupied_spaces.add((index_to_alpha[i], str(fr1))) else: for i in range(to0 + 1, fr0): if self._board[index_to_alpha[i], str(fr1)] != ' ': occupied_spaces.add((index_to_alpha[i], str(fr1))) return len(occupied_spaces) def fake_move(self, fr, to): """Moves pieces as instructed from one space to another, updates board""" # Makes the move on a test board so that it can be checked for checkmate, flying general, stalemate board = self._test_board from_space = fr to_space = to # False if space not on board or origin is empty if True in [to_space not in board, from_space not in board, board[from_space] == ' ']: return False # Gets approval from move_helper, which handles individual piece cases valid = self.move_helper(from_space, to_space, board) # Use the test board to see if the move creates a flying general or puts the piece in check if valid and no_flying_general(board): # Add to turn count, put piece in destination, make origin empty self._turn += 1 board[to_space] = board[from_space] board[from_space] = ' ' if not self.is_in_check(self._color, board): return True return False def test_prospective_move(self, fr, to, color): """Tests a move before it is made""" # Copy current state of board to the test board self._test_board = dict(self.board) # Validate in move_helper() if self.move_helper(fr, to, self._test_board): self.fake_move(fr, to) # If the move takes piece out of check if not self.is_in_check(color, self._test_board): return True return False def checkmate(self, position): """Test to see if a position is in checkmate""" looking = True # Convert position to numbers so General moves can be calculated convert_position = (alpha_to_index[position[0]], int(position[1])) a, i = convert_position[0], convert_position[1] valid_moves = [] color = 'black' if self.board[position].islower() else 'red' # Count theoretically possible moves, including off board moves = [(a + 1, i), (a - 1, i), (a, i + 1), (a, i - 1)] # Cull on-board moves culled_moves = [move for move in moves if 9 >= move[0] > 0 and 10 >= move[1] > 0] # Convert back to str tuple moves_str = [(index_to_alpha[move[0]], str(move[1]))for move in culled_moves] # see if king can move out of check while looking: for move in moves_str: try: if self.test_prospective_move(position, move, color): valid_moves.append(move) except: pass looking = False # If there is at least one valid move, it's not checkmate. if len(valid_moves) > 0: return False return True def main(): pass if __name__ == '__main__': main()
93aa9b024c6d492fdfac21cb71e6d26080e1a21b
patrick333/euler-project-solutions
/euler006/solution.py
145
3.546875
4
#!/usr/bin/python #Sum square difference def main(): N=0 for i in range(1, 101): for j in range(i+1,101): N=N+i*j print 2*N main()
f99c94a3adccac346bf853a83f1724e900d3b56e
ericbgarnick/AOC
/y2019/saved/day10/day10.py
5,324
3.578125
4
import math import sys from fractions import Fraction from functools import partial from typing import Tuple, Set, List Point = Tuple[int, int] ASTEROID = '#' def day10_part1(puzzle_data: List[List[str]]) -> Tuple[Point, int]: max_x = len(puzzle_data[0]) max_y = len(puzzle_data) best_num_visible = 0 best_position = None asteroid_coords = _find_asteroid_coords(puzzle_data) for candidate in asteroid_coords: num_visible = 0 seen_asteroids = {candidate} for other in asteroid_coords: if other not in seen_asteroids: num_visible += 1 seen_asteroids.add(other) seen_asteroids |= set(_calc_points_in_line(candidate, other, asteroid_coords, max_x, max_y)) if num_visible > best_num_visible: best_num_visible = num_visible best_position = candidate return best_position, best_num_visible def day10_part2(puzzle_data: List[List[str]], origin: Point) -> int: laser_count = 200 max_x = len(puzzle_data[0]) max_y = len(puzzle_data) asteroid_coords = _find_asteroid_coords(puzzle_data) seen_asteroids = {origin} radii = [] for other in asteroid_coords: if other not in seen_asteroids: seen_asteroids.add(other) radius = _calc_points_in_line(origin, other, asteroid_coords, max_x, max_y) radii.append(radius) seen_asteroids |= set(radius) ordered_radii = _sort_radii(origin, radii) lasered = _laser_asteroids(ordered_radii, laser_count) last_x, last_y = lasered[-1] return last_x * 100 + last_y def _find_asteroid_coords(asteroid_map: List[List[str]]) -> Set[Point]: asteroid_coords = set() for y, row in enumerate(asteroid_map): for x, pos in enumerate(row): if pos == ASTEROID: asteroid_coords.add((x, y)) return asteroid_coords def _calc_points_in_line(candidate: Point, other: Point, asteroids: Set[Point], max_x: int, max_y: int) -> List[Point]: diff_x = other[0] - candidate[0] diff_y = other[1] - candidate[1] last_x = max_x if diff_x > 0 else -1 last_y = max_y if diff_y > 0 else -1 if diff_x != 0: slope = Fraction(diff_y, diff_x) diff_y = abs(slope.numerator) if last_y > -1 else -1 * abs(slope.numerator) diff_x = abs(slope.denominator) if last_x > -1 else -1 * abs(slope.denominator) else: diff_y = 1 if last_y > -1 else -1 diff_x = 0 if diff_x and diff_y: # diagonal x_vals = [x for x in range(candidate[0], last_x, diff_x)] y_vals = [y for y in range(candidate[1], last_y, diff_y)] points_in_line = list(zip(x_vals, y_vals)) elif diff_x: # horizontal points_in_line = [(x, candidate[1]) for x in range(candidate[0], last_x, diff_x)] else: # vertical points_in_line = [(candidate[0], y) for y in range(candidate[1], last_y, diff_y)] # skip candidate coords and those that are not asteroids return [p for p in points_in_line[1:] if p in asteroids] def _sort_radii(origin: Point, radii: List[List[Point]]) -> List[List[Point]]: sort_func = partial(_angle_from_origin, origin) return sorted(radii, key=sort_func) def _angle_from_origin(origin: Point, radius: List[Point]) -> float: origin_x, origin_y = origin point_x, point_y = radius[0] # Switch y because this coordinate system is upside-down delta_y = origin_y - point_y delta_x = point_x - origin_x if delta_x < 0 < delta_y: delta_y *= -1 to_add = math.pi elif delta_x < 0 and delta_y == 0: to_add = math.pi elif delta_x < 0 and delta_y < 0: delta_y *= -1 to_add = math.pi else: to_add = 0 try: angle = math.acos(delta_y / math.sqrt(delta_x ** 2 + delta_y ** 2)) except ZeroDivisionError: angle = 0 angle += to_add return angle def _laser_asteroids(asteroid_radii: List[List[Point]], num_shots: int) -> List[Point]: cur_radius_idx = -1 shot_asteroids = [] while len(shot_asteroids) < num_shots and len(asteroid_radii): cur_radius_idx = (cur_radius_idx + 1) % len(asteroid_radii) try: cur_radius = asteroid_radii[cur_radius_idx] except IndexError as e: raise e shot_asteroids.append(cur_radius[0]) if len(cur_radius) == 1: # drop current radius and decrement idx asteroid_radii = (asteroid_radii[:cur_radius_idx] + asteroid_radii[cur_radius_idx + 1:]) cur_radius_idx -= 1 else: cur_radius = cur_radius[1:] asteroid_radii[cur_radius_idx] = cur_radius return shot_asteroids if __name__ == '__main__': data_file = sys.argv[1] data = [list(line.strip()) for line in open(data_file, 'r').readlines()] position, visible = day10_part1(data) print(f"PART 1:\n{visible} visible asteroids from {position}") print(f"PART 2:\n{day10_part2(data, position)}")
c3eeb6e2e57956c572e9321ebb2aa10481947234
Ibbukanch/Python-programs
/pythonprograms/Functional/Factors.py
565
4.375
4
# Program to find the number of prime Factors from math import * def factors(n): #While loop will run if the number is Even list =[] while n%2==0: list.append(2) print (2,end=" ") n=n/2 x=int(sqrt(n)) #for loop will run if the Number is odd for i in range(3,x+1,2): while n%i==0: list.append(i) print (i,end=" ") n=n/i #Here it will come if the number is prime number if n>2: list.append(n) print(n) return list n=int(input("Enter the Number")) factors(n)
ddbee64118b08ce3fe945333dd44967cd2dd23d9
remo5000/vignesh-aoc-2017
/day_7a.py
469
3.578125
4
from given_inputs import day_7a_final def find_root(input): names = [line.split(' ', 1)[0] for line in input.splitlines()] number_of_parents = {name: 0 for name in names} for line in input.splitlines(): if '->' not in line: continue children = line.split('-> ')[1].split(', ') for child in children: number_of_parents[child] += 1 for program in number_of_parents: if number_of_parents[program] == 0: return program print(find_root(day_7a_final))
b035507b538e7a7ee2524e456abd892565bc2b67
tgandor/meats
/toys/math/prime_gen.py
4,001
3.765625
4
#!/usr/bin/env python # http://code.activestate.com/recipes/117119/ from __future__ import print_function from itertools import islice import argparse def eppstein(): '''Yields the sequence of prime numbers via the Sieve of Eratosthenes.''' D = {} # map composite integers to primes witnessing their compositeness q = 2 # first integer to test for primality while 1: if q not in D: yield q # not marked composite, must be prime D[q*q] = [q] # first multiple of q not already marked else: for p in D[q]: # move each witness to its next multiple D.setdefault(p+q,[]).append(p) del D[q] # no longer need D[q], free memory q += 1 def martelli(): D = {} # map composite integers to primes witnessing their compositeness q = 2 # first integer to test for primality while True: p = D.pop(q, None) if p: x = p + q while x in D: x += p D[x] = p else: D[q*q] = q yield q q += 1 def hochberg(): yield 2 D = {} q = 3 while True: p = D.pop(q, 0) if p: x = q + p while x in D: x += p D[x] = p else: yield q D[q*q] = 2*q q += 2 def me(): yield 2 D = {} q = 3 while True: if q not in D: yield q D[q*q] = [q] else: for p in D[q]: D.setdefault(p+p+q, []).append(p) del D[q] q += 2 def me_pop(): yield 2 D = {} q = 3 while True: divs = D.pop(q, None) if divs: for p in divs: D.setdefault(p+p+q, []).append(p) else: yield q D[q*q] = [q] q += 2 def me_defaultdict1(): from collections import defaultdict yield 2 D = defaultdict(list) q = 3 while True: divs = D.pop(q, None) if divs: for p in divs: D[p+p+q].append(p) else: yield q D[q*q].append(q) q += 2 def me_defaultdict2(): from collections import defaultdict yield 2 D = defaultdict(list) q = 3 while True: divs = D.pop(q, None) if divs: for p in divs: D[p+p+q].append(p) else: yield q D[q*q] = [q] q += 2 ALL_GENERATORS = [eppstein, martelli, hochberg, me, me_pop, me_defaultdict1, me_defaultdict2] def test(max_primes=25): for f in ALL_GENERATORS: print(str(f), ':') for p in islice(f(), max_primes): print(p, end=' ') print() def speed_test(max_primes=10**6): import tqdm for f in ALL_GENERATORS: print(str(f), ':') for p in tqdm.tqdm(islice(f(), max_primes), total=max_primes): # print(p, end=' ') pass print() def validate(max_primes=10**6): reference = list(islice(eppstein(), max_primes)) for f in ALL_GENERATORS[1:]: print(str(f), ':') result = list(islice(f(), max_primes)) print('OK' if result == reference else 'Fail') def output(max_primes): prime_gen = hochberg() if max_primes > 0: prime_gen = islice(prime_gen, max_primes) for p in prime_gen: print(p) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--test', action='store_true') parser.add_argument('--speed', action='store_true') parser.add_argument('--validate', action='store_true') parser.add_argument('--limit', '-n', type=int, default=10**4) args = parser.parse_args() if args.test: test(args.limit) exit() if args.validate: validate(args.limit) if args.speed: speed_test(args.limit) if not (args.speed or args.validate): output(args.limit)
21e73ce069e3ae065beb2806a14256220fef1a2c
stradtkt/Soccer-League
/league_builder.py
2,367
4.34375
4
""" 1. In your Python program, read the data from the supplied CSV file. Store that data in an appropriate data type so that it can be used in the next task. 2. Create logic that can iterate through all 18 players and assign them to teams such that each team has the same number of players. The number of experienced players on each team should also be the same. 3. Finally, the program should output a text file named -- teams.txt -- that contains the league roster listing the team name, and each player on the team including the player's information: name, whether they've played soccer before and their guardians' names. """ import csv FILE_IN = "soccer_players.csv" FILE_OUT = "teams.txt" more_xp = [] less_xp = [] def get_players(): """ Opens the soccer_players.csv file, then grabs the fieldnames and seperates the experienced from the non experienced players You would use these list items in the create_teams functions. That is the more_xp and the less_xp lists """ with open(FILE_IN) as players: fieldnames = ['Name', 'Height (inches)', 'Soccer Experience', 'Guardian Name(s)'] reader = csv.DictReader(players, delimiter=",", fieldnames=fieldnames) rows = list(reader) for row in rows: if row['Soccer Experience'] == 'NO': less_xp.append([row['Name'], row['Height (inches)'], row['Soccer Experience'], row['Guardian Name(s)']]) elif row['Soccer Experience'] == 'YES': more_xp.append([row['Name'], row['Height (inches)'], row['Soccer Experience'], row['Guardian Name(s)']]) else: del row create_teams() def create_teams(): """ Splits up the teams evenly so all teams have some with experience and some without experience """ sharks = '' dragons = '' raptors = '' for player in more_xp[0:3] + less_xp[0:3]: sharks += ', '.join(player) + '\n' for player in more_xp[3:6] + less_xp[3:6]: dragons += ', '.join(player) + '\n' for player in more_xp[6:9] + less_xp[6:9]: raptors += ', '.join(player) + '\n' with open(FILE_OUT, 'w') as new_teams: new_teams.writelines("Sharks\n" + sharks + "\n\n\n\n\n" + "Dragons\n" + dragons + "\n\n\n\n\n" + "Raptors\n" + raptors + "\n\n\n\n\n") if __name__ == '__main__': get_players()
aec83612969e919f5715e12ca9753b6720e4a895
RussAbbott/GA_examples
/truculent.py
14,038
3.6875
4
# This file is part of DEAP. # # DEAP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # DEAP is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with DEAP. If not, see <http://www.gnu.org/licenses/>. """ In the puzzle truculent: https://www.transum.org/Software/Puzzles/Truculent.asp the 8 nodes are connected in a single cycle. Numbering clockwise starting at the top right, the cycle is: 1, 4, 7, 2, 5, 8, 3, 6. We can think of this as a simple list of length 8. From this point on, we can talk in terms of such a list and not talk about the actual nodes. A solution to the puzzle will be a list of length 7, called solution, of some permutation of 7 distinct elements of 1..8. solution[i] represents the position where one (a) puts the token at step i and then (b) slides it to the left. (solution is of length 7 since we only have to put down 7 tokens.) Here is some pseudo-code that is fleshed out in Individual.set_fitness. for i in range(8): if positions[solution[i]] is empty and positions[solution[i]+1] is empty: # put a counter at positions[solution[i]] and slide it to the right (mod 8) put a counter at positions[solution[i]] else: break The fitness of the given solution is the number of tokens successfully put into the positions. """ from deap import base, tools from random import choice, random, sample """ Typically we need an Individual class and a Population class. An individual is a list of "genes". These are what get mutated. "Genes" are typically primitive elements like ints or bools. In Truculent, the "genes" are indexes into the positions list. The Population is a list of individuals. """ class Individual(list): positions = 8 indices = list(range(positions)) def __init__(self): # DEAP stores fitness values in a Fitness class, which offers some basic operations. (See base.py.) # Must set the "weights" before instantiating the Fitness class. # The weights which must be a tuple. We use it to keep track of # the actual fitness along with the rotation and the ending positions. base.Fitness.weights = (1, ) self.fitness = base.Fitness() # Define these here to keep PyCharm happy self.best_positions = None self.parent_1 = self.parent_2 = self.pre_mutation = None # The class Individual is a subclass of list. So must have a list. # Every candidate solution will be a permutation of range(8). the_list = sample(Individual.indices, Individual.positions) super().__init__(the_list) def set_fitness(self): """ Compute the fitness of this individual and store it at self.fitness.values. """ original_list = list(self) self.best_positions = ['_'] * 8 # To keep PyCharm happy positions = None # Try starting at all positions in our list and wrapping around. for i in Individual.indices: # Try all rotations of self rotation = Utils.rotate_by(original_list, i) positions = ['_'] * 8 for j in range(len(rotation)): indx = rotation[j] # Put a token at positions[indx] if it and the position # either to its left or to its right are unoccupied. # No need to worry about indx-1 being -1 since that is equivalent to index 7. if positions[indx] == '_' and (positions[indx - 1] == '_' or positions[(indx + 1) % 8] == '_'): positions[indx] = 'abcdefg'[j] else: # If we can't place any more tokens we have reached the fitness of this individual. break # Determine which rotation is best. We use this later to display the results. if (sum(positions[j] != '_' for j in range(len(positions))) > sum(self.best_positions[j] != '_' for j in range(len(self.best_positions)))): # Replace this individual with its best rotation and save the best positions record. self[:] = rotation self.best_positions = positions self.fitness.values = (sum([self.best_positions[j] != '_' for j in range(len(positions))]), ) class Population(list): """ The Population holds the collection of Individuals that will undergo evolution. """ # Which generation this is. gen = 0 # An expressions that when executed generates an individual. individual_generator = None # The size of the population pop_size = None # The maximum number of generations to allow. max_gens = None # The probabilities of performing crossover and mutation respectively. CXPB = None MUTPB = None # Whether to print intermediate output. (The default is True.) verbose = None # A reference to the DEAP toolbox. toolbox = base.Toolbox( ) def __init__(self, pop_size, max_gens, individual_generator, mate=None, CXPB=0.5, mutate=None, MUTPB=0.2, select=tools.selTournament, verbose=True): # individual_generator is a function that when executed returns an individual. # See its use in generating the population at the end of __init__. Population.individual_generator = individual_generator Population.pop_size = pop_size Population.max_gens = max_gens Population.CXPB = CXPB Population.MUTPB = MUTPB Population.verbose = verbose # Choose the genetic operators. # In the following we are using the DEAP mechanism that allows us to name operators # in the toolbox. It's a bit hokey, but it's a major aspect of how DEAP works. # Select a crossover operator. We are using our own crossover operator defined below. # We could use a built-in operator. self.toolbox.register("mate", mate) # Select a mutation operator. Again, we are using our own mutation operator. self.toolbox.register("mutate", mutate) # Select the operator for selecting individuals for the next generation. # In Tournament selection each individual of the next generation is selected # as the 'fittest' of <n> individuals drawn randomly from the current generation. # A larger <n> results in a more elitist selection process. # A tournament size of 2 will repeatedly select two random elements of the current # population put the most fit into the next population. self.toolbox.register("select", select, tournsize=2) # Create a list of Individuals as the initial population. pop = [Population.individual_generator() for _ in range(pop_size)] super().__init__(pop) def eval_all(self): """ Evaluate all elements in the population and return (one of) the fittest. """ for ind in self: if not ind.fitness.valid: ind.set_fitness( ) best_ind = tools.selBest(self, 1)[0] return best_ind def generate_next_generation(self): """ Generate the next generation. It is not returned; it replaces the current generation. """ Population.gen += 1 # Select the next generation of individuals to use as the starting point. # Use tournament selection to select the base population. # Since these are the elite elements of the population and since pop-size # are selected we will almost certainly include duplicates. # But there is no guarantee that the best is kept. offspring = self.toolbox.select(self, self.pop_size) # Now make each element a clone of itself. # We do this because the genetic operators modify the elements in place. offspring = list(map(self.toolbox.clone, offspring)) # offspring will be the new population. # Apply crossover and mutation to the offspring. # Mark those that are the result of crossover or mutation as having invalid fitnesses. # Pair the offspring off even-odd. for (child_1, child_2) in zip(offspring[::2], offspring[1::2]): # cross two individuals with probability CXPB # Set the parents to None so that we can tell whether crossover occurred child_1.parent_1 = child_1.parent_2 = None child_2.parent_1 = child_2.parent_2 = None # Keep track of what the elements were before crossover. c_1 = list(child_1) c_2 = list(child_2) if random( ) < self.CXPB: # Set the parents to c_1 and c_2 so that we can tell that crossover occurred child_1.parent_1 = child_2.parent_1 = c_1 child_1.parent_2 = child_2.parent_2 = c_2 self.toolbox.mate(child_1, child_2) # fitness values of the children must be recalculated later del child_1.fitness.values del child_2.fitness.values for mutant in offspring: mutant.pre_mutation = None # mutate an individual with probability MUTPB if random( ) < self.MUTPB: mutant.pre_mutation = list(mutant) self.toolbox.mutate(mutant) del mutant.fitness.values # The new generation replaces the current one. # Recall that self is the population. self[:] = offspring # Evaluate all individuals -- but don't re-evaluate those that haven't changed. # Return the best individual. best_ind = self.eval_all() if self.verbose: Utils.print_stats(self, best_ind) return best_ind class Utils: @staticmethod def cx_all_diff(ind_1, ind_2): """ Perform crossover between ind_1 and ind_2 without violating all_different. This is our own crossover operator. """ ind_1_new = Utils.cx_over(ind_1, ind_2) ind_2[:] = Utils.cx_over(ind_2, ind_1) ind_1[:] = ind_1_new @staticmethod def cx_over(ind_1, ind_2): inner_indices = [2, 3, 4, 5] ind_1r = Utils.rotate_by(ind_1, choice(inner_indices)) ind_2r = Utils.rotate_by(ind_2, choice(inner_indices)) indx = choice(inner_indices) child = ind_1r[: indx] + [item for item in ind_2r if item not in ind_1r[: indx]] return child @staticmethod def mut_move_elt(ind): """ This is our own mutation operator. It moves an element from one place to another in the list. """ # Ensures that the two index positions are different. [indx_1, indx_2] = sample(Individual.indices, 2) ind.insert(indx_2, ind.pop(indx_1)) @staticmethod def print_best(best_ind, label=''): cx_segment = f'{best_ind.parent_1} + {best_ind.parent_2} => ' if best_ind.parent_1 else '' mutation_segment = f'{best_ind.pre_mutation} => ' if best_ind.pre_mutation else '' print(' ' + cx_segment + mutation_segment + str(best_ind)) print(f' Best {label}individual: {best_ind}, ' f'[{", ".join(best_ind.best_positions)}], ' f'{best_ind.fitness.values[0]}' ) @staticmethod def print_stats(pop, best_ind): print(f"\n-- Generation {Population.gen}/{Population.max_gens} --") # Gather all the fitnesses in a list and print the stats. # Again, ind.fitness.values is a tuple. We want the first value. fits = [ind.fitness.values[0] for ind in pop] mean = sum(fits) / pop.pop_size sum_sq = sum(x * x for x in fits) std = abs(sum_sq / pop.pop_size - mean ** 2) ** 0.5 print(f" Min: {min(fits)}; Mean {round(mean, 2)}; Max {max(fits)}; Std {round(std, 2)}") Utils.print_best(best_ind) @staticmethod def rotate_by(lst, amt): return lst[amt:] + lst[:amt] def main(verbose=True): # Create an initial population. We are using a *tiny* population so that # the answer doesn't appear immediately. Even so the initial population # often contains a solution--no evolution required. pop = Population(pop_size=3, max_gens=50, individual_generator=Individual, mate=Utils.cx_all_diff, CXPB=0.5, mutate=Utils.mut_move_elt, MUTPB=0.2, verbose=verbose) # Evaluate the fitness of all population elements and return the best. best_ind = pop.eval_all() if verbose: Utils.print_stats(pop, best_ind) # Utils.print_best(best_ind, 'initial ') # print("\nStart evolution") # We have succeeded when the fitness shows that we can place 7 tokens. # Generate new populations until then or until we reach max_gens. success = 'unsuccessful' for _ in range(Population.max_gens): best_fit = best_ind.fitness.values[0] if best_fit == 7: success = 'successful' break best_ind = pop.generate_next_generation() print(f"\n-- After {Population.gen} generations, end of {success} evolution --") if __name__ == "__main__": main()
e27326b8eb91842ad99c3a99e39eebd4256b0a96
SebastianoBrig/compitiVacanzeSistemi
/atbash.py
506
3.921875
4
def main(): dizionario = {'a':'z', 'b':'y','c':'x','d':'w','e':'v','f':'u','g':'t','h':'s','i':'r','j':'q','k':'p','l':'o','m':'n','n':'m','o':'l','p':'k','q':'j','r':'i','s':'h', 't':'g','u':'f','v':'e','w':'d','x':'c','y':'b','z':'a'} tmp= input("insert the message ") message = tmp.lower() res="" for i in message: if i == ' ': res+=' ' else: res+=dizionario[i] print(res) if __name__=="__main__": main()
b8ed521497757db74d622fe602883f207163cab4
rafaelperazzo/programacao-web
/moodledata/vpl_data/77/usersdata/170/41998/submittedfiles/exercicio24.py
143
3.734375
4
# -*- coding: utf-8 -*- import math a=int(input('Digite a:')) b=int(input('Digite b:')) anterior=a atual=b resto=anterior%atual while resto!=0:
bb1a7fb4bf387e74cd80bd76f9f8b242055872ba
iuricuneo/docmaster
/docmaster/searchengine/filerequirer.py
1,556
3.5
4
""" Class to handle creation of commands and interfacing with file handler. """ import commands import filehandler import userrequests as ureq class FileRequirer: """ Will receive the request upon creation and process it to create a command and forward to file handler. Holds instance of file handler. FIXME: merge this in SearchEngine? """ def __init__(self): self.req = None def process_request(self, request): """ Processes given request creating a command out of it and forwarding it to file handler. Once it has been handled, process returned value to return results to search engine. :request: userrequests.Request : Request to be handled. """ self.req = request command = self.get_command() file_handler = filehandler.FileHandler(command) file_handler.handle_command() return command.result def get_command(self): """ Operates on the request to generate a command out of it. Returns an instance of the command. """ req_type = type(self.req) if req_type == ureq.CreateEntryRequest: return commands.CreateCommand(self.req.results) elif req_type == ureq.ReadEntryRequest: return commands.ReadCommand(self.req.results) elif req_type == ureq.UpdateEntryRequest: return commands.UpdateCommand(self.req.results) elif req_type == ureq.DeleteEntryRequest: return commands.DeleteCommand(self.req.results)
c57ebff4467629cf707461ab0ce6474968ce7716
richardneililagan/euler
/python/algorithms/0057.py
558
3.828125
4
#!/usr/bin/env python3 from functools import lru_cache # :: --- @lru_cache(maxsize = None) def pn (n): """ P(n) = 2 + (1 / P(n - 1)) where P(1) = 2 returns (a, b) where a, b is (a / b) in fractional form """ if n <= 1: return (2, 1) # :: --- a, b = pn(n - 1) return b + 2 * a, a def generator (end): for n in range(end): a, b = pn(n) yield b + a, a def main (): g = generator(1000) print(sum(1 for a, b in g if len(str(a)) > len(str(b)))) # :: --- if __name__ == "__main__": main()
ed924830ba940a4c966205a35a246894d02affbc
jasonromulus/Generator
/histogram_tuple.py
848
4.125
4
source_text = "one fish two fish red fish blue fish" # Got help from Jackson Ho def histogram_tuple(source_text): # create tuple list histogram_tuple = [] for word in source_text: found = False # loops through my tuple for index, value in enumerate(histogram_tuple): # this checks if tuple and word match if value[0] == word: num = value[1] + 1 found = True # this takes out the tuple histogram_tuple.pop(index) # this takes new word and appends it to the list histogram_tuple.append((word, num)) break # this is for if the word is not found if not found: histogram_tuple.append((word, 1)) if __name__ == '__main__': histogram_tuple(source_text)
33ec9efbddc8238cb4752d7dcd2570a1913b0260
gauravburjwal/100DaysOfCode
/Programs/Day002/binary_search.py
281
3.90625
4
def binary_search(nums, item): first = 0 last = len(nums) - 1 found = False while( first <= last and not found): mid = (first + last) // 2 if nums[mid] == item : found = True else: if item < nums[mid]: last = mid - 1 else: first = mid + 1 return found
3b50a7b2360678b0c3ebd143bcf029558e958271
RumenKotsew/PythonPlayground
/week1/anagrams.py
300
3.953125
4
def is_anagram(word1, word2): word1 = word1.lower() word2 = word2.lower() for i in word1: if i in word2: word1 = word1.replace(i, "", 1) word2 = word2.replace(i, "", 1) if word1 == "" and word2 == "": return True else: return False
73d297d20d1a8aef6c98f402d296de7e93d8ea42
chris-martin/hocon-python
/hocon/impl/PathBuilder.py
1,512
3.515625
4
from .. import exceptions class PathBuilder(object): """ Attributes: _keys: Stack<String> - the keys are kept "backward" (top of stack is end of path) _result: Path """ def __init__(self): self._keys = [] self._result = None def _check_can_append(self): if self._result is not None: raise exceptions.BugOrBroken( "Adding to PathBuilder after getting result") def append_key(self, key): """ :param key: String :return: None """ self._check_can_append() self._keys.append(key) def append_path(self, path): """ :param path: Path :return: None """ self.checkCanAppend() first = path.first # String remainder = path.remainder # path while True: self._keys.append(first) if remainder is not None: first = remainder.first remainder = remainder.remainder else: break def result(self): """ :return: Path """ # note: if keys is empty, we want to return null, which is a valid # empty path if self._result is None: remainder = None # Path while len(self._keys) != 0: key = self._keys.pop() # String remainder = Path(key, remainder) self._result = remainder return self._result
11351e2cf872b788e7aa28217ae6b611d4a0c2ec
anasahmed700/python
/6thClass/Classes/car.py
1,919
4.0625
4
class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometerReading = 500 # OBJECT 9 STEP def descriptive_name(self): longName = str(self.year) + ' ' + self.make.title() + ' ' + self.model return longName # Modifying an Attribute’s Value Through a Method def update_odometer(self, mileage): # from OBJECT 10 STEP if mileage >= self.odometerReading: self.odometerReading = mileage else: print('you can\'t roll back the odometer!') # Incrementing an Attribute’s Value Through a Method def increment_odometer(self, miles): self.odometerReading += miles def get_odometer(self): # from OBJECT 10 STEP return 'This car has '+str(self.odometerReading)+ ' miles on it.' def __str__(self): # FROM OBJECT 12 return "Make = " + self.make + ", Model = " + self.model + ", Year = " + str(self.year) # class Battery(): # """A simple attempt to model a battery for an electric car.""" # def __init__(self, battery_size=70): # """Initialize the battery's attributes.""" # self.battery_size = battery_size # # def describe_battery(self): # """Print a statement describing the battery size.""" # print("This car has a " + str(self.battery_size) + "-kWh battery.") # # def get_range(self): # if self.battery_size == 70: # range = 240 # elif self.battery_size == 85: # range = 270 # massage = 'this car can go approximately ' + str(range) # massage += ' miles on a full charge!' # print(massage) # # class ElectricCar(Car): # def __init__(self,make,model,year): # super().__init__(make,model,year) # self.battery = Battery()
46f058c8ebd28b6d877262d8581d3a54dbeb52a8
ClarkeJ2000/CA117-Programming-2
/week8_vid1.py
234
3.6875
4
class Time(object): def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute slef.second = second def __str__(self): return '{:02d}:{:02d}:{:02d}'.format(self.hour, self.minute, self.second)
76ff7ae70f3750d6a36d08fc0a3d552d92779de3
Jose-Humberto-07/pythonFaculdade
/listas/nomes.py
157
3.921875
4
print("Nomes") nomes = [] for i in range(10): print("Informe 10 nomes: ") nomes.append(input()) nomes.sort(reverse=True) print(nomes)
63701b8e385f8e01c36891a54d8743259f459193
rcmadden/30DaysOfCode
/00_todo.py
1,246
3.859375
4
# http://echorand.me/site/notes/articles/python_custom_class/article.html ''' class Point: def __init__(self): #print('Self identifier:: ', id(self)) #if __name__ == '__main__': # create an instance of the class # p = Point() # print('Point object identifier {}'.format(id(p))) # p = Point() # print('Point object identifier', id(p)) ''' ''' class Point: def __init__(self, point): self.point = point #print('Self identifier:: ', id(self)) ( # returns the string representation of the point (str(self.point)) def __str__(self): return 'Point: {0}'.format(str(self.point)) p1 = Point((1,2,3)) print(p1) ''' class List: def __init__(self): list_id = id(self) title = "Todo" type = ('Todo', 'Shopping') members = "" items ="Add items to your list" print(list_id,title, type, members, items) class Items: def __init__(self): item_id = id(self) status = ("Todo", "Done", "Asssigned", "Owner") class Members: member_id = id(self) lists = # call list object items = "Get started" groups = "Self" privilages = "owner" if __name__ == '__main__': DueToday = List() print(DueToday)
9d7ddfebe6c97f7bbe5938e4063e0ddd24367842
9838dev/coding
/arrays/sort_array.py
357
3.78125
4
# sort array which contains 0's,1's,2's def sort_array(arr): count=[0]*3 for i in arr: count[i]+=1 for i in range(1,3): count[i]+=count[i-1] temp = arr.copy() for i in range(len(arr)): arr[count[temp[i]]-1] = temp[i] count[temp[i]]-=1 arr=[2,2,1,1,0,0,0,0,1,2,2,2,0,0,0,0,1] sort_array(arr) print(arr)
450ac24c87acb32a46c2786f1d93b08d02142e26
gdevine/HIEv_stats
/hiev_stats.py
6,288
3.515625
4
''' Python script to return a series of stats from the HIEv database Author: Gerard Devine Date: September 2015 - Note: A valid HIEv API key is required ''' import os import json import urllib2 import csv from datetime import datetime, date, timedelta def get_hiev_csv(filename): ''' Function that downloads and returns a csv-reader object of the most recent facilities or experiments info file from HIEv ''' request_url = 'https://hiev.uws.edu.au/data_files/api_search' api_token = os.environ['HIEV_API_KEY'] request_headers = {'Content-Type' : 'application/json; charset=UTF-8', 'X-Accept': 'application/json'} request_data = json.dumps({'auth_token': api_token, 'filename': filename}) # --Handle the returned response from the HIEv server request = urllib2.Request(request_url, request_data, request_headers) response = urllib2.urlopen(request) js = json.load(response) # Grab the latest - in those cases where there are multiple resukts returned js_latest = (sorted(js, key=lambda k: k['updated_at'], reverse=True))[0] download_url = js_latest['url']+'?'+'auth_token=%s' %api_token request = urllib2.Request(download_url) f = urllib2.urlopen(request) return csv.reader(f, delimiter=',', quotechar='"', skipinitialspace=True) def match_count(match_dict, jsondata): ''' Function that recieves a key to match, the value to match it against and returns the number of matching entries found within the supplied json data ''' count = 0 #loop through each record of the json for record in jsondata: #check all key value pairs against the current record and add to count if all are present matched = True for key in match_dict: if record[key]: if str(record[key]) != str(match_dict[key]): matched = False break else: matched = False count += matched return count; ## MAIN PROGRAM # -- Set global http call values request_url = 'https://hiev.uws.edu.au/data_files/api_search' api_token = os.environ['HIEV_API_KEY'] request_headers = {'Content-Type' : 'application/json; charset=UTF-8', 'X-Accept': 'application/json'} # -- Get listing of all HIEv files request_data = json.dumps({'auth_token': api_token}) request = urllib2.Request(request_url, request_data, request_headers) response = urllib2.urlopen(request) js_all = json.load(response) # -- Get listing of HIEv files uploaded in the last day upload_from_date = str(date.today() - timedelta(days=1)) upload_to_date = str(date.today()- timedelta(days=0)) request_data = json.dumps({'auth_token': api_token, 'upload_from_date': upload_from_date, 'upload_to_date': upload_to_date}) request = urllib2.Request(request_url, request_data, request_headers) response = urllib2.urlopen(request) js_lastday = json.load(response) # -- Begin writing the stats dictionary hiev_stats = {} # root element hiev_stats['hiev_stats'] = {} # Include date and time of when the sript was run hiev_stats['hiev_stats']['date_generated'] = str(datetime.today().strftime("%a %b %d %Y - %H:%M")) # total files hiev_stats['hiev_stats']['total_files'] = len(js_all) # files uploaded in the last day hiev_stats['hiev_stats']['last_day_files'] = len(js_lastday) # files by type types = hiev_stats['hiev_stats']['types'] = [] for type in ['RAW', 'PROCESSED', 'CLEANSED', 'ERROR', 'PACKAGE', 'UNKNOWN']: type_record = {} type_record['type'] = type type_record['total_files']=match_count({'file_processing_status':type}, js_all) type_record['last_day_files']=match_count({'file_processing_status':type}, js_lastday) types.append(type_record) # begin facilities nested section, first reading in the facility and experiment information from the most recent HIEv files # convert each to a list - makes it easier to reiterate over facilities_csv = list(get_hiev_csv('HIEv_Facilities_List_'))[1:] experiments_csv = list(get_hiev_csv('HIEv_Experiments_List_'))[1:] facilities = hiev_stats['hiev_stats']['facilities'] = [] for facrow in facilities_csv: fac_record={} fac_record['id'] = facrow[0] fac_record['name'] = facrow[1] #get a count of the total number of files uploaded for this facility fac_record['total_files'] = match_count({'facility_id': str(facrow[0])}, js_all) #get a count of the number of files uploaded in the last 24 hours for this facility fac_record['last_day_files'] = match_count({'facility_id': str(facrow[0])}, js_lastday) # finally append the facility record to the full facilities list facilities.append(fac_record) # Type by facility - For each facility begin a 'type' nested section types = fac_record['Types'] = [] for type in ['RAW', 'PROCESSED', 'CLEANSED', 'ERROR', 'PACKAGE', 'UNKNOWN']: type_record = {} type_record['type'] = type type_record['total_files']=match_count({'facility_id': str(facrow[0]), 'file_processing_status':type}, js_all) type_record['last_day_files']=match_count({'facility_id': str(facrow[0]), 'file_processing_status':type}, js_lastday) types.append(type_record) # For each facility begin an experiments nested section, reading in experiment information from the most recent HIEv file experiments = fac_record['experiments'] = [] # Loop over experiment csv and pull out any lines that match the current facility ID for exprow in experiments_csv: if exprow[1] == facrow[0]: exp_record={} #add the ID and name of the matching experiment exp_record['id'] = exprow[0] exp_record['name'] = exprow[2] #get a count of the total number of files uploaded for this experiment exp_record['total_files'] = match_count({'experiment_id':str(exprow[0])}, js_all) #get a count of the number of files uploaded in the last 24 hours for this experiment exp_record['last_day_files'] = match_count({'experiment_id':str(exprow[0])}, js_lastday) # finally append the facility record to the full facilities list experiments.append(exp_record) # -- Write the data to json file with open('hiev_stats.json', 'w') as f: json.dump(hiev_stats, f, sort_keys = True, indent = 4, ensure_ascii=False) f.close()
7276128abf4351cb1d0219ab802444dcd5ad88a2
ArnabG99/BeginnerPythonPrograms
/isVowel.py
174
4.25
4
ch = input("Enter character: ") ch = ch.lower() if(ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u"): print("Is a vowel") else: print("Not a vowel")
9833d999f22c137e01b9280de220d7c717065313
FronTexas/Fron-Algo-practice
/maximal_square_code_fights.py
2,132
3.734375
4
def isValidIndex(matrix,i,j): return 0<=i and i < len(matrix) and 0<=j and j < len(matrix[i]) def follows_prev_top_left(matrix,i,j): return isValidIndex(matrix,i-1,j-1) and matrix[i-1][j-1] == '1' and isValidIndex(matrix,i-1,j) and matrix[i-1][j] == '1' and isValidIndex(matrix,i,j-1) and matrix[i][j-1] == '1' def printAt(current_i,current_j,i,j,current,h,l,square_height,square_length,cell_matrix,x,y): if current_i == i and current_j ==j: print '------------' print '(i,j) = ' + str((i,j)) print 'current_top_left = ' + str(current['top_left']) print 'x,y = ' + str((x,y)) print 'h = ' + str(h) print 'l = ' + str(l) print 'square_height = ' + str(square_height) print 'square_length = ' + str(square_length) def maximalSquare(matrix): cell_matrix = [[{'top_left':(0,0),'length':0,'height':0} for i in range(len(matrix[0]))] for j in range(len(matrix))] max_answer = 0 for i in range(len(matrix)): for j in range(len(matrix[i])): current = cell_matrix[i][j] if matrix[i][j] == '1': current['length'] = 1 current['height'] = 1 l = cell_matrix[i][j-1]['length'] if isValidIndex(matrix,i,j-1) else 0 h = cell_matrix[i-1][j]['height'] if isValidIndex(matrix,i-1,j) else 0 x,y = cell_matrix[i-1][j-1]['top_left'] if isValidIndex(matrix,i-1,j-1) and matrix[i-1][j-1] == '1' else (i,j) current['top_left'] = (max(i-h,x), max(j-l,y)) current_x,current_y = current['top_left'] square_height = i - current_x + 1 square_length = j - current_y + 1 if square_length == square_height: max_answer = max(max_answer,square_length * square_height) current['length'] += l current['height'] += h return max_answer matrix = [ ['1','0','1','0','0'], ['1','0','1','1','1'], ['1','1','1','1','1'], ['1','0','0','1','0'] ] print maximalSquare(matrix)
efb68b24fc0ecf0513d4ff3c609b5568bd1de75c
pinheirogus/Curso-Python-Udemy
/POO/Agregacao/aula105_classes.py
578
3.84375
4
# Objetos existem independentes class CarrinhoDeCompras: def __init__(self): self.produtos = [] def inserir_produto(self, produto): self.produtos.append(produto) def listar_produtos(self): for produto in self.produtos: print(f' {produto.nome}, R$ {produto.valor:.2f}') def somar_total(self): total = 0 for produto in self.produtos: total += produto.valor return f' R$ {total:.2f}' class Produto: def __init__(self, nome, valor): self.nome = nome self.valor = valor
e32257dcb1b667fad6a443e4a0625c8d8fad9078
Pyk017/Competetive-Programming
/GFG/Arrays/Find all pairs with a given sum/solution.py
1,157
3.515625
4
#User function Template for python3 class Solution: def allPairs(self, A, B, N, M, X): ans = dict() res = [] for item in B: ans[X - item] = item # print(ans) for item in A: if item in ans: res.append([item, ans[item]]) return sorted(res) #{ # Driver Code Starts #Initial Template for Python 3 def main(): T = int(input()) while(T > 0): sz = [int(x) for x in input().strip().split()] N, M, X = sz[0], sz[1], sz[2] A = [int(x) for x in input().strip().split()] B = [int(x) for x in input().strip().split()] ob=Solution() answer = ob.allPairs(A, B, N, M, X) sz = len(answer) if sz==0 : print(-1) else: for i in range(sz): if i==sz-1: print(*answer[i]) else: print(*answer[i], end=', ') T -= 1 if __name__ == "__main__": main() # } Driver Code Ends
8d5d591c3d9b3b74a08b9fb9b8d8004d5e7a6db8
NevssZeppeli/my_ege_solutions
/19.06/пробник от 7.06/2-1422.py
243
4.03125
4
print('x', 'y','w','z') for x in range(2): for y in range(2): for w in range(2): for z in range(2): if (not (z and (not w)) or ( (z <= w) == (x <= y) )) == False: print(x,y,w,z)
748bfa678f47744f6e953012e700c7de28b2dc4e
Xavier577/DSA
/data_structures/Stack/stack.py
442
3.71875
4
class stack: def __init__(self): self.store = [] def push(self, value): self.store.append(value) def pop(self): return self.store.pop() def peek(self): return self.store[len(self.store) - 1] def contains(self, value): return value in self.store def values(self): return list(self.store) def isEmpty(self): return True if len(self.store) < 1 else False
d1bd1009ec64bc64407ae8e09785e410fac622be
JoseVictorAmorim/CursoEmVideoPython
/cursoemvideo/ex0014.py
219
3.984375
4
celsius = float(input('Qual o valor da temperatura em ºC? ')) kelvin = celsius+273 farenheit = ((celsius*9)+160)/5 print('A temperatura de {}ºC equivale a {:.2f}ºK e a {:.2f}ºF!'.format(celsius, kelvin, farenheit))
0c5daa01a3e74106c1b91034f43a577f16d43c32
hongwenshen/Python_Study
/Python 100例/Python 练习实例97.py
592
3.625
4
#!/usr/bin/env python # coding=UTF-8 ''' @Description: About practicing python exercises @Author: Shenhongwen @LastEditors: Shenhongwen @Date: 2019-03-21 20:59:49 @LastEditTime: 2019-03-21 21:03:31 ''' ''' 题目:从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。 ''' if __name__ == "__main__": from sys import stdout filename = input('输入文件名:\n') fp = open(filename, "w") ch = input('输入字符串:\n') while ch != '#': fp.write(ch) stdout.write(ch) ch = input('') fp.close()
c72dd7fec6980047981238f264cca783a9cbff2c
Hanlen520/Leetcode-4
/src/110. 平衡二叉树.py
806
3.859375
4
""" 给定一个二叉树,判断它是否是高度平衡的二叉树。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 这里注意两点 # 1. 这里的result变量没法在depth函数里使用,必须加self # 2. 求二叉树的深度要记住 class Solution: def isBalanced(self, root: TreeNode) -> bool: self.result = True def depth(root): if root: dep_left, dep_right = depth(root.left), depth(root.right) if abs(dep_left - dep_right) >= 2: self.result = False return max(dep_left, dep_right) + 1 else: return 0 depth(root) return self.result
eeba17ee5064c671ee5f75da5a6e0a984e839900
cuber-it/aktueller-kurs
/Tag5/zugriff_kontrolliert_java_style.py
793
3.5
4
class Calculon: def __init__(self, start_value=0): self._acc = str(start_value) def add(self, value): # sieht doof aus, aber ich habe entschieden das so zu implementieren # da intern, geht es neimand was an! berechnung = int(self._acc) + value self._acc = str(berechnung) def sub(self, value): berechnung = int(self._acc) - value self._acc = str(berechnung) # Java style - nicht so gut # Gewinn: intern können die Daten vorliegen wie sie wollen# der Bentzer bekommt immer int bzw kann immer int geben def set_value(self, value): self._acc = str(value) def get_value(self): return int(self._acc) c = Calculon() c.add(5) print(c.get_value()) c.set_value(0) c.sub(5) print(c.get_value())
154f6e54795f6c051d8fbf2fa99d2c327118f12a
cascales27/m02_boot_0
/tablamultiplicar.py
309
3.828125
4
def tablaMult(n): try: resultado = int(n) except: resultado = None return resultado numero = None while numero == None: strNumero = input("Introduzca valor: ") numero = tablaMult(strNumero) for i in range(1, 11): print("{} x {}".format(numero, i, numero * i))
6fe3c0cabb88876bae4f8a2fa406ffc8dcf1894e
Rohitparihar1182/Tkinter-projects
/rock_paper_scissor.py
2,299
3.671875
4
from tkinter import * import random def game(event): var=event.widget.cget("text") global options var2=options[random.randint(0,2)] com.set(var2) if var==options[0]: if var2==options[0]: str1.set("TIE") elif var2==options[1]: str1.set("LOSE") x=s1.get() x+=1 s1.set(x) elif var2==options[2]: str1.set("WIN") x=s2.get() x+=1 s2.set(x) elif var==options[1]: if var2==options[0]: str1.set("WIN") x=s2.get() x+=1 s2.set(x) elif var2==options[1]: str1.set("TIE") elif var2==options[2]: str1.set("LOSE") x=s1.get() x+=1 s1.set(x) elif var==options[2]: if var2==options[0]: str1.set("LOSE") x=s1.get() x+=1 s1.set(x) elif var2==options[1]: str1.set("WIN") x=s2.get() x+=1 s2.set(x) elif var2==options[2]: str1.set("TIE") root=Tk() root.geometry("900x900") root.minsize(900,900) root.maxsize(900,900) root.configure(bg="yellow") root.title("Welcome to Rock Paper n Scissor game") options=[" Rock "," Paper ","Scissor"] colours=["red","white","green"] Label(root,text="Computer",font=("arial",20)).place(x=10,y=10) com=StringVar() com.set("") Com_entry=Entry(root,textvariable=com,font=("arial",20)).place(x=10,y=50,height=30,width=100) Label(root,text="Score",font=("arial",20)).place(x=700,y=10) Label(root,text="Com|You",font=("arial",20)).place(x=700,y=50) s1=IntVar() s1.set(0) s1_entry=Entry(root,textvariable=s1,font=("arial",20)).place(x=700,y=80,height=30,width=60) s2=IntVar() s2.set(0) s2_entry=Entry(root,textvariable=s2,font=("arial",20)).place(x=760,y=80,height=30,width=60) for i in range(3): B=Button(root,text=options[i],bg=colours[i],padx=60,pady=40,relief=SUNKEN) B.pack() B.bind("<Button-1>",game) str1=StringVar() str1.set("") E=Entry(root,textvariable=str1,fg="yellow",bg="blue",font=("arial",40,"bold")).place(x=200,y=400,height=200,width=200) root.mainloop()
6ccde65be7290128a5d3d245462af76ba677f9f9
sanyache/algorithm
/BubbleSort.py
302
4.09375
4
def bubblesort(DataList): for i in range(len(DataList)-1): for j in range(len(DataList)-1-i): if DataList[j] > DataList[j+1]: DataList[j], DataList[j+1] = DataList[j+1], DataList[j] return DataList DataList = [3,5,6,1,4] bubblesort(DataList) print DataList
5e094834d765f0e40c694269e6c40c7fc84884cb
SandeepPadhi/Algorithmic_Database
/Array/quicksort.py
1,215
3.5625
4
from itertools import permutations A=[54, 546, 548, 60] def partition(low,high): global A pivot=A[high] pindex=high for i in range(low,high+1): if i<pindex: if A[i]<=pivot: A[pindex],A[i]=A[i],A[pindex] pindex-=1 else: break A[pindex],A[high]=A[high],A[pindex] print(pindex) return pindex def quicksort(low,high): if low<high: p=partition(low,high) quicksort(low,p-1) quicksort(p+1,high) quicksort(0,len(A)-1) print(A) """ Quicksort 2: # Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. A=[54, 546, 548, 60,313,1,2,3,1,2,112] def partition(low,high): global A #descending order pindex=high pivot=A[low] for i in range(high,low,-1): if A[i]<pivot: A[pindex],A[i]=A[i],A[pindex] pindex-=1 A[pindex],A[low]=A[low],A[pindex] return pindex def quicksort(low,high): if low<high: p=partition(low,high) quicksort(low,p-1) quicksort(p+1,high) quicksort(0,len(A)-1) print(A) """
f45312411cf79ede6b1b2e6765d5049e220a5bde
Risvy/30DaysOfLeetCode
/Day_20/20.py
325
3.84375
4
/* https://leetcode.com/problems/reverse-words-in-a-string-iii/ Tags: String, Easy */ class Solution: def reverseWords(self, s: str) -> str: s2= s.split() ans="" for i in s2: ans= ans+i[::-1]+" " ans= ans[:len(ans)-1:] return ans
c26133d9fb80434e1736b256612cba7324dae20a
rarezhang/leetcode
/math/172.FactorialTrailingZeroes.py
1,024
4
4
""" Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. trailing zeros are a sequence of 0 in the decimal representation (or more generally, in any positional representation) of a number, after which no other digits follow. """ # top solution # Because all trailing 0 is from factors 5 * 2. # But sometimes one number may have several 5 factors, for example, 25 have two 5 factors, 125 have three 5 factors. In the n! operation, factors 2 is always ample. So we just count how many 5 factors in all number from 1 to n. class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int """ result = 0 while n >= 5: n /= 5 result += n return result class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int """ return 0 if n == 0 else n / 5 + self.trailingZeroes(n/5)
45309a36590ee0987751f788fa7b055b2702f058
syurskyi/Python_Topics
/100_databases/001_sqlite/examples/Introduction_to_SQLite_Databases_for_Python_Programming/02.Using SQLite With Python/0202.Create A Database Table.py
435
3.796875
4
import sqlite3 # connect to database # conn = sqlite3.connect(':memory:') conn = sqlite3.connect('customer.db') # Create a cursor c = conn.cursor() # Create a Table c.execute("""CREATE TABLE customers ( first_name text, last_name text, email text )""") # Datatypes: # NULL # INTEGER # REAL # TEXT # BLOB # Commit our command conn.commit() # Close our connection conn.close()
28af100ef56bfc3ff9dc8cda2c6175a46b759bec
jordanjj8/exercising_with_python
/IF.py
786
4.1875
4
# Jordan Leung # 2/13/2019 # 5-8 Hello Admin usernames = ['jjleung', 'nubcake', 'jordanjj8', 'jordanl', 'jjleung88'] #usernames = [] if usernames: for username in usernames: if username == 'jjleung': print("Hello Student, would you like to see your grades?") else: print("Hello boob, you have entered old usernames that Jordan used to use...") else: print("Please type in usernames! ") # 5-10 checking new usernames current_users = usernames[:] new_users = ['hello', 'singer_babe', 'jordanl', 'guitar_lover', 'jjleung'] for user in new_users: if user in current_users: print("Please replace " + user + " and add a new username") else: print("Adding username " + user + " to the list")
1b43cd7daf09f34773c1763a3773e33c3518a782
adistar01/Madlibs
/Samples/py1.py
1,012
3.734375
4
def madlib(): adj1 = input("Enter an adjective : ") noun1 = input("Enter a noun : ") verb1 = input("Enter a verb(past) : ") adverb1 = input("Enter an adverb : ") adj2 = input("Enter an adjective : ") noun2 = input("Enter a noun : ") noun3 = input("Enter a noun : ") adj3 = input("Enter an adjective : ") verb2 = input("Enter a verb: ") adverb2 = input("Enter an adverb : ") verb3 = input("Enter a verb(past) : ") adj4 = input("Enter an adjective : ") mad = f"Today I went to the zoo.I saw a(n) {adj1} {noun1} jumping up and down on a tree. He {verb1} {adverb1} through the large tunnel that led to its {adj2} {noun2}. I got some peanuts and passed them through the cage to a gigantic grey {noun3} towering above my head. Feeding that animal made me hungry. I went to get a {adj3} scoop of ice cream. It filled my stomach. Afterwards, I had to {verb2} {adverb2} to catch our bus. When I got home, I {verb3} my mom for a {adj4} day at the zoo." return mad
183784dd59cc050d4433339538e72e2bec59f989
lspshun/woaipython
/面向对象进阶/重写父类方法.py
869
3.890625
4
# 所谓重写,就是子类中,有一个和父类相同名字的方法,在子类中的方法会覆盖掉父类中同名的方法 #coding=utf-8 class Cat(object): def sayHello(self): print("halou-----1") class Bosi(Cat): def sayHello(self): print("halou-----2") bosi = Bosi() bosi.sayHello() '''调用父类的方法 #coding=utf-8 class Cat(object): def __init__(self,name): self.name = name self.color = 'yellow' class Bosi(Cat): def __init__(self,name): # 调用父类的__init__方法1(python2) #Cat.__init__(self,name) # 调用父类的__init__方法2 #super(Bosi,self).__init__(name) # 调用父类的__init__方法3 super().__init__(name) def getName(self): return self.name bosi = Bosi('xiaohua') print(bosi.name) print(bosi.color) '''
f366af8ac31e05ccb9664448e59f5026e96e7b18
sherms77/isLower
/isLower3.py
355
4.1875
4
# Pg.80 - How to think like a cs # example 3 # refer to isLower1.py for notes import string def isLower3(ch): return 'a' <= ch <= 'z' print(isLower3('e')) # in['e']: print(isLower1('e')) out['e']: True print(isLower3('E')) # in['E']: print(isLower1('E')) out['E']: False # Python 2 code from book: # def isLower(ch): # return 'a' <= ch <= 'z'
e1041dfdf73709e1a38217bf03bad519848c4338
CeeGeeArt/P3
/Team.py
565
3.828125
4
class Team: points = 0 name = "" # constructor def __init__(self, name): self.name = name # Getters def getPoints(self): return self.points def getName(self): return self.name # Setters / add one point # setName only relevant if the teams should be able to change their names. def setName(self, name): self.name = name def setPoints(self, points): self.points = points def addPoint(self): self.points += 1 def addDoublePoints(self): self.points += 2
9d37679d4c17fdb544d5caab1f4178e9cc0c08a3
green-fox-academy/peterjuhasz
/week-3/python/project_sudoku/sudoku_purecode_codewars_draft.py
3,636
3.578125
4
puzzle = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] compare_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] def zero_rowindexes(row, matrix): zeros_indexes_in_row = [] for i in range(len(matrix[row])): if matrix[row][i] == 0: zeros_indexes_in_row.append(i) return zeros_indexes_in_row def collect_numbers_row(row, matrix): collected_numbers_in_row = [] for i in range(len(matrix[row])): if matrix[row][i] != 0: collected_numbers_in_row.append(matrix[row][i]) return collected_numbers_in_row def collect_numbers_column(column, matrix): collected_numbers_in_column = [] for i in range(len(matrix[column])): if matrix[i][column] != 0: collected_numbers_in_column.append(matrix[i][column]) return collected_numbers_in_column def collect_numbers_square(row,column, matrix): if row < 3: s_row = 0 elif row < 6: s_row = 3 else: s_row = 6 if column < 3: s_column = 0 elif column < 6: s_column = 3 else: s_column = 6 square_column = 0 collected_numbers_in_square = [] while square_column < 3 : for r in range(len(matrix[:3])): if matrix[s_row][s_column+r] != 0: collected_numbers_in_square.append(matrix[s_row][s_column+r]) s_row += 1 square_column += 1 return collected_numbers_in_square def collect_numbers_for_zero(row, column, matrix): a = collect_numbers_column(column, matrix) b = collect_numbers_row(row, matrix) c = collect_numbers_square(row, column, matrix) all_number_for_zero = a + b + c return len(set(all_number_for_zero)) def missing_numbers(row, column, matrix): a = collect_numbers_column(column, matrix) b = collect_numbers_row(row, matrix) c = collect_numbers_square(row, column, matrix) all_number_for_zero = a + b + c missing_number=(set(compare_list) - set(all_number_for_zero)) return missing_number def matrix_print(a): print(a[0]) print(a[1]) print(a[2]) print(a[3]) print(a[4]) print(a[5]) print(a[6]) print(a[7]) print(a[8]) print('\n') def optimum_list(row, matrix): row = 0 while row < 9: zero_value = [] row_zero_value = [] for r in range(len(zero_rowindexes(row,matrix))): zero_value.append(collect_numbers_for_zero(row, zero_rowindexes(row, matrix)[r], matrix)) row += 1 print (zero_value) return(zero_value) def solution(matrix): row = 0 run = 0 while row < 9: change = 0 szam = 0 r = 0 while r < len(zero_rowindexes(row, matrix)): if collect_numbers_for_zero(row, zero_rowindexes(row, matrix)[r], matrix) == 8: puzzle[row][zero_rowindexes(row, matrix)[r]] = (missing_numbers(row, zero_rowindexes(row, matrix)[r], matrix)).pop() else: r += 1 row += 1 return puzzle def is_solved(matrix): for n in range(len(matrix)): for i in range(len(matrix[n])): if matrix[n][i] == 0: return False return True def sudoku(puzzle): while is_solved(puzzle) == False: puzzle = solution(puzzle) return puzzle print(sudoku(puzzle)) # print('\n') # print ("puzzle start:") # matrix_print(puzzle_basic) # print ("Solved:") # matrix_print(puzzle)
10a1fc441a535a8693ebad6c584ff75e403bc56c
prangya123/pammi_test
/compare-arr.py
831
3.65625
4
#!/bin/python3 import math import os import random import re import sys # Complete the compareTriplets function below. def compareTriplets(a, b): alice=0 bob=0 list = [] for i in range(len(a)) : for j in range(len(b)): if i==j: if a[i] > b[j]: alice = alice + 1 elif a < b: bob = bob +1 print ("alice is", alice) print ("bob is", bob) list.append(alice) list.append(bob) print (list) return list if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) result = compareTriplets(a, b) # fptr.write(' '.join(map(str, result))) # fptr.write('\n') # fptr.close()
b44f33adc84edaa3e8f7af9f30beb40b94159ba2
pirofex/quality-lab
/lab2/coverage/tests/test_evaluator.py
1,959
3.6875
4
import unittest import calculator.parser as parser import calculator.converter as converter import calculator.evaluator as evaluator class TestEvaluate(unittest.TestCase): def setUp(self): self.parser = parser.Parser() self.converter = converter.Converter() self.evaluator = evaluator.Evaluator() def evaluate(self, iExpr): parsedExpr = self.parser.parse(iExpr) convertedExpr = self.converter.convert(parsedExpr) evaluatedExpr = self.evaluator.evaluate(convertedExpr) return evaluatedExpr def testArithmetical(self): self.assertEqual(self.evaluate("3+2"), 5) self.assertEqual(self.evaluate("3-2"), 1) self.assertEqual(self.evaluate("3*2"), 6) self.assertEqual(self.evaluate("3/2"), 1.5) self.assertEqual(self.evaluate("3//2"), 1) self.assertEqual(self.evaluate("3%2"), 1) self.assertEqual(self.evaluate("3^2"), 9) def testLogical(self): self.assertEqual(self.evaluate("!3"), False) self.assertEqual(self.evaluate("!0"), True) self.assertEqual(self.evaluate("3=2"), False) self.assertEqual(self.evaluate("3=3"), True) def testFunctional(self): self.assertEqual(self.evaluate("sin(0)"), 0) self.assertEqual(self.evaluate("cos(0)"), 1) self.assertEqual(self.evaluate("tan(0)"), 0) self.assertEqual(self.evaluate("sqrt(9)"), 3) self.assertEqual("%.4f" % self.evaluate("log(2.71828182846)"), '1.0000') self.assertEqual(self.evaluate("log10(10)"), 1) def testEvaluatorError(self): # arguments count error self.assertRaises(evaluator.EvaluateError, self.evaluate, "sqrt()" ) self.assertRaises(evaluator.EvaluateError, self.evaluate, "3+" ) if __name__ == '__main__': unittest.main()
5e875036e7f418aa12a3f25611f41caf08b5b4ea
wwwjf/wPython
/test_if.py
68
3.71875
4
a = 'abc' if a == 'abc': print(True) else: print(False)
d73d8503561e3590ba1b9cc95640f3040393ac8b
thenerdpoint60/PythonCodes
/Transpose_Matrix.py
885
4.28125
4
#thenerdpoint60's code #Finding the transpose of the matrix of the same rows and column m=int(input("Enter number of rows for matrix1:")) n=int(input("Enter number of columns for matrix1:")) matrix1=[] #MATRIX 1 matrix2=[] #Matrix 2 the transpose matrix for i in range(0,n): matrix1.append([]) matrix2.append([]) for i in range(0,m): #creating empty matrix for j in range(0,n): matrix1[i].append(j) matrix1[i][j]=0 matrix2[i].append(j) matrix2[i][j]=0 for i in range(0,m): for j in range(0,n): print("Enter value in row: ",i+1," & column: ",j+1) matrix1[i][j]=int(input())#input for the matrix for i in range(len(matrix1)): for j in range(len(matrix1[0])): matrix2[j][i]=matrix1[i][j]#transposing the matrix for i in matrix2: print(i)#printing the transpose matrix