blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d91f8c6f3078c969d6efec2b9f38583e18ca4057
hbcelebi/leetcode
/#34_First_Last_Position_of_Element/main.py
2,202
3.96875
4
""" Created on Mon May 3 14:40:08 2021 @author: hbc """ # This is a O(N) computational complexity and O(1) space complexity solution to the problem from typing import List ### Here starts my code class Solution(object): def searchRange(self, nums, target): # The algorithm first finds the initial position of the target, then the last position # Initialize the variables left_idx = 0 right_idx = len(nums) - 1 first_position = -1 # let's do binary search to find the first location while(left_idx <= right_idx): # set the middle index inbetween the two indexes mid_idx = int((left_idx + right_idx)/2) # if we already found the target check if it is the first location if nums[mid_idx] == target: if mid_idx == 0 or nums[mid_idx-1] != target: first_position = mid_idx right_idx = mid_idx - 1 elif nums[mid_idx] < target: left_idx = mid_idx + 1 else: right_idx = mid_idx - 1 # if there is no first_position then there is no target value inside the array if first_position == -1: return [-1, -1] # Initialize the variables for the second loop left_idx = 0 right_idx = len(nums) - 1 # let's do binary search to find the last location while(left_idx <= right_idx): # set the middle index inbetween the two indexes mid_idx = int((left_idx + right_idx)/2) # if we already found the target check if it is the last position if nums[mid_idx] == target: if mid_idx == len(nums) - 1 or nums[mid_idx+1] != target: last_position = mid_idx left_idx = mid_idx + 1 elif nums[mid_idx] < target: left_idx = mid_idx + 1 else: right_idx = mid_idx - 1 # return the positions return [first_position, last_position] s = Solution() result = s.searchRange([10, 11, 11, 11, 14, 15], 11) print(result)
dcb3a69cba18bcf1049581c10e4b0ebe1b2de839
alanjimenez21/Python-Programming
/Python_Programming/Lab02Part1.py
946
4.03125
4
""" PROBLEM 1 A hotdog stand sells hotdogs, potato chips and sodas. Hotdogs are $2.50 each. Potato chips are $1.50 per bag. Sodas are $1.25 per cans. Design a program to do the following. Ask the user to enter number of hotdogs, chips and sodas ordered by the customer. The program will calculate and display the total amount due. """ #Define Variables hot_dogs = 2.5 potato_chips = 1.5 sodas = 1.25 #Prompt the user to input amounts print("Welcome to Fair Eatings!") count_hot_dogs = int(input("How many hot dogs would you like? ")) count_potato_chips = int(input("How many potato chips would you like? ")) count_sodas = int(input("How many sodas would you like? ")) #Calculations total_hot_dogs = hot_dogs * count_hot_dogs total_potato_chips = potato_chips * count_potato_chips total_sodas = sodas * count_sodas amount_due = total_hot_dogs+total_potato_chips+total_sodas #Display Amount print("Your total amount due is $", amount_due)
43ce9547597ddefbeb4adc9ef6ff25eb1a69120d
stevenhuangcode/programming
/Quiz Python.py
1,349
4.0625
4
# Quiz Game correct = 0 incorrect = 0 # Question 1 if input("What is the name of the famous tower in Paris?").lower() == "eiffel": print("Correct") correct += 1 else: print("Incorrect") incorrect += 1 # Question 2 Donnie_Yen = input("How many Ip Man movies are there (ft. Donnie Yen)") if Donnie_Yen == "4" or Donnie_Yen.lower() == "four": print("Correct") correct += 1 else: print("Incorrect") incorrect += 1 # Question 3 if input("Capital of New York / a. NYC b. NCY c. CYN d. Albany").lower() == "d": print("Correct") correct += 1 else: print("Incorrect") incorrect += 1 # Question 4 if input("Which country does pineapple pizza come from?").lower() == "canada": print("Correct") correct += 1 else: print("Incorrect") incorrect += 1 # Question 5 if input("True or False, there is a Popeye's in Richmond").lower() == "true": print("Correct") correct += 1 else: print("Incorrect") incorrect += 1 print(f" You have {correct} correct answers and {incorrect} incorrect answers") if (correct / (correct + incorrect)) * 100 >= 60: print(f" Nice. You passed with a score of {(correct / (correct + incorrect)) * 100} %") elif (correct / (correct + incorrect)) * 100 <= 60: print(f" Oops. You failed with a score of {(correct / (correct + incorrect)) * 100} %")
5f82bae6c5e2b1ddd90221e14b5b15d8d831a0c9
jessewalton/Practice-Problems
/python/soldier_game/soldier_game_oop.py
1,575
3.515625
4
#!/usr/bin/env python class SoldierGame(object): soldier_health = [] soldier_class = [] soldier_attack = [] """ def add_soldier(self, _health, _class, _attack): soldier_health.append(100) soldier_class.append(0) soldier_attack.append(0) """ def addSoldier(self, soldier_instance): self.soldier_health.append(soldier_instance.health_stat) #self.soldier_class.append(soldier_instance.soldier_class) def printAll(self): for i in self.soldier_health: print i class Soldier(object): health_stat = 100 def __init__(self, uid, team): self.uid = uid self.team = team self.attack_stat = 0 def attack(self, enemy): if self.team != enemy.team: enemy.health_stat = enemy.health_stat - self.attack_stat def print_status(self): print "ID:", self.uid print "Team:", self.team print "Health:", self.health_stat #print "Attack:", self.attack_stat class Grenadier(Soldier): def __init__(self, uid, team): Soldier.__init__(self, uid, team) self.attack_stat = 30 self.health_stat = 100 class Heavy(Soldier): def __init__(self, uid, team): Soldier.__init__(self, uid, team) self.attack_stat = 50 self.health = 200 # start new game newGame = SoldierGame() ally_grenadier_1 = Grenadier(1, "Blue") ally_heavy_2 = Heavy(2, "Blue") enemy_grenadier_1 = Grenadier(3, "Red") soldiers = [ally_grenadier_1, ally_heavy_2, enemy_grenadier_1] for soldier in soldiers: newGame.addSoldier(soldier) newGame.printAll()
e65e559b186bd83f1d3611eee3dde6885f87e688
cutieskye/algorithmia
/dynamic-programming/placing_parentheses.py
1,381
3.546875
4
import sys def evaluate(a, b, operation): if operation == '+': return a + b if operation == '-': return a - b if operation == '*': return a * b assert False def extrema(i, j, minima, maxima, operations): minimum = sys.maxsize maximum = -sys.maxsize - 1 for k in range(i, j): a = evaluate(minima[i][k], minima[k + 1][j], operations[k]) b = evaluate(minima[i][k], maxima[k + 1][j], operations[k]) c = evaluate(maxima[i][k], minima[k + 1][j], operations[k]) d = evaluate(maxima[i][k], maxima[k + 1][j], operations[k]) minimum = min(minimum, a, b, c, d) maximum = max(maximum, a, b, c, d) return minimum, maximum def get_maximum_value(expression): operations = expression[1::2] numbers = expression[::2] length = len(numbers) minima = [[0 for _ in range(length)] for _ in range(length)] maxima = [[0 for _ in range(length)] for _ in range(length)] for i in range(length): minima[i][i] = maxima[i][i] = int(numbers[i]) for s in range(1, length): for i in range(length - s): j = i + s minima[i][j], maxima[i][j] = extrema( i, j, minima, maxima, operations) return maxima[0][-1] if __name__ == "__main__": print(get_maximum_value(input()))
7277fe4d8193078e028d761da397fd714c736799
gustavofcosta/curso-python
/Totos exercícios e desafios/ex044.py
977
3.890625
4
print('=='*50) print('Calculadora de desconto ou juros, conforme a forma de pagamento.') print(' '*50) produto = float(input('informe o valor do produto R$ ')) print('Qual é a forma de pagamento?') print(' '*50) print(''' [1] - À vista dinheiro/cheque 10% de desconto. [2] - À vista cartão 5% de descont [3] - Em até 2 vezes no cartão preço normal. [4] - 3 vezes ou mais no cartão 20% de juros. ''') precione = int(input('Qual é a opção? ')) if precione == 1: print('À vista dinheiro/cheque 10% de desconto valor de R${}'.format(produto * 0.9)) elif precione == 2: print('À vista com cartão 5% de desconto, valor de R${}'.format(produto * 0.95)) elif precione == 3: print('Em até 2 vezes no cartão preço normal, valor de R${}'.format(produto)) elif precione == 4: quantas = int(input('Quantas parcelas: ')) divi = (produto*1.2) / quantas print('{} X {} no cartão 20% de juros, valor de R${}'.format(quantas, divi, produto*1.2))
da4033aecd44cb88fd090aaa6e829d688178bc48
yadavraganu/Codeforce
/1000/Donut_Shops.py
252
3.625
4
for i in range(int(input())): arr=list(map(int,input().split())) a=arr[0] b=arr[1] c=arr[2] if a<c: a1="1" else: a1="-1" if c<a*b: b1=b else: b1='-1' print(str(a1)+" "+str(b1))
fe725b9712f2046af414b8ec25ee638d4c351f54
boconlonton/python-deep-dive
/part-3/4-specialized_dictionary/1-default_dict.py
3,125
3.625
4
"""defaultdict""" from collections import defaultdict, namedtuple from datetime import datetime from functools import partial, wraps counts = defaultdict(lambda: 0) sentence = "able was I ere I saw elba" for c in sentence: counts[c] += 1 print(counts) print(isinstance(counts, defaultdict)) # True print(isinstance(counts, dict)) # True # Factory function c = defaultdict(int) # equals to defaultdict(lambda: 0) print(bool()) print(list()) print(str()) # Usage of defaultdict persons = { 'john': {'age': 20, 'eye_color': 'blue'}, 'jack': {'age': 25, 'eye_color': 'brown'}, 'jill': {'age': 22, 'eye_color': 'blue'}, 'eric': {'age': 35}, 'michael': {'age': 27} } eye_colors = {} for person, details in persons.items(): if 'eye_color' in details: color = details['eye_color'] else: color = 'unknown' if color in eye_colors: eye_colors[color].append(person) else: eye_colors[color] = [person] print(eye_colors) eye_colors = {} for person, details in persons.items(): color = details.get('eye_color', 'unknown') person_list = eye_colors.get(color, []) person_list.append(person) eye_colors[color] = person_list print(eye_colors) eye_colors = defaultdict(list) for person, details in persons.items(): color = details.get('eye_color', 'unknown') eye_colors[color].append(person) print(eye_colors) persons = { 'john': defaultdict(lambda: 'unknown', age=20, eye_color='blue'), 'jack': defaultdict(lambda: 'unknown', age=20, eye_color='brown'), 'jill': defaultdict(lambda: 'unknown', age=22, eye_color='blue'), 'eric': defaultdict(lambda: 'unknown', age=35), 'michael': defaultdict(lambda: 'unknown', age=27) } eye_colors = defaultdict(lambda: []) for person, details in persons.items(): eye_colors[details['eye_color']].append(person) print(eye_colors) eyedict = partial(defaultdict, lambda: 'unknown') # eyedict1 = lambda *args, **kwargs: defaultdict(lambda: 'unknown', *args, **kwargs) persons = { 'john': eyedict(age=20, eye_color='blue'), 'jack': eyedict(age=20, eye_color='brown'), 'jill': eyedict(age=22, eye_color='blue'), 'eric': eyedict(age=35), 'michael': eyedict(age=27) } eye_colors = defaultdict(lambda: []) for person, details in persons.items(): eye_colors[details['eye_color']].append(person) print(eye_colors) # Additional arguments of defaultdict() d = defaultdict(lambda: ' ', k1=100, k2=200) print(d) # Factory function NOT need to be a deterministic function def function_stats(): d = defaultdict(lambda: {"count": 0, "first_called": datetime.utcnow()}) Stats = namedtuple('Stats', 'decorator data') def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): d[fn.__name__]['count'] += 1 return fn(*args, **kwargs) return wrapper return Stats(decorator, d) stats = function_stats() @stats.decorator def func_1(): pass @stats.decorator def func_2(): pass func_1() func_2() func_1() print(stats.data)
aabf61afa9492620a637fea2b46a298dd89ff3da
gustavo-mota/programming_fundamentals
/8_Sétima_lista/1.2_cc/1.2.py
522
3.734375
4
string = str(input("Digite o nome sem espaços no fim: ")) sobre = [] novo_nome = [] for i in string: novo_nome.append(i) x = len(novo_nome) - 1 while x > 0: if ord(novo_nome[x]) == 32: break else: if ord(novo_nome[x]) >= 97 and ord(novo_nome[x]) <= 122: novo_nome[x] = chr(ord(novo_nome[x]) - 32) sobre.append(novo_nome[x]) novo_nome.pop() x -= 1 sobre.reverse( ) sobre.append(",") for s in sobre: print(s,end="") for i in novo_nome: print(i,end="")
029459a5c18b52788819a9738844c98cfc69a81b
SurakshaRV/python-lab-1BM17CS108
/rvsFibonacci.py
227
4.03125
4
def fib(n): if n<=1: return n else: return (fib(n-1)+fib(n-2)) n=int(input("how many numbers? ")) if n<=0: print("enter a positive integer: ") else: for i in range(1,n+1): print(fib(i))
e3128c429b227bc4762dcbe9385369a7e447c982
joshtaylora/HackerRank
/CountingValleys/CountValleys.py
1,017
4.125
4
import math import os import random import re import sys # # Complete the 'countingValleys' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER steps # 2. STRING path # def countingValleys(steps, path): downDist = 0 upDist = 0 valCount = 0 travel = 0 for index, step in enumerate(path): if step == 'U': travel += 1 upDist += 1 print("path[%d]: %s, travel: %d" % (index, step, travel)) elif step =='D': downDist += 18 travel -= 1 print("path[%d]: %s, travel: %d" % (index, step, travel)) if travel == 0 and index > 0 and path[index] == 'U' and upDist > 0: valCount += 1 print("path[%d]: %s, travel: %d valley ++" % (index, step, travel)) return valCount if __name__ == '__main__': steps = 8 path = 'UDDDUDUU' result = countingValleys(steps, path) print(result)
24ad8ff5db3fd0744f2f7d54f50a29fbc75a5d70
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Pirouz_N/lesson08/sparsearray.py
17,807
3.640625
4
#!/usr/bin/env python3 """ Purpose: Sparse Array python certificate from UW Author: Pirouz Naghavi Date: 07/13/2020 """ # imports from collections.abc import Sequence import operator class SparseArray: """Sparse Array is data structure for spare data. The list hold information describing the HTML element as well as a class attribute describing the HTML tag called tag. It also contains instance attributes such as contents which is a list that contains the contents. It is very likely that the contents could include element which would be the sub elements to the current element. There are two major methods append and render. Append adds more contents to the contents list. Render adds the current element. Attributes: date: This attribute contains all the values in the data including zeros. """ def __init__(self, init_data=None, dim=None): """Initialises the Sparse Array class. Args: init_data: Is the initializing data. If it is not provided empty structure will be created. This value will be a sparse array of objects or 2 sparse array of objects. In case of a 2D sparse array of object every row need not to have the same length additional zeros will be automatically added. If init_data is not sequence it will be treated as an object set for index zero of the data. dim: Dimensionality of the array. Raises: ValueError: If dim is specified as two dimensional but it is not a Sequence. """ self._data = {} self._num_row = 0 self._num_col = 0 self._dim = dim if dim is not None and (dim == 1 or dim == 2) else 1 if init_data is not None: if isinstance(init_data, Sequence): if len(init_data) != 0: self._initial_sequence_update(init_data) else: self._data[0] = init_data def _initial_sequence_update(self, init_data): """Initialises the Sparse Array class when initial data is a sequence. Args: init_data: Is the initializing data. If it is not provided empty structure will be created. This value will be a sparse array of objects or 2 sparse array of objects. In case of a 2D sparse array of object every row need not to have the same length additional zeros will be automatically added. If init_data is not sequence it will be treated as an object set for index zero of the data. Raises: ValueError: If dim is specified as two dimensional but it is not a Sequence. """ self._num_row = len(init_data) for i, row_val in enumerate(init_data): if self._dim == 1: if row_val != 0 and row_val != 0.0 and row_val != '': self._data[i] = row_val else: self._num_col = len(row_val) if len(row_val) > self._num_col else self._num_col try: for j, col_val in enumerate(row_val): if col_val != 0 and col_val != 0.0 and col_val != '': self._data[(i, j)] = col_val except ValueError as err: raise ValueError("Every row of initial data must be a sequence." + str(err)) @property def data(self): """It returns array slice based on the passed slice and value. This will return a row. Returns: The property of data as a form of list of lists. """ if self._dim == 2: return [[self._data[(i, j)] if (i, j) in self._data else 0 for j in range(self._num_col)] for i in range(self._num_row)] else: return [self._data[i] if i in self._data else 0 for i in range(self._num_row)] @data.setter def data(self, init_data): """Resets the Sparse Array class from blank with initial data. Args: init_data: Is the initializing data. If it is not provided empty structure will be created. This value will be a sparse array of objects or 2 sparse array of objects. In case of a 2D sparse array of object every row need not to have the same length additional zeros will be automatically added. If init_data is not sequence it will be treated as an object set for index zero of the data. dim: Dimensionality of the array. Raises: ValueError: If dim is specified as two dimensional but it is not a Sequence. """ self._data = {} self._num_row = 0 self._num_col = 0 self._dim = dim if dim is not None and (dim == 1 or dim == 2) else 1 if init_data is not None: if isinstance(init_data, Sequence): if len(init_data) != 0: self._initial_sequence_update(init_data) else: self._data[0] = init_data @staticmethod def _slice_range(slc, length): return range(operator.index(slc.start) if slc.start is not None else 0, operator.index(slc.stop) if slc.stop is not None else length, operator.index(slc.step) if slc.step is not None else 1) def _two_d_tuple_get_item_both_slice(self, item): """It returns an array slice based on the passed slice tuple. This will return a list of lists. Args: item: Slice tuple that needs to be returned. Returns: This will return a list of lists based on the tuple of slices. """ return [[self._data[(i, j)] if (i, j) in self._data else 0 for j in self._slice_range(item[1], self._num_col)] for i in self._slice_range(item[0], self._num_row)] def _two_d_tuple_get_item_one_slice(self, item): """It returns an array slice based on the passed slice and value. This will return a row. Args: item: Slice and value that needs to be returned. Returns: This will return a row as a list based on the slice and value. """ return [[self._data[(i, j)] if (i, j) in self._data else 0 for j in self._slice_range(item[1], self._num_col)] for i in range(operator.index(item[0]), operator.index(item[0]) + 1)] def _two_d_tuple_get_item_two_slice(self, item): """It returns an array slice based on the passed slice and value. This will return a column vector. Args: item: Slice and value that needs to be returned. Returns: This will return a column vector as a list of list based on the slice and value. """ return [[self._data[(i, j)] if (i, j) in self._data else 0 for j in range(operator.index(item[1]), operator.index(item[1]) + 1)] for i in self._slice_range(item[0], self._num_row)] def _two_d_tuple_get_item_no_slice(self, item): """It returns array slice based on the passed slice and value. This a value located at provided index. Args: item: Index tuple that needs to be returned. Returns: This will return a value based on the tuple of values. """ return self._data[(operator.index(item[0]), operator.index(item[1]))] \ if (operator.index(item[0]), operator.index(item[1])) in self._data else 0 def _two_d_tuple_get_item(self, item): """It returns an array slice based on the passed tuple. This a value located at provided index tuple. Args: item: Index or slice tuple that needs to be returned. Returns: This will return a value, row, column vector, or matrix based on the tuple of values. """ if len(item) == 2: if isinstance(item[0], slice) and isinstance(item[1], slice): return self._two_d_tuple_get_item_both_slice(item) elif isinstance(item[0], slice) and not isinstance(item[1], slice): return self._two_d_tuple_get_item_two_slice(item) elif not isinstance(item[0], slice) and isinstance(item[1], slice): return self._two_d_tuple_get_item_one_slice(item) else: return self._two_d_tuple_get_item_no_slice(item) else: raise IndexError("Dimension tuple for two array must be two dimensional") def _two_d_get_item(self, item): """It returns an array slice based on the passed tuple, slice, or value. This a value located at index tuple. Args: item: Index or slice tuple that needs to be returned. Returns: This will return a value, row, column vector, or matrix based on the tuple of values. """ if isinstance(item, tuple): return self._two_d_tuple_get_item(item) elif isinstance(item, slice): return [[self._data[(i, j)] if (i, j) in self._data else 0 for j in range(self._num_col)] for i in self._slice_range(item[0], self._num_row)] else: return[[self._data[(i, j)] if (i, j) in self._data else 0 for j in range(self._num_col)] for i in range(operator.index(item), operator.index(item) + 1)] def _one_d_get_item(self, item): """It returns an array slice based on the passed slice, or value. This is located at index or slice. Args: item: Index or slice that needs to be returned. Returns: This will return a value, or list based on slice or value. """ if isinstance(item, slice): return [self._data[i] if i in self._data else 0 for i in self._slice_range(item[0], self._num_row)] else: return self._data[operator.index(item)] if operator.index(item) in self._data else 0 def __getitem__(self, item): """It returns an array slice based on the passed slice, or value for 1D and 2D. Args: item: Index or slice or as tuple of indexes or slices combo that needs to be returned for 1D or 2D. Returns: This will return a value, list, list of list as vector, or list of lists as matrix based on item. Raises: TypeError: When values are not operator.index convertible to ints. IndexError: When index of values are out of bounds. """ try: if self._dim == 2: return self._two_d_get_item(item) else: return self._one_d_get_item(item) except TypeError as err: raise TypeError("Indices must be integers." + str(err)) except IndexError as err: raise IndexError("Provided index is out of bounds of the data." + str(err)) def _set_two_d(self, item, value): """It sets a value at a certain tuple for 2D. Args: item: Index tuple that the value needs to be placed into. value: That needs to be placed in the index tuple. Raises: TypeError: When values are not operator.index convertible to ints. IndexError: When index of values are out of bounds. """ if isinstance(item, tuple): if len(item) == 2: self._num_row = operator.index(item[0]) + 1 if self._num_row - 1 < operator.index(item[0]) \ else self._num_row self._num_col = operator.index(item[1]) + 1 if self._num_col - 1 < operator.index(item[1]) \ else self._num_col self._data[(operator.index(item[0]), operator.index(item[1]))] = value else: raise IndexError("2D array requires a tuple of indices with length of two.") else: raise IndexError("2D array requires a tuple of indices.") def _set_one_d(self, item, value): """It sets a value at a certain index for 1D. Args: item: Index that the value needs to be placed into. value: That needs to be placed in the index. Raises: TypeError: When values are not operator.index convertible to ints. IndexError: When index of values are out of bounds. """ self._num_row = operator.index(item) + 1 if self._num_row - 1 < operator.index(item) \ else self._num_row self._data[operator.index(item)] = value def __setitem__(self, item, value): """It sets a value at a certain index for 1D or index tuple for 2D. Args: item: Index or index tuple that the value needs to be placed into. value: That needs to be placed in the index or index tuple. Raises: TypeError: When values are not operator.index convertible to ints. IndexError: When index of values are out of bounds. """ try: if self._dim == 2: self._set_two_d(item, value) else: self._set_one_d(item, value) except TypeError as err: raise TypeError("Indices must be integers." + str(err)) except IndexError as err: raise IndexError("Provided index is out of bounds of the data." + str(err)) def __len__(self): """It the length of the current instance.""" if self._dim == 2: return self._num_row else: return self._num_row @property def shape(self): """It the shape of the current instance.""" if self._dim == 2: return self._num_row, self._num_col else: return self._num_row def _delitem_two_d(self, key): """It removes item at key for 2D.""" if isinstance(key, tuple) and len(key) == 2: del self._data[key] self._num_row = max(self._data)[0] + 1 if self._num_row - 1 == operator.index(key[0]) \ else self._num_row self._num_col = max(self._data, key=lambda x: x[1])[1] + 1 if self._num_col - 1 == operator.index(key[1]) \ else self._num_col else: raise IndexError("The item for 2D array must be a tuple of length 2.") def _delitem_one_d(self, key): """It removes item at key for 1D.""" del self._data[key] self._num_row = max(self._data) + 1 if self._num_row - 1 == operator.index(key) \ else self._num_row def __delitem__(self, key): """It removes item at key. For 2D keys must be tuples of length 2. For 1D an integer value should suffice.""" try: if self._dim == 2: self._delitem_two_d(key) else: self._delitem_one_d(key) except TypeError as err: raise TypeError("Indices must be integers." + str(err)) except IndexError as err: raise IndexError("Provided index is out of bounds of the data." + str(err)) @staticmethod def _print_two_d_item(data, index, start, end_short, end_long): """Prints item of sparse 2D array.""" obj_str = "" obj_str += start if len(data[index]) < 15: obj_str += str(data[index]) + end_short else: obj_str += '[' + str(data[index][0]) + ', ' + str(data[index][1]) + ', ' + str( data[index][2]) + ', ..., ' \ + str(data[index][len(data[index]) - 3]) + ', ' + str( data[index][len(data[index]) - 2]) + ', ' \ + str(data[index][len(data[index]) - 1]) obj_str += end_long return obj_str def _str_two_d(self, all_data): """Prints data of sparse 2D array.""" obj_str = '' if self._num_row == 0: obj_str += "{}D Sparse Array ([".format(self._dim) + '[]' + '])' elif self._num_row == 1: obj_str += "{}D Sparse Array ([".format(self._dim) + str(all_data[0]) + '])' else: obj_str += self._print_two_d_item(all_data, 0, "{}D Sparse Array ([", ',\n', '],\n') for i in range(1, self._num_row - 1): obj_str += self._print_two_d_item(all_data, i, " ", ',\n', '],\n') obj_str += self._print_two_d_item(all_data, self._num_row - 1, " ", '])', ']])') return obj_str def __str__(self): """Prints data of sparse array.""" all_data = self.data if self._dim == 2: return self._str_two_d(all_data) else: return "{}D Sparse Array (".format(self._dim) + str(all_data) + ')' if __name__ == "__main__": """blank = SparseArray() blank[0] = 100 blank[1] = 100 blank[100] = 1000 blank[1000] = 1 print(blank) print(len(blank)) del blank[1000] print(blank) print(len(blank)) two_d_blank = SparseArray(dim=2) two_d_blank[1, 100] = 100 two_d_blank[0, 0] = 100 two_d_blank[2, 5] = 'better than numpy! lol' print(two_d_blank) del two_d_blank[2, 5] print(two_d_blank) one_d_init = SparseArray([1, 2, 3, 4, 5, 6]) one_d_init[20] = 100 one_d_init[200] = 'better than numpy! lol' print(one_d_init) del one_d_init[200] print(one_d_init) two_d_init = SparseArray([[1, 2, 3, 4, 5, 6]], dim=2) print(two_d_init) two_d_init[100, 100] = 'I am "cool"' print(two_d_init) print(two_d_init.shape) print(two_d_init[1, 1]) print(two_d_init[99:, 100]) two_d_init[52, 52] = 'I am "cool"' print(two_d_init[50:59, 50:59]) print(SparseArray(two_d_init[50:59, 50:59], dim=2))"""
45934f287630608a4298ac6a5b627e0266dd363d
tomasmarcenaro/Tic-Tac-Toe-project
/tictactoe.py
4,464
3.796875
4
# write your code here movs = "_________" movs2 = [movs[0:3], movs[3:6], movs[6:9]] print("---------") for s in movs2: print("|", *s, "|") print("---------") row_winX = None row_winO = None col_winO = None col_winX = None diag_winX = None diag_winO = None winner = any([row_winX, row_winO, col_winX, col_winO, diag_winX, diag_winO]) def indice(x, y): indx = (x - 1) + (9 - (3 * y)) return indx def check_result(matrix, moves): # check rows global row_winX global col_winX global diag_winX global row_winO global col_winO global diag_winO global winner col1 = [sub[0] for sub in matrix] col2 = [sub[1] for sub in matrix] col3 = [sub[2] for sub in matrix] columns = [col1, col2, col3] diag1 = [matrix[0][0], matrix[1][1], matrix[2][2]] diag2 = [matrix[0][2], matrix[1][1], matrix[2][0]] for i in matrix: if i.count("O") == 3 and i.count("X") == 3: print("Impossible") elif i.count("X") == 3: row_winX = True print("X wins") winner = True elif i.count("O") == 3: row_winO = True print("O wins") winner = True if diag1.count("X") == 3 or diag2.count("X") == 3: print("X wins") diag_winX = True winner = True elif diag1.count("O") == 3 or diag2.count("O") == 3: print("O wins") diag_winO = True winner = True # check columns for c in columns: if c.count("O") == 3: col_winO = True winner = True if c.count("X") == 3: col_winX = True winner = True if col_winX is True and col_winO is True: print("Impossible") elif col_winO is True: print("O wins") elif col_winX is True: print("X wins") # Draw/impossible and not finished if row_winX is not True and col_winX is not True and diag_winX is not True and row_winO is not True and col_winO is not True and diag_winO is not True: if moves.count("X") > (moves.count("O") + 1) or moves.count("O") > (moves.count("X") + 1): print("Impossible") elif moves.count("_") == 0: print("Draw") winner = True elif moves.count("_") > 0: print("Game not finished") elif moves.count("X") > (moves.count("O") + 1) or moves.count("O") > (moves.count("X") + 1): print("Impossible") return winner #get and check coordinates while winner is False: while True: try: x, y = map(int, input("Enter the coordinates: ").split()) while x > 3 or y > 3: print("Coordinates should be from 1 to 3!") x, y = map(int, input("Enter the coordinates: ").split()) else: i = indice(x, y) while movs[i] == "X" or movs[i] == "O": print("This cell is occupied! Choose another one!") x, y = map(int, input("Enter the coordinates: ").split()) i = indice(x, y) break except ValueError: print("You should enter numbers!") #index again for new matrix. For efficiency, this should be improved, since the value is in the loop i = indice(x, y) # new matrix movs = movs[:i] + "X" + movs[i + 1:] movs2 = [movs[0:3], movs[3:6], movs[6:9]] print("---------") for s in movs2: print("|", *s, "|") print("---------") check_result(movs2, movs) if winner is True: break while True: try: x, y = map(int, input("Enter the coordinates: ").split()) while x > 3 or y > 3: print("Coordinates should be from 1 to 3!") x, y = map(int, input("Enter the coordinates: ").split()) else: i = indice(x, y) while movs[i] == "X" or movs[i] == "O": print("This cell is occupied! Choose another one!") x, y = map(int, input("Enter the coordinates: ").split()) i = indice(x, y) break except ValueError: print("You should enter numbers!") movs = movs[:i] + "O" + movs[i + 1:] movs2 = [movs[0:3], movs[3:6], movs[6:9]] print("---------") for s in movs2: print("|", *s, "|") print("---------") check_result(movs2, movs) if winner is True: break
ffd3b9d9d940171b060575665f8f9ade3bd3101c
AkilaSachin/Binary-Tree
/Binary Search Tree/Binary Search Tree.py
3,993
4.0625
4
# Creating the Binary node class class binaryNode: def __init__(self, data): self.data = data self.left = None self.right = None # Adding new child to node def addChild(self, data): if data == self.data: return if data < self.data: if self.left: self.left.addChild(data) else: self.left = binaryNode(data) else: if self.right: self.right.addChild(data) else: self.right = binaryNode(data) # In-Order Traversal method / Left, Root, Right Traversal (Remember "In-Order" means root is in between Left and Right) def inOrderTraversal(self): nodes = [] if self.left: nodes += self.left.inOrderTraversal() nodes.append(self.data) if self.right: nodes += self.right.inOrderTraversal() return nodes # Pre-Order Traversal method / Root, Left, Right Traversal (Remember "Pre-Order" means root is in before the Left and Right) def preOrderTraversal(self): nodes = [] nodes.append(self.data) if self.left: nodes += self.left.preOrderTraversal() if self.right: nodes += self.right.preOrderTraversal() return nodes # Post-Order Traversal method / Left, Right, Root Traversal (Remember "Post-Order" means root is in after the Left and Right) def postOrderTraversal(self): nodes = [] if self.left: nodes += self.left.postOrderTraversal() if self.right: nodes += self.right.postOrderTraversal() nodes.append(self.data) return nodes #Searching a value in the Tree def search(self, val): if self.data == val: return True if self.data > val: if self.left: return self.left.search(val) else: return False if self.data < val: if self.right: return self.right.search(val) else: return False # Finding the minimum value in the tree def min(self): if self.left: return self.left.min() else: return self.data # Finding the Maximum value in the tree def max(self): if self.right: return self.right.max() else: return self.data # Calculating the Sum of all nodes in the tree def sum(self): sum = 0 if self.left: sum += self.left.sum() if self.right: sum += self.right.sum() sum += self.data return sum # Deleting a node in the tree def delete(self,val): if val < self.data: if self.left: self.left = self.left.delete(val) elif val > self.data: if self.right: self.right = self.right.delete(val) else: if self.left is None and self.right is None: return None if self.left is None: return self.right if self.right is None: return self.left minVal = self.right.min() self.data = minVal self.right = self.right.delete(minVal) return self # Building the tree def buildTree(values): root = binaryNode(values[0]) for i in range(1, len(values)): root.addChild(values[i]) return root if __name__ == "__main__": numbers = [17, 4, 1, 20, 9, 23, 18, 34, 18, 4] tree = buildTree(numbers) print(tree.inOrderTraversal()) print(tree.preOrderTraversal()) print(tree.postOrderTraversal()) print(tree.search(17)) print(tree.search(1000)) print(tree.min()) print(tree.max()) print(tree.sum()) tree.delete(20) print(tree.inOrderTraversal()) tree.delete(9) print(tree.inOrderTraversal())
ac49270a8fa76c3715502212e597638ef8b8fab3
JulianCSalazar/Python_Tutorial
/Sorting Algorithms.py
4,393
4.125
4
def merge(L, R): print(L) print(R) L_i, R_i = 0, 0 temp = [] while (L_i < len(L)) and (R_i < len(R)): if (L[L_i] < R[R_i]): temp.append(L[L_i]) L_i = L_i + 1 else: temp.append(R[R_i]) R_i = R_i + 1 if L_i == len(L): temp.extend(R[R_i:]) elif R_i == len(R): temp.extend(L[L_i:]) print(temp) return temp def mergesort(A): if (len(A) <= 1): return A mid_point = len(A)//2 left_side = A[:mid_point] right_side = A[mid_point:] print("A is:", A) left_side = mergesort(left_side) right_side = mergesort(right_side) print("MERGING") return merge(left_side, right_side) def in_place_merge(A, left_start, left_end, right_start, right_end): print("left indices:", left_start, left_end) print("right indices:", right_start, right_end) L_i, R_i = left_start, right_start while (L_i <= left_end) and (R_i <= right_end): if (A[L_i] < A[R_i]): R_i = R_i + 1 else: swap(A, L_i, R_i) L_i = L_i + 1 def in_place_mergesort(A, left_pt, right_pt): if ((right_pt-left_pt) <= 1): return mid_point = ((right_pt - left_pt) // 2) + left_pt in_place_mergesort(A, left_pt, mid_point) in_place_mergesort(A, mid_point, right_pt) print("MERGING") in_place_merge(A, left_pt, mid_point-1, mid_point, right_pt-1) print(A) def swap(A, index_1, index_2): temp = A[index_1] A[index_1] = A[index_2] A[index_2] = temp def partition(A, p): i, j = 0, len(A)-1 while (i < j): while (A[i] < p): i = i+1 while (A[j] > p): j = j-1 swap(A, i, j) def quicksort(A): print("A is:", A) if (len(A) <= 1): return A mid_index = len(A)//2 print("mid_index is:", mid_index) pivot = A[mid_index] print("pivot is:", pivot) partition(A, pivot) print("Post-Partition:", A) left_side = A[:mid_index] right_side = A[mid_index:] left_side = quicksort(left_side) right_side = quicksort(right_side) print(left_side, right_side) return left_side+right_side def in_place_partition(A, pivot, left_start, right_end): while (left_start < right_end): while (A[left_start] <= pivot) and (left_start < right_end): left_start = left_start + 1 while (A[right_end] > pivot) and (right_end > left_start): right_end = right_end - 1 swap(A, left_start, right_end) def in_place_quicksort(A, left_pt, right_pt): print("Array is:", A) if (right_pt-left_pt <= 1): return mid_index = (left_pt + right_pt)//2 pivot = A[mid_index] print("Pivot is:", pivot, "at index:", mid_index) in_place_partition(A, pivot, left_pt, right_pt) print("Post-partition:", A) in_place_quicksort(A, left_pt, mid_index) in_place_quicksort(A, mid_index, right_pt) return def complete_heapify(A, left_pt, right_pt): for i in range (left_pt+1, right_pt): bubble_up(A, i, (i-1)//2) def bubble_up(A, i, j): if A[i] > A[j]: swap(A, i, j) bubble_up(A, j, j//2) return def sink_down(A, i, working_range): left_child_index = (i*2) + 1 right_child_index = (i*2) + 2 #make sure you are within the working range if (left_child_index > working_range): return elif (right_child_index > working_range): swap_index = left_child_index elif (A[left_child_index] > A[right_child_index]): swap_index = left_child_index else: swap_index = right_child_index if (A[i] < A[swap_index]): swap(A, i, swap_index) sink_down(A, swap_index, working_range) else: return def heapsort(A): print("Initiating heapify") complete_heapify(A, 0, len(A)) print("Heapify complete. Result is:", A) print(" ") for i in range(len(A)-1): print("Swapping", A[0], "and", A[len(A)-(i+1)]) swap(A, 0, len(A)-(i+1)) print("Swap complete. Result is", A) print("Beginning sink") sink_down(A, 0, len(A)-(i+2)) print("Sink Complete. Result is:", A) print(" ") A = [ 1, -1, 4, 16, 3, 7, 0, -4] in_place_mergesort(A, 0, len(A)) print(A)
9478534055d40df30b7eca244b1c3d1a6774e7ca
BigBlackWolf/LeetCodeProblems
/DynamicProgramming/maximum-subarray.py
588
4.0625
4
""" Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. """ class Solution: def maxSubArray(self, nums) -> int: for i, j in enumerate(nums[1:]): max_x = max(nums[i] + j, j) nums[i + 1] = max_x return max(nums)
1f8b0b8f424ff5c82ae3e9b2dd3e407c109ad0dc
KF10/ichw
/pyassign2/currency.py
1,856
4.15625
4
#!/usr/bin/env python3 """currency.py: provide a 'exchange' function which return the amount of another currency when you want to convert a certain amount of currency to another. __author__ = "Kuangwenyu" __pkuid__ = "1800013245" __email__ = "[email protected]" """ from urllib.request import urlopen import json def exchange(currency_from, currency_to, amount_from): """Returns: amount of currency received in the given exchange. In this exchange, the user is changing amount_from money in currency currency_from to the currency currency_to. The value returned represents the amount in currency currency_to. The value returned has type float. Parameter currency_from: the currency on hand Precondition: currency_from is a string for a valid currency code Parameter currency_to: the currency to convert to Precondition: currency_to is a string for a valid currency code Parameter amount_from: amount of currency to convert Precondition: amount_from is a float """ doc = urlopen('http://cs1110.cs.cornell.edu/2016fa/a1server.php?from={0}&to={1}&amt={2}'. format(currency_from, currency_to, amount_from)) docstr = doc.read() doc.close() jstr = docstr.decode('ascii') ret_dict = json.loads(jstr) # 将jstr转为字典 convert = ret_dict['to'] mylist = convert.split() amount_to = float(mylist[0]) return amount_to def test_exchange(): """test the 'exchange' function. """ assert(17.13025 == exchange('USD', 'CNY', 2.5)) assert(2.1589225 == exchange('USD', 'EUR', 2.5)) assert(0.018484513053739 == exchange('AOA', 'AUD', 3.7)) def test_all(): """test all cases. """ test_exchange() print('All tests passed') def main(): """main module """ test_all() if __name__ == '__main__': main()
aafe2cd67a5b4ab6e3c7d8e33abfe770830717bc
kos0ng/code-challenge
/ProblemSolvinghackerrank/sequenceequation.py
576
3.578125
4
#!/bin/python import math import os import random import re import sys # Complete the permutationEquation function below. def permutationEquation(p): ind=[] for i in range(len(p)): ind.append(p.index(i+1)+1) result=[] for i in ind: result.append(p.index(i)+1) for i in result: print i if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(raw_input()) p = map(int, raw_input().rstrip().split()) result = permutationEquation(p) # fptr.write('\n'.join(map(str, result))) # fptr.write('\n') # fptr.close()
6da46c0e975d4ff98e67b71914bb9e57d609220e
Justintime8/Python_Coding
/loops_dictionaries.py
121
3.859375
4
food = {'french fries' : 1, 'ice cream' : 8, 'kbbq' : 19, 'jian bing' : 88} for key in food : print(key, food[key])
4c0a9fcd022e936324a290302bfa3b7c4bd610ba
git-ahi/pomodoro-api
/app/auth/v1/models/user_models.py
863
3.609375
4
class UserModels: """ Class for the user operations """ users = [] def __init__(self, username, task, task_timer, break_timer, task_completed): """ Initialize the user models """ self.id = len(UserModels.users) + 1 self.username = username self.task = task self.task_timer = task_timer self.break_timer = break_timer self.task_completed = task_completed def save_user(self): """ Method to register user instance and update the data structure """ user_record = dict( id=self.id, username=self.username, task=self.task, task_timer=self.task_timer, break_timer=self.break_timer, task_completed=self.task_completed ) self.users.append(user_record)
9abd108e7e72f6a0db7a2fcb2da64fbb97575d61
conor-mcmullan/Scoring-Player-System
/scoring_system.py
3,982
3.78125
4
import thread score_system = {} def set_player_list(player_count): score_system.clear() for player in xrange(player_count): score_system.update({chr(ord('a')+player): 0}) def print_scoreboard(): for key in sorted(score_system): if key is sorted(score_system)[-1]: v = "%s: %s" else: v = "%s: %s, " print v % (key, score_system[key]), println(add_line(1)) def update_player_score(player): if str(player).lower() in score_system.keys(): if str(player).islower(): score_system[str(player).lower()] += 1 elif str(player).isupper(): score_system[str(player).lower()] -= 1 else: println(add_line(1)+"NON_VALID_PLAYER"+add_line(1)) print_scoreboard() def add_line(num): for n in xrange(num): return "\n" def println(msg): print str(msg) def start_menu_system(): user_input = -1 while(user_input not in [0, 1]): println(add_line(3)+"START MENU"+add_line(1)+"1: Start Game") println("0: Exit Game"+add_line(2)+"...") try: user_input = int(raw_input('choice: ')) except ValueError: println(add_line(1)+"| Not a valid choice |") finally: if user_input is 0: exit(0) elif user_input is 1: main_menu() else: println(add_line(1) + "| Not a valid choice|") start_menu_system() def main_menu(): user_input = -1 while (user_input not in [0, 1, 2]): println(add_line(2)+"MAIN MENU"+add_line(1)+"1: Enter Number Of Players") println("2: View Instructions") println("0: Exit Game" + add_line(2) + "...") try: user_input = int(raw_input('choice: ')) except ValueError: println(add_line(1) + "| Not a valid choice|") finally: if user_input is 0: exit(0) elif user_input in [1, 2]: in_game_menu(user_input) else: println(add_line(1) + "| Not a valid choice|") def in_game_menu(case): if case is 1: user_input = -1 while (user_input < 1 or user_input > 26): println(add_line(2) + "IN GAME MENU"+add_line(1)) try: user_input = int(raw_input('Enter Number Of Players: ')) if (user_input < 1 or user_input > 26): println(add_line(1)+"| Not a valid number of players |") except ValueError: println(add_line(1) + "| Not a valid number|") finally: if (user_input < 1 or user_input > 26): println(add_line(1) + "| Not a valid number|") else: set_player_list(user_input) game_loop() elif case is 2: println(add_line(2)+"Altering the scores."+ add_line(1)+"Scores a point: the letter of players name is typed in lowercase."+ add_line(1)+"Loses a point: the letter of players name is typed in uppercase.") main_menu() def game_loop(): user_input = "not end" print_scoreboard() while (user_input != ("END" or "end")): try: println(add_line(2)+"LOWER = ++"+add_line(1)+"UPPER = --" + add_line(1)) user_input = str(raw_input('player: ')) except ValueError: println(add_line(1) + "| Not a valid choice |") finally: if user_input == ("END" or "end"): start_menu_system() elif user_input != ("END" or "end"): if len(user_input) > 1: solve_a_string(user_input) else: update_player_score(user_input) def solve_a_string(solve): for letter in xrange(len(solve)): update_player_score(solve[letter]) if __name__ == "__main__": thread.start_new_thread(start_menu_system())
500f9ee3ff8f16ef1e5904f4d043b9d05f9bc9e6
Donkey-1028/algorithms
/alghorithms-of-everyone/quick_sort.py
1,692
3.671875
4
""" 퀵정렬 Median of Three 방식 """ def choice_pivot(arr, left, right): """ 리스트의 첫번째값, 마지막값, 가운데값중 어떠한 값을 pivot 으로 이용할지 정렬하고 리턴 """ center = (left + right) // 2 if arr[left] > arr[right]: arr[left], arr[right] = arr[right], arr[left] if arr[center] > arr[right]: arr[center], arr[right] = arr[right], arr[center] if arr[left] > arr[center]: arr[left], arr[center] = arr[center], arr[left] return center def quick_sort(arr, left, right, pivot_index): if right - left <= 0: return #pivot은 리스트의 Median of three를 이용하여 가운데로 설정. pivot = arr[pivot_index] j = left for i in range(left, right): #pivot을 기준으로 작으면 왼쪽, 크면 오른쪽에 정렬 if arr[i] < pivot: arr[i], arr[j] = arr[j], arr[i] j += 1 #pivot을 기준으로 왼쪽으로 정렬된 리스트를 다시 퀵정렬 하기 위해 다음 pivot 설정 next_min_pivot = choice_pivot(arr, left, pivot_index) #왼쪽으로 정렬된 리스트 퀵정렬 quick_sort(arr, left, pivot_index, next_min_pivot) #pivot을 기준으로 오른쪽으로 정렬된 리스트를 다시 퀵정렬 하기 위해 다음 pivot 설정 next_max_pivot = choice_pivot(arr, pivot_index+1, right) #오른쪽으로 정렬된 리스트 퀵정렬 quick_sort(arr, pivot_index+1, right, next_max_pivot) def sort(arr): pivot_index = choice_pivot(arr, 0, len(arr)-1) quick_sort(arr, 0, len(arr)-1, pivot_index) t = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5, 11, 12] sort(t) print(t)
dab053eeafd8ebdeb1f9314c7b27648175f98bfc
abbisQQ/Server-Client-in-python-simple-and-threaded-for-more-than-one-connection-at-a-time
/server.py
1,312
3.640625
4
import socket import sys # Create a Socket() def create_socket(): try: global host global port global s host = "127.0.0.1" port = 9999 s = socket.socket() except socket.error as msg: print("Socket Creation Error: " + str(msg)) # Binding the socket and listening for connections def bind_socket(): try: global host global port global s print("Binding the Port: " + str(port)) s.bind((host, port)) s.listen(5) except socket.error as msg: print("Socket Binding Error: " + str(msg) +"\n" +"Retrying...") bind_socket() # Establish connection def socket_accept(): conn,addreess = s.accept() print("Connection has been established with : " +addreess[0] + ":"+str(addreess[1])) send_commands(conn) conn.close() # Send Commands to Client def send_commands(conn): while True: cmd = input() if cmd == "quit": conn.close() s.close() sys.exit() if len(str.encode(cmd))>0: conn.send(str.encode(cmd)) client_responce = str(conn.recv(1024), "utf-8") print(client_responce, end="") def main(): create_socket() bind_socket() socket_accept() main()
6cd97f1b067f7988aa03dc252feebba05b4e4a19
Zhangmingyang-Su/Data-Structure-and-Algorithm
/BFS.py
2,002
3.828125
4
# Vertical Traversal for a Binary Tree #Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). #If two nodes are in the same row and column, the order should be from left to right. # Input: [3,9,20,null,null,15,7] # 3 # / \ # 9 20 # / \ # 15 7 #Output:[[9],[3,15],[20],[7]] from collections import deque, defaultdict def vertival_traverse(root): if not root: return [] collection = defaultdict(list) queue = deque([(root, 0)]) while queue: node,count = queue.popleft() if node is not None: collection[count].append(node.val) queue.append((node.left, count - 1)) queue.append((node.right, count + 1)) return [collection[x] for x in sorted(collection.key())] # 2 In a given grid, each cell can have one of three values: # the value 0 representing an empty cell; # the value 1 representing a fresh orange; # the value 2 representing a rotten orange. # Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. # Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. # Input: [[2,1,1],[1,1,0],[0,1,1]] # Output: 4 from collections import deque def orangeRotting(grid): if not grid: return -1 cnt = 0 Q = deque([]) N, M = len(grid), len(grid[0]) for i in range(N): for j in range(M): if grid[i][j] == 1: cnt += 1 if grid[i][j] == 2: Q.append((i, j)) res = 0 while Q: next_level = deque([]) size = len(Q) for _ in range(size): i, j = Q.popleft() for x,y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if 0 <= x < N and 0 <= y < M and grid[x][y] == 1: grid[x][y] = 2 cnt -= 1 next_level.append((x, y)) Q = next_level res += 1 return max(0, res - 1) if cnt == 0 else -1
dfb178847d6a18bb405251e33f383b25b7cd2f06
t0kage/palettes
/imagehelper.py
397
3.578125
4
from PIL import Image, ImageDraw def draw_image_from_palette(palette, height): paletteout = Image.new('HSV', (len(palette)*height, height), color=255) palettedraw = ImageDraw.Draw(paletteout) for i in range(len(palette)): shape = (height * i, height, height * (i + 1), 0) palettedraw.rectangle(shape, fill=palette[i]) paletteout.show()
32c2dfdba80a9c2fb6889545ef6b07a6e588ea4b
fshahinfar1/SlidingPuzzle
/board.py
3,286
3.578125
4
import pygame import card from random import randrange tmp = [0, 1, 2, 3, 4, 5, 6, 7, 8] white = (255, 255, 255) class Board(object): def __init__(self): self.grid = [] self.z_pos = [2, 2] lst_tmp = [] count = 1 self.cols , self.rows = 3, 3 for i in range(self.cols): for j in range(self.rows): #index = randrange(len(tmp)) #num = tmp[index] #new_card = card.Card(num) new_card = card.Card(count) lst_tmp.append(new_card) count += 1 if count == 9: count = 0 #del tmp[index] self.grid.append(lst_tmp) lst_tmp = [] self.pos = (50, 50) self.size = self.width, self.height = 200, 200 self.shuffle() def shuffle(self): key_map = {0: self.k_up, 1: self.k_down, 2: self.k_left, 3: self.k_right} for t in range(100): x = randrange(4) key_map[x]() def change_cards(self, pos0, pos1): x0, y0 = pos0 x1, y1 = pos1 if x1 < 0 or y1 < 0 or x1 > 2 or y1 > 2: return self.grid[x0][y0], self.grid[x1][y1] = self.grid[x1][y1], self.grid[x0][y0] self.z_pos = pos1 def get_zero(self): for i in range(3): for j in range(3): if self.grid[i][j].num == 0: return i, j return -1, -1 def draw(self, screen): rect = [self.pos[0],self.pos[1],self.width,self.height] pygame.draw.rect(screen,white,rect) for i in range(3): for j in range(3): new_pos = [0,0] new_pos[0] = 3 + self.pos[0] + (j * 65) new_pos[1] = 3 + self.pos[1] + (i * 65) self.grid[i][j].draw(screen, new_pos) def k_up(self): new_pos = [0, 0] new_pos[0] = self.z_pos[0] + 1 new_pos[1] = self.z_pos[1] self.change_cards(self.z_pos, new_pos) def k_down(self): new_pos = [0, 0] new_pos[0] = self.z_pos[0] -1 new_pos[1] = self.z_pos[1] self.change_cards(self.z_pos, new_pos) def k_right(self): new_pos = [0, 0] new_pos[0] = self.z_pos[0] new_pos[1] = self.z_pos[1] - 1 self.change_cards(self.z_pos, new_pos) def k_left(self): new_pos = [0, 0] new_pos[0] = self.z_pos[0] new_pos[1] = self.z_pos[1] + 1 self.change_cards(self.z_pos, new_pos) def check_board_state(self): correct_rows = 0 for i in range(self.rows): row = self.grid[i][:] if row[0].num != i + 1 + i * (self.cols - 1): continue # check the next row this one is not correct flag = True for j in range(self.cols - 1): if row[j].num +1 != row[j+1].num: if not ((i == self.rows - 1) and (j == self.cols -2) and (row[j+1].num == 0)): flag = False break # this row is not correct if flag: correct_rows += 1 if correct_rows == self.rows: return True return False
d003b7b30059067b1138037c409a3b1fcda98244
mohanRajCodes/python-project-todo
/buttonLearn.py
1,077
3.75
4
#####Button##### from tkinter import * import tkinter #import tkMessageBox from tkinter import messagebox top = Tk("Hello","Hello") def sayHello(): #messagebox = "Hello World !!!" #Text = "Hello " #Message = "Hello Message" #tkinter.messagebox.showinfo("Hellow", "World"); messagebox.showinfo("Heelo","Heelllo"); B = Button(top,text="Hello",command=sayHello); B.pack() B.flash(); top.mainloop() # Importing tkinter module from tkinter import * from tkinter.ttk import * # creating Tk window master = Tk() # setting geometry of tk window master.geometry("200x200") # button widget b1 = Button(master, text = "Absolute !") b1.place( x =100, y = 10 ) b3 = Button(master, text = "Relative !") b3.place( relx =0.5, y = 50 ,anchor= NW) # label widget l = Label(master, text = "I'm a Label") l.place(anchor = NW) # button widget b2 = Button(master, text = "GFG") b2.place(relx = 0.5, rely = 0.5, anchor = CENTER) # infinite loop which is required to # run tkinter program infinitely # until an interrupt occurs mainloop()
17e32ef0c8e37e87d29256cf6fab48593ffcf17e
wxhheian/ptcb
/ch2/ex2_1.py
821
4.09375
4
#你需要将一个字符串分割成多个字段,但分割符号(包括空格)不是固定的 #string对象的split()方法只适用于简单的字符串分割,它不允许有多个分割符 #re.split()分割字符串适用不同的分割符号 #正则表达式分割字符窗 import re def split_str(): line = 'asdf fjdk; afed, fjek,asdf, foo' print(re.split(r'[;\s,]\s*',line)) print(re.split(r'(;|,|\s)\s*',line)) #正则表达式如果使用了()捕获分组,那么被匹配到的文本也将出现在结果列表中 fields = re.split(r'(;|,|\s)\s*',line) values = fields[::2] delimiter = fields[1::2] + [''] print(''.join(v+d for v,d in zip(values,delimiter))) print(re.split(r'(?:,|;|\s)\s*',line)) if __name__ == '__main__': split_str()
c0fb24ecb5f350eebdf4c7df607c30c1a6fb40d4
lozanocelia/DyClee
/datasets/customCircunferencesDataset.py
3,002
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from math import pi, cos, sin, radians import random # config ------------------------------------------------------------------------------------------ # circumference properties h = 0 k = 0 ratio = 1 maxRatioInc = 0.5 ratioPortionForCenterPoints = 10 / 100 * ratio # batch represents the amount of points to generate per list at a given angle # we will have 180 * batch points in each list pointsPerAngle = 5 # pointsPerListToAppend represents the amount of points from a list to be added one next to the other to the dataset pointsPerListToAppendToDataset = 100 # dataset formation ------------------------------------------------------------------------------------------ # the idea is to get an angle and then use the circunference geometric interpretation and trigonometry to generate points # on it def point(theta): # increase a little bit the radio [or not] r = ratio + random.uniform(0, maxRatioInc) # increase or decrease theta (angle) theta = theta + random.uniform(0, radians(1)) - random.uniform(0, 0.5) # cos(theta) * r --> difference between the point x coordinate and the circumference center one (h) # sin(theta) * r --> difference between the point y coordinate and the circumference center one (y) return [h + cos(theta) * r, k + sin(theta) * r] def generatePoints(): # points lists upperPoints = [] lowerPoints = [] centerPoints = [] # theta represents the angle with respect to the x axis from which we will rotate around the circumference center for theta in range(0, 180): for i in range(0, pointsPerAngle): # to generate the upper points we move from right to left (from 0° to 180°) upperPoints.append(point(radians(theta))) # to generate the lower points we move from left to right (from 180° to 360°) lowerPoints.append(point(pi + radians(theta))) # to generate the center points we move from right to left but considering a small portion of the original ratio # centerPoints.append(point(h, k, centerPointsR, maxRadioInc, radians(theta))) return upperPoints, centerPoints, lowerPoints def generateDataset(): upperPoints, centerPoints, lowerPoints = generatePoints() # parameters regarding the points batchs per list formation batchUpperLimit = 0 batchLowerLimit = 0 limIterator = len(upperPoints) res = [] for i in range(0, limIterator): # increment the batchUpperLimit batchUpperLimit += pointsPerListToAppendToDataset # select points batches from every list res = res \ + upperPoints[batchLowerLimit:batchUpperLimit] \ + centerPoints[batchLowerLimit:batchUpperLimit] \ + lowerPoints[batchLowerLimit:batchUpperLimit] # now make batchLowerLimit equal to batchUpperLimit batchLowerLimit = batchUpperLimit return res customCircunferencesDataset = generateDataset()
a0e39f647eb81dad3737c78f859ccf576dc8fca3
iamdoublewei/Leetcode
/Python3/2363. Merge Similar Items.py
2,712
3.734375
4
''' You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item. The value of each item in items is unique. Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei. Note: ret should be returned in ascending order by value. Example 1: Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]] Output: [[1,6],[3,9],[4,5]] Explanation: The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6. The item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9. The item with value = 4 occurs in items1 with weight = 5, total weight = 5. Therefore, we return [[1,6],[3,9],[4,5]]. Example 2: Input: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]] Output: [[1,4],[2,4],[3,4]] Explanation: The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4. The item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4. The item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. Therefore, we return [[1,4],[2,4],[3,4]]. Example 3: Input: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]] Output: [[1,7],[2,4],[7,1]] Explanation: The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7. The item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. The item with value = 7 occurs in items2 with weight = 1, total weight = 1. Therefore, we return [[1,7],[2,4],[7,1]]. Constraints: 1 <= items1.length, items2.length <= 1000 items1[i].length == items2[i].length == 2 1 <= valuei, weighti <= 1000 Each valuei in items1 is unique. Each valuei in items2 is unique. ''' class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: lookup = {} for item in items1: if item[0] in lookup: lookup[item[0]] += item[1] else: lookup[item[0]] = item[1] for item in items2: if item[0] in lookup: lookup[item[0]] += item[1] else: lookup[item[0]] = item[1] lookup = sorted(lookup.items(), key=lambda x: x[0]) return [list(x) for x in lookup]
32e85340ccf3c97854074f9f845664c8a5102c3e
OldDon/UdemyPythonCourse
/UdemyPythonCourse/string_formatting.py
989
3.8125
4
name = "Dave" age = 50 accurate_age = 49+11/12 print("Hello %s is %d years old. Or better yet, %f years old." % (name, age, accurate_age)) # %s format string # %d format integer # %f format float print("Hello %s is %d years old. Or better yet, %.2f years old." % (name, age, accurate_age))# %s format string # %d format integer # %.2f format float to 2 decimal places print("Hello %s is currently %d years old. In ten years time will be %.2f" % (name, age, accurate_age + 10))# %s format string data = ("Dave", "Elliott", 53.44) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data)
700a02d84ec74c21d8ed06e4c8767625fb31ff6c
Kylar42/wvup
/Project Euler/euler220c.py
1,698
3.734375
4
import time listOfPowers=[] for i in range(0, 50): listOfPowers.append(pow(2,i)) def divisiblePowerOf2odd(someNumber): #print "number looking at is: %i" % someNumber for i in range(0, len(listOfPowers)): pow = listOfPowers[i] if(0 == someNumber % pow): dividend = someNumber / pow if(0 == dividend % 2): continue else: return pow def leftOrRight(someNumber): pow2 = divisiblePowerOf2odd(someNumber) oddNum = someNumber / pow2 mod = oddNum % 4 #print "lr somenum: %i pow: %i mod %i" % (someNumber, pow2, mod) if(mod == 3): return True#L elif(mod == 1): return False#R else: print "Found bad value: %i 2pow: %i mod: %i" % (someNumber, pow2, mod) def nextTuple(currentlocation, move): x = currentlocation[0] y = currentlocation[1] direction = currentlocation[2] #print "x: %i y: %i d: %i" % (x,y,direction) step = False if(0 == direction): y += 1 elif(1 == direction): x += 1 elif(2 == direction): y -= 1 elif(3 == direction): x -= 1 step = True return (step, (x, y, direction)) def rotate(currentlocation, move): dir = currentlocation[2] if(move): dir = (dir-1) %4 else: dir = (dir+1) %4 return (currentlocation[0], currentlocation[1], dir) # x: 2 y: -1 d: 2 is step #5. #curTuple = (2,0,1)#after turn 3? curTuple = (2,-1,2)#turn 4 #print leftOrRight(6) dest = 1000000 startTime = time.time() for i in range(5,dest): nextchar = leftOrRight(i) #print "i: %i %c" % (i, nextchar) #(didStep, curTuple) = nextTuple(curTuple, nextchar) curTuple = rotate(curTuple, nextchar) (didStep, curTuple) = nextTuple(curTuple, 'F') #if(i % 10000 == 0): # print "running val: %i" % i print time.time() - startTime print curTuple
fc2e695e9d09d0d62ee8bcaccb975d6f4e64fabe
GlitchLight/Algorithms_DataStructures_Python
/Алгоритмы/Базовые алгоритмы/Небольшое число Фибоначчи/small_fibo.py
442
3.703125
4
# Дано целое число 1 <= n <= 40. Вычислить n-e число Фибоначчи def fib(n): # put your code here if n == 0: return 0 elif n == 1: return 1 else: a = 0 b = 1 for i in range(2, n + 1): F = a + b a = b b = F return F def main(): n = int(input()) print(fib(n)) if __name__ == "__main__": main()
c3c23f50ca59841ffc24dcd595f692544cd8476f
curiousTauseef/Face-Recognizer
/interface.py
1,442
3.75
4
import tkinter as tk class App(tk.Tk): """ Basic app class to initialize everything """ def __init__(self, title: str = None, size: tuple = None) -> None: super().__init__() self.geometry('{}x{}'.format(size[0], size[1])) self.size = size self.bind('<Escape>', self.kill) self.resizable(False, False) self.title(title) def kill(self, event): self.destroy() def add_button(self, side: str = "top", padding: tuple = (20, 20), width: int = 10, text: str = "Button", frame: tk.Frame = None) -> tk.Button: if frame is None: frame = self btn = tk.Button(frame) btn['text'] = text btn['width'] = width btn.pack(side=side, padx=padding[0], pady=padding[1]) return btn def add_label(self, text: str = "label", width: int = 30, frame: tk.Frame = None, side: str = 'top') -> tk.Label: if frame is None: frame = self lbl = tk.Label(frame, anchor='w') lbl['text'] = text lbl['width'] = width lbl.pack(side=side) return lbl def add_entry(self, frame: tk.Frame = None, initial_text: str = '', side: str = 'top') -> tk.Entry: if frame is None: frame = self entry = tk.Entry(frame) entry.insert(0, initial_text) entry.pack(side=side, expand=tk.YES, fill=tk.X) return entry
832f5de6e017bf726afcc9813423812316808670
krnets/codewars-practice
/8kyu/Find Maximum and Minimum Values of a List/index.py
1,510
4
4
# 8kyu - Find Maximum and Minimum Values of a List """ Your task is to make two functions, max and min that take a(n) array/vector of integers list as input and outputs, respectively, the largest and lowest number in that array/vector. maximun([4,6,2,1,9,63,-134,566]) returns 566 minimun([-52, 56, 30, 29, -54, 0, -110]) returns -110 maximun([5]) returns 5 minimun([42, 54, 65, 87, 0]) returns 0 You may consider that there will not be any empty arrays/vectors. """ # def minimun(arr): # low = float("inf") # for i in arr: # if i < low: # low = i # return low # def maximun(arr): # high = float("-inf") # for i in arr: # if i > high: # high = i # return high def minimun(arr): low = arr[0] for i in arr[1:]: if i < low: low = i return low def maximun(arr): high = arr[0] for i in arr[1:]: if i > high: high = i return high # def minimun(arr): # return list(sorted(arr))[0] # def maximun(arr): # return list(sorted(arr))[-1] q = minimun([-52, 56, 30, 29, -54, 0, -110]) # -110 q q = minimun([42, 54, 65, 87, 0]) # 0 q q = minimun([1, 2, 3, 4, 5, 10]) # 1 q q = minimun([-1, -2, -3, -4, -5, -10]) # -10 q q = minimun([9]) # 9 q q = maximun([-52, 56, 30, 29, -54, 0, -110]) # 56 q q = maximun([4, 6, 2, 1, 9, 63, -134, 566]) # 566 q q = maximun([5]) # 5 q q = maximun([534, 43, 2, 1, 3, 4, 5, 5, 443, 443, 555, 555]) # 555 q q = maximun([9]) # 9 q
61290954e301f984a07dc1c7d8159ce9602e1914
bozhikovstanislav/Python-Fundamentals
/List-Dictionarys/List_HomeWork/06.OddNumberAtOddPosition.py
244
3.828125
4
from typing import List number_list = list(map(int, input().split(' '))) list_odd: List[int] = [] list_odd = [print(f'Index {x} -> {number_list[x]}') for x in range(0, len(number_list)) if x % 2 != 0 and number_list[x] % 2 != 0]
d55cee6bf20e0cab58ed87dac7135e7d9631f861
mfreund/python-labs
/08_file_io/08_01_words_analysis.py
585
4.34375
4
''' Write a script that reads in the words from the words.txt file and finds and prints: 1. The shortest word (if there is a tie, print all) 2. The longest word (if there is a tie, print all) 3. The total number of words in the file. ''' word_list = [] with open('words.txt', 'r') as words: for word in words.readlines(): word = word.strip() word_list.append(word) print(f"The shortest word is {min(word_list, key=len)}") print(f"The longest word is {max(word_list, key=len)}") print(f"The total amount of words in this file is {len(word_list)}")
d0d36c703297f42c876a546e7bad230bb1472158
EliakinCosta/python_sessao_da_tarde
/code/numeros_pares_certo.py
91
3.765625
4
lista = [1, 2, 3, 4, 5, 6, 7, 8] print([elemento for elemento in lista if elemento%2==0])
c7239c264302414454693a6ad824499ac0007558
JoshCLWren/python_stuff
/map.py
453
4.09375
4
num = [2, 4, 6, 8, 10] doubles = list(map(lambda x: x*2, num)) print(doubles) people = ["josh", "me", "too"] peeps = map(lambda name: name.upper(), people) list(peeps) print(peeps) # map(function or lambad here: iterator, what you are iteratin) returns the item mapped with the function performed on each element in it nums = [1,2,3,4] def decrement_list(nums): return list(map(lambda numbers: numbers - 1, nums)) print(decrement_list(nums))
1763dbf110d5348a2697f5f34ea4a86266e47a90
acaciooneto/cursoemvideo
/ex_aulas/ex.aula9-022.py
191
3.609375
4
nome = input('Digite seu nome completo: ') print(nome.upper()) print(nome.lower()) print(nome.title()) name = nome.split() joi = ''.join(name) print(len(joi)) print(name) print(len(name[0]))
b681a6b9a43fc18140c325d0e77e3bb0387097e6
naveen6797/python-tutorials
/programs/odd_or_not.py
188
4.3125
4
number = int(input("enter number:")) if number % 2 != 0: print("{} is odd number".format(number)) else: print("{} is not odd number".format(number)) print("program is completed")
60e703f031930da758af9e094df059e85f554e4c
forzen-fish/python-notes
/10.面向对象下/2单继承与多继承.py
781
3.984375
4
""" 单继承 class Dog(object): def __init__(self,color = "white"): self.color = color def run(self): print("run") class RED_Dog(Dog): pass dog1 = RED_Dog("red") dog1.run() print(dog1.color) 父类的私有方法和私有属性是不会被子类继承的,也不能被子类访问 """ """ 多继承 子类继承多个父类 语法格式: class 子类(父类1,父类2...) 代码 class 陆地生物: def ludi(self): print("地上爬的") class 水下生物: def shuixia(self): print("水里游的") class 蛤蟆(陆地生物,水下生物): pass 蛤蟆1 = 蛤蟆() 蛤蟆1.shuixia() 蛤蟆1.ludi() 如果继承关系复杂,通过mro算法找到合适的类, 调用__mro__()方法可以查看先后顺序 """
36e20861253990eed5deaade35ecb4aa9325d4c0
michaelcyng/python_tutorial
/tutorial6/while_loop_examples/break.py
357
4.25
4
print("Please enter a positive integer") required_count = int(input()) count = 1 print("Start counting") while count <= required_count: # The following runs as long as this condition is true print("Count: {0}".format(count)) count += 1 if count > 5: print("Count is greater than 5. Exit the loop") break print("Left the loop")
2bfa29f73a3bd92d34a316489fd0c8d9b16e8e89
karthikgvsk/project-euler
/p34.py
860
4.03125
4
# Digit factorials # upper bound is important from math import log def getDigits(num): l = [] while num > 10: l.append(num % 10) num = num // 10 if num == 10: l.append(1) l.append(0) else: l.append(num) return l # producing the factorial list factList = [1] i = 1 prod = 1 while i <= 9: prod = prod * i factList.append(prod) i = i + 1 # taking the right numbers num = 1 LARGE = 2 * log(factList[9]) * factList[9] mainList = [] stop = False while not stop: #num <= LARGE: digits = getDigits(num) sum1 = 0 for digit in digits: sum1 = sum1 + factList[digit] if num == sum1: mainList.append(num) num = num + 1 nineFactorial = factList[9] if num > nineFactorial * log(num): stop = True print mainList print factList print sum(mainList) print "you should subtract 3 from the sum" print "since cases 1 and 2 are not to be included"
a05ceb6d95e4271e5342de877f075d24d3e88593
janeosaka/AdventOfCode
/2020/day5/Day5_BinaryBoarding.py
737
3.59375
4
def open_file(): with open('../seats.txt', 'r') as f: seat_list = f.readlines() return seat_list def part1(): seat_list = open_file() seats = [] for record in seat_list: record = (record.replace('F', '0').replace('B', '1').replace('R', '1').replace('L', '0')) row = int(record[:7], 2) col = int(record[7:], 2) seat = (row * 8) + col seats.append(seat) print(max(seats)) return sorted(seats) print(part1()) def part2(): seat_list = part1() for i, seats in enumerate(seat_list): if min(seat_list) < seats < max(seat_list): if seat_list[i + 1] - seats == 2: print(seats + 1) break part2() exit()
c53361d698f1e4991cb0a691ccccf367a1b293b3
kashyap1810/pythonbasics-
/list.py
315
3.96875
4
#list employees=['adam','john','greg','danna','ashley'] print('employees length : '+ str(employees.__len__())) employees[1]='jack' print(employees) employees.insert(3,'mavrik') print(employees) employees.remove('mavrik') print(employees) employees.append('mavrik') print(employees) employees.pop() print(employees)
767deef8f9cbf2ae558b5d42aaa2ed0866082cf7
ejonakodra/holbertonschool-machine_learning-1
/pipeline/0x04-data_augmentation/5-hue.py
430
3.765625
4
#!/usr/bin/env python3 """ Defines function that changes the hue of an image """ import tensorflow as tf def change_hue(image, delta): """ Changes the hue of an image parameters: image [3D td.Tensor]: contains the image to change delta [float]: the amount the hue should change returns: the altered image """ return (tf.image.adjust_hue(image, delta))
5634707575cfaa10215d34abb0d39ab42748c7a8
kolevatov/python_lessons
/week4/4_9.py
963
4.28125
4
# Быстрое возведение в степень """ Возводить в степень можно гораздо быстрее, чем за n умножений! Для этого нужно воспользоваться следующими рекуррентными соотношениями: aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n. Реализуйте алгоритм быстрого возведения в степень. Если вы все сделаете правильно,то сложность вашего алгоритма будет O(logn). Формат ввода Вводится действительное число a и целое число n. Формат вывода Выведите ответ на задачу. """ A = float(input()) N = int(input()) if N % 2 == 0: result = (A ** 2) ** (N // 2) else: result = A * A ** (N - 1) print(result)
1be6126987ffad639cf9fdadf4073cfabc8b5aae
shubham1172/pyfinbar
/pyfinbar/stock_record.py
1,222
3.625
4
from pyfinbar.console import Colors class StockRecord: '''StockRecord represents the state of a stock. Ticker is the stock symbol. Prevclose is the last day's closing price. Close is today's closing price. usage: record = StockRecord("YESBANK", 12, 14.5) ''' def __init__(self, ticker, prevclose, close): super().__init__() self.ticker = ticker self.prevclose = prevclose self.close = close def change(self): return 100*(self.close - self.prevclose)/self.prevclose def to_string(self, colored=False): delta = self.change() s = "%s %.2f " % (self.ticker, self.close) suff = "%+.2f%%" % delta if not colored: return s + suff if delta > 0: color = Colors.GREEN elif delta < 0: color = Colors.RED else: color = Colors.GRAY return s + color + suff + Colors.ENDC def to_object(self): return \ { "TICKER": self.ticker, "CLOSE": "%.2f" % self.close, "CHANGE": "%+.2f%%" % self.change() } def __str__(self): return self.to_string()
2adcce7c1c754878c998011df308de8d56787f33
Foknetics/AoC_2019
/day_15/part2-1.py
1,520
3.53125
4
import json with open('tile_map.json') as tile_data: string_map = json.load(tile_data) tile_map = {} for coord in string_map.keys(): x, y = coord[1:-1].split(', ') tile_map[(int(x), int(y))] = string_map[coord] def print_map(): output = '' for y in range(21, -20, -1): row = '' for x in range(-21, 20): tile = tile_map.get((x, y)) if tile is None: row += ' ' elif tile == 2: row += 'O' elif tile == 3: row += 'o' elif tile == 0: row += '█' elif tile == 1: row += '░' output += row+'\n' print(output, end='\r') def lacking_oxygen(): tiles = [] for coord in tile_map: tiles.append(tile_map[coord]) return 1 in tiles minutes = 0 while lacking_oxygen(): minutes += 1 for coord in tile_map: if tile_map[coord] == 2: x, y = coord if tile_map.get((x+1, y)) == 1: tile_map[(x+1, y)] = 3 if tile_map.get((x-1, y)) == 1: tile_map[(x-1, y)] = 3 if tile_map.get((x, y+1)) == 1: tile_map[(x, y+1)] = 3 if tile_map.get((x, y-1)) == 1: tile_map[(x, y-1)] = 3 #print(f'After {minutes} minutes') #print_map() for coord in tile_map.keys(): if tile_map[coord] == 3: tile_map[coord] = 2 print(f'Oxygen will spread in {minutes} minutes')
1240a0f951459bf4d50a7a78c6c315c9d9ff0472
nathanychin/Python-MySQL
/main.py
1,332
3.53125
4
from database import cursor, db def add_log(text, user): sql = ("INSERT INTO logs(text, user) VALUES (%s, %s)") cursor.execute(sql, (text, user,)) db.commit() log_id = cursor.lastrowid print("Added log {}".format(log_id)) def get_logs(): sql = ("SELECT * FROM logs ORDER BY created DESC") cursor.execute(sql) result = cursor.fetchall() for row in result: print(row[1]) def get_log(id): sql = ("SELECT * FROM logs WHERE id = $s") cursor.execute(sql, (id,)) result = cursor.fetchone() for row in result: print(row) def update_log(id, text): sql = ("UPDATE logs SET text = %s WHERE id = %s") cursor.execute(sql, (text, id)) db.commit() print("Updated log {}".format(id)) def delete_log(id): sql = ("DELETE FROM logs WHERE id = %s") cursor.execute(sql, (id,)) db.commit() print("Log {} deleted".format(id)) # Logs added to table add_log('This is log one', 'Nathan') add_log('This is log two', 'Meagan') add_log('This is log three', 'Jack') # Get all current logs get_logs() # Get this specific log get_log(2) # Update this specific log update_log(2, 'Updated log') # Show update get_logs() # Delete this specific log delete_log(2) # Show current logs get_logs()
54ac6f0e4b3a024a298d119291dcf1e38e5bf894
maobinchen/data_structure
/c7/insert_sort.py
903
3.53125
4
from DoublyLinkedBase import PositionalList import random def insertion_sort(L): if len(L) > 1: marker = L.first() while marker != L.last(): pivot = L.after(marker) value = pivot.element() if value > marker.element(): marker = pivot else: walk = marker while walk != L.first() and L.before(walk).element() > value: walk = L.before(walk) L.delete(pivot) L.add_before(walk,value) if __name__ == '__main__': PQ = PositionalList() s = PQ.add_first(1) PQ.add_after(s,5) PQ.add_before(s,3) PQ.add_first(9) PQ.add_first(11) print PQ insertion_sort(PQ) print PQ N = 100 L = PositionalList() for i in range(N) : L.add_first(random.randint(1,1000)) print L insertion_sort(L) print L
955729066bdc244656809bd520dfb8b45f13efce
SimmonsChen/LeetCode
/周赛/5543. 两个相同字符之间的最长子字符串.py
752
3.875
4
""" 给你一个字符串 s,请你返回 两个相同字符之间的最长子字符串的长度 ,计算长度时不含这两个字符。 如果不存在这样的子字符串,返回 -1 。 子字符串 是字符串中的一个连续字符序列 """ class Solution(object): def maxLengthBetweenEqualCharacters(self, s): """ :type s: str :rtype: int """ res = -2 mylist = list(s) for i, item in enumerate(mylist): if item in mylist[:i]: if res < i - s.index(item) - 1: res = i - s.index(item) - 1 return res if res != -2 else -1 if __name__ == '__main__': s = Solution() print(s.maxLengthBetweenEqualCharacters(s="aa"))
17104dc4e9a0b27958a6e57d5b65ecdbd501bb2c
sungwooman91/python_code
/03.Data_Science/csv_test.py
1,240
3.6875
4
import csv with open("Demographic_Statistics_By_Zip_Code.csv", newline="") as infile: data = list(csv.reader(infile)) ## No1_COUNT PARTICIPANTS countParticipantsIndex = data[0].index("COUNT PARTICIPANTS") print("The index of 'COUNT PARTICIPANTS': %s" % countParticipantsIndex) # print("The index of 'COUNT PARTICIPANTS': " +str(countParticipantsIndex)) countParticipants = [] # index = 0 for row in data[1:]: countParticipants.append(int(row[countParticipantsIndex])) print("The contents of 'COUNT PARTICIPANTS': %s" % countParticipants) ## No2_COUNT CITIZEN STATUS TOTAL countCitizenStatusTotalIndex = data[0].index("COUNT CITIZEN STATUS TOTAL") print("The index of 'COUNT CITIZEN STATUS TOTAL': %s" % countCitizenStatusTotalIndex) countCitizenStatusTotal = [] for row in data[1:]: countCitizenStatusTotal.append(int(row[countCitizenStatusTotalIndex])) print("The contents of 'COUNT CITIZEN STATUS TOTAL': %s" % countCitizenStatusTotal) ## No3_COUNT FEMALE countFemaleIndex = data[0].index("COUNT FEMALE") print("The index of 'COUNT FEMALE': %s" % countFemaleIndex) countFemale = [] for row in data[1:]: countFemale.append(int(row[countFemaleIndex])) print("The contents of 'COUNT FEMALE': %s" % countFemale)
eb076b873094942de4200320d1c3f1e64c7bccdc
pacerrabbit/mock-signup-page
/models.py
1,003
3.578125
4
# Standard libs from collections import OrderedDict # Mock user collection # Maps username to User object. Only stores data in memory, so it won't persist # anything when the app exits. I'm using an OrderedDict so that users will be # listed in the order in which they're created. USER_COLLECTION = OrderedDict() class User(object): @classmethod def create(cls, username, email, password_hash): # Create a user and store them in the mock collection user = User(username, email, password_hash) USER_COLLECTION[username] = user return user @classmethod def get_by_username(cls, username): # Retrieve a user by their username return USER_COLLECTION.get(username, None) @classmethod def get_all(cls): # Retrieve all users return USER_COLLECTION.values() def __init__(self, username, email, password_hash): self.username = username self.email = email self.password_hash = password_hash
c49d9801cd29c28921e00116463ce6732b58105f
cooleel/HackerRank
/Mini_Max_Sum.py
380
3.828125
4
#!/bin/python3 #by Shanshan Wang #https://www.hackerrank.com/cooleel #!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): min_ = sum(arr)-max(arr) max_ = sum(arr)-min(arr) print(min_, max_) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
b48e773d9cd3894c3dc7b772d9014ebfc92cf187
joseangel-sc/CodeFights
/Arcade/SortingOutpost/maximumSum.py
1,108
3.671875
4
def maximumSum(A, Q): A.sort() b = [0]*len(A) for q in Q: for i in range(q[0],q[1]+1): b[i] += 1 b.sort() sol = 0 for i in range(len(A)): sol += A[i]*b[i] return sol '''You are given an array of integers A. Range sum query is defined by a pair of non-negative integers L and R (L <= R). An output to a range sum query on the given array is the sum of all elements of A with indices from L to R inclusive. Find an algorithm that given a list of range sum queries can rearrange the array A in such a way that the total sum of all of the query outputs is maximized. Example For A = [2, 1, 2] and Q = [[0, 1]], the output should be maximumSum(A, Q) = 4. Input/Output [time limit] 4000ms (py) [input] array.integer A An initial array. Constraints: 2 ≤ A.length ≤ 10, 1 ≤ A[i] ≤ 10. [input] array.array.integer Q Array of range sum queries, each query is an array of two non-negative integers. Constraints: 1 ≤ Q.length ≤ 10, 0 ≤ Q[i][j] ≤ 10. [output] integer Maximum possible total sum of the given range sum query outputs.'''
3c7b41a6fccbf14805c150cab1e44d9043f0518f
kalyons11/kevin
/kevin/leet/score_of_parentheses.py
1,671
3.765625
4
""" https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/587/week-4-february-22nd-february-28th/3651/ """ class Solution: def score_of_parentheses(self, S: str) -> int: # recursive approach potentially? # need to get down to base cases of (), (A), (AB) # know S is balanced # len(S) is even - same number of ( and ) in proper stack ordering # stack never errors out, stack empty at end of string # can we use this? if S == '()': return 1 # attempt to find index that splits into A and B case # index must be at least 2, and can increment by 2 for split in range(2, len(S) - 1, 2): if self._is_balanced(S[:split]) and self._is_balanced(S[split:]): return self.score_of_parentheses(S[:split]) + \ self.score_of_parentheses(S[split:]) # otherwise, must be (A) case return 2 * self.score_of_parentheses(S[1:len(S) - 1]) def _is_balanced(self, s: str) -> bool: # return True iff s is balanced count = 0 for c in s: if c == '(': count += 1 elif c == ')': count -= 1 if count < 0: return False return count == 0 # taken from discussion # O(n) runtime, O(1) memory - very nice class SolutionOptimized: def score_of_parentheses(self, S: str) -> int: ans, bal = 0, 0 for i, s in enumerate(S): bal = bal + 1 if s == "(" else bal - 1 if i > 0 and S[i-1:i+1] == "()": ans += 1 << bal return ans
e15bdc4a6356b0ef710261bf94ab3120245d7b3c
LezamaCybart/scientific_computing_with_python_fcc
/probability_calculator/prob_calculator.py
1,280
3.703125
4
import copy import random # Consider using the modules imported above. class Hat: hat = dict() contents = list() def __init__(self, **balls): self.hat = balls for color in self.hat: for number in range(self.hat[color]): self.contents.append(color) def draw(self, amount): top = amount balls_drawed = list() if top >= len(self.contents): balls_drawed = self.contents else: while(top > 0): balls_drawed.append(self.contents.pop(random.randint(0, top))) top = top -1 return balls_drawed def experiment(hat, expected_balls, num_balls_drawn, num_experiments): m = 0 the_expected_balls = list() for color in expected_balls: for number in range(expected_balls[color]): the_expected_balls.append(color) #the_expected_balls.sort() for experiment in range(num_experiments): copy_hat = copy.copy(hat) returned_balls = copy_hat.draw(num_balls_drawn) #returned_balls.sort() #if the_expected_balls in returned_balls: if all(elem in the_expected_balls for elem in returned_balls): m = m +1 return m / num_experiments
9e699bbab2e386ac0fd8b8bcb3723dc3661a05ab
dogac00/Python-General
/linked-list-python.py
571
3.9375
4
class Node: def __init__(self, value): self.value = value self.next = None def printNode(self): print(self.value, end=" -> None") class LinkedList: def __init__(self, value): self.value = value self.next = None def insertValue(self, value): while self.next: self = self.next self.next = Node(value) def printList(self): while self: print(self.value, end=" -> ") self = self.next print("None") myList = LinkedList(5) myList.insertValue(7) myList.insertValue(9) myList.insertValue(11) myList.printList()
6a74266d357961d84c5bfa28c894d348d6bbe95d
SerhiiDior/soft_100_task
/100_tasks/unit_test/problems/2.py
96
3.921875
4
number=int(input("Number=")) fact=1 i=1 while (i<=number): fact=fact*i i+=1 print(fact)
e60e90488ec575599e4bef54832824c5629b8cd0
rajarajann/Labs
/openbook3_task1.py
971
3.65625
4
fin = open ("Bus_Stops.csv") def total_terminals(): fin = open("Bus_Stops.csv") counter = 0 for lines in fin: line_list = lines.split(",") if line_list[10] == "Terminal": counter +=1 print ("Total number of Terminals :", counter) def total_busstop(): fin = open("Bus_Stops.csv") counter = 0 for lines in fin: line_list = lines.split(",") if line_list[10] == "Conventional Transit Bus Stop": counter +=1 print ("Total number of Conventional Transit Bus Stop :", counter) total_terminals() total_busstop() def assessible_terminals(line_list): #fin = open("Bus_Stops.csv") counter = 0 if line_list [7] == "Accessible": counter +=1 accessible_terminals = line_list[6] print (accessible_terminals) return counter print ("List of Accessible Terminals:") for lines in fin: line_list = lines.split(",") assessible_terminals(line_list)
fdfb999efb42ecd020cb699359e30e7632a2de0e
Gijsbertk/afvinkblok1
/5.21.py
672
3.84375
4
import random #importeert library print('Je doet steen papier schaar, voor steen kies je 1 voor papier 2 en schaar 3') #print wat je moet doen def main(): game() #roept functie aan def game(): #functie speler = int(input('Kies een nummer voor steen papier schaar: ')) #vraagt om functie comp = random.randint(1, 3) # random getal wordt toegekend aan variabele print(comp) #print varaiabele while speler == comp: # als variabele gelijk is aan input speler = int(input('Kies een nummer voor steen papier schaar: ')) #opnieuw comp = random.randint(1, 3) # opnieuw main() #auteur gijsbert ekja
be4cc927cf5fcdb7da54ecacf3a5b6a24bd646f5
jamesro/BlackJackLearn
/blackjack/player.py
4,699
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from .cards import * from .hand import Hand from .table import Table class Player: def __init__(self, bank=1000): self.gameState = "" self.table = Table() self.bank = bank self.wins = 0 self.losses = 0 self.pushes = 0 self.naturals = 0 def bet(self,amount): self.gameState = "InPlay" self.betAmount = amount self.bank -= self.betAmount print("Betting $",amount) self.table.deal() if self.table.hand.total() == 21: print("Blackjack.") self.endPlay(Natural =True) def hit(self,Double=False): self.table.hand += self.table.deck.pop() print("\nHit: ",self.table.hand,"\n") if self.table.hand.total() == 21: self.endPlay() elif self.table.hand.total() > 21: self._lose() elif Double==True: # You can't keep playing after doubling self.endPlay() def stand(self): self.table.dealer_hand += self.table.hole_card print("\nStand.\nDealer's hand: ",self.table.dealer_hand) self.endPlay() def double(self): if len(self.table.hand.cards) == 2: self.bank -= self.betAmount self.betAmount *= 2 print("Double. Bet is $",self.betAmount) self.hit(Double=True) elif len(self.table.hand.cards) > 2: raise DoubleError("Cannot double after hitting") def endPlay(self,Natural=False): while self.table.dealer_hand.total() < 17: self.table.dealer_hand += self.table.deck.pop() print("Dealer's hand: ",self.table.dealer_hand) if self.table.dealer_hand.total() == self.table.hand.total() <= 21: if Natural==True: self._natural() else: self._push() elif (self.table.dealer_hand > self.table.hand) and (self.table.dealer_hand.total() <= 21): self._lose() elif (self.table.dealer_hand.total() > 21) and (self.table.hand.total() <= 21): self._win() elif (self.table.dealer_hand < self.table.hand) and (self.table.hand.total() <= 21): self._win() def deckCheck(self): if len(self.table.deck._cards) <= 15: self.table.deck = Deck() def split(self): if self.table.hand.cards[0].hard == self.table.hand.cards[1].hard: if not self.table.hand.is_split: print("Split. Betting $",self.betAmount) self.bank -= self.betAmount self.table.splitHand.append(Hand(self.table.hand.cards[1], self.table.deck.pop(),is_split=True)) self.table.hand = Hand(self.table.hand.cards[0], self.table.deck.pop(),is_split=True) print("Your first hand: ",self.table.hand) else: raise SplitError("Hand has already been split") else: raise SplitError("Hand cannot be split") # def _endSplitGame(self): # try: # if this is the end of the first of the two hands # self.table.hand = self.table.other_hand # del self.table.other_hand # #self.gameState = "InPlay" # print("Your second hand: ",self.table.hand) # if self.table.hand.total() == 21: # self.endPlay() # except: # pass def _win(self): self.gameState = "Won" self.bank += 2 * self.betAmount print("\nYou win. You have $",self.bank,"\n") self.wins += 1 # if self.table.hand.is_split: # self._endSplitGame() self.deckCheck() def _lose(self): self.gameState = "Lost" print("\nYou lose. You have $",self.bank,"\n") self.losses += 1 # if self.table.hand.is_split: # self._endSplitGame() self.deckCheck() def _natural(self): self.naturals += 1 self.gameState = "Natural" self.bank += self.betAmount + 1.5*self.betAmount print("\nYou win. You have $",self.bank,"\n") # if self.table.hand.is_split: # self._endSplitGame() self.deckCheck() def _push(self): self.pushes += 1 self.gameState = "Push" self.bank += self.betAmount print("\nDraw. You have $",self.bank,"\n") # if self.table.hand.is_split: # self._endSplitGame() self.deckCheck() class SplitError(Exception): pass class DoubleError(Exception): pass
7541be8d53fe79ac6ce7ff459d67f0c3a1804e51
adarshnamsani/exam
/python-test1.py
3,371
4.21875
4
from placeholders import * def get_odds_list(count): """ This method returns a list of the first 'count' odd numbers in descending order. e.g count = 3 should return [5,3,1] """ return None def get_odd_mountain(count): """ odd mountain is a list of odd numbers going up from 1 and then back to 1. e.g. odd_mountain of size 5 is [1,3,5,3,1] odd_mountain of size 4 is [1,3,3,1] Hint: use the list functions and a builtin function we have already seen. """ return None def get_multiples_desc(number, count): """ return the first count multiples of number in desc order in a list. e.g call with input (3,2) returns [6,3] call with input(5,3) returns [15,10, 5] Hint: one line of code, use a builtin function we have already seen in the lists lesson. """ return None def get_sorted_diff_string(first, second): """ returns a string which contains letters in first but not in second. e.g.s apple and pig returns ael. """ return None def get_sorted_without_duplicates(input): """ returns a string in which characters are sorted and duplicates removed e.g apple returns aelp, engine returns egin """ return None def create_palindrome(word): pass # Sort the words that are passed in by word length instead of word content. # e.g ["apple", "dog", "elephant"] should result in ["elephant", "apple", "dog"] # hint: use list.sort, don't write your own def sort_by_length(words): pass def test_odds_list(): assert [1] == get_odds_list(1) assert [] == get_odds_list(0) assert [5,3,1] == get_odds_list(3) assert [9,7,5,3,1] == get_odds_list(5) def test_get_odd_mountain(): assert [1,1] == get_odd_mountain(2) assert [1,3,1] == get_odd_mountain(3) assert [1,3,5,7,5,3,1] == get_odd_mountain(7) assert [] == get_odd_mountain(0) def test_get_multiples_desc(): assert [6,3] == get_multiples_desc(3,2) assert [15, 10, 5] == get_multiples_desc(5,3) assert [] == get_multiples_desc(6, 0) assert [3,2,1] == get_multiples_desc(1, 3) def test_sorted_diff_string(): assert "" == get_sorted_diff_string("apple", "apple") assert "aelp" == get_sorted_diff_string("apple", "") assert "do" == get_sorted_diff_string("dog", "pig") assert "in" == get_sorted_diff_string("pineapple", "apple") def test_sorted_without_duplicates(): assert "aelp" == get_sorted_without_duplicates("apple") assert "eorz" == get_sorted_without_duplicates("zeroo") assert "" == get_sorted_without_duplicates("") assert "abcd" == get_sorted_without_duplicates("abcdabcd") def test_create_palindrome(): assert "battab" == create_palindrome("bat") assert "abba" == create_palindrome("ab") assert "" == create_palindrome("") assert None == create_palindrome(None) def test_sort_by_length(): assert ["apple", "bear", "dog"] == sort_by_length(["dog", "apple", "bear"]) assert ["apple", "bear", "dog"] == sort_by_length(["apple", "dog", "bear"]) assert ["apple", "dog", "cat"] == sort_by_length(["dog", "apple", "cat"]) assert ["elephant", "apple"] == sort_by_length(["apple", "elephant"]) assert ["three", "four", "one", "two"] == sort_by_length(["one", "two", "three", "four"]) assert [] == sort_by_length([]) assert None == sort_by_length(None)
d105ed0b71fc01c837aa6a8fa155b79f7dc66fc1
sridhar667/hello-world
/oddoreven.py
174
3.625
4
n = input() lst = [int(i) for i in n] for i in lst: if i%2==0: lst.remove(i) s = sum(lst) if s%2==0: print('Even') else: print('Odd')
9686d36a56d4e23d947011244a324ae568c81159
larsQue11/knn_electron_app
/backend/knn_iris.py
6,915
3.65625
4
# Course: CS7267 # Student name: William Stone # Student ID: 000-272-306 # Assignment #: 1 # Due Date: September 16, 2019 # Signature: # Score: import numpy as np from math import sqrt import csv import sys #retrieve data from CSV file def getData(dataPath): with open(dataPath) as dataFile: data = np.array(list(csv.reader(dataFile))) return data #calculate the Euclidean distance: sqrt( sum( (x.i - y.i)^2 ) ) def EuclideanDistance(testIris, knownIris): sumOfDifferences = 0 if testIris.sepal_length != -1: sumOfDifferences = sumOfDifferences + ((testIris.sepal_length-knownIris.sepal_length) ** 2) if testIris.sepal_width != -1: sumOfDifferences = sumOfDifferences + ((testIris.sepal_width-knownIris.sepal_width) ** 2) if testIris.petal_length != -1: sumOfDifferences = sumOfDifferences + ((testIris.petal_length-knownIris.petal_length) ** 2) if testIris.petal_width != -1: sumOfDifferences = sumOfDifferences + ((testIris.petal_width-knownIris.petal_width) ** 2) return sqrt(sumOfDifferences) #a function to evaluate the query against k neighbors #returns a prediction based on the evaluation def FindNeighbors(k,model,query): neighbors = [] #calculate the Euclidean distance between the query and all Irises in the model #the neighbors array keeps a running track of the k nearest neighbors, it is sorted closest-furthest #after each iteration, allowing the algorithm to test just the last position for iris in model: iris.setDistance(EuclideanDistance(query,iris)) if len(neighbors) < k: neighbors.append(iris) else: if iris.distance < neighbors[k-1].distance: neighbors[k-1] = iris neighbors.sort(key=lambda x: x.distance) #find the mode amongst the classifications is found in the final list of neighbors numSetosas = 0 numVersicolors = 0 numVirginicas = 0 for neighbor in neighbors: if neighbor.species == "Setosa": numSetosas = numSetosas + 1 elif neighbor.species == "Versicolor": numVersicolors = numVersicolors + 1 elif neighbor.species == "Virginica": numVirginicas = numVirginicas + 1 if numSetosas > numVersicolors: if numSetosas > numVirginicas: prediction = "Setosa" else: prediction = "Virginica" else: if numVersicolors > numVirginicas: prediction = "Versicolor" else: prediction = "Virginica" return prediction #a function that returns the index of the row for the corresponding species being tested def UpdateTable(species): if species == "Setosa": dim = 0 elif species == "Versicolor": dim = 1 else: dim = 2 return dim #a custom object to represent the Iris's data values class Iris(): def __init__(self, irisData): self.sepal_length = float (irisData[0]) self.sepal_width = float (irisData[1]) self.petal_length = float (irisData[2]) self.petal_width = float (irisData[3]) self.distance = -1 if len(irisData) > 4: if irisData[4] == 'Iris-setosa': self.species = 'Setosa' elif irisData[4] == 'Iris-versicolor': self.species = 'Versicolor' elif irisData[4] == 'Iris-virginica': self.species = 'Virginica' else: pass def setDistance(self, distance): self.distance = distance def main(): dataPath = './data/iris_dataset.csv' retrievedData = getData(dataPath) #create lists of Iris objects: half for training, half for testing trainingSet = [] testingSet = [] count = 0 for iris in retrievedData: myIris = Iris(iris) if count % 2 == 0: trainingSet.append(myIris) else: testingSet.append(myIris) count = count + 1 #build confusion matrix ''' +------------+---------+------------+-----------+ | | Setosa | Versicolor | Virginica | +------------+---------+------------+-----------+ | Setosa | TP(S) | E(S,Ve) | E(S,Vi) | | Versicolor | E(Ve,S) | TP(Ve) | E(Ve,Vi) | | Virginica | E(Vi,S) | E(Vi,Ve) | TP(Vi) | +------------|---------+------------+-----------| ''' confusionMatrix = np.zeros(shape=(3,3)) #creates a 2D array (3x3 table) containing all zeros #if input from user has been found, retrieve the input and set parameters if sys.argv[1]: #set K value k = int (sys.argv[1]) #create an Iris userInput = [sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5]] checkInput = sum(float (x) for x in userInput) userIris = Iris(userInput) #test the training model: update the confusion matrix for evaluation calculations for testIris in testingSet: #make a prediction for the current test case based on the specified K value and the model prediction = FindNeighbors(k,trainingSet,testIris) row = UpdateTable(testIris.species) col = UpdateTable(prediction) confusionMatrix[row,col] = confusionMatrix[row,col] + 1 #increment corresponding cell in the matrix #TP: the cell where the actual and predicted values intersect #TN: sum of all cells not in the classifier's row or column #FP: sum of all cells in the current column excluding TP #FN: sum of all cells in the current row excluding TP #calculate overall accuracy of model: (TP+TN)/(TP+TN+FP+FN) accuracy = (confusionMatrix[0,0] + confusionMatrix[1,1] + confusionMatrix[2,2]) / np.sum(confusionMatrix) accuracy = '{:.4}'.format(str(accuracy)) #calculate precision: TP/(TP+FP) precisionSetosa = confusionMatrix[0,0] / np.sum(confusionMatrix,axis=0)[0] precisionSetosa = '{:.4}'.format(str(precisionSetosa)) precisionVersicolor = confusionMatrix[1,1] / np.sum(confusionMatrix,axis=0)[1] precisionVersicolor = '{:.4}'.format(str(precisionVersicolor)) precisionVirginica = confusionMatrix[2,2] / np.sum(confusionMatrix,axis=0)[2] precisionVirginica = '{:.4}'.format(str(precisionVirginica)) #make prediction if checkInput > -4: prediction = FindNeighbors(k,trainingSet,userIris) else: prediction = "N/A" #print the output to an array which is returned to iris.js and then to the HTML document output = [k,prediction,accuracy,precisionSetosa,precisionVersicolor,precisionVirginica] for out in output: print(out) sys.stdout.flush() else: print(f"Nothing received") sys.stdout.flush() if __name__ == '__main__': main()
5a359f517804a9e8f474a91363bd3684c11c98ec
coding-with-fun/Python-Lectures
/Lec 1/Task/stringOperations.py
814
4.375
4
s = "This is string example" ''' Reverse string ''' reverse = s[::-1] print("Reverse string is: "+reverse) print() ''' Reverse words ''' words = s.split(" ") revWords = [revWord[::-1] for revWord in words] revStr = " ".join(revWords) print("Reversed words are: "+revStr) print() ''' Split and join ''' splitString = s.split(" ") print("Splitted string is: ") print(splitString) joinString = "*".join(splitString) print("Joined string is: "+joinString) print() print("Interchanged chars are: "+splitString[0][1]+splitString[0][0]+splitString[0][3]+splitString[0][2]) print() ''' Replace is ''' seperateString = s.split(" ") for x in range(len(seperateString)): if seperateString[x]=="is": seperateString[x]="was" joinString = " ".join(seperateString) print("Edited string is: "+joinString) print()
00a85601f190c68c0aaad68309463506c2a42221
celsopa/CeV-Python
/mundo01/ex020.py
451
4.09375
4
# Exercício Python 020: O mesmo professor do desafio 019 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. from random import shuffle lista = list([input("Aluno 1: "), input("Aluno 2: "), input("Aluno 3: "), input("Aluno 4: ")]) shuffle(lista) print(f"""A ordem de apresentação é: 1º: {lista[0]}, 2º: {lista[1]}, 3º: {lista[2]}, 4º: {lista[3]}.""")
216290b62d6ae4a1499f9ff309dbfd8cd530a5d4
CSC510-G35-Fall2022/csc510-g35-hw2
/codes/num.py
1,995
3.84375
4
import random as r import math from codes.utilities import utilities as u import codes.commandLine as c class Num: '''Holds number cols and applies functions to them''' def __init__(self, c, s): self.n = 0 self.name = s self._has = [] self.at = c or 0 self.lo = math.inf self.hi = -math.inf self.isSorted=True if s[-1] == '-': self.w = -1 else: self.w = 1 def nums(self): ''' Sorts the has list and sets isSorted to True ''' if not self.isSorted: self._has.sort() self.isSorted=True return self._has def add(self, v): ''' Adds a new value to the list and replaces a random old value if size exceeds attribute defined by the["nums"] config :param v: value to add to the list ''' #print(v) v = float(v) if v!="?": self.n = self.n + 1 self.lo = min(float(v), self.lo) self.hi = max(float(v), self.hi) if len(self._has) < c.the["nums"]: pos = len(self._has) self._has.insert(pos, v) elif r.random() < c.the["nums"] / self.n: pos = r.randrange(len(self._has)) self._has[pos] = v self.isSorted = False def div(self): ''' Returns the diversity of the nums object :return: diversity of sym object ''' a=self.nums() return (u.per(a, 0.9) - u.per(a, 0.1)) / 2.58 ''' Returns the median of the nums object ''' def mid(self): ''' Returns the median of the nums col :return: median of nums list ''' return u.per(self.nums(), 0.5) def __string__(self): return 'at: {0} hi: {1} isSorted: {2} lo: {3} n: {4} name: {5} w: {6}'.format(self.at, self.hi, self.isSorted, self.lo, self.n, self.name, self.w)
1f9d49f012f8280ee930b6ed6fb86448da98892e
pangyouzhen/data-structure
/tree/104 maxDepth.py
1,144
3.6875
4
# Definition for a binary tree node. # 插入,删除,查找 from base.tree.tree_node import TreeNode class Solution: def maxDepth(self, root: TreeNode): """ :rtype:最高深度 """ if root is None: return 0 left_depth = self.maxDepth(root.left) right_depth = self.maxDepth(root.right) # max(left的深度+ right的深度) + 最后一个node return max(left_depth, right_depth) + 1 def maxDepth2(self,root:TreeNode): if not root: return 0 curr = [root] h = 0 while curr: next_levels = [] for i in curr: if i.left: next_levels.append(i.left) if i.right: next_levels.append(i.right) curr = next_levels h += 1 return h if __name__ == '__main__': root = "[3,9,20,null,null,15,7]" tree = TreeNode.from_strs(root) sol = Solution() sol2 = Solution().maxDepthTreave assert sol.maxDepth(tree) == 3 print(sol2(tree))
64a77e1838f97a847cf19e4316ea13ee147e5cd9
mbazhlekova/mit-intro-programming-python
/week 1/lectures/guess-and-check.py
117
3.859375
4
cube = 27 for guess in range(cube + 1): if guess**3 == cube: print("Cube root of ", cube, " is ", guess)
bf4aac580efc2e69b8cd3feefc4fb85d0d177f3e
DiyanKalaydzhiev23/fundamentals---python
/dictionaries - exresice/softuni exam results.py
999
3.71875
4
languages = {} banned = [] results = {} data = input().split("-") while "exam finished" not in data: if "banned" in data: banned.append(data[0]) data = input().split("-") continue name = data[0] language = data[1] points = int(data[2]) current_points = 0 if language in languages: languages[language] += 1 if name in results: if points > results[name]: results[name] = points else: results[name] = points else: languages[language] = 1 results[name] = points data = input().split("-") results = dict(sorted(results.items(), key=lambda x: (-x[1], x[0]))) languages = dict(sorted(languages.items(), key=lambda x: (-x[1], x[0]))) print("Results:") for name in results: if name in banned: continue else: print(f"{name} | {results[name]}") print("Submissions:") [print(f"{language} - {languages[language]}") for language in languages]
8b3fef93387829c36b3081fa1343b5d02613763c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2710/60776/311893.py
517
3.515625
4
list=[] a=input().split(' ') renshu=int(a[0]) yujushu=int(a[1]) for i in range(0,yujushu): a=input().split(' ') if a[0]=='M': list1=[] list1.append(int(a[1])) list1.append(int(a[2])) list.append(list1) else: list1=[] for j in range(0,len(list)): if list[j][0]<=int(a[1]) and list[j][1]>=int(a[2]): list1.append(list[j][1]) list1.sort() if list1==[]: print(-1) else: print(list1[0])
6c0a79810d142cd1e1057cf45a808321e5c5e62e
bf108/Prediction-of-US-City-Temp-with-Linear-Regression
/Predicting_US_Cities_Annual_Temp_Linear_Regression.py
9,475
3.609375
4
import numpy as np import pylab import matplotlib.pyplot as plt import re # cities in our weather data CITIES = [ 'BOSTON', 'SEATTLE', 'SAN DIEGO', 'PHILADELPHIA', 'PHOENIX', 'LAS VEGAS', 'CHARLOTTE', 'DALLAS', 'BALTIMORE', 'SAN JUAN', 'LOS ANGELES', 'MIAMI', 'NEW ORLEANS', 'ALBUQUERQUE', 'PORTLAND', 'SAN FRANCISCO', 'TAMPA', 'NEW YORK', 'DETROIT', 'ST LOUIS', 'CHICAGO' ] INTERVAL_1 = list(range(1961, 1985)) INTERVAL_2 = list(range(1985, 2016)) class Climate(object): """ The collection of temperature records loaded from given csv file """ def __init__(self, filename): """ Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str) """ self.rawdata = {} f = open(filename, 'r') header = f.readline().strip().split(',') for line in f: items = line.strip().split(',') date = re.match('(\d\d\d\d)(\d\d)(\d\d)', items[header.index('DATE')]) year = int(date.group(1)) month = int(date.group(2)) day = int(date.group(3)) city = items[header.index('CITY')] temperature = float(items[header.index('TEMP')]) if city not in self.rawdata: self.rawdata[city] = {} if year not in self.rawdata[city]: self.rawdata[city][year] = {} if month not in self.rawdata[city][year]: self.rawdata[city][year][month] = {} self.rawdata[city][year][month][day] = temperature f.close() def get_yearly_temp(self, city, year): """ Get the daily temperatures for the given year and city. Args: city: city name (str) year: the year to get the data for (int) Returns: a numpy 1-d array of daily temperatures for the specified year and city """ temperatures = [] assert city in self.rawdata, "provided city is not available" assert year in self.rawdata[city], "provided year is not available" for month in range(1, 13): for day in range(1, 32):#change back to 32 for full month if day in self.rawdata[city][year][month]: temperatures.append(self.rawdata[city][year][month][day]) return np.array(temperatures) def get_daily_temp(self, city, month, day, year): """ Get the daily temperature for the given city and time (year + date). Args: city: city name (str) month: the month to get the data for (int, where January = 1, December = 12) day: the day to get the data for (int, where 1st day of month = 1) year: the year to get the data for (int) Returns: a float of the daily temperature for the specified time (year + date) and city """ assert city in self.rawdata, "provided city is not available" assert year in self.rawdata[city], "provided year is not available" assert month in self.rawdata[city][year], "provided month is not available" assert day in self.rawdata[city][year][month], "provided day is not available" return self.rawdata[city][year][month][day] def get_monthly_mean(self, city, month, year): assert city in self.rawdata, "provided city is not available" assert year in self.rawdata[city], "provided year is not available" assert month in self.rawdata[city][year], "provided month is not available" mean_temp = [] for day in range(1,32):#change back to 32 for full month if day in self.rawdata[city][year][month]: mean_temp.append(self.rawdata[city][year][month][day]) mean = sum(mean_temp)/float(len(mean_temp)) return mean # Problem 1 def generate_models(x, y, degs): """ Generate regression models by fitting a polynomial for each degree in degs to points (x, y). Args: x: a list with length N, representing the x-coords of N sample points y: a list with length N, representing the y-coords of N sample points degs: a list of degrees of the fitting polynomial Returns: a list of numpy arrays, where each array is a 1-d array of coefficients that minimizes the squared error of the fitting polynomial """ # TODO models = [] xval = np.array(x) yval = np.array(y) for d in degs: models.append(pylab.polyfit(xval, yval, d)) return models # Problem 2 def r_squared(observed, predicted): """ Calculate the R-squared error term. Args: y: list with length N, representing the y-coords of N sample points estimated: a list of values estimated by the regression model Returns: a float for the R-squared error term """ # TODO error = ((predicted - observed)**2).sum() meanError = error/len(observed) return 1 - (meanError/np.var(observed)) # Problem 3 def evaluate_models_on_training(x, y, models,dataSet): """ For each regression model, compute the R-square for this model with the standard error over slope of a linear regression line (only if the model is linear), and plot the data along with the best fit curve. For the plots, you should plot data points (x,y) as blue dots and your best fit curve (aka model) as a red solid line. You should also label the axes of this figure appropriately and have a title reporting the following information: degree of your regression model, R-square of your model evaluated on the given data points Args: x: a list of length N, representing the x-coords of N sample points y: a list of length N, representing the y-coords of N sample points models: a list containing the regression models you want to apply to your data. Each model is a numpy array storing the coefficients of a polynomial. dataSet: String outlining data set in analysis e.g Boston, Chicago or USA Returns: None """ # TODO styles = ['r-','g-','y-'] pylab.plot(x,y,'b-',label = 'Mean Temperature Data') # rSquares = {} i = 0 for m in models: # rSquares[m] = [] estYVals = pylab.polyval(m, np.array(x)) # rSquares[m].append(estYVals) error = round(r_squared(np.array(y), estYVals),5) pylab.plot(x,estYVals,styles[i],label = (str(str(i+1) + "Order Polynomial" + "\n" + " R-Squared Error: " + str(error)))) i +=1 pylab.title('Average Annual {} Temperatures'.format(dataSet)) pylab.xlabel('Years') pylab.ylabel('Average Temperature Deg C') pylab.legend(loc = 'best') ### Begining of program ''' Code to plot avg annual temp for all US cities The regression models are show on the plots also with respective errors The linear regression appears to be much more accurate than the ploynomials versions ''' def usAverageTemp(): raw_data = Climate('data.csv') avg_temp1 = [] for year in INTERVAL_1: avg = 0 for city in CITIES: avg += sum(raw_data.get_yearly_temp(city,year))/float(len(raw_data.get_yearly_temp(city,year))) avg_temp1.append(avg/float(len(CITIES))) avg_temp2 = [] for year in INTERVAL_2: avg = 0 for city in CITIES: avg += sum(raw_data.get_yearly_temp(city,year))/float(len(raw_data.get_yearly_temp(city,year))) avg_temp2.append(avg/float(len(CITIES))) models = generate_models(INTERVAL_1,avg_temp1,[1,2]) evaluate_models_on_training(INTERVAL_2,avg_temp2,models,'USA') def cityAverageTemp(city): city = city.upper() while city not in CITIES: [print(c) for c in CITIES] city = input('City not available, select a city from above list: ').upper() raw_data = Climate('data.csv') avg_temp1 = [] for year in INTERVAL_1: avg_temp1.append(sum(raw_data.get_yearly_temp(city,year))/float(len(raw_data.get_yearly_temp(city,year)))) avg_temp2 = [] for year in INTERVAL_2: avg_temp2.append(sum(raw_data.get_yearly_temp(city,year))/float(len(raw_data.get_yearly_temp(city,year)))) models = generate_models(INTERVAL_1,avg_temp1,[1,2]) evaluate_models_on_training(INTERVAL_2,avg_temp2,models,city.title()) def annualCityTemp(city, year): import calendar city = city.upper() while city not in CITIES: [print(c) for c in CITIES] city = input('City not available, select a city from above list: ').upper() while not min(INTERVAL_1) < year < max(INTERVAL_2): year = int(input('Please pick a year between 1960 and 2016: ')) raw_data = Climate('data.csv') monthly_mean = [raw_data.get_monthly_mean(city,i,year) for i in range(1,13)] months = [calendar.month_abbr[i] for i in range(1,13)] x_vals = np.arange(len(months)) plt.bar(x_vals, monthly_mean, align='center', alpha=0.5) plt.xticks(x_vals,months) plt.ylabel('Mean Monthly Temperature Deg C') plt.title('Monthly Mean Temperature of {} during {}'.format(city.title(),year))
f682a67759afb0a5e5b25a77f16bd86bc94c29c7
godxvincent/pythonbasico
/ModuloAccesoBD/BaseDatosRestaurante.py
4,625
3.84375
4
import sqlite3 import os def crear_db(): conexion = sqlite3.connect("restaurante.db") cursor = conexion.cursor() try: sentencia = """CREATE TABLE categoria( id INTEGER PRIMARY KEY AUTOINCREMENT, nombre VARCHAR(100) UNIQUE NOT NULL) """ cursor.execute(sentencia) except sqlite3.OperationalError: print("La tabla categoria ya fue creada") except Exception as e: print(type(e).__name__) finally: print("Continua con el proceso") try: sentencia = """CREATE TABLE plato( id INTEGER PRIMARY KEY AUTOINCREMENT, nombre VARCHAR(100) UNIQUE NOT NULL, categoria_id INTEGER NOT NULL, FOREIGN KEY(categoria_id) REFERENCES categoria(id))""" cursor.execute(sentencia) except sqlite3.OperationalError: print("La tabla plato ya fue creada") except Exception as e: print(type(e).__name__) finally: print("Continua con el proceso") conexion.commit() conexion.close() def agregar_categoria(): os.system("cls") while (True): print("Por favor ingresar una categoria") categoria = input() listaCategorias = [] listaCategorias.append(categoria.title()) try: conexion = sqlite3.connect("restaurante.db") cursor = conexion.cursor() cursor.execute("INSERT INTO categoria VALUES (null,?)", listaCategorias) except sqlite3.IntegrityError: print("**********************ERROR*************************") print("La categoria {} ya esta registrada".format(categoria)) print("**********************ERROR*************************") except Exception as e: print(type(e).__name__) else: print("Categoria creada exitosamente") break finally: conexion.commit() conexion.close() def agregar_plato(): # Se cargan las categorias disponibles. conexion = sqlite3.connect("restaurante.db") cursor = conexion.cursor() cursor.execute("SELECT * FROM categoria") categorias = cursor.fetchall() conexion.commit() conexion.close() os.system("cls") while (True): print("Por favor ingrese el nombre del plato que desea registrar") nombrePlato = input() print("Por favor indique a cual categoria pertenece el plato") for categoria in categorias: print("Código Categoria '{}', Nombre Categoria '{}'". format(categoria[0], categoria[1])) idCategoria = input() try: platoTupla = (nombrePlato.title(), int(idCategoria)) conexion = sqlite3.connect("restaurante.db") cursor = conexion.cursor() cursor.execute("INSERT INTO plato VALUES (null,?,?)", platoTupla) except sqlite3.IntegrityError: print("El plato {} ya se encuentra registrado". format(nombrePlato, idCategoria)) except Exception as e: print(type(e).__name__) break else: print("Plato registrado correctamente") break finally: conexion.commit() conexion.close() def visualizar_menu(): conexion = sqlite3.connect("restaurante.db") cursor = conexion.cursor() cursor.execute( "SELECT a.nombre, b.nombre FROM categoria a join plato b on (a.id = b.categoria_id)") menu = cursor.fetchall() for plato in menu: print("Categoria: {} - Plato: {}".format(plato[0], plato[1])) conexion.commit() conexion.close() def menuOpciones(): os.system("cls") while True: print("********************************************************") print("Bienvenido al menu para adicionar categorias de platos ") print("Ingrese opción 1 para adicionar nuevas categorias") print("Ingrese opción 2 para adicionar un plato a una categoria") print("Ingrese opción 3 para visualizar el menú") print("Ingrese opción 4 para salir del menú") print("*******************************************************") opcion = input("Ingrese una opción\n") if opcion == "1": agregar_categoria() elif opcion == "2": agregar_plato() elif opcion == "3": visualizar_menu() elif opcion == "4": print("Gracias por usar nuestro sistema") break else: print("***Opción no válida***") # crear_db() menuOpciones()
f619f9942ad4af68e1a9ef369d0f4b036f41cc1a
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap18_Tkinter/07_label.py
520
3.671875
4
from tkinter import * root = Tk() root.title("Lables") label = Label(root, text="Hey, How are you doing?", relief=RAISED) label.pack() Label(root, text='Sufficient width', fg='white', bg='purple', relief=RAISED).pack() Label(root, text='Width of x', fg='white', bg='green', relief=RAISED).pack(fill='x') Label(root, text='Height of y', fg='white', bg='black', relief=RAISED).pack(side='left', fill='y') Label(root, text='Height of y', fg='white', bg='blue', relief=RAISED).pack(side='left',fill='y') root.mainloop()
f949ee0f65234c925a8d22b4df252bb5cfd8c137
Fiinall/UdemyPythonCourse
/Loops/Determining Factorial - Alternative.py
438
4.25
4
print(""" Hello I Can Help You to Determine Your Numbers Factorial To Exit Press the "q" """) while True: Number = (input("Please Enter Your Number")) if (Number == "q"): print("Exiting...") break else: Factorial = 1 Number = int(Number) for i in range(1,Number+1) : Factorial = i*Factorial i += 1 print(Factorial)
9bba419a842ef4d5c1b3a1811bd2a9afb1f7b318
jonasht/cursoIntesivoDePython
/exercisesDosCapitulos/07-entradaDeUsuario-E-lacosWhile/7.3-multiplosDDez.py
170
3.921875
4
n = int(input('\ninforme o numero para ver é multiplo de 10,\nn:')) print('o numero é multiplo de dez' if n % 10 == 0 else 'o numero não é multiplo de dez')
3b37021ba5655f6a5b20e5ceb54294d3cf472bc0
andysai/python
/黑马程序员-python/python从0开始学编程/day03/16-猜拳游戏功能实现.py
565
4.28125
4
""" 1 出拳 玩家:手动输入 电脑:1 固定:剪刀 2. 随机 2 判断输赢 2.1 玩家获胜 2.2 平局 2.3 电脑获胜 """ # 1 出拳 # 玩家 player = int(input("请出拳(0--石头;1--剪刀;2--布):")) # 电脑 computer = 1 # 2 判断输赢 # 玩家获胜 if ((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 0)) : print('玩家获胜') # 平局 elif player == computer: print('平局,别走,再来一次') # 电脑获胜 else: print('电脑获胜')
61cd48dd6701147f1438ebba6eb01ee06f766ef7
xtorrentgorjon/Python-Examples
/Multiprocessing/Threads/threads.py
466
3.90625
4
##### # Python Examples: # threads.py # # Simple threading example. # # Xavier Torrent Gorjon ##### import threading THREAD_NUMBER = 4 class thread_class(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.__n = 0 def run(self): n = self.__n while n < 1000: n+=1 print self.name, n if __name__ == "__main__": thread_list = [] for i in range(THREAD_NUMBER): thread_list.append(thread_class()) for i in thread_list: i.start()
ead747179025becc977d7e79bd4624438a331426
ajpri/UHD_CS3321-Spr2020-25973-LMS
/functions.py
617
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 4 11:51:57 2020 @author: austin """ grades = ("A", "C", "F") def calcgpa(inputgrades): sum = 0 for grade in grades: if grade.upper() == "A": sum += 4 elif grade.upper() == "B": sum += 3 elif grade.upper() == "C": sum += 2 elif grade.upper() == "D": sum += 1 elif grade.upper() == "F": sum += 0 return sum/len(inputgrades) print(round(calcgpa(grades),2))
2581f0e8a881aa7112ca2e1cf5396d673a2962c4
jspencersharp/Portfolio
/Functions/sept7.lecture.py
642
3.6875
4
# class that rep's superhero - name, city, powers, class Hero(): def __init__ (self, name, city, powers): self.name = name self.city = city self.powers = powers hero1 = Hero("superman", "New York", "x-ray vision") print hero1.name #create villain class Villian(): def __init__(self,name,city,powers): self.name=name self.city=city self.powers=powers villian1=Villian("joker","gotham","violence") class Sidekick(): def __init__(self, name, city, powers): self.name=name self.city=city self.powers=powers sidekick1 = Sidekick("bob","gotham","none")
ebdb6a3030065b25ba68888d1943e760a7f88253
machineMachineLearning/PythonProgramming
/program21_RNN.py
23,300
4.03125
4
# we use: http://www.deeplearningitalia.com/wp-content/uploads/2017/12/Dropbox_Chollet.pdf # we use: F. Chollet, Deep learning with Python # RNN # an RNN is a for loop that re-uses quantities computed during the previous iteration of the loop # RNNs, LSTM-RNNs and GRU-RNNs # LSTM-RNNs and GRU-RNNs are better than RNNs # LSTM-RNNs and GRU-RNNs are better than vanilla RNNs # LSTM-RNNs are used in (https://research.google.com/pubs/archive/44312.pdf) # GRU-RNNs are used in (https://pdfs.semanticscholar.org/702e/aa99bcb366d08d7f450ed7e354f9f6920b23.pdf) import numpy as np #state_t = 0 #for input_t in input_sequence: #output_t = activation(dot(W, input_t) + dot(U, state_t) + b) #state_t = output_t timesteps = 100 # the input sequence has 100 timesteps input_features = 32 # the dimensionality of the output is 32 output_features = 64 # the dimensionality of the output is 64 # we define the input inputs = np.random.random((timesteps, input_features)) # the input is random noise # initialize the state state_t = np.zeros((output_features,)) # the state is initialized to zero W = np.random.random((output_features, input_features)) U = np.random.random((output_features, output_features)) b = np.random.random((output_features,)) successive_outputs = [] # use for loop for input_t in inputs: output_t = np.tanh(np.dot(W, input_t) + np.dot(U, state_t) + b) # we define the output #output_t = np.tanh(np.dot(W, input_t) + np.dot(U, state_t) + b) # we use tanh successive_outputs.append(output_t) state_t = output_t final_output_sequence = np.concatenate(successive_outputs, axis=0) # we use SimpleRNN from keras.layers import SimpleRNN # SimpleRNN has inputs: (batch_size, timesteps, input_features) from keras.models import Sequential from keras.layers import Embedding, SimpleRNN model = Sequential() model.add(Embedding(10000, 32)) model.add(SimpleRNN(32)) model.summary() model = Sequential() model.add(Embedding(10000, 32)) model.add(SimpleRNN(32, return_sequences=True)) model.summary() # we now stack several recurrent layers one after the other model = Sequential() model.add(Embedding(10000, 32)) model.add(SimpleRNN(32, return_sequences=True)) model.add(SimpleRNN(32, return_sequences=True)) model.add(SimpleRNN(32, return_sequences=True)) model.add(SimpleRNN(32)) model.summary() # we use IMDB from keras.datasets import imdb # we use the IMDB movie review classification problem from keras.preprocessing import sequence max_features = 10000 maxlen = 500 batch_size = 32 print('Loading data...') (input_train, y_train), (input_test, y_test) = imdb.load_data(num_words=max_features) print(len(input_train), 'train sequences') print(len(input_test), 'test sequences') print('We pad sequences (samples x time)') input_train = sequence.pad_sequences(input_train, maxlen=maxlen) input_test = sequence.pad_sequences(input_test, maxlen=maxlen) print('input_train shape:', input_train.shape) print('input_test shape:', input_test.shape) # we use an Embedding layer and a SimpleRNN layer # we use: SimpleRNN from keras.layers import Dense model = Sequential() model.add(Embedding(max_features, 32)) model.add(SimpleRNN(32)) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history = model.fit(input_train, y_train, epochs=10, batch_size=128, validation_split=0.2) # we train the model # we see: # 5120/20000 [======>.......................] - ETA: 17s - loss: 0.6916 - acc: 0.5273 # 5248/20000 [======>.......................] - ETA: 17s - loss: 0.6917 - acc: 0.5274 # 5376/20000 [=======>......................] - ETA: 17s - loss: 0.6916 - acc: 0.5283 # 5504/20000 [=======>......................] - ETA: 17s - loss: 0.6913 - acc: 0.5305 # 5632/20000 [=======>......................] - ETA: 17s - loss: 0.6912 - acc: 0.5314 # 13696/20000 [===================>..........] - ETA: 7s - loss: 0.2009 - acc: 0.9265 # 13824/20000 [===================>..........] - ETA: 7s - loss: 0.2010 - acc: 0.9266 # 13952/20000 [===================>..........] - ETA: 7s - loss: 0.2018 - acc: 0.9261 # Epoch 8/10 # we plot the training and validation loss and accuracy # we use plt to plot figures import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] # we define the epochs epochs = range(1, len(acc) + 1) # we plot the training and validation accuracy plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() # we now plot the training and validation loss # plot the training and validation loss plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # use: https://www.w3resource.com/c-programming-exercises/recursion/index.php # we use: http://interactivepython.org/runestone/static/pythonds/index.html# # website: http://interactivepython.org/runestone/static/pythonds/index.html# # we use: http://interactivepython.org/runestone/static/pythonds/BasicDS/toctree.html # we use lambda expressions in Python # use: https://docs.python.org/2/reference/expressions.html#lambda # we use: https://docs.python.org/2/reference/expressions.html # website: https://docs.python.org/2/reference/expressions.html#lambda # recursion, Fibonacci series # recursion and memoization to solve stack overflow problems # we use: https://www.w3resource.com/c-programming-exercises/recursion/index.php # Fibonacci series with recursion def Fib_rec(n): if n == 0: return 1 if n == 1: return 1 return Fib_rec(n - 1) + Fib_rec(n - 2) print(Fib_rec(1)) print(Fib_rec(2)) print(Fib_rec(10)) print('') # Fibonacci series with no recursion def Fib(n): prev = 1 last = 1 for i in range(1, n): # prev = last last, prev = (prev + last), last return last print(Fib(1)) print(Fib(2)) print(Fib(10)) print('') # sum of N terms from Fibonacci def sumFib(n): prev = 1 last = 1 sum1 = 2 if n == 0: return 1 for i in range(1, n): # prev = last last, prev = (prev + last), last sum1 += last return sum1 print(sumFib(3)) print(sumFib(4)) print(sumFib(10)) print('') # sum of N terms from Fibonacci def sumFib_rec(n): if n == 0: return 1 if n == 1: return 2 return 1 + sumFib_rec(n - 2) + sumFib_rec(n - 1) print(sumFib_rec(3)) print(sumFib_rec(4)) print(sumFib_rec(10)) print('') # print(Fib(1)) # print(Fib(2)) # print(Fib(10)) # memoization # recursion and memoization # Fibonacci series and memoization # tuple and list unpacking a = [3, 4, 5, 600] # unpack list to variables m1, m2, m3, m4 = a print(m4) m1, m2 = 3, 4 #same as: m1, m2 = (3, 4) print(m1, m2) print('') # the left-hand side => same elements as needed # m1, m2 = a => error too many values to unpack # unpack m1, m2, *r = a # in r => elements are stored as a list # we use a list for "r" m1, m2, *r = (1, 2, 3, 4, 5, 6, 7) print(r) # use unpacking m1, m2, *r = 1, 2, 3, 4, 5, 6, 7 print(r) # var1 = 4 and list1 = [3,2,1] var1, *list1 = 4,3,2,1 # we use tuples and unpacking print(list1) print('') # to terminate a while loop: use "break" or "pass" # use: "and", "or" # and, or, in, not in, !=, == # De Morgan's laws # use: https://en.wikipedia.org/wiki/De_Morgan%27s_laws # use: while not found and lower<=upper # we use: while not found and not lower>upper # we now use: while not (found or lower>upper) # we use De Morgan's laws # use: while not (found or lower>upper) # https://en.wikipedia.org/wiki/De_Morgan%27s_laws # use: https://www.tutorialspoint.com/computer_logical_organization/demorgan_theroems.htm # use: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html # we use: http://interactivepython.org/runestone/static/pythonds/index.html# # binary search => sorted list # binary search is stable => 9 searches to find item # binary search needs a sorted list def binarySearch(list1, item1): upper = len(list1) - 1 lower = 0 found = False while not found and upper >= lower: mid = (upper + lower) // 2 #print(upper) #print(lower) if list1[mid] == item1: found = True elif list1[mid] < item1: lower = mid + 1 else: upper = mid - 1 # if upper < lower: # break return found list1 = [4, 5, 6, 7] print(binarySearch(list1, 6)) list1 = [4, 5, 6, 7, 5, 2, 3, 1, -1, -3, -2, 0] list1.sort() print(binarySearch(list1, 6)) print(binarySearch(list1, -4)) print('') # the greatest common divisor (gcd) # use: https://en.wikipedia.org/wiki/Greatest_common_divisor # greatest common divisor def gcd(a, b): if a == b: return a # return mkd(abs(a-b), min(a,b)) return gcd(a - b, b) if a > b else gcd(a, b - a) # return x if a>b else y # use: return x if a>b else y # we use: x if a>b else y print(gcd(15, 3)) print(gcd(12, 18)) print(gcd(90, 12)) # https://www.w3resource.com/c-programming-exercises/recursion/index.php # recursion programming exercises # use: https://www.w3resource.com/c-programming-exercises/recursion/index.php # we use: https://www.geeksforgeeks.org/recursion-practice-problems-solutions/ # http://interactivepython.org/courselib/static/thinkcspy/Recursion/ProgrammingExercises.html # use: http://interactivepython.org/runestone/static/pythonds/index.html# # recursion coding exercises # Python recursion exercises # recursion programming exercises # main website: https://www.w3resource.com/c-programming-exercises/recursion/index.php # Compute the sum 1/2 + 3/5 + 5/8 + .... for N terms with recursion and with no recursion. # 1/2 + 3/5 + 5/8 + 7/11 + 9/14 + .... # sum of 1/2 + 3/5 + 5/8 + 7/11 + 9/14 + .... for N terms with recursion and with no recursion # sum of N terms with no recursion def functionSum(n): sum1 = 0 for i in range(n): #sum1 += (2*n+1) / (2*n+n+2) sum1 += (2*i+1) / (3*i+2) return sum1 print(functionSum(1)) print(functionSum(2)) print(functionSum(3)) print(functionSum(4)) print(functionSum(10)) print('') # sum of N terms with no recursion def functionSum2(n): sum1 = 0 var1 = 1 var2 = 2 for i in range(n): sum1 += var1 / var2 var1 += 2 var2 += 3 return sum1 print(functionSum2(1)) print(functionSum2(2)) print(functionSum2(3)) print(functionSum2(4)) print(functionSum2(10)) print('') # sum of N terms with recursion def functionSum_rec(n): if n == 1: return 1/2 #return ((2*(n-1)+1) / (2*(n-1)+(n-1)+2)) + functionSum_rec(n-1) return ((2*n - 1) / (3*n - 1)) + functionSum_rec(n - 1) print(functionSum_rec(1)) print(functionSum_rec(2)) print(functionSum_rec(3)) print(functionSum_rec(4)) print(functionSum_rec(10)) print('') # sum of N terms with recursion def functionSum2_rec(n, var1=0, var2=0): if n == 1: return 1/2 if (var1 == 0 and var2 == 0): var1 = (2*n - 1) var2 = (3*n - 1) #else: # pass return (var1/var2) + functionSum2_rec(n-1, var1-2, var2-3) print(functionSum2_rec(1)) print(functionSum2_rec(2)) print(functionSum2_rec(3)) print(functionSum2_rec(4)) print(functionSum2_rec(10)) print('') # Python Online: Interactive Python problems # http://interactivepython.org/runestone/static/pythonds/index.html # Recursion with finite memory and stack. Trees, graphs. # use: http://interactivepython.org/runestone/static/pythonds/index.html # List of interview questions: # www.github.com/MaximAbramchuck/awesome-interview-questions # Website for Python coding questions: # https://www.springboard.com/blog/data-science-interview-questions/#programming # use: https://www.w3resource.com/c-programming-exercises/recursion/index.php # https://www.springboard.com/blog/data-science-interview-questions # we use: http://interactivepython.org/runestone/static/pythonds/index.html# # we use: http://interactivepython.org/runestone/static/pythonds/BasicDS/toctree.html # website: http://interactivepython.org/runestone/static/pythonds/index.html# # we use lambda expressions in Python # use: https://docs.python.org/2/reference/expressions.html#lambda # we use: https://docs.python.org/2/reference/expressions.html # website: https://docs.python.org/2/reference/expressions.html#lambda # recursion, Fibonacci series # recursion and memoization to solve stack overflow problems # we use: https://www.w3resource.com/c-programming-exercises/recursion/index.php # Find the n-term of the series: a(n) = a(n-1)*2/3 with recursion and with no recursion. # recursion for a(n) = a(n-1)*2/3 def function1(n): if n == 0: return 1 return (2/3) * function1(n-1) print('') print(function1(1)) print(function1(2)) print(function1(3)) print(function1(9)) print('') # no recursion for a(n) = a(n-1)*2/3 def function2(n): k = 1 for i in range(1,n+1): k *= 2/3 return k print('') print(function2(1)) print(function2(2)) print(function2(3)) print(function2(9)) print('') # use: http://interactivepython.org/runestone/static/pythonds/index.html # use: https://www.w3resource.com/c-programming-exercises/recursion/index.php # website: http://interactivepython.org/runestone/static/pythonds/index.html# # we use: http://interactivepython.org/runestone/static/pythonds/BasicDS/toctree.html # we use lambda expressions in Python # use: https://docs.python.org/2/reference/expressions.html#lambda # website: https://www.w3resource.com/c-programming-exercises/recursion/index.php # we use: https://docs.python.org/2/reference/expressions.html # website: https://docs.python.org/2/reference/expressions.html#lambda import numpy as np # we use Python's build-in functions # use: https://docs.python.org/3/library/functions.html # we use *args and **kwargs # https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ # use one-line code # write as few lines of code as possible # use comprehensions a = [i for i in range(2, 100 + 1, 2)] print(a) # we use list comprehensions a = [i for i in range(1, 101) if i % 2 == 0] print(a) # create a generator object, use "(.)" a = (i for i in range(1, 101) if i % 2 == 0) # the generator object can be used only once # the generator object can be used one time only print(list(a)) print('') # positional arguments => position matters # we can call function1 using "function1(y=1, x=2)" # function with positional arguments x, y def function1(x, y): return x - y # positional arguments: the position matters print(function1(3, 5)) # named arguments, no matter the order print(function1(y=3, x=5)) # both positional arguments and named arguments print(function1(4, y=7)) # in functions, position can matter and can not matter # positional arguments for function # positional parameters, function inputs, arguments print('') print(max(2,6,9,3)) print(sum([2,6,9,3])) # functions can have default values # define a function with default values def func2(x, y=9, z=1): # the default value is for z return (x + y) * z # If we do not give a value for z, then z=1=(default value) # we can have default values in functions # default values go to the end of the arguments # use: (1) default values, (2) *args, (3) **kwargs # we use default values, one asterisk (i.e. *) and two asterisks (i.e. **) # we now use *args and **kwargs # use: https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ # default arguments can be only at the end, even more than one g = func2(2, 5, 7) print(g) print('') for i in range(5): print(i, "-", i ** 2) # use *args at the end # we use un-named arguments *args # (1) *args at the end of the arguments in a function # (2) default values at the end of the arguments in a function # *args must be in the end of the arguments def apodosi(*apodoseis): k = 1 for i in apodoseis: k *= i return k # use: (1) *args, and (2) **kwargs # "**kwargs" is a dictionary dict # we use keys and values # "**kwargs" is a dictionary and has keys and values # **kwargs must be at the end and hence after *args def apodosi(*apodoseis, **kwargs): # we use the "max" key in the dictionary if "max" in kwargs: n = kwargs["max"] else: n = len(apodoseis) k = 1 for i in range(n): k *= apodoseis[i] return k # **kwargs must be at the end and hence after *args def apodosi2(*apodoseis, **kwargs): # we use the "max" key in the dictionary if "max" in kwargs: # we use min(., len(apodoseis)) n = min(kwargs["max"], len(apodoseis)) else: n = len(apodoseis) k = 1 for i in range(n): k *= apodoseis[i] return k print('') print(apodosi(1.11, 1.22, 1.31)) print(apodosi2(1.11, 1.22, 1.31)) print('') # use: "*m" amd "myFunction(*m)" m = [2.3, 1.4, 1.8, 1.5, 2.4] # we use: "*m" amd "myFunction(*m)" # when we have a list m, then we use "*m" to get its elements print(apodosi(*m, max=3)) print(apodosi2(*m, max=3)) # use *list1 to break the list print(apodosi2(*m, max=13)) # the function does not work if we do not use "*" # use *args and **kwargs in functions # website: https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ # use: https://www.geeksforgeeks.org/args-kwargs-python/ # convert to binary # convert the number n to binary n = 14 # we use the stack data structure # define a list that will be used as a stack stack1 = [] # stack: the last item that enters the stack is the first item out # the stack data structure is Last In First Out (LIFO) # the queue data structure is First In First Out (FIFO) print('') # every program uses an execution stack # the execution stack in Python is short # Every program has a stack that contains the parameters and the local variables of the functions # that have been called. The stack is LIFO. The last parameter of a function gets out first, i.e. LIFO, # when many funnctions have been called in a recursion. # recursion problems # recursion and memoization # Fibonacci series and memoization # the stack overflow error # stack overflow: when recursion, when the execution stack is full # we use a while loop while n != 0: # d is the last digit d = n % 2 # print(d) stack1.insert(0, d) # we remove the last digit n = n // 2 # print the elements for i in stack1: print(i, end="") print() def toBinary(n): if n == 0: return toBinary(n // 2) print(n % 2, end='') toBinary(14) print() toBinary(14) print() # d is the last digit # d = n % 2 # stack1.insert(0, d) # we remove the last digit #n = n // 2 # we use base 8 def toOctal(n): if n == 0: return toOctal(n // 8) print(n % 8, end='') # use base 10 def toDecimal(n): if n == 0: return toDecimal(n // 10) print(n % 10, end='') # 453%10 = 3 = last digit # 453//10 = 45 = remove last digit # x%10 = last digit # x//10 = remove last digit # we use base 3 def toTernary(n): if n == 0: return toTernary(n // 3) print(n % 3, end='') # sum of N numbers def sumToN(N): sum = 0 for i in range(1, N + 1): sum += i return sum # recursion, sum of N numbers def sumToN_rec(N): #print(N) if N == 1: return 1 # return 1 + sumToN_rec(N-1) return N + sumToN_rec(N - 1) print('') print(sumToN_rec(4)) #print(sumToN_rec(40000)) print(sumToN_rec(40)) # recursion problems # coding recursion exercises # programming recursion exercises # recursion and memoization # write code with and without recursion # use one-line code # lambda expressions => one line only # comprehensions, list comprehensions => one line only # use comprehensions: lists or generator objects # comprehensions with "(.)" => generator objects # generator objects are created for one time only # positional arguments # define functions and call them with positional arguments # positional arguments or non-positional arguments, default values # default values go at the end, *args goes at the end # use *args and **kwargs, **kwargs goes at the end # use function1(*list1), use "*list1" # we use "*list1" to break the list to its elements # dictionary: keys and values # dictionaries have keys and values # we use *args and ** kwargs # website: https://www.geeksforgeeks.org/args-kwargs-python/ # **kwargs => named arguments, dictionary # dictionary has keys and values # we use keys as an index to acccess the values # "if "max" in dict1:": "max" is a key and not a value # stack data structure => LIFO # LIFO, last in first out, stack, execution stack # recursion, memoization, execution stack, stack overflow # limited stack, limited short execution stack # recursion, Fibonacci series => stack overflow # memoization, we use lookup table, memoization to store values # Find the n-term of the series: a(n) = a(n-1)*2/3 with recursion and with no recursion. # recursion for a(n) = a(n-1)*2/3 def function1(n): if n == 0: return 1 return (2/3) * function1(n-1) print('') print(function1(1)) print(function1(2)) print(function1(3)) print(function1(9)) print('') # no recursion for a(n) = a(n-1)*2/3 def function2(n): k = 1 for i in range(1,n+1): k *= 2/3 return k print('') print(function2(1)) print(function2(2)) print(function2(3)) print(function2(9)) print('') # Compute the sum 1/2 + 3/5 + 5/8 + .... for N terms with recursion and with no recursion. # 1/2 + 3/5 + 5/8 + 7/11 + 9/14 + .... # sum of 1/2 + 3/5 + 5/8 + 7/11 + 9/14 + .... for N terms with recursion and with no recursion # sum of N terms with no recursion def functionSum(n): sum1 = 0 for i in range(n): #sum1 += (2*n+1) / (2*n+n+2) sum1 += (2*i+1) / (3*i+2) return sum1 print(functionSum(1)) print(functionSum(2)) print(functionSum(3)) print(functionSum(4)) print(functionSum(10)) print('') def functionSum2(n): sum1 = 0 var1 = 1 var2 = 2 for i in range(n): sum1 += var1 / var2 var1 += 2 var2 += 3 return sum1 print(functionSum2(1)) print(functionSum2(2)) print(functionSum2(3)) print(functionSum2(4)) print(functionSum2(10)) print('') # sum of N terms with recursion def functionSum_rec(n): if n == 1: return 1/2 #return ((2*(n-1)+1) / (2*(n-1)+(n-1)+2)) + functionSum_rec(n-1) return ((2*n - 1) / (3*n - 1)) + functionSum_rec(n - 1) print(functionSum_rec(1)) print(functionSum_rec(2)) print(functionSum_rec(3)) print(functionSum_rec(4)) print(functionSum_rec(10)) print('') def functionSum2_rec(n, var1=0, var2=0): if n == 1: return 1/2 if (var1 == 0 and var2 == 0): var1 = (2*n - 1) var2 = (3*n - 1) #else: # pass return (var1/var2) + functionSum2_rec(n-1, var1-2, var2-3) print(functionSum2_rec(1)) print(functionSum2_rec(2)) print(functionSum2_rec(3)) print(functionSum2_rec(4)) print(functionSum2_rec(10)) print('')
34bb662ffa26ffed3a8e3d795b02c659a9993fb6
liwenkaitop/test
/sort.py
369
3.90625
4
# 冒泡排序 def bubblesort(srcDatas): """对一个列表中的数据进行从小到大的冒泡排序,返回排序成功""" if len(srcDatas)<=2: return True for i in range(0,len(srcDatas)-1): for j in range(0,len(srcDatas)-1-i): if srcDatas[j] > srcDatas[j+1]: data = srcDatas[j] srcDatas[j] = srcDatas[j+1] srcDatas[j+1] = data return True
5f8b8eac76af2502611fe1a213ebeb4ebc5143b0
VaishnaviReddyGuddeti/Python_programs
/Python_Lists/list()Constructor.py
214
4.21875
4
# It is also possible to use the list() constructor to make a new list. #Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist)
c23e399f934381d0d7364c423d9b554c1f4e9572
arishabh/HTML-and-CSS
/HTML - INFO-I 101/py4.py
595
4.125
4
import random name = input("Enter your name: ") sentence = "*proper fell on the *adj *noun today." sentence = sentence.split() nouns = ['table', 'chair', 'floor', 'ground', 'staircase', 'playground'] adj = ['huge', 'small', 'tiny', 'enormous', 'humungous'] count = 0; for word in sentence: if (word == '*noun'): sentence[count] = random.choice(nouns) if (word == '*proper'): sentence[count] = name if (word == '*adj'): sentence[count] = random.choice(adj) count += 1 st = '' for word in sentence: st += word + ' ' print(st)
42b084d6a687ef7acf2d59c8a50bb47d902beca6
jihoondio/leetcode
/1588. Sum of All Odd Length Subarrays.py
528
3.5625
4
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: _sum = sum(arr) arr_sum = [arr[0]] for i in range(1, len(arr)): arr_sum.append(arr[i] + arr_sum[i - 1]) curr_odd = 3 while curr_odd <= len(arr): for j in range(curr_odd - 1, len(arr)): odd_sum = arr_sum[j] if j >= curr_odd: odd_sum -= arr_sum[j - curr_odd] _sum += odd_sum curr_odd += 2 return _sum
575a0095523dd275b7e6a5f89266f4feae0afdbb
UCD-pbio-rclub/Pithon_JohnD
/July_18_2018/Problem_1.py
803
4.125
4
# Problem 1 # Write a function that reports the number of sequences in a fasta file import string import re import glob def fastaCount(): files = glob.glob('*') filename = input('Enter the name of the fasta file if unsure, enter ls for \ current directory listings: ') if filename == 'ls': for i in files: print(i) filename = input('Enter the name of the fasta file: ') if filename in files: with open(filename, 'r') as f: count = 0 line = f.readline() while line != '': if line.startswith('>'): count += 1 line = f.readline() print('There are', count, 'fasta records in', filename) else: print('File could not be found')
9211ee4ebe955333df1e0e5150510cb8b5f5c6b6
RajashriST/python_demo
/factorial.py
172
3.890625
4
#factorial fact=1 def factorial(x): if x>1: return x*factorial(x-1) elif x==1: return 1 fact=factorial(6) print(fact) #import math #print(math.factorial(5))
d6b13141fee2ead8606aaa9c5f64ce6b0812627c
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/834. 树中距离之和.py
1,878
3.65625
4
""" 给定一个无向、连通的树。树中有 N 个标记为 0...N-1 的节点以及 N-1 条边 。 第 i 条边连接节点 edges[i][0] 和 edges[i][1] 。 返回一个表示节点 i 与其他所有节点距离之和的列表 ans。 示例 1: 输入: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] 输出: [8,12,6,10,10,10] 解释: 如下为给定的树的示意图: 0 / \ 1 2 /|\ 3 4 5 我们可以计算出 dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) 也就是 1 + 1 + 2 + 2 + 2 = 8。 因此,answer[0] = 8,以此类推。 说明: 1 <= N <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-of-distances-in-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import collections from typing import List class Solution: def sumOfDistancesInTree(self, N: int, edges: List[List[int]]) -> List[int]: """ 思路:dfs @param N: @param edges: @return: """ graph = collections.defaultdict(set) for u, v in edges: graph[u].add(v) graph[v].add(u) ans = [0] * N cnt = [1] * N def dfs(node=0, parent=None): for child in graph[node]: if child != parent: dfs(child, node) cnt[node] += cnt[child] ans[node] += ans[child] + cnt[child] dfs() def dfs2(node=0, parent=None): for child in graph[node]: if child != parent: ans[child] = ans[node] + N - 2 * cnt[child] dfs2(child, node) dfs2() return ans if __name__ == '__main__': N = 6 edges = [[0, 1], [0, 2], [2, 3], [2, 4], [2, 5]] print(Solution().sumOfDistancesInTree(N, edges))
760d25432c1695c002f764837262c94f4bcbcf85
linbojun/ResNet
/resnet/Util.py
4,046
3.859375
4
import tensorflow as tf import numpy as np from matplotlib import pyplot as plt import os import random import math def accuracy(logits, labels): """ Calculates the model's prediction accuracy by comparing logits to correct labels – no need to modify this. :param logits: a matrix of size (num_inputs, self.num_classes); during training, this will be (batch_size, self.num_classes) containing the result of multiple convolution and feed forward layers :param labels: matrix of size (num_labels, self.num_classes) containing the answers, during training, this will be (batch_size, self.num_classes) NOTE: DO NOT EDIT :return: the accuracy of the model as a Tensor """ #print("probs: ", probs) #print("labels: ",labels ) #print("In accuracy(self, probs, labels): tf.argmax(probs, 1) = ", tf.argmax(probs, 1)) #correct_predictions = tf.equal(tf.argmax(logits, 1), labels) #print("Util, accuracy: logits %s" % (logits)) #print("Util, accuracy: labels %s" % (labels)) correct_predictions = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) #print("Util, accuracy: correct_predictions %s" % (correct_predictions)) return tf.reduce_mean(tf.cast(correct_predictions, tf.float32)) def visualize_loss(losses): """ Uses Matplotlib to visualize the losses of our model. :param losses: list of loss data stored from train. Can use the model's loss_list field NOTE: DO NOT EDIT return: doesn't return anything, a plot should pop-up """ x = [i for i in range(len(losses))] plt.plot(x, losses) plt.title('Loss per batch') plt.xlabel('Batch') plt.ylabel('Loss') plt.show() def test(model, test_inputs, test_labels): # Tests the model on the test inputs and labels. You should NOT randomly # flip images or do any extra preprocessing. # :param test_inputs: test data (all images to be tested), # shape (num_inputs, width, height, num_channels) # :param test_labels: test labels (all corresponding labels), # shape (num_labels, num_classes) # :return: test accuracy - this should be the average accuracy across # all batches num_batch = int(test_labels.shape[0] / model.batch_size) tot = 0.0 for i in range(num_batch): image_batch = test_inputs[i*model.batch_size:(i+1)*model.batch_size] label_batch = test_labels[i*model.batch_size:(i+1)*model.batch_size] logits = model.call(image_batch) accur = accuracy(logits,label_batch) tot += accur print(tot / num_batch) return tot / num_batch def train(model, images, labels, save_path): ''' :param images: (num_image, width, height, num_channels) :param labels: (num_labels, num_class) ''' n = images.shape[0] indice = tf.range(n) indice = tf.random.shuffle(indice) labels = tf.gather(labels, indice) images = tf.gather(images, indice) images = tf.image.random_flip_left_right(images) num_batch = int(n/model.batch_size) for i in range(num_batch): #for i in range(1): print("batch ", i, "of ", num_batch) start_pos = i * model.batch_size end_pos = (i+1) * model.batch_size image_batch = images[start_pos : end_pos] label_batch = labels[start_pos : end_pos] with tf.GradientTape() as tape: #logits = model.call(image_batch) predictions = model(image_batch, training = True) loss_val = model.loss(predictions, label_batch) #loss_val = model.loss(y_true=label_batch, y_pred=predictions) print("loss: %s" % (loss_val)) print("__________________________") # print("""loss: %s, \n logits: %s # ===============""" % (loss_val, predictions)) model.loss_list.append(loss_val) gradients = tape.gradient(loss_val, model.trainable_variables) model.optimizer.apply_gradients(grads_and_vars=zip(gradients, model.trainable_variables)) model.save(save_path) return
12de4c87d49bb6979b9164a56fb369969f35d763
MiekoHayasaka/Python_Training
/day0202/code4_5.py
324
3.90625
4
count=0 student_num=int(input('学生の数を入力>>')) score_list=list() while count < student_num: count += 1 score=int(input('{}人目の試験の得点を入力>>'.format(count))) score_list.append(score) print(score_list) total=sum(score_list) print('平均点は{}点です'.format(total / student_num))
3f12f4f0fa954c93e271a86042756bc392682866
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_297.py
826
4.0625
4
def main(): temperature = float(input("What is the temperature: ")) print("Please enter C for Celsius or K for Kelvin") choice = input("Celsius or Kelvin: ") if(choice == "K"): tempc = (temperature - 273.15) if (tempc < 0): print("Water is solid at this temperature.") elif ((tempc > 0)and(tempc < 100)): print("Water is a liquid at this temperature.") elif (tempc > 100): print("Water is a gas at this temperature.") if(choice == "C"): if (temperature < 0): print("Water is solid at this temperature.") elif ((temperature > 0)and(temperature < 100)): print("Water is a liquid at this temperature.") elif (temperature > 100): print("Water is a gas at this temperature.") main()
fea35d9e1b68cfed9b91e7cd123ef773870a7967
randolphwong/libdw
/libdw/boundarySM.py
4,128
3.8125
4
""" Very simple behavior for following the boundary of an obstacle in the world, with the robot's 'right hand' on the wall. """ import sm from soar.io import io ###################################################################### # Global Variables ###################################################################### # Thresholds in meters sideClearDist = 0.3 clearDist = 0.25 # Speeds forwardSpeed = 0.25 rotationalSpeed = 0.25 # Actions stop = io.Action(0, 0) go = io.Action(forwardSpeed, 0) left = io.Action(0, rotationalSpeed) right = io.Action(sideClearDist*rotationalSpeed, -rotationalSpeed) ###################################################################### # Sensor Utilities ###################################################################### # Return True if the minimum of the selected sensor values is less # than a threshold # Type: (list(num), num) -> boolean def clearTest(selectedSensors, threshold): return min(selectedSensors) > threshold # All of these have type: sensors -> boolean def frontClear(sensors): return clearTest(frontSonars(sensors), clearDist) def leftClear(sensors): return clearTest(leftSonars(sensors), sideClearDist) def rightClear(sensors): return clearTest(rightSonars(sensors), sideClearDist) # Select out sets of sonar values. Type sensors -> list(num) # Front 4 sonars def frontSonars(sensors): return sensors.sonars[2:6] def front6Sonars(sensors): return sensors.sonars[1:7] # Left 3 sonars def leftSonars(sensors): return sensors.sonars[0:3] # Right 3 sonars def rightSonars(sensors): return sensors.sonars[5:8] def rightmostSonar(sensors): return sensors.sonars[7:8] def wallInFront(sensors): return not clearTest(front6Sonars(sensors), clearDist) def wallOnRight(sensors): return not clearTest(rightmostSonar(sensors), sideClearDist) def pickAction(state): if state == 'turningLeft': return left elif state == 'turningRight': return right elif state == 'stop': return stop else: return go class BoundaryFollowerSM4(sm.SM): """State machine with instances of ``io.SensorInput`` as input and ``io.Action`` as output. Follows a boundary with the robot's 'right hand' on the wall. Has four internal states: 'turningLeft', 'turningRight', 'movingForward', and 'following' """ startState = 'movingForward' def getNextValues(self, state, inp): if state == 'turningLeft': if wallInFront(inp): nextState = 'turningLeft' elif wallOnRight(inp): nextState = 'following' else: nextState = 'turningLeft' elif state == 'turningRight': if wallOnRight(inp): nextState = 'following' else: nextState = 'turningRight' elif state == 'movingForward': if wallInFront(inp): nextState = 'turningLeft' else: nextState = 'movingForward' else: # state is 'following' if wallInFront(inp): nextState = 'turningLeft' elif wallOnRight(inp): nextState = 'following' else: nextState = 'turningRight' return (nextState, pickAction(nextState)) class BoundaryFollowerSM2(sm.SM): """State machine with instances of ``io.SensorInput`` as input and ``io.Action`` as output. Follows a boundary with the robot's 'right hand' on the wall. Has two internal states: 'seek' and 'following'. """ startState = 'seek' def getNextValues(self, state, inp): if state == 'seek': if wallInFront(inp): return ('following', left) elif wallOnRight(inp): return ('following', go) else: return ('seek', go) else: if wallInFront(inp): return ('following', left) elif wallOnRight(inp): return ('following', go) else: return ('following', right)
b197426a48c7e62b524bca20bab44726dd521a66
pandeyab/create_your_own_image_classifier
/Part 2 - Neural Networks in PyTorch.py
8,036
3.921875
4
#!/usr/bin/env python # coding: utf-8 # # Neural networks with PyTorch # # Next I'll show you how to build a neural network with PyTorch. # In[1]: # Import things like usual get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") import numpy as np import torch import helper import matplotlib.pyplot as plt from torchvision import datasets, transforms # First up, we need to get our dataset. This is provided through the `torchvision` package. The code below will download the MNIST dataset, then create training and test datasets for us. Don't worry too much about the details here, you'll learn more about this later. # In[2]: # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) # Download and load the training data trainset = datasets.MNIST('MNIST_data/', download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) # Download and load the test data testset = datasets.MNIST('MNIST_data/', download=True, train=False, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True) # In[36]: dataiter = iter(trainloader) images, labels = dataiter.next() # We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. We'd use this to loop through the dataset for training, but here I'm just grabbing the first batch so we can check out the data. We can see below that `images` is just a tensor with size (64, 1, 28, 28). So, 64 images per batch, 1 color channel, and 28x28 images. # In[37]: plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r'); # ## Building networks with PyTorch # # Here I'll use PyTorch to build a simple feedfoward network to classify the MNIST images. That is, the network will receive a digit image as input and predict the digit in the image. # # <img src="assets/mlp_mnist.png" width=600px> # # To build a neural network with PyTorch, you use the `torch.nn` module. The network itself is a class inheriting from `torch.nn.Module`. You define each of the operations separately, like `nn.Linear(784, 128)` for a fully connected linear layer with 784 inputs and 128 units. # # The class needs to include a `forward` method that implements the forward pass through the network. In this method, you pass some input tensor `x` through each of the operations you defined earlier. The `torch.nn` module also has functional equivalents for things like ReLUs in `torch.nn.functional`. This module is usually imported as `F`. Then to use a ReLU activation on some layer (which is just a tensor), you'd do `F.relu(x)`. Below are a few different commonly used activation functions. # # <img src="assets/activation.png" width=700px> # # So, for this network, I'll build it with three fully connected layers, then a softmax output for predicting classes. The softmax function is similar to the sigmoid in that it squashes inputs between 0 and 1, but it's also normalized so that all the values sum to one like a proper probability distribution. # In[5]: from torch import nn from torch import optim import torch.nn.functional as F # In[ ]: class Network(nn.Module): def __init__(self): super().__init__() # Defining the layers, 128, 64, 10 units each self.fc1 = nn.Linear(784, 128) self.fc2 = nn.Linear(128, 64) # Output layer, 10 units - one for each digit self.fc3 = nn.Linear(64, 10) def forward(self, x): ''' Forward pass through the network, returns the output logits ''' x = self.fc1(x) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) x = F.softmax(x, dim=1) return x model = Network() model # ### Initializing weights and biases # # The weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance. # In[ ]: print(model.fc1.weight) print(model.fc1.bias) # For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values. # In[ ]: # Set biases to all zeros model.fc1.bias.data.fill_(0) # In[ ]: # sample from random normal with standard dev = 0.01 model.fc1.weight.data.normal_(std=0.01) # ### Forward pass # # Now that we have a network, let's see what happens when we pass in an image. This is called the forward pass. We're going to convert the image data into a tensor, then pass it through the operations defined by the network architecture. # In[31]: # Grab some data dataiter = iter(trainloader) images, labels = dataiter.next() # Resize images into a 1D vector, new shape is (batch size, color channels, image pixels) images.resize_(64, 1, 784) # or images.resize_(images.shape[0], 1, 784) to not automatically get batch size # Forward pass through the network img_idx = 0 ps = model.forward(images[img_idx,:]) img = images[img_idx] helper.view_classify(img.view(1, 28, 28), ps) # As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random! # # PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](https://pytorch.org/docs/master/nn.html#torch.nn.Sequential)). Using this to build the equivalent network: # In[38]: # Hyperparameters for our network input_size = 784 hidden_sizes = [128, 64] output_size = 10 # Build a feed-forward network model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]), nn.ReLU(), nn.Linear(hidden_sizes[0], hidden_sizes[1]), nn.ReLU(), nn.Linear(hidden_sizes[1], output_size), nn.Softmax(dim=1)) print(model) # Forward pass through the network and display output images, labels = next(iter(trainloader)) images.resize_(images.shape[0], 1, 784) ps = model.forward(images[0,:]) helper.view_classify(images[0].view(1, 28, 28), ps) # You can also pass in an `OrderedDict` to name the individual layers and operations. Note that a dictionary keys must be unique, so _each operation must have a different name_. # In[45]: from collections import OrderedDict model = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(input_size, hidden_sizes[0])), ('relu1', nn.ReLU()), ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])), ('relu2', nn.ReLU()), ('output', nn.Linear(hidden_sizes[1], output_size)), ('softmax', nn.Softmax(dim=1))])) model # Now it's your turn to build a simple network, use any method I've covered so far. In the next notebook, you'll learn how to train a network so it can make good predictions. # # >**Exercise:** Build a network to classify the MNIST images with _three_ hidden layers. Use 400 units in the first hidden layer, 200 units in the second layer, and 100 units in the third layer. Each hidden layer should have a ReLU activation function, and use softmax on the output layer. # In[ ]: ## TODO: Your network here # In[ ]: ## Run this cell with your model to make sure it works ## # Forward pass through the network and display output images, labels = next(iter(trainloader)) images.resize_(images.shape[0], 1, 784) ps = model.forward(images[0,:]) helper.view_classify(images[0].view(1, 28, 28), ps)
5b8b60e383c8ad3b9597a0774b7c55706fcc0497
acbahr/Python-Practice-Projects
/magic_8_ball_gui.py
1,524
4.3125
4
# 1. Simulate a magic 8-ball. # 2. Allow the user to enter their question. # 3. Display an in progress message(i.e. "thinking"). # 4. Create 20 responses, and show a random response. # 5. Allow the user to ask another question or quit. # Bonus: # - Add a gui. # - It must have box for users to enter the question. # - It must have at least 4 buttons: # - ask # - clear (the text box) # - play again # - quit (this must close the window) # Basic text in TKinter is called a label import random import tkinter as tk """ def magic_8ball(): root = tk.Tk() # constructor class in TKinter. Creates a blank window active = True responses = ['Yes', 'No', 'Maybe', 'Try Again', "It's Possible", 'It is in the stars', 'Ask me another time', 'I am not sure', 'Ask your mother', 'Ask your father', 'Only if you Live Bearded'] while active: label1 = tk.Label(text='What would you like to ask?') label1.pack() entry = tk.Entry(width=75) entry.pack() question = entry.get() if question != 'n' or question != 'N': thinking = tk.Label(text='thinking....') thinking.pack() return random.choice(responses) else: print('thinking...') print(random.choice(responses)) try_again = input('Would you like to try again? y/n: ') if try_again.lower() == 'n': active = False root.mainloop() # mainloop keeps running the window until closed by user magic_8ball() """
ff245a18811f529e5d756c478819b3f41e2b97ae
elsaVelazquez/faster-pet-adoption
/src/pipelines/data_ingestion/read_in_data.py
511
3.578125
4
import numpy as np import pandas as pd def read_df_csv(path): '''read in file ''' # print('read df') return pd.read_csv(path) #, parse_dates=True, squeeze=True) def read_text_file(fname): '''Reads the filename - should have a .txt extension. Returns a text string containing the entire description. ''' f = open(fname, 'r') textstring = f.read() return textstring def explore_data(df): # print(df.head()) return df if __name__ == "__main__": pass
295e926b58dd752b3d5a392892578746ba8cb2f1
shaheerkhan199/python_assignment
/Assignment1/Q5.py
159
4.25
4
first_name = input("Enter First name:") last_name = input("Enter Last name:") print("your name in reverse Order", first_name.reverse()," ",last_name.reverse())
609c085bed92d83d98b5a63bce2e6e46b90d6665
pedrottoni/Studies-Python
/Cursoemvideo/Mundo2/exercise070.py
1,609
4.09375
4
""" Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: A) qual é o total gasto na compra. B) quantos produtos custam mais de R$1000. C) qual é o nome do produto mais barato. """ amount = greater_thousand = cheapeast_product = 0 cheapeast_product_name = '' while True: product = str(input('Nome do produto: ')) # Recebe o preço e garante que ele seja um número price = input('Preço: ') while price.isnumeric() == False: price = input('Valor inválido\nPreço: ') price = float(price) # Faz o produto mais barato ser o primeiro se ele for igual a zero, caso não seja, verifica se o preço atual é menor do que o valor mais barato recebido if cheapeast_product == 0: cheapeast_product = price if price < cheapeast_product: cheapeast_product = price cheapeast_product_name = product # Verifica se o preço é maior que 1000, caso for, acrescenta um produto na contagem dos maiores que 1000 if price > 1000: greater_thousand += 1 # Calcula o valor total da compra amount += price keep = str(input('Deseja continuar? [S|N]')).upper().strip() while len(keep) > 1 or keep not in 'SN': keep = str( input('Valor inválido\nDeseja continuar? [S|N]')).upper().strip() if keep == 'N': break print(f'O total da compra foi: R${amount:.2f}\nProdutos que custaram mais de 1000: {greater_thousand}\nO produto mais barato foi {cheapeast_product_name} que custou R${cheapeast_product:.2f} ')