blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
18c02f7f7b334e60c9731474eb0ff13d750aec1b
drcsturm/project-euler
/p028.py
997
3.625
4
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: # 21 22 23 24 25 # 20 7 8 9 10 # 19 6 1 2 11 # 18 5 4 3 12 # 17 16 15 14 13 # It can be verified that the sum of the numbers on the diagonals is 101. # What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? import numpy as np np.set_printoptions(linewidth=240) size = 1001 z = np.empty((size, size), dtype=np.int64) count = 1 row = size//2 col = size//2 loc = 0 z[row, col] = 1 while True: loc += 1 for i in range(loc): count += 1 if col+i+1 == size:break z[row, col+i+1] = count col += loc if col == size: break for i in range(loc): count += 1 z[row+i+1, col] = count row += loc loc += 1 for i in range(loc): count += 1 z[row, col-i-1] = count col -= loc for i in range(loc): count += 1 z[row-i-1, col] = count row -= loc print(np.sum(np.diagonal(z)) + np.sum(np.diagonal(np.rot90(z))) - 1)
79649b8391d4a804042b64155fe59ed010f7a877
TomasArteaga/MCOC-NIVELACION
/21082019/000310.py
148
3.859375
4
a=[3,10,-1] print (a) a.append(1) print(a) a.append("hello") print(a) a.append([1,2]) print(a) #3:10-4:10 a.pop() print(a) a.pop() print(a)
0338d7a580795e77abc73b84f1bf28a729011e57
erikhansen816/unit2
/quiz2.py
837
4.40625
4
#Erik Hansen #9/25/2017 #quiz2.py - Quiz program on unit 2 num1 = int(input('Enter a number: ')) num2 = int(input('Enter a second number: ')) #This part determines which number is the biggest if num1>num2: print('The first number is bigger') elif num2>num1: print('The second number is bigger') else: print('The numbers are the same') #This part determines their divisibility by 3 if num1%3 == 0 and num2%3 == 0: print('Both are divisible by 3') elif num1%3 == 0: print('The first is divisible by 3') elif num2%3 == 0: print('The second is divisible by 3') else: print('Neither are divisible by 3') #This part asks for the product and determines if the answer is correct product = int(input('What is the product of these two numbers? ')) if product == num1*num2: print('Correct') else: print('Incorrect')
348d320f762d784a9f54df8546104b6e3c5e7455
AntonBrazouski/thinkcspy
/12_Dictionaries/lab_12_01b.py
236
3.75
4
# def countA(text): # count = 0 # for c in text: # if c == 'a': # count = count + 1 # return count # # print(countA("banana")) # def countA(text): return text.count("a") print(countA('bananamama'))
3c1d91a5d1830f6f27cdf66bb42315d4c168ca61
jithu7432/physics
/Mathematics/Polynomials/Chebyshev.py
666
3.515625
4
#JJ from pandas import DataFrame f = lambda v: v ** 4 - 8 * v + 3 df = lambda u:(f(u + h) - f(u)) / h ddf = lambda z: (df(z + h) - df(z)) / h fl, dfl, xl, xll, ddfl = ([] for _ in range(5)) epsilon = 1e-5 h = 1e-5 x = float(input("Enter initial guess: ")) while True: xl.append(x), ddfl.append(ddf(x)), fl.append(f(x)), dfl.append(df(x)) x = x - (f(x) / df(x)) - (f(x) * f(x) * ddf(x)) / (2 * (df(x) ** 3)) xll.append(x) if abs(f(x)) <= epsilon: break data = {"X": xl, "f(x)": fl, "f'(x)": dfl, "f''(x)": ddfl, "Xn": xll} frame = DataFrame(data) print(frame) print("The root of the equation is:", x)
8998694693af206789c407f00936ad609f9625a3
mariihespana/8ProjectsInPython
/Project_7_Adventure_Game.py
2,951
3.796875
4
# Projeto 7 - Jogo de Aventura (ADAPTADO - MINHA VERSÃO) # Um jogo de decisões onde terão vários finais diferentes de acordo com cada resposta dada Cenario1 = 'Você está em uma guerra entre duas nações. As nações são representadas por Gregos e Romanos.' Cenario2 = 'Infelizmente, não se têm espadas para todos. Durante a luta, você pode escolher entre utilizar um escudo ou uma espada para enfrentar os inimigos.' Cenario3 = 'Todos os guerreiros podem escolher entre serem treinados por especialistas de guerra.' class JogoDeAventura: def __init__(self): self.pergunta1 = 'De qual lado você gostaria de jogar?' self.pergunta2 = 'Você escolhe lutar com a espada ou com o escudo?' self.pergunta3 = 'Você gostaria de ser treinado pela Cavalaria Pesada do Império ou pelos Guerreiros da Elite?' self.resultado1 = 'VOCÊ É UM HERÓI!!! E CONSEGUIU VENCER O OPONENTE!.' self.resultado2 = 'VOCÊ NÃO CONSEGUIU VENCER O OPONENTE.' def Iniciar(self): print(Cenario1) self.resposta1 = input(self.pergunta1) if self.resposta1 == 'Gregos': print(Cenario2) self.resposta11 = input(self.pergunta2) if self.resposta11 == 'Espada': print(Cenario3) self.resposta111 = input(self.pergunta3) if self.resposta111 == 'Cavalaria Pesada do Império': print(self.resultado1) if self.resposta111 == 'Guerreiros da Elite': print(self.resultado2) if self.resposta11 == 'Escudo': self.resposta111 = input(self.pergunta3) print(Cenario3) if self.resposta111 == 'Cavalaria Pesada do Império': print(self.resultado2) exit() if self.resposta111 == 'Guerreiros da Elite': print(self.resultado1) exit() if self.resposta1 == 'Romanos': print(Cenario2) self.resposta11 = input(self.pergunta2) if self.resposta11 == 'Espada': print(Cenario3) self.resposta111 = input(self.pergunta3) if self.resposta111 == 'Cavalaria Pesada do Império': print(self.resultado1) if self.resposta111 == 'Guerreiros da Elite': print(self.resultado2) if self.resposta11 == 'Escudo': self.resposta111 = input(self.pergunta3) print(Cenario3) if self.resposta111 == 'Cavalaria Pesada do Império': print(self.resultado2) exit() if self.resposta111 == 'Guerreiros da Elite': print(self.resultado1) exit() Jogo = JogoDeAventura() Jogo.Iniciar()
a9359143adf9c85f1c7df097b91662aa2f54696b
ioyy900205/.leetcode
/24.swap-nodes-in-pairs.py
1,181
3.703125
4
# @lc app=leetcode id=24 lang=python3 # # [24] Swap Nodes in Pairs # # @lc tags=linked-list # @lc imports=start from imports import * # @lc imports=end # @lc idea=start # # # # @lc idea=end # @lc group= # @lc rank= # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: pass # @lc code=end # @lc main=start if __name__ == '__main__': print('Example 1:') print('Input : ') print('head = [1,2,3,4]') print('Exception :') print('[2,1,4,3]') print('Output :') print(str(Solution().swapPairs([1,2,3,4]))) print() print('Example 2:') print('Input : ') print('head = []') print('Exception :') print('[]') print('Output :') print(str(Solution().swapPairs([]))) print() print('Example 3:') print('Input : ') print('head = [1]') print('Exception :') print('[1]') print('Output :') print(str(Solution().swapPairs([1]))) print() pass # @lc main=end
69f1c9b1336ce6cb01ba58b0fa0301b961641bda
eloranta/Euler
/python/Problem60/main.py
2,581
3.546875
4
def generate_primes(limit): primes = [True] * limit primes[0] = False primes[1] = False for n, is_prime_number in enumerate(primes): if is_prime_number: yield n for i in range(n * n, limit, n): primes[i] = False def create_primes(limit): primes = [] p = [True] * limit p[0] = False p[1] = False for n, is_prime_number in enumerate(p): if is_prime_number: primes.append(n) for i in range(n * n, limit, n): p[i] = False return primes def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False if n == 3: return True if n % 3 == 0: return False p = 5 q = 2 while n >= p * p: if n % p == 0: return False; p = p + q q = 6 - q return True def is_valid(a, b): return is_prime(int(str(a) + str(b))) and is_prime(int(str(b) + str(a))) def example_60(): primes = create_primes(10000) primes.remove(2) primes.remove(5) for i in range(len(primes)): for j in range(len(primes)): if j <= i: continue if is_valid(primes[i], primes[j]): for k in range(len(primes)): if k <= j: continue if is_valid(primes[i], primes[k]) and\ is_valid(primes[j],primes[k]): for l in range(len(primes)): if l <= k: continue if is_valid(primes[i],primes[l]) and \ is_valid(primes[j], primes[l]) and \ is_valid(primes[k], primes[l]): for m in range(len(primes)): if m <= l: continue if is_valid(primes[i], primes[m]) and \ is_valid(primes[j], primes[m]) and \ is_valid(primes[k], primes[m]) and \ is_valid(primes[l], primes[m]): print(primes[i], primes[j], primes[k], primes[l], primes[m]) print(primes[i] + primes[j] + primes[k] + primes[l] + primes[m]) return example_60()
24e71a33e622cde6c82a638078fd85f7406f82b2
daniel-reich/ubiquitous-fiesta
/bupEio82q8NMnovZx_15.py
740
3.671875
4
def track_robot(instructions): horizontal_movement = 0 vertical_movement = 0 final_instructions = [] for element in instructions: specific_instructions = element.split() if specific_instructions[0] == 'right': horizontal_movement += int(specific_instructions[1]) elif specific_instructions[0] == 'left': horizontal_movement -= int(specific_instructions[1]) elif specific_instructions[0] == 'up': vertical_movement += int(specific_instructions[1]) else: vertical_movement -= int(specific_instructions[1]) final_instructions.append(horizontal_movement) final_instructions.append(vertical_movement) return final_instructions
94fc2cc180624536668c6c57f3e3b9f5ec7d659a
kunal27071999/KunalAgrawal_week_1
/Week_1_datastructure_part1_Q60.py
262
4.3125
4
"""60. WAP to add list of elements to a given set Input set_1 = {"a", "b", "c"} list_1 = ["b", "d", "e"]""" sample_set = {"a", "b", "c"} list_of_num = ["b", "d", "e"] for elem in list_of_num: sample_set.add(elem) print('Modified Set: ') print(sample_set)
2c056c332738a99c6b67e9ef3ddd3242a3161736
arnabs542/DataStructures_Algorithms
/bitwise/Different_Bits_Sum_Pairwise.py
1,119
3.546875
4
''' Different Bits Sum Pairwise We define f(X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2. You are given an array of N positive integers, A1, A2 ,..., AN. Find sum of f(Ai, Aj) for all pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 109+7. Problem Constraints: 1 <= N <= 105 1 <= A[i] <= 231 - 1 Input 1: A = [1, 3, 5] Input 2: A = [2, 3] Ouptut 1: 8 Output 2: 2 ''' class Solution: def cntBits(self, a): sum = 0 m = 10**9 + 7 # count the number of 1s in each parity of every number for i in range(32): count_1 = 0 for j in range(len(a)): if a[j] & (1<<i): count_1 += 1 # multiply number of 1s with number of 0s, this will give us number of diff bits for all pairs in that parity # multiple by 2 because we can have f(i,i) too sum += 2 * count_1 * (len(a)-count_1) sum = sum % m return sum
5352a4b028c85879f963ee5367f0cad7feb18f03
TingHuanClay/Python_Libraries_Practice
/src/Pandas/pandas_demo.py
11,709
3.765625
4
import pandas as pd groceries = None def pands_series_demo(): global groceries groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=[ 'eggs', 'apple', 'milk', 'bread']) print(groceries) """ Output: eggs 30 apple 6 milk Tes bread No dtype: object """ print(f"groceries.shape: {groceries.shape}") print(f"groceries.ndim: {groceries.ndim}") print(f"groceries.size: {groceries.size}") """ Output: groceries.shape: (4,) groceries.ndim: 1 groceries.size: 4 """ print(f"groceries.index: {groceries.index}") print(f"groceries.values: {groceries.values}") """ Output: groceries.index: Index( ['eggs', 'apple', 'milk', 'bread'], dtype='object') groceries.values: [30 6 'Tes' 'No'] """ # Check is there specific item in the index sets is_contain_banana = 'banana' in groceries print(f"is_contain_banana: {is_contain_banana}") is_contain_bread = 'bread' in groceries print(f"is_contain_bread: {is_contain_bread}") def pands_series_access_demo(): print('\n============= pands_series_access_demo [START] ============= ') print('\nUsing the value of Index to get the elements in the series') print(f"groceries['eggs'] : {groceries['eggs']}") # Double Quote print(f"groceries['milk', 'bread'] : \n{groceries[['milk', 'bread']]}") # Using Index to get the first and the last element in the series print('\nUsing Index to get the first and the last element in the series') print(f"groceries[0] : {groceries[0]}") print(f"groceries[-1] : {groceries[-1]}") print(f"groceries[[0, 2]] : {groceries[[0, 2]]}") # modify the value by accessing index print() groceries['eggs'] = 2 print(groceries) # use drop to delete item from the series "OUT of the place" print('After dropping Apple:') print(groceries.drop('apple')) # use drop to delete item from the series "In place" with the paramter groceries.drop('apple', inplace=True) print(groceries) def pands_series_operation_demo(): print('\n\n==== pands_series_operation_demo [START] ==== ') fruits = pd.Series([10, 6, 3], ['apples', 'oranges', 'bananas']) print(fruits) print(fruits + 2) print(fruits - 2) print(fruits / 2) print() import numpy as np print(f"np.sqrt(fruits):\n{np.sqrt(fruits)}") print(f"np.exp(fruits):\n{np.exp(fruits)}") print(f"np.power(fruits, 2):\n{np.power(fruits, 2)}") # modify element by assign index and value all 'OUT of SPACE' print("\nmodify element by assign index and value:\n") print(f"fruits['bananas'] + 2: \n{fruits['bananas'] + 2}") print( f"fruits[['apples', 'oranges']]] * 2: \n{fruits[['apples', 'oranges']] * 2}") print(f"fruits.iloc[0] - 2: \n{fruits.iloc[0] - 2}") print( f"fruits.loc[['apples', 'oranges']] / 2: \n{fruits.loc[['apples', 'oranges']] / 2}") def pandas_frame_demo(): # Shopping cart for 2 people with the item value and item names items = { 'Bob': pd.Series([245, 25, 55], index=['bike', 'pants', 'watch']), 'Alice': pd.Series([40, 110, 500, 45], index=['book', 'glasses', 'bike', 'pants']) } print(type(items)) # Convert dictionary to Data Frame shopping_carts = pd.DataFrame(items) print(shopping_carts) # Create dataFrame with 'Default' Index, which is 0, 1, 2, 3... data = { 'Bob': pd.Series([245, 25, 55]), 'Alice': pd.Series([40, 110, 500, 45]) } df = pd.DataFrame(data) print(df) # get the attribute of the data frame print(f"shopping_carts.values: \n{shopping_carts.values}") print(f"shopping_carts.shape: {shopping_carts.shape}") print(f"shopping_carts.ndim: {shopping_carts.ndim}") print(f"shopping_carts.size: {shopping_carts.size}") # Get the subsets from the data frame by COLUMN print('Get the subsets from the data frame by "COLUMN"') bob_shopping_carts = pd.DataFrame(items, columns=['Bob']) print(bob_shopping_carts) # Get the subsets from the data frame by INDEX print('Get the subsets from the data frame by "INDEX"') sel_shopping_carts = pd.DataFrame(items, index=['pants', 'watch']) print(sel_shopping_carts) # Get the subsets from the data frame by COLUMN & INDEX print('Get the subsets from the data frame by "INDEX" & "COLUMN"') alice_sel_shopping_carts = pd.DataFrame( items, index=['glasses', 'bike'], columns=['Alice']) print(alice_sel_shopping_carts) # Create Index for the dataframe, even though there is NO index in the 'Dictionary' # NO index in the following dictionary data = { 'Integers': [1, 2, 3], 'Float': [4.5, 8.2, 9.6] } df = pd.DataFrame(data, index=['label 1', 'label 2', 'label 3']) print(df) """ Output: Integers Float label 1 1 4.5 label 2 2 8.2 label 3 3 9.6 """ # Create Index for the dataframe, even though there is NO index in the 'Array' # NO index in the following Array items = [ {'bike': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bike': 15, 'pants': 5} ] store_item = pd.DataFrame(items, index=['store 1', 'store 2']) print(store_item) """ Output: bike glasses pants watches store 1 20 NaN 30 35 store 2 15 50.0 5 10 """ def pandas_frame_access_demo(): items = [ {'bike': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bike': 15, 'pants': 5} ] store_items = pd.DataFrame(items, index=['store 1', 'store 2']) print(store_items) print() print(store_items[['bike']]) print() print(store_items[['bike', 'pants']]) print() print(store_items.loc[['store 1']]) print() # # Please be NOTICED that column label first, then row label comes in Data Frame # print(store_items['bike']['store 2']) print() # Add a new item into data frame store_items['shirts'] = [15, 2] print(store_items) print() """ combined existed data in the data frame """ print('\ncombined existed data in the data frame\n') # Add a new 'COLUMN' combined from existed columns in the data frame store_items['suits'] = store_items['shirts'] + store_items['pants'] print(store_items) print() # Add a new 'ROW' combined from existed rows in the data frame # You have to create a new data frame and append it to existed data frame new_items = [{'bike': 20, 'pants': 30, 'watches': 35, 'glasses': 4}] new_store = pd.DataFrame(new_items, index=['store 3']) print(new_store) store_items = store_items.append(new_store) print(store_items) # Add a new column from existed column, but only part of rows store_items['new_watches'] = store_items['watches'][1:] print(store_items) # Insert a new column with specified position # df.insert(index of column, column name, data) store_items.insert(5, 'shoes', [8, 5, 0]) print(store_items) """ using 'pop()' to delete column """ store_items.pop('new_watches') print(store_items) """ using 'drop()' to delete column or row (it depends on the axis specified) """ # Drop column with axis = 1 store_items = store_items.drop(['watches', 'shoes'], axis=1) print(store_items) # Drop column with axis = 0 store_items = store_items.drop(['store 1', 'store 2'], axis=0) print(store_items) """ Rename the column in data frame: 'pd.rename(columns: {A: a}, {B: b})' """ store_items = store_items.rename(columns={'bike': 'hats'}) print(store_items) """ Rename the row in data frame: 'pd.rename(index: {A: a}, {B: b})' """ store_items = store_items.rename(index={'store 3': 'last store'}) print(store_items) def pandas_data_clean_demo(): """ How to deal with the Nan value in the data frame bike glasses pants shirts shoes suits watches store 1 20 NaN 30 15.0 8 45.0 35 store 2 15 50.0 5 2.0 5 7.0 10 store 3 20 4.0 30 NaN 10 NaN 35 """ items = [ {'bike': 20, 'pants': 30, 'watches': 35, 'shirts': 15, 'shoes': 8, 'suits': 45}, {'watches': 10, 'glasses': 50, 'bike': 15, 'pants': 5, 'shirts': 2, 'shoes': 5, 'suits': 7}, {'bike': 20, 'pants': 30, 'watches': 35, 'glasses': 4, 'shoes': 10} ] store_items = pd.DataFrame(items, index=['store 1', 'store 2', 'store 3']) print(store_items) # Count the number of Nan value in the Data frame x = store_items.isnull().sum().sum() print(f"NaN values count: {x}") # Count the number of Not-Nan value in the Data frame x = store_items.count().sum().sum() print(f"Not-NaN values count: {x}") # Drop the ROWS which has NaN value OUT of place print(store_items.dropna(axis=0)) # Drop the COLUMNS which has NaN value "OUT of place" print(store_items.dropna(axis=1)) # Drop the COLUMNS which has NaN value "In place" # store_items.dropna(axis=1, inplace=True) # fill the Nan value with specified value print(store_items.fillna(0)) # fill the Nan value with PREVIOUS 'row' value print(store_items.fillna(method="ffill", axis=0)) # fill the Nan value with PREVIOUS 'column' value print(store_items.fillna(method="ffill", axis=1)) # fill the Nan value with NEXT 'row' value print(store_items.fillna(method="backfill", axis=0)) # fill the Nan value with NEXT 'column' value print(store_items.fillna(method="backfill", axis=1)) # fill the Nan value with 'column' value print(store_items.fillna(method="linear", axis=0)) print(store_items.fillna(method="linear", axis=1)) def pandas_file_and_groupby_demo(): google_stock = pd.read_csv('./goog-1.csv') print(type(google_stock)) print(google_stock.shape) # print(google_stock) print(google_stock.head()) print(google_stock.head(2)) print(google_stock.tail()) print(google_stock.tail(3)) # Check the Nan value in the Data frame print('Check the Nan value in the Data frame') print(google_stock.isnull().any()) # get statistic information of the data frame print('get statistic information of the data frame') print(google_stock.describe()) print('get statistic information of the column in the data frame') print(google_stock['Adj Close'].describe()) print('get max statistic information of the data frame') print(google_stock.max()) print('get mean statistic information of the data frame') print(google_stock.mean()) print('get min statistic information of the column in the data frame') print(google_stock['Close'].min()) # Correlation value print('\nget correlation information of the data frame') print(google_stock.corr()) # groupby() for aggregation information # data.groupby(['Year'])['Salary'].sum() # data.groupby(['Year'])['Salary'].mean() # data.groupby(['Name'])['Salary'].sum() # data.groupby(['Year', 'Department'])['Salary'].sum() if __name__ == '__main__': # pands_series_demo() # pands_series_access_demo() # pands_series_operation_demo() # pandas_frame_demo() # pandas_frame_access_demo() # pandas_data_clean_demo() pandas_file_and_groupby_demo()
2ebcf2277f9a22e7f1236a03dfa85cff555159c6
SouvikBhattacharji2020/My_Code
/Python/BasicPythonProgram/Class_8_CBSE/Loop_in_for_3.py
247
4.125
4
# # homework 4/8/2020 # # 1 # 2 3 # 4 5 6 # 7 8 9 10 # a=int(input("Enter number of row : ")) b=1 print("#") for i in range(1,a+1): print("#",end=" ") for j in range(1,i+1): print(b,end=" ") b+=1 print() print("#")
0bc2adfcc56a227f3609c01b5ac54748606e3970
evennia/evennia
/evennia/contrib/rpg/health_bar/health_bar.py
4,901
3.703125
4
""" Health Bar Contrib - Tim Ashley Jenkins 2017 The function provided in this module lets you easily display visual bars or meters - "health bar" is merely the most obvious use for this, though these bars are highly customizable and can be used for any sort of appropriate data besides player health. Today's players may be more used to seeing statistics like health, stamina, magic, and etc. displayed as bars rather than bare numerical values, so using this module to present this data this way may make it more accessible. Keep in mind, however, that players may also be using a screen reader to connect to your game, which will not be able to represent the colors of the bar in any way. By default, the values represented are rendered as text inside the bar which can be read by screen readers. The health bar will account for current values above the maximum or below 0, rendering them as a completely full or empty bar with the values displayed within. No installation, just import and use `display_meter` from this module: ```python from evennia.contrib.rpg.health_bar import display_meter health_bar = display_meter(23, 100) caller.msg(prompt=health_bar) ``` """ def display_meter( cur_value, max_value, length=30, fill_color=["R", "Y", "G"], empty_color="B", text_color="w", align="left", pre_text="", post_text="", show_values=True, ): """ Represents a current and maximum value given as a "bar" rendered with ANSI or xterm256 background colors. Args: cur_value (int): Current value to display max_value (int): Maximum value to display Keyword Arguments: length (int): Length of meter returned, in characters fill_color (list): List of color codes for the full portion of the bar, sans any sort of prefix - both ANSI and xterm256 colors are usable. When the bar is empty, colors toward the start of the list will be chosen - when the bar is full, colors towards the end are picked. You can adjust the 'weights' of the changing colors by adding multiple entries of the same color - for example, if you only want the bar to change when it's close to empty, you could supply ['R','Y','G','G','G'] empty_color (str): Color code for the empty portion of the bar. text_color (str): Color code for text inside the bar. align (str): "left", "right", or "center" - alignment of text in the bar pre_text (str): Text to put before the numbers in the bar post_text (str): Text to put after the numbers in the bar show_values (bool): If true, shows the numerical values represented by the bar. It's highly recommended you keep this on, especially if there's no info given in pre_text or post_text, as players on screen readers will be unable to read the graphical aspect of the bar. Returns: str: The display bar to show. """ # Start by building the base string. num_text = "" if show_values: num_text = "%i / %i" % (cur_value, max_value) bar_base_str = pre_text + num_text + post_text # Cut down the length of the base string if needed if len(bar_base_str) > length: bar_base_str = bar_base_str[:length] # Pad and align the bar base string if align == "right": bar_base_str = bar_base_str.rjust(length, " ") elif align == "center": bar_base_str = bar_base_str.center(length, " ") else: bar_base_str = bar_base_str.ljust(length, " ") if max_value < 1: # Prevent divide by zero max_value = 1 if cur_value < 0: # Prevent weirdly formatted 'negative bars' cur_value = 0 if cur_value > max_value: # Display overfull bars correctly cur_value = max_value # Now it's time to determine where to put the color codes. percent_full = float(cur_value) / float(max_value) split_index = round(float(length) * percent_full) # Determine point at which to split the bar split_index = int(split_index) # Separate the bar string into full and empty portions full_portion = bar_base_str[:split_index] empty_portion = bar_base_str[split_index:] # Pick which fill color to use based on how full the bar is fillcolor_index = float(len(fill_color)) * percent_full fillcolor_index = max(0, int(round(fillcolor_index)) - 1) fillcolor_code = "|[" + fill_color[fillcolor_index] # Make color codes for empty bar portion and text_color emptycolor_code = "|[" + empty_color textcolor_code = "|" + text_color # Assemble the final bar final_bar = ( fillcolor_code + textcolor_code + full_portion + "|n" + emptycolor_code + textcolor_code + empty_portion + "|n" ) return final_bar
6e3387e3489b1040b753b542f2e3f2d4edfec3dc
davidbezerra405/PytonExercicios
/ex023.py
864
3.953125
4
num = str(input('Informe um número entre 0 e 9999: ')).strip() print('O número informado tem {} digito(s).'.format(len(num))) numint = int(num) print('') #print('String') #print('-'*10) #print('Unidade: {}'.format(num[3])) #print('Dezena: {}'.format(num[2])) #print('Centena: {}'.format(num[1])) #print('Milhar: {}'.format(num[0])) print('') print('Inteiro') print('-'*10) #numm = int((numint - numint % 1000) / 1000) #numint = int(numint % 1000) #numc = int((numint - numint % 100) / 100) #numint = int(numint % 100) #numd = int((numint - numint % 10) / 10) #numint = int(numint % 10) #numu = int((numint - numint % 1)) numu = numint // 1 % 10 numd = numint // 10 % 10 numc = numint // 100 % 10 numm = numint // 1000 % 10 print('Unidade: {}'.format(numu)) print('Dezena: {}'.format(numd)) print('Centena: {}'.format(numc)) print('Milhar: {}'.format(numm))
ed142339bc35c7d15eeddb75643dfd588b0f9516
karthik-siru/practice-simple
/strings/dsa_7.py
1,173
3.984375
4
''' Algorithm : So , the longest palindrome , will start in the middle . So , the key idea is to to find the longest palindrome , with ith index as center . and to cover the even length strings we , run the expand fundtion with ith index and i+1 th index as center Note : This approach is better than Dynamic programmming approach because , we don't use extra space here . ''' class Solution: def expand (self, s, left, right ) : n = len(s) while left >= 0 and right < n and s[left] == s[right] : left -= 1 right += 1 return s[left+1 : right ] def longestPalin(self, S): # code here if S == "" : return 0 longest = "" for i in range(len(S)) : p1 =self.expand(S, i-1 , i+1 ) if len(p1) > len(longest) : longest = p1 p2 = self.expand(S, i , i +1 ) if len(p2) > len(longest): longest = p2 return longest
f657d093d2347d965c3a24032d4e3aa2067d8e48
kpsimon/general-python
/beginner/gamesofchance.py
5,214
3.9375
4
import random money = 100 num = random.randint(1, 10) #Write your game of chance functions here def coinflip(guess, bet, money): flip = random.randint(1,2) g_val = guess.upper() while not (g_val == "HEADS" or g_val == "TAILS"): g_val = input("Invalid guess. Heads or Tails:").upper() while not (bet.isdigit() and int(bet) <= money): bet = input("Invalid bet. Enter your bet:") if ((g_val == "HEADS") and (flip == 1)) or ((g_val == "TAILS") and (flip == 2)): print("The flip was " + g_val + ", you won!\n") flag = 0 elif (g_val == "HEADS" and flip == 2): print("The flip was TAILS, you lost.\n") flag = 1 elif (g_val == "TAILS" and flip == 1): print("The flip was HEADS, you lost.\n") flag = 1 if flag: print("You earned -" + str(bet) +".") return int(bet) * -1 else: print("You earned " + str(bet) + ".") return int(bet) def cho_han(guess, bet, money): die1 = random.randint(1,6) die2 = random.randint(1,6) g_val = guess.upper() while not (g_val == "ODD" or g_val == "EVEN"): g_val = input("Invalid guess. Odd or Even:").upper() while not (bet.isdigit() and int(bet) <= money): bet = input("Invalid bet. Enter your bet:") is_even = (die1 + die2) % 2 == 0 if (is_even and g_val == "EVEN") or (not is_even and g_val == "ODD"): print("The sum of the die were " + g_val + ", you won!\n") flag = 0 # elif (not is_even and g_val == "ODD"): # print("The sum of the die were " + g_val + ", you won!\n") elif (not is_even and g_val == "EVEN"): print("The sum of the die were ODD, you lost!\n") flag = 1 elif (is_even and g_val == "ODD"): print("The sum of the die were EVEN, you lost!\n") flag = 1 if flag: print("You earned -" + str(bet) + ".") return int(bet) * -1 else: print("You earned " + str(bet) + ".") return int(bet) def card_game(p1_bet, p2_bet): deck = list(range(1,52)) while not p1_bet.isdigit(): p1_bet = input("Invalid bet. Player 1 enter your bet:") while not p2_bet.isdigit(): p2_bet = input("Invalid bet. Player 2 enter your bet:") p1_card = deck[random.randint(0,len(deck))]%13 deck.remove(p1_card) p2_card = deck[random.randint(0,len(deck))]%13 if p1_card == 0 or p1_card == 1: p1_card += 13 if p2_card == 0 or p2_card == 1: p2_card += 13 #ace 2 3 4 5 6 7 8 9 10 jack queen king #1 2 3 4 5 6 7 8 9 10 11 12 0 print("Player 1 drew: " + str(p1_card) + ", Player 2 drew: " + str(p2_card) + ".") if p1_card > p2_card: print("Player 1 wins $" + str(p1_bet) + ".") elif p1_card < p2_card: print("Player 2 wins $" + str(p2_bet) + ".") else: print("Tie! Both players earn $0.") def roulette(guess,bet, money): while not (guess.upper() == "ODD" or guess.upper() == "EVEN" or guess.isdigit()): guess = input("Invalid guess. Odd, Even, or Number:") while not bet.isdigit(): bet = input("Invalid bet. Enter your bet:") answers = list(range(0,36)) answers.append("00") ball_roll = answers[random.randint(0,len(answers))] if guess.upper() == "EVEN": if ball_roll % 2 == 0 and ball_roll != 0 and ball_roll != "00": flag = (0, 0, 1) else: flag = (1, 1, 1) elif guess.upper() == "ODD": if ball_roll % 2 == 1 and ball_roll != 0 and ball_roll != "00": flag = (0, 1, 1) else: flag = (1, 0, 1) elif guess.isdigit(): if guess == str(ball_roll): flag = (1, 2, 35) else: flag = (1, 2, 35) print("BALL ROLL:", ball_roll) if flag[0] == 0: if flag[1] == 0: print("The roll was EVEN, you won $" + str(flag[2]*int(bet)) + ".") elif flag[1] == 1: print("The roll was ODD, you won $" + str(flag[2]*int(bet)) + ".") elif flag[1] == 2: print("The ball landed on your bet. You won $" + str(flag[2]*int(bet)) + ".") return flag[2]*int(bet) elif flag[0] == 1: if flag[1] == 0: print("The roll was EVEN, you lost $" + bet + ".") elif flag[1] == 1: print("The roll was ODD, you lost $" + bet + ".") elif flag[1] == 2: print("The roll was not " + guess + ", you lost $" + bet + ".") return int(bet) * -1 #Call your game of chance functions money = 10 print("Current Money = " + str(money)) decision = input("Play Coin Flip? (Y/N)").upper() while decision == "Y" and money > 0: money += coinflip(input("Heads or Tails:"), input("Enter your bet:"), money) print("\n") print("Current Money = " + str(money)) decision = input("Keep playing? (Y/N)").upper() print("\n") decision = input("Play Cho Han? (Y/N)").upper() while decision == "Y" and money > 0: money += cho_han(input("Odd or Even:"), input("Enter your bet:"), money) print("\n") print("Current Money = " + str(money)) decision = input("Keep playing? (Y/N)").upper() print("\n") decision = input("Play Card Game? (Y/N)").upper() while decision == "Y": card_game(input("Player 1 - Enter your bet:"),input("Player 2 - Enter your bet:")) decision = input("Keep playing? (Y/N)").upper() print("\n") decision = input("Play Roulette? (Y/N)").upper() while decision == "Y" and money > 0: money += roulette(input("Odd, Even, or Number:"),input("Enter your bet:"), money) print("\n") print("Current Money = " + str(money)) decision = input("Keep playing? (Y/N)").upper() print("\n") print("\nYour money after playing:", money) print("Thanks for playing!")
120db75cf67bb0111573e039d4aaf275588fea43
Ojooh/SANS-SURVEY-WITH-tkinter
/survey.py
9,774
3.5625
4
import tkinter from tkinter import * #import Question import time #import Image import random #create the questions #bcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc #ssssssssssssssssssssssssssssssssss' question_prompts = [ "1. What is your position within the company?", "2. Does your company have a security team?", "3. Do you know who to contact in case you are hacked or if your computer is infected? ", "4. Have you ever found a virus or Trojan on your computer at work?", "5. Do you know how to tell if your computer is hacked or infected? ", "6. Have you ever given your password from work to someone else? ", "7. If you format a hard drive or erase the files on it all the information on it is permanently lost.", "8. How secure do you feel your computer is? ", "9. Is the firewall on your computer enabled? ", "10. Is your computer configured to be automatically updated? ", "11. How careful are you when you open an attachment in email? ", "12. Do you know what a phishing attack is? ", "13. Do you know what an email scam is and how to identify one? ", "14. Is anti-virus currently installed, updated and enabled on your computer?", "15. My computer has no value to hackers, they do not target me.", "16. Does your company have policies on which websites you can visit? ", "17. Does your company have policies on which websites you can visit? ", "18. Is instant messaging allowed in our organization? ", "19. Can you use your own personal devices, such as your mobile phone, to store or transfer confidential company" " information? ", "20. Have you downloaded and installed software on your computer at work?", "21. Has your boss or anyone else you know at work asked you for your password? ", "22. Do you use the same passwords for your work accounts as you do for your personal accounts " "at home, such as Facebook, Twitter or your personal email accounts? ", "23. How often do you take information from the office and use your computer at home to work on it?", "24. Have you logged into work accounts using public computers, such as from a library, " "cyber café or hotel lobby? ", "25. If you delete a file from your computer or USB stick, that information can no longer be recovered. ", ] #create the multiple choices answers_choice = [ ["a. Full/Part time employee ","b. Contractor/Vendor ","c. Other "], ["a. Yes, we have a company security team. ","b. No, we do not have a company security team. ","c. I do not know."], ["a. Yes, I know who to contact. ","b. No, I do not know who to contact. ", "c. I am not sure "], ["a. Yes, my computers has been infected before","b. No, my computer has never been infected. ", "c. I do not know what a virus or Trojan is. "], ["a. Yes, I know what to look for to see if my computer is hacked or infected. ", "b. No, I do not know what to look for to see if my computer is hacked or infected. ", "c. I am not sure"], ["a. Yes ","b. No "," c. Not sure"], ["a. True ","b. False ", "c. Dont Know"], ["a. Very secure ","b. Secure ","c. Not secure "], ["a. Yes, it is enabled. ", "b. No, it is not enabled. ","c. I do not know what a firewall is. "], ["a. Yes, it is. ","b. No, it is not. ","c. I do not know. "], ["a. I always make sure it is from a person I know and I am expecting the email. ", "b. As long as I know the person or company that sent me the attachment I open it. ", "c. There is nothing wrong with opening attachments. "], ["a. Yes, I do. ","b. No, I do not. ","c. Not sure"], ["a. Yes I do. ","b. No, I do not. ","c. Not sure."], ["a. Yes it is. ","b. No it is not. ","c. I do not know how to tell / I do not know what anti-virus is. "], ["a. True ","b. False","c. I cant say."], ["a. No, there are no policies, I can visit whatever websites I want while at work", "b. Yes, there are policies limiting what websites I can and cannot visit while at work, but I do not " "know the policies.", "c. Yes, there are policies and I know and understand them. "], ["a. No, there are no policies, I can send whatever emails I want to whomever I want while at work. ", "b. Yes, there are policies limiting what emails I can and cannot send while at work, " "but I do not know the policies. ","c. Yes, there are policies and I know and understand them. "], ["a. Yes, instant messaging is allowed in our organization. ","b. No, instant messaging " "is not allowed in our organization. ","c. I do not know. "], ["a. Yes I can","b. No I cannot. ","c. I do not know"], ["a. Yes I have. ","b. No I have not. ","c. Not sure"], ["a. Yes, they have ","b. No, they have not. ","c. I can not remember"], ["a. Yes I do. ", "b. No I do not. ", "c. Not sure"], ["a. Almost every day. ", "b. At least once a week/ monthly ", "c. Never"], ["a. Yes, I have ", "b. No, I have not ", "c. I can not remember"], ["a. True ", "b. False", "c. I do not know"], ] answers = [1,0,0,1,0,0,1,1,0,2,0,1,2,1,2,1,2,2,1,1,1,1,0,1,1] user_answer = [] indexes = [] gee = [] def gen(): global indexes for i in range(25): indexes.append(i) def showresult(score): labelQ2.destroy() r1.destroy() r2.destroy() r3.destroy() labelimage2 = Label( root, background = "#ffffff", border = 0, ) labelimage2.pack() labelresulttext = Label( root, font = ("Comic sans",20), background = "#ffffff", ) labelresulttext.pack() if score >= 20: img = PhotoImage(file="start.png") labelimage2.configure(image=img) labelimage2.image = img labelresulttext.configure(text="You have a high level of Cyber user security awareness!!") elif (score >= 10 and score < 20): img = PhotoImage(file="next.png") labelimage2.configure(image=img) labelimage2.image = img labelresulttext.configure(text="You Can Be Better with a Cyber user security awareness revision!!") else: img = Photoimage(file="next.png") labelimage2.configure(image=img) labelimage2.image = img labelresulttext.configure(text="You Can Be Better with a Cyber user security awareness training!!") def calc(): # global indexes, user_answer, answers x = 0 score = 0 for i in indexes: if user_answer[x] == answers[i]: score = score + 5 x += 1 print(score) showresult(score) def selectedbtn(): global radiovar,user_answer global labelQ2,r1,r2,r3 x = radiovar.get() user_answer.append(x) print(user_answer) # time.sleep(1) d = 1 if len(gee) == 0: gee.append(d) labelQ2.config(text=question_prompts[gee[0]]) r1['text'] = answers_choice[gee[0]][0] r2['text'] = answers_choice[gee[0]][1] r3['text'] = answers_choice[gee[0]][2] else: if gee[0] == 24: print(indexes) print(user_answer) calc() else: y = gee[0] + 1 gee[0] = y labelQ2.config(text=question_prompts[gee[0]]) r1['text'] = answers_choice[gee[0]][0] r2['text'] = answers_choice[gee[0]][1] r3['text'] = answers_choice[gee[0]][2] # countquest = 0 #<!---- show first question and move to next question ----> def Questionshow(): global labelQ2,r1,r2,r3 labelQ2 = Label( root, text=(question_prompts[0]), font=("Comic sans MS", 24, "bold"), background="#ffffff", width=500, justify="center", wraplength=1000, ) labelQ2.pack() #create the option buttons global radiovar radiovar = IntVar() radiovar.set(-1) r1 = Radiobutton( root, text= answers_choice[0][0], font = ("Comic sans MS", 20, "bold"), value = 0, variable = radiovar, ) r1.pack() r2 = Radiobutton( root, text=answers_choice[0][1], font=("Comic sans MS", 20, "bold"), value=1, variable=radiovar, background="#ffffff", ) r2.pack() r3 = Radiobutton( root, text=answers_choice[0][2], font=("Comic sans MS", 20, "bold"), value=2, variable=radiovar, background="#ffffff", ) r3.pack() img4 = PhotoImage(file='nextt.png') btnnext = Button( image=img4, relief=FLAT, border=0, #command=Sleepsome, command=selectedbtn, ) btnnext.pack() create_image(image=img4) #<!----- end of optionbuttons-----> #<!----- move to first question -----> def StartIspressed(): labeltext.destroy() btnStart.destroy() labelimage1.destroy() gen() Questionshow() #<----- Program start here -----> root = tkinter.Tk() root.title("Cyber User Awareness Test") root.geometry("1500x800") root.config(background="#ffffff") # root.iconbitmap('c:/New Folder/halo_shield.ico') root.resizable(0,0) labeltext = Label( root, text = "Welcome!, Thank you for offering to participate in this test. Click start to begin.", font = ("Comic sans MS", 24, "bold"), background = "#ffffff", ) labeltext.pack(pady=(0,50)) img2 = PhotoImage(file='user_awareness1.png') labelimage1 = Label( root, image = img2, background = "#ffffff", ) labelimage1.pack(pady=(40,0)) img1 = PhotoImage(file='start.png') btnStart = Button( root, image = img1, relief = FLAT, border = 0, command = StartIspressed, ) btnStart.pack() root.mainloop()
c26cc47c30550ed0d2c408d77d4037d4dbf8ce4c
kiwi-33/Programming_1_practicals
/p4-5/p4-5p2.py
359
4.28125
4
length= float(input("Enter a number: ")) import math square= length**2 cube= length**3 circle= (math.pi)*(length**2) sphere = (4/3)*(math.pi)*(length**3) cylinder = (math.pi)*(length**2)*(length) if length < 0: print ("Length must be >=0. Please try again") else: print (square) print (cube) print (sphere) print (cylinder)
9c8bc69616e3e09c95dd47215b96e5809517e151
bytezen/Game-AI-Summer-Short-Course-2018
/new_steering_behaviors/util.py
1,601
3.90625
4
import pygame as pg from pygame.math import Vector2 def _rotate(surface, angle, pivot, offset): """Rotate the surface around the pivot point Args: surface (pygame.Surface): The surface that is to be rotated angle (float): Rotate by this angle pivot (tuple, list, pygame.math.Vector2): The pivot point offset (pygame.math.Vector2): This vector is added to the pivot point after the rotation Returns: rotated image (pygame.Surface): the new rotated surface rect (pygame.Rect): A rect with proper positioning for the rotated surface """ #rotate the image rotated_image = pg.transform.rotozoom(surface, -angle, 1) #rotate the offset vector rotated_offset = offset.rotate(angle) #Add the rotated offset vector to the center point to shift the rectangle rect = rotated_image.get_rect(center = pivot + rotated_offset) return rotated_image , rect def _clamp_vector(vector,min_length, max_length): """make sure that a vectors length is between minimum and maximum Args: vector (Vector2) - the vector to scale min_length (positive float) - the minimum length of the vector max_length (positive float) - the maximum length of the vector Return: the vector passed in is changed if necessary """ length = vector.length() if length > .001: if length < min_length: return vector.scale_to_length(min_length) elif length > max_length: return vector.scale_to_length(max_length) else: return vector
03395c858b3ba4ad022b5db9b3504875b65d4ccf
rehoot/SBList
/SBLtest01.py
1,464
3.5625
4
from SBList import * # The first test will ensure that the append function works properly. # A prior version would insert before the last entry instead of appending sb = SBList([]) sb.append(0) sb.append(1) sb.append(2) sb.append(3) assert(sb == [0,1,2,3]) sb.insert(4, 4) assert(sb == [0,1,2,3,4]) sb.insert(4, 3.5) assert(sb == [0,1,2,3,3.5,4]) sb.insert(0, 0.5) assert(sb == [0.5, 0,1,2,3,3.5,4]) # Test a simple undo and some insertions sl = SBList([1,2,6,3,12,7]) sl.insert(2, 90) sl.undo() sl.insert(2, 90) sl.insert(4, 50) sl.insert(5, 9999999) sl.insert(3, 20) sl.delete(6) sl.insert(3, 30) sl sl.sort() sl sl.delete(3) assert(sl.get_list() == [1, 2, 3, 7, 12, 20, 30, 50, 90]) #### ####################################################################### # Test insert, sort, delete: sl = SBList([1,2,6,3,12,7]) sl.sort() sl.undo() print('######## B') print('answer should be:\n[1, 2, 6, 3, 12, 7]') print(sl) print('------------------------------------------') sl = SBList([1,2,6,3,12,7]) sl.insert(2, 90) sl.undo() sl.insert(2, 90) sl.insert(4, 50) sl.insert(3, 20) sl.insert(3, 30) sl.sort() assert(sl.get_list() == [1, 2, 3, 6, 7, 12, 20, 30, 50, 90]) sl.delete(3) sl assert(sl.get_list() == [1, 2, 3, 7, 12, 20, 30, 50, 90]) #print('state after delete 3 is: ' + sl.show_state()) #print('base list is ' + sl.show_l()) #print('answer should be:\n[1, 2, 3, 7, 12, 20, 30, 50, 90]') #print(sl) #print(repr(sl.order())) ############################
c1cf328e10f7bd746b4398020232705a2a34bb32
AaronCWacker/copycat
/main.py
3,058
3.9375
4
#!/usr/bin/env python3 """ Main Copycat program. To run it, type at the terminal: > python main.py abc abd ppqqrr --interations 10 The script takes three to five arguments. The first two are a pair of strings with some change, for example "abc" and "abd". The third is a string which the script should try to change analogously. The fourth (which defaults to "1") is a number of iterations. One can also specify a defined seed value for the random number generator. This instruction produces output such as: iiijjjlll: 670 (avg time 1108.5, avg temp 23.6) iiijjjd: 2 (avg time 1156.0, avg temp 35.0) iiijjjkkl: 315 (avg time 1194.4, avg temp 35.5) iiijjjkll: 8 (avg time 2096.8, avg temp 44.1) iiijjjkkd: 5 (avg time 837.2, avg temp 48.0) wyz: 5 (avg time 2275.2, avg temp 14.9) xyd: 982 (avg time 2794.4, avg temp 17.5) yyz: 7 (avg time 2731.9, avg temp 25.1) dyz: 2 (avg time 3320.0, avg temp 27.1) xyy: 2 (avg time 4084.5, avg temp 31.1) xyz: 2 (avg time 1873.5, avg temp 52.1) The first number indicates how many times Copycat chose that string as its answer; higher means "more obvious". The last number indicates the average final temperature of the workspace; lower means "more elegant". """ import argparse import logging from copycat import Copycat, Reporter, plot_answers, save_answers class SimpleReporter(Reporter): """Reports results from a single run.""" def report_answer(self, answer): """Self-explanatory code.""" print('Answered %s (time %d, final temperature %.1f)' % ( answer['answer'], answer['time'], answer['temp'], )) def main(): """Program's main entrance point. Self-explanatory code.""" logging.basicConfig(level=logging.INFO, format='%(message)s', filename='./output/copycat.log', filemode='w') parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=None, help='Provide a deterministic seed for the RNG.') parser.add_argument('--iterations', type=int, default=1, help='Run the given case this many times.') parser.add_argument('--plot', action='store_true', help='Plot a bar graph of answer distribution') parser.add_argument('--noshow', action='store_true', help='Don\'t display bar graph at end of run') parser.add_argument('initial', type=str, help='A...') parser.add_argument('modified', type=str, help='...is to B...') parser.add_argument('target', type=str, help='...as C is to... what?') options = parser.parse_args() copycat = Copycat(reporter=SimpleReporter(), rng_seed=options.seed) answers = copycat.run(options.initial, options.modified, options.target, options.iterations) for answer, d in sorted(iter(answers.items()), key=lambda kv: kv[1]['avgtemp']): print('%s: %d (avg time %.1f, avg temp %.1f)' % (answer, d['count'], d['avgtime'], d['avgtemp'])) if options.plot: plot_answers(answers, show=not options.noshow) save_answers(answers, 'output/answers.csv') if __name__ == '__main__': main()
704b57e0ec9ee6144b65f7915c0ed0d414364084
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/codeabbey/_CodeAbbey_Challenges-master/Problem5_MinOf3.py
390
3.5
4
infile = open("prob5.txt") count = infile.readline() ans = "" for i in range(int(count)): a,b,c = infile.readline().split(" ") if int(a)>=int(b): #take b if int(b)>int(c): #take c ans += c +" " else: ans += b+" " else: #take a if int(a)>int(c): # take c ans += c+" " else: ans += a+" " print(ans)
6188d0fabd41646bd447583561508af05e2df9a5
Mugisha-isaac/python
/list.py
1,041
4.09375
4
num=[1,2,3] students=['mugisha',"isaac","byiringiro"] print(students) fruits = ["mango","apple","orange"] # print('mango' in fruits) # for fruit in fruits: # print(fruit) # print(len(fruits)) # print(range(4)) # for i in range(len(fruits)): # print('at index',i,"element is",fruits[i] # animals =["cat","cow","hen","chick"] both = animals + fruits print(both) print(animals*5) print(animals[1:3]) fruits[1:3]=["beans","vagetables"] print(fruits) matrix = [[1,2,3],[4,5,6],[7,8,9]] print(matrix[1][2]) fruits.append('lemon') print(fruits) fruits.sort(reverse=True) print(fruits) print(fruits.index('beans')) print(fruits.insert(2,'dog')) print(fruits.count('mango')) fruits.append('mango') print(fruits.count('mango')) fruits.pop(4) print(fruits) fruits.remove('vagetables') print(fruits) sentence = "he is playing" list_sen =list (sentence) print(list_sen) print(sentence.split(" ")) num=[1,2,3,4,5,6,7,8] print(max(num)) print(min(num)) # homework # path = C:\Users\User\Desktop\courses\python #output = courses.python
fed3d37d3dd6fe24bd8968d53dba61c95f2cf476
SysSciAndHealth/crcsim
/bin/createLinks.py
1,962
4.03125
4
#!/usr/bin/env python3 """ createLinks.py: read a "renumbered" directory and make a link to every file in that directory in the target directory. This has the effect of making the ordinary and renumbered directories look like one directory. If you are wondering why sych a thing should be needed, see the README file in /projects/systemsscience/linuxOutputs/or/out-OR-full-/dev-OR/var/crcsim/model Usage: createLinks.py renumberedDir targetDir """ import sys import os ''' For the given path, get the List of all files in the directory tree ''' def getListOfFiles(dirName): # create a list of file and sub directories # names in the given directory listOfFile = os.listdir(dirName) allFiles = list() # Iterate over all the entries for entry in listOfFile: # Create full path fullPath = os.path.join(dirName, entry) # If entry is a directory then get the list of files in this directory if os.path.isdir(fullPath): allFiles = allFiles + getListOfFiles(fullPath) else: allFiles.append(fullPath) return allFiles def main(): if len(sys.argv) < 3: print ("usage: createLinks.py renumberedDir targetDir") return inputDir = sys.argv[1] targetDir = sys.argv[2] if not os.path.exists(inputDir): print ("Input error: input dir " + inputDir + " does not exist.") return if not os.path.exists(targetDir): print ("Input error: target dir " + targetDir + " does not exist.") return renumberedFiles = getListOfFiles(inputDir) nFiles = len(renumberedFiles) print("Number of files " + str(nFiles)) for i in range(nFiles): srcFile = renumberedFiles[i] dstFile = srcFile.replace(inputDir, targetDir) print (srcFile) print (dstFile) os.symlink(srcFile, dstFile) if __name__ == "__main__": main()
58500f48b8b218fab8fb42504a4d6d99d56f3257
martinyordanov90/homework-hackBG
/6/1-List-Functions/COUNT ITEM.py
199
3.953125
4
def count_item(n, numbers): count = 0 for number in numbers: if n == number: count += 1 return count n = 2 numbers = [1,2,2,2,2,2,2,3,4,5] print(count_item(n,numbers))
48c7323349ddc44be054d998390b932cd7b8c856
elitewarri0r/project_euler
/Problem 4.py
792
4.3125
4
''' The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' #problem 4 # built-in function for flipping str, x = x[::-1] multiplier1 = int(input(" enter a number that's 3 dight : ")) multiplier2 = multiplier1 op = 0 product1 = multiplier1*multiplier2 # When this loop runs we multiply the numbers for x in range((1000 - multiplier1)) : product1 = multiplier1*multiplier2 y = str(product1) # Here we flip the product and check if it is a palindrome or not z = (y[::-1]) if z == y : op = product1 multiplier1 = multiplier1 + 1 multiplier2 = multiplier2 + 1 print(op,'is the largest palindrome made from the product of two 3-digit numbers.')
ff33e5f009830122d3aa0f152053c1610b1566d8
killswitchh/Leetcode-Problems
/Medium/LongestSubstringWithoutRepeatingCharacters.py
524
3.59375
4
""" https://leetcode.com/problems/longest-substring-without-repeating-characters/ """ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: left=0 right=0 n=len(s) l=[] max=0 while(right < len(s)): if(s[right] not in l): l.append(s[right]) right+=1 if(len(l)>max): max=len(l) else: l.pop(0) left+=1 return(max)
f730af53259a6870135f89bd59ed0a7556065d13
Tapsanchai/basic_pythom
/python_basic1.py
4,060
3.8125
4
# print & set variables """ คอมเม้นใหญ่ """ print("hello") v_str = "Parew" v_flt = 5.456 v_num = 789 v_bool = True v_array = [v_str, v_flt, v_num, v_bool] print(v_array, "=" ,type(v_array)) print("v_array[1] * v_array[2] =", float(v_array[1] * v_array[2]), "\n") # convert type variables con_v = int(v_flt); sum = con_v + v_num print("{v_flt} =", v_flt) print("{v_flt} convert to Int =", con_v) print(con_v, "+", v_num, "=", sum, "\n") # function input stream """ yourname = input("Enter your name: ") num1 = int(input("Number1 :")) num2 = int(input("Number2 :")) sum2 = num1 + num2 print("Wellcome, Mr.", yourname) print("num1 + num2 =", sum2) """ # if-else """ age = int(input("Enter your age: ")) if age >= 18: print("คุณสามารถเข้าดูได้") elif age < 18: print("คุณอายุต่ำกว่า 18 ปี!!") else: print("คุณกรอกข้อมูลไม่ถูกต้อง โปรดลองใหม่..") """ # if-else termary operator code = '001' print(code, "\n") if code == '001' else print("error", "\n") #acession index of string name_full = "Kuma Parew" print(name_full) print(name_full[:5]) print(name_full[5:10]) print(name_full[:-1]) # นับจำนวนตัวอักษรทั้งหมดในชุดข้อมูล print("จำนวนตัวอักษร =", len(name_full)) name_full2 = " Kuma Parew " print(name_full2) # ลบช่องว่างออก ทั้งหน้าสุดและหลังสุด print("ลบช่องว่าง =", name_full2.strip()) # ทำให้เป็นตัวพิมพ์ใหญ่ทั้งหมด print(name_full2.upper()) # ทำให้เป็นตัวพิมพ์เล็กทั้งหมด print(name_full2.lower()) name_full3 = "test" print(name_full3) # ทำให้เป็นตัวอักษรตัวแรกขึ้นต้นด้วยตัวพิมพ์ใหญ่ print(name_full3.capitalize()) # การแทนที่ข้อความ print(name_full.replace("Parew","Mee")) txt1 = "Hi, My name is Parew." # ตรวจข้อความ ว่ามีคำหรือข้อความที่ต้องการค้นหาหรือไม่ clicked = "name" in txt1 # ถ้ามีข้อความที่ต้องการค้นหา ให้แทนที่ข้อความ แต่ถ้าไม่มี ให้แสดงว่าไม่มีข้อความที่ค้นหา print("มีข้อความที่ต้องการค้นหา =", clicked) ,print("เปลี่ยนข้อความ name => Name555", txt1.replace("name","Nmae555"), "\n") if (clicked) else print("ไม่มีข้อความที่ค้นหา", clicked, "\n") # การจัดรูปแบบข้อความ โดยการนำข้อมูลไปแสดงใน เทมเพจข้อความที่สร้างไว้ fname_lname = "Thapsaenchai Chasanguan" grade = 3.5 salary = 28700.45616847 tem_txt = "ชื่อ:{0}\t เกรด:{1}\t อาชีพ:{2}\t เงินเดือน:{3:.3f}\t" print(tem_txt.format(fname_lname,grade,"Python Developer",salary)) # การนับจำนวนคำหรือประโยคที่ต้องการค้นหา ในชุดข้อความ zoo_txt = "dog cat dog" print(zoo_txt) print("มีคำว่า 'dog' จำนวน =",zoo_txt.count("dog"), "คำ") # เช็คคำขึ้นต้นหรือคำนำหน้า client_name = "Mr.Yohoho" if client_name.startswith("Mr."): print("He is gentlemen.") else: print("She is Ladies.") # เช็คคำลงท้าย rotery = "1545" print("คุณถูกรางวัล") if rotery.endswith("45") else print("คุณไม่ถูกรางวัล")
b9e10a145429022614da4426e4d461b77cb12007
Raolaksh/Python-programming
/If statement & comparision.py
466
4.15625
4
def max_num(num1, num2, num3): if num1 >= num2 and num1>= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print(max_num(300, 40, 5)) print("we can also compare strings or bulleans not only numbers") print("these are comparision operators") print("! sign means not equal and if we have to tell python that this " "is equal to this we have to put double = like this == ")
09af988f89eca6949b836e1e7744748645c1e89f
Gborgman05/algs
/py/merge_trees.py
725
4.0625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]: if not root1 and not root2: return None else: node = TreeNode((0 if not root1 else root1.val) + (0 if not root2 else root2.val)) node.right = self.mergeTrees(None if not root1 else root1.right, None if not root2 else root2.right) node.left = self.mergeTrees(None if not root1 else root1.left, None if not root2 else root2.left) return node
ff09c37531a98b3d4c344ffc1956f3fdc84a5bab
Eccie-K/pycharm-projects
/while loop.py
172
3.609375
4
age = 1 while age <= 10: age += 1 print("you qualify", age) while age > 0: age -= 1 print(age) a = ["foo", "bar", "joy"] while a: print(a.pop(-1))
4c04f9ccbf5051d6cb53c0a0ae1172b54b04f969
harshildarji/Python-HackerRank
/Regex and Parsing/Group(), Groups() & Groupdict().py
196
3.515625
4
# Group(), Groups() & Groupdict() # https://www.hackerrank.com/challenges/re-group-groups/problem import re s = re.search(r'(?!_)(\d|\w)\1', input()) print('-1' if s is None else s.group(0)[0])
89623e79bbcdd1896925b55fee663236346942eb
artem-aksenkin/nginx
/The biggest eve of 3.py
352
4.0625
4
x=int(input("type x value ")) y=int(input("type y value ")) z=int(input("type z value ")) if x>y and x>z and x%2==0: print(x) elif y>x and y>z and y%2==0: print(y) elif z>x and z>y and z%2==0: print(z) elif z==x and z==y and x%2==0 and y%2==0 and z%2==0: print ("all numberes are equal") else: print ("no one even number entered")
21e786aa0546e020ead4a93bf9bda2fc4c3fb233
candyer/leetcode
/2021 March LeetCoding Challenge/15_tinyURL.py
1,867
4.34375
4
# https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/590/week-3-march-15th-march-21st/3673/ # Encode and Decode TinyURL # Note: This is a companion problem to the System Design problem: Design TinyURL. # TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl # and it returns a short URL such as http://tinyurl.com/4e9iAk. # Design the encode and decode methods for the TinyURL service. # There is no restriction on how your encode/decode algorithm should work. # You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. from string import ascii_letters, digits from random import randint class Codec: def __init__(self): self.string = ascii_letters + digits self.full_to_tiny = {} self.tiny_to_full = {} self.url_head = 'http://tinyurl.com/' def shorten_url(self): """randomly select 6 characters from self.string""" return ''.join([self.string[randint(1, 61)] for _ in range(6)]) def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL.""" if longUrl in self.full_to_tiny: return self.url_head + self.full_to_tiny[longUrl] else: tail = self.shorten_url(longUrl) self.full_to_tiny[longUrl] = tail self.tiny_to_full[tail] = longUrl return self.url_head + tail def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL.""" tail = shortUrl[-6:] if tail in self.tiny_to_full: return self.tiny_to_full[tail] else: return None # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
363636278bdae82e2f79f1b55f8402f31f66bc7a
PMiskew/Year9DesignCS4-PythonPM
/General Techniques Python/ListsParallel.py
509
4.4375
4
#Parallel lists are lists that are designed to share common information in an index #Let's image a game where there are weapons that have damage and defense options weapon = ["sword","gun","sheild"] attack = [65,95,30] defense = [65,10,95] value = 1 while value != -1: print("1: Sword") print("2: Gun") print("3: Sheild") value = int(input("What option do you want?")) print("You chose "+weapon[value - 1]) print("Attack: ",attack[value - 1]) print("Defense: ",defense[value - 1]) print("DONE")
cc90012c15eaef0c750234a02676072d68e1e1cd
python-practice-b02-927/kuleshov
/lab2/ex5.py
431
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 10 09:44:48 2019 @author: student """ import turtle def square(a): for i in range(4): turtle.forward(a) turtle.right(90) n = 10 a = 30 c = 30 turtle.shape('turtle') for i in range(n): square(a) turtle.penup() turtle.backward(c) turtle.left(90) turtle.forward(c) turtle.right(90) turtle.pendown() a += 2*c
ff8f85d3d20208fc0b0b644da580caaad66973ea
cica-mica/zadaci_prva_zbirka
/1.1_vjezbe1.py
384
3.65625
4
""" Napravite program koji ce ispisati je li srednja cifra unesenog trocifrenog broja parna, neparna ili nula. """ x = int(input('Unesite zeljeni broj ')) srednja_cifra = (x//10)%10 print (srednja_cifra) if srednja_cifra == 0: print('Srednja cifra je 0') elif srednja_cifra % 2 == 0: print('Srednja cifra je parna') else: print('Srednja cifra je neparna')
9f99ffadd38adf99ca2bfc7c483b324b96d183a6
HACKunamatata1/finalProject
/Platform.py
693
3.796875
4
class Platform: """THIS WIL DEFINE A PLATFORM. ATTENTION: A PLATFORM IS NOT A FLOOR. PLATFORMS ONLY OCUPPY ONE CELL. FLOORS ARE GENERATED ON THE MAINGAME() CLASS""" def __init__(self, platform_x, platform_y): #position attributes self.platform_x = platform_x self.platform_y = platform_y @property def platform_x(self): return self.__platform_x @platform_x.setter def platform_x(self, platform_x): self.__platform_x = platform_x @property def platform_y(self): return self.__platform_y @platform_y.setter def platform_y(self, platform_y): self.__platform_y = platform_y
4f3740af3ece3ee2cf9f1646a2734d69709dd795
NiteshMistry/Complex-Data-Structures-Codecademy
/02-trees/03-trees-node-ii.py
334
3.78125
4
# Define your "TreeNode" Python class below class TreeNode: def __init__(self, value): self.value = value self.children = [] def add_child(self, child_node): print("Adding " + child_node.value) self.children.append(child_node) root = TreeNode("I am Root") child = TreeNode("A wee sappling") root.add_child(child)
4bc4fc5e88b9c2786b7374eaad8f85393220578a
dev-11/codility-solutions
/Solutions/Training/Lesson_07/stone_wall.py
402
3.5625
4
def solution(H): wall = [None] * len(H) wall_position = 0 used_blocks = 0 for height in H: while wall_position > 0 and wall[wall_position - 1] > height: wall_position -= 1 if wall_position < 1 or wall[wall_position - 1] != height: wall[wall_position] = height wall_position += 1 used_blocks += 1 return used_blocks
74235da9ba73aea55e8dd6f62bebe8ca93e84b72
Xiya01/python
/hangman.py
1,871
3.921875
4
import os, time def game(): nb_of_tries = 3 word = input("Write your word: ") list1= [] list2 =[] for letters in word: #put letters into a list list1.append(letters) os.system('cls') for a in list1: #display letter as "_" for players a = "_" list2.append(a) print(list2) #display list while nb_of_tries > 0: #game mechanics nb_of_tries -= 1 letter = input("Write your letter: ") os.system('cls') for z in list2: if letter == z: os.system('cls') print("Write another letter") break i = 0 y = "no" for x in list1: #put a correct letter to a list if letter == x: y = "yes" list2[i] = letter i += 1 if y == "yes": nb_of_tries += 1 print(list2) if list(letter) == list1: #win condition os.system('cls') print(list1) print("You won!") break if nb_of_tries == 0: #lose print("You lost. Try again!") break if list1 == list2: #win condition print("You won!") break def player_1(): print("Hello player # 1") def player_2(): print("Hello player # 2") while True: i = 0 player_choice = input("Hello! Choose one of the options:\n 1. Start \n 2. Exit \n" ) while i <= 2: #number of rounds if player_choice == "1": time.sleep(1) os.system('cls') player_1() game() time.sleep(1) os.system('cls') player_2() game() time.sleep(1) i += 1 if player_choice == "2": break
6e94a64fbead139373db2aad450cad28a1803587
caojp123/data
/二叉树.py
3,633
4.0625
4
# coding: utf-8 class Node: def __init__(self, item=None): self.value = item self.lchild = None self.rchild = None # 二叉树Binary tree class BinaryTree: def __init__(self, item=None): self.__root = item # 检测二叉树中是否有元素 def isEmpty(self): return self.__root is None # 向二叉树中添加元素 def addNode(self, item): node = Node(item) if self.isEmpty(): self.__root = node return None queue = [self.__root] while True: cursor = queue.pop(0) if cursor.lchild is None: cursor.lchild = node break else: queue.append(cursor.lchild) if cursor.rchild is None: cursor.rchild = node break else: queue.append(cursor.rchild) # 层级遍历 def traverse(self): if self.isEmpty(): return None queue = [self.__root] while queue: cursor = queue.pop(0) print(cursor.value, end=' ') if cursor.lchild is not None: queue.append(cursor.lchild) if cursor.rchild is not None: queue.append(cursor.rchild) print() # 先序遍历 def preorderTraverse(self): if self.isEmpty(): return None stack = [self.__root] while stack: cursor = stack.pop() print(cursor.value, end=' ') if cursor.rchild is not None: stack.append(cursor.rchild) if cursor.lchild is not None: stack.append(cursor.lchild) print() # 中序遍历 def middleTraverse(self): if self.isEmpty(): return None stack = [self.__root] while stack: cursor = stack.pop() if isinstance(cursor, Node): if cursor.rchild or cursor.lchild: if cursor.rchild: stack.append(cursor.rchild) stack.append(cursor.value) if cursor.lchild: stack.append(cursor.lchild) else: print(cursor.value, end=' ') else: print(cursor, end=' ') print() # 后续遍历 def tailTraverse(self): if self.isEmpty(): return None stack = [self.__root] while stack: cursor = stack.pop() if isinstance(cursor, Node): if cursor.lchild or cursor.rchild: stack.append(cursor.value) if cursor.rchild: stack.append(cursor.rchild) if cursor.lchild: stack.append(cursor.lchild) else: print(cursor.value, end=' ') else: print(cursor, end=' ') print() if __name__ == '__main__': import random testList = [i for i in range(10)] random.shuffle(testList) b binaryTree = BinaryTree() for item in testList: binaryTree.addNode(item) # binaryTree.addNode(1) # binaryTree.addNode(2) # binaryTree.addNode(3) # binaryTree.addNode(4) # binaryTree.addNode(5) # binaryTree.addNode(6) # binaryTree.addNode(7) # binaryTree.addNode(8) # binaryTree.addNode(9) binaryTree.traverse() binaryTree.preorderTraverse() binaryTree.middleTraverse() binaryTree.tailTraverse()
e31c8935b8516c9db70c275e996d22b9e8154b72
Madisonjrc/csci127-assignments
/lab_01/program1.py
905
3.6875
4
def greeter(name): return "hello"+name+"!" print(greeter("stan")) print(greeter("ollie")) def make_abba(a, b): return a+b+b+a def hello_name(name): return "Hello "+ name+"!" def near_hundred(n): return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10)) def missing_char(str, n): front= str[:n] back=str[n+1:] return front+back def monkey_trouble(a_smile, b_smile): if a_smile==True and b_smile==True: return True if a_smile==False and b_smile==False: return True if a_smile==True and b_smile==False: return False if a_smile==False and b_smile==True: return False def parrot_trouble(talking, hour): if talking==True and hour!=[7,8,9,10,11,12,13,14,15,16,17,18,19]: return True else: return False print(monkey_trouble(True,False)) print(near_hundred(10)) print(hello_name("dolly")) print(make_abba("hi","bye")) print(missing_char("hello",2))
03d9e7258ac81a298aa6a6c5b8d377784f440def
torres1-23/holberton-system_engineering-devops
/0x15-api/2-export_to_JSON.py
1,042
3.765625
4
#!/usr/bin/python3 """This modules gets information from {JSON} Placeholder API to list information about an employee, and stores it on a json format in a file. Usage: Accepts one argument, the id of the employee to list info. Execute this module like this: <python3 2-export_to_JSON.py <id of user>> json file will have the name: <user_id>.json """ import json import requests import sys if __name__ == "__main__": user_info_list = [] id = sys.argv[1] url = 'https://jsonplaceholder.typicode.com/users/{}'.format(id) user_info = requests.get(url) user_name = user_info.json()['username'] url_todo = url + '/todos' user_todos_info = requests.get(url_todo) todos_list = user_todos_info.json() for dic in todos_list: user_info_list.append( {'task': dic['title'], 'completed': dic['completed'], 'username': user_name}) user_info_dict = {id: user_info_list} with open("{}.json".format(id), "w") as file: json.dump(user_info_dict, file)
352d36799dc6abc14b6d3e790ac06360fb14816b
EduardoRosero/python
/curso python/paquete/TinyIntError/__init__.py
374
3.625
4
from .validate import validate_valor, validate_tiny_int from .error import TinyIntError #Definimos la funcion que me retorne su el numero comple o no con la condicion buscada e TinyInt def tiny_int(valor): try: if validate_valor(valor) and validate_tiny_int(valor): return True else: raise TinyIntError() except TinyIntError as error: print(error)
c58b1e6ace2828fe7eebd1fa6a79597a3736fa60
RhuanAlndr/CursoemVideo_Python
/ex026 - Aula 9.py
298
3.796875
4
f = input('Escreva uma frase qualquer: ').strip().lower() print('A letra "a" aparece {} na sua frase.'.format(f.count('a'))) print('A letra "a" aparece a primeira vez na posição {}.'.format(f.find('a') + 1)) print('A letra "a" aparece pela última vez na posição {}.'.format(f.rfind('a') + 1))
54ab7c419cbf86b2ddf236d9e8e01bec296dda03
butter-scotch/SameTree
/SameTree.py
508
3.734375
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSameTree(self, p, q): if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left) result1 = TreeNode([1,2,1]) result2 = TreeNode([1,1,2]) result = Solution() print(result.isSameTree(result1, result2))
7dd94b4b5d70dc3b9def902dc86af76b26b3a9ee
Yashkumar-Shinde/Python-programming-lab
/factorial.py
146
3.59375
4
#Yashkumar Shinde 11810825 M 53 a= int(input("Enter a number")) i=1 fact=1 for j in range(0,a): fact=fact*i i=i+1 print ("Factorial is:", fact)
95b7f97e8312ac9787765bb444fd4179317ffc76
sunjunee/Coding-Interview-Guide
/codes/T1-2.py
1,527
4.3125
4
# -*- coding: utf-8 -*- """ @ Author: Jun Sun {Python3} @ E-mail: [email protected] @ Date: 2018-05-30 17:14:52 """ # T1-2 由两个栈组成的队列 # 编写一个类,用两个栈实现一个队列,支持队列的基本操作 # add、poll、peek # add:队尾添加,poll:队头删除,peek:返回队头 # 用两个栈保存队列中的数据,栈1用于存push的数据 # 栈2用于pop数据。如果栈2为空,则将栈1的元素全部 # 取出来放到栈2(先进后出 + 先进后出 => 先进先出) class Queue(): def __init__(self): self.Stack1 = [] self.Stack2 = [] def add(self, x): self.Stack1.append(x) def poll(self): if(self.Stack2 != []): return self.Stack2.pop() else: # 如果stack2空了,则把stack1里面的数据全部加入到stack1 while(self.Stack1 != []): self.Stack2.append(self.Stack1.pop()) return self.Stack2.pop() def peek(self): if(self.Stack2 != []): return self.Stack2[-1] else: # 如果stack2空了,则把stack1里面的数据全部加入到stack1 while(self.Stack1 != []): self.Stack2.append(self.Stack1.pop()) if(self.Stack2 != []): return self.Stack2[-1] if __name__ == "__main__": s = Queue() s.add(1) print(s.peek()) s.add(3) print(s.peek()) s.add(2) print(s.peek()) print(s.poll()) print(s.poll()) print(s.poll())
acacc72d1c2171179fe92373a3e36834365cc5b6
ramlaxman/cisco-feb2020
/dictdiff.py
1,073
4.1875
4
#!/usr/bin/env python3 # dictdiff takes two dicts as arguments # it returns a dict representing the difference between them # if a key-value pair exists (identical) in both, ignore it in the output # if a key exists in both, with different values, return # a key-value pair with the key and a list as the value, with # the elements [first, second] # if a key exists in just one, return None as the value def dictdiff(first, second): output = {} for one_key in first.keys() | second.keys(): v1 = first.get(one_key) v2 = second.get(one_key) if v1 != v2: output[one_key] = [v1, v2] return output d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 1, 'b': 2, 'c': 4} print(dictdiff(d1, d1)) # prints {} print(dictdiff(d1, d2)) # # # # # prints {'c': [3, 4]} d1 = {'a': 1, 'b': 2, 'd': 3} d2 = {'a': 1, 'b': 2, 'c': 4} print(dictdiff(d1, d2)) # # # # # prints {'c': [None, 4], 'd': [3, None]} d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 1, 'b': 2, 'd': 4} print(dictdiff(d1, d2)) # # # prints {'c': [3, None], 'd': [None, 4]}
6ac8b15e4def29aea60f22a51347d55225d6e136
cs50/cscip14315
/2021-07-06/contacts5.py
227
4.25
4
people = [ {"name": "David", "email": "[email protected]"}, {"name": "Kareem", "email": "[email protected]"}, {"name": "Carter", "email": "[email protected]"} ] for i in range(3): print(f"Email {people[i]['name']} at {people[i]['email']}")
66b8472217e7fc3fc7197acf1af145020173ceb2
rrothkopf/programming1.0
/Labs/Ch4Lab.py
4,576
3.84375
4
''' Chapter 4 Lab Raven Rothkopf 9/30/19 ''' print("Welcome to Voyage! You are a sailor out on the sea in search of adventure. \nNot long ago, you saw a storm brewing far behind you and knew your boat was too small to survive it! \nChoose your actions wisely to get back to dry land, who knows what you might discover along the way?") # variables done = False # condition for game loop player_position = 0 thirst = 0 boat_damage = 0 storm_position = -20 drinks = 3 import random # Answer options / while not done: print("\nRemember, choose carefully!") print("A. Sail ahead at full speed.") print("B. Sail ahead at moderate speed.") print("C. Quench your thirst.") print("D. Drop your anchor for the night and repair your boat.") print("E. Status check.") print("Q. Quit.") print() answer = input("Enter your choice: ") if answer.upper() == "Q": done = True print("Thanks for playing!") elif answer.upper() == "A": print("You sailed ahead at full speed.") position_1 = random.randrange(8, 11) player_position += position_1 print("You traveled", position_1, "knots.") boat_damage += random.randrange(2, 4) storm_position += random.randrange(4, 8) thirst += 1 elif answer.upper() == "B": print("You sailed ahead at moderate speed.") position_2 = random.randrange(5, 7) player_position += position_2 print("You traveled", position_2, "knots.") boat_damage += random.randrange(1, 2) storm_position += random.randrange(7, 10) thirst += 1 elif answer.upper() == "C": if drinks > 0: print("You quenched your thirst.") thirst = 0 drinks -= 1 elif drinks <= 0: print("Your bottle is empty!") elif answer.upper() == "D": print("You dropped your anchor for the night. You also repaired the damages to your boat, looking good as new!") storm_position += random.randrange(9, 11) boat_damage = 0 elif answer.upper() == "E": print("Status Update:") print("Total knots traveled: ", player_position) print("Drinks left in your bottle: ", drinks) print("Storm is", player_position - storm_position, "knots behind you!") if thirst >= 5 and done == False: print("\nYou died of thirst!") print("Game over :(") done = True elif thirst == 3 or thirst == 4 and done == False: print("You are getting thirsty!") if boat_damage >= 9 and done == False: print("\nYour boat is too damaged to continue! You capsize and sink.") print("Game over :(") done = True if boat_damage == 6 or boat_damage == 7 or boat_damage == 8 and done == False: print("Your boat is pretty beat up! You might want to stop and repair it.") if storm_position >= player_position and done == False: print("\nThe storm caught you!") print("Game over :(") done = True elif player_position - storm_position <= 7 and done == False: print("\nThe storm is close!") # secret island story line if random.randrange(20) == 4 and done == False and (answer == "A" or answer == "B" or answer == "C"): print("\nYou stumble upon a secret island! You quench your thirst, refill your bottle and repair your boat.") thirst = 0 drinks = 3 boat_damage = 0 if random.randrange(75) == 6 and done == False and (answer == "A" or answer == "B" or answer == "C"): print("\nOh no! A water vortex opened up and swallowed you and your boat, you died.") print("Game over :(") done = False if player_position >= 100 and done == False: print("\nYou made it on to dry land safe and sound! Can't say the same for your boat.") print("Congratulations! Thank you for playing.") answer1 = input("Would you like to play again?") if answer1.upper() == "YES" or answer1.upper() == "Y": done = False player_position = 0 thirst = 0 boat_damage = 0 storm_position = -20 drinks = 3 print("\n\nWelcome to Voyage! You are a sailor out on the sea in search of adventure. \nNot long ago, you saw a storm brewing far behind you and knew your boat was too small to survive it! \nChoose your actions wisely to get back to dry land, who knows what you might discover along the way?") if answer1.upper() == "NO" or answer1.upper() == "N": done = True
95cf5e0f5e52885fd607e6218cb79721fc31e87c
melike-eryilmaz/pythonProgrammingLanguageForBeginners
/inputs.py
537
3.875
4
#12/12/2020 #Kullanıcıdan veri almak için input() kullanırız ve input olarak alınan değerler string olarak alınır. name = input('Please enter your name : ') surname = input('Please enter your surname : ') firstNumber = input('Please enter first number : ') secondNumber = input('Please enter second number : ') #inputlar string olarak alındığı için matematiksel işlemleri tip dönüşümü yaptıktan sonra yapmalıyız. print('Sum:',firstNumber+secondNumber) print('Real Sum : ',int(firstNumber)+int(secondNumber))
246db1cfcb31f7ba033febd460f483148afd8825
matiek8/Python
/Horner_s_method.py
1,116
3.859375
4
""" Дан многочлен P(x)=a[n] xⁿ+a[n₋₁] xⁿ⁻¹+...+a[₁] x+a[₀] и число x. Вычислите значение этого многочлена, воспользовавшись схемой Горнера: Формат ввода Сначала программе подается на вход целое неотрицательное число n≤20, затем действительноечисло x, затем следует n+1 вещественное число — коэффициенты многочлена от старшего к младшему. Формат вывода Программа должна вывести значение многочлена. Примечания При решении этой задачи нельзя использовать массивы и операцию возведения в степень. Программа должна иметь сложность O(n). """ n = int(input()) s = n x = float(input()) i = 0 p = 0 while i != n + 1: a = float(input()) p = p + a * x ** s s = s - 1 i = i + 1 print(p)
85c91709abafe50c918d184e5d872dc31b4ad0f8
sphamv/fcc-python-projects-time-calculator
/time_calculator.py
7,293
3.890625
4
def add_time(*args): MINUTES_DAY = 1440 MINUTES_WEEK = 10080 WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] start = args[0] duration = args[1] try: weekday = args[2].capitalize() weekday_pos = WEEKDAYS.index(weekday) except: weekday = "" if len(start.split()) !=2 or int(start.split()[0].split(":")[0])>12 or start.split()[1] not in ["AM", "PM"]: return "Error: Invalid starting time format" if int(duration.split(":")[1])>59: return "Error: Invalid duration time format" #extract and convert starting time into minutes if start.split()[1] == 'AM': s_hours = int(start.split()[0].split(":")[0]) s_minutes = int(start.split()[0].split(":")[1]) + (s_hours * 60) else: s_hours = int(start.split()[0].split(":")[0]) + 12 s_minutes = int(start.split()[0].split(":")[1]) + (s_hours * 60) d_minutes = int(duration.split(":")[0])*60 + int(duration.split(":")[1]) sum_minutes = s_minutes + d_minutes days = 0 if d_minutes == 0: if len(weekday)>0: return start + ", " + weekday else: return start if sum_minutes > MINUTES_DAY: days = int((sum_minutes / MINUTES_DAY)) #print ("days: ", days) new_time = "" # Display new time if it is still the same day if days==0: if sum_minutes < MINUTES_DAY/2: daytime = "AM" if sum_minutes%60 != 0: new_hours = int((sum_minutes - (sum_minutes % 60)) / 60) if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = sum_minutes % 60 else: new_hours = int(sum_minutes / 60) if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = 0 if len(weekday)>0: if new_minutes < 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime + ", " + weekday else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime + ", " + weekday else: if new_minutes < 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime else: daytime = "PM" if sum_minutes%60 != 0: new_hours = int((sum_minutes - (sum_minutes % 60)) / 60)-12 if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = sum_minutes % 60 else: new_hours = int(sum_minutes / 60)-12 if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = 0 # keep the double digit format if minutes are less than 10 if len(weekday)>0: if new_minutes < 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime + ", " + weekday else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime + ", " + weekday else: if new_minutes < 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime return new_time # Display the time if the new time is on the next day or more else: try: new_weekday_pos = weekday_pos + days if new_weekday_pos < 7: new_weekday = WEEKDAYS[new_weekday_pos] else: new_weekday_pos = ((weekday_pos + days)%7) print(new_weekday_pos) new_weekday = WEEKDAYS[new_weekday_pos] except: new_weekday = "" rem_minutes = sum_minutes % MINUTES_DAY # print("rem_minutes: ", str(rem_minutes)) if rem_minutes <=(MINUTES_DAY/2): daytime = "AM" if rem_minutes % 60 != 0: new_hours = int((rem_minutes - (rem_minutes % 60)) / 60) if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = rem_minutes % 60 # print ("new_minutes: ", new_minutes, type(new_minutes)) else: new_hours = int(rem_minutes / 60) if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = 0 if len(weekday)>0: if new_minutes < 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime + ", " + new_weekday else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime + ", " + new_weekday else: if new_minutes < 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime # print ("new time: ", new_time) else: daytime = "PM" if rem_minutes % 60 != 0: new_hours = int((rem_minutes - (rem_minutes % 60)) / 60)-12 if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = rem_minutes % 60 else: new_hours = int(rem_minutes / 60)-12 if new_hours == 0: #display 12 pm instead of reverting to 0 new_hours +=12 new_minutes = 0 # keep the double digit format if minutes are less than 10 if len(weekday)>0: if new_minutes< 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime + ", " + new_weekday else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime + ", " + new_weekday else: if new_minutes< 10: new_time = str(new_hours) + ":" + "0" + str(new_minutes) + " " + daytime else: new_time = str(new_hours) + ":" + str(new_minutes) + " " + daytime if days < 2: return new_time + " (next day)" else: return new_time + " (" + str(days) + " days later)" #print(add_time("11:06 PM", "2:02")) # print(add_time("11:43 AM", "00:20")) # print(add_time("10:10 PM", "3:30")) # print(add_time("6:30 PM", "205:12")) # print(add_time("11:30 AM", "192:32", "mOnDay")) #print (add_time("11:43 PM", "24:20", "tueSday")) #print(add_time("5:01 AM", "0:00")) #print(add_time("8:16 PM", "466:02", "tuesday")) #print(add_time("11:59 PM", "24:05", "Wednesday"))
788c103477b61d3e98ac05237573be6752fe9051
Dwensdc/Upeu_practice1_FDP
/secuenciales/ejercicio3CLSS.py
590
3.8125
4
def muestraMenorEdad(): #Definir Variables y otros pnombre="" pedad=0 #Datos de entrada p1nombre=input("Ingrese Nombre 1ra Persona:") p1edad=int(input("Ingrese edad 1ra Persona:")) p2nombre=input("Ingrese Nombre 2da Persona:") p2edad=int(input("Ingrese edad 2da Persona:")) p3nombre=input("Ingrese Nombre 3ra Persona:") p3edad=int(input("Ingrese edad 3ra Persona:")) #Proceso if p1edad<p2edad and p1edad<p3edad: pnombre=p1nombre pedad=p1edad elif p2edad<p1edad and #datos de salida print("la persona con menor edad es:",pnombre,"y su edad es:",pedad)
163417296994290f4a1451ac8b1f1a2744fd5b1d
jrthorne/python_exercises
/Week2-questions/easy/draw_face.py
2,913
4.53125
5
# Draw a face by jason # # THE EXERCISE DESCRIPTION # # Use the 'turtle' package to draw a human face to the screen. # Include as many features as you can - for example, # start with a head and add eyes, eyebrows, mouth, .... # A SOLUTION # # Problem solving strategy: # 1. Import the turtle library from turtle import * # 2. set the speed to the fastest possible speed('fastest') # 3. Draw the head - a circle up() goto(100,100) down() color('pink') fill(1) circle(100) fill(0) # 4. Draw two eyes # a. Lift the pen, relocate it, then set the pen down at new location # i. lift the pen up # ii. relocate the pen # iii. set the pen down up() goto(70,190) down() # b. Draw one circle with another smaller solid circle inside # i. draw one circle # ii. turn colour filler on # iii. draw a smaller circle # ii. turn colour filler off color('white') fill(1) circle(20) fill(0) # c. Lift the pen, relocate it, then set the pen down at new location # d. Draw one circle with another smaller solid circle inside color('black') fill(1) circle(10) fill(0) # and again for the right eye up() goto(130,190) down() color('white') fill(1) circle(20) fill(0) color('black') fill(1) circle(10) fill(0) # 5. Draw a mouth # a. Lift the pen, relocate it, then set the pen down at new location up() goto(80,150) right(90) down() color('red') fill(1) circle(20, 180) fill(0) color('black') circle(20,-180) # 6. Draw the eyebrows # a. Lift the pen, relocate it, then set the pen down at new location up() goto(50,250) left(110) down() color('brown') pensize(10) forward(30) # end for # now the right eyebrow up() right(20) forward(45) right(20) down() forward(30) # b. Draw first eyebrow # c. Lift the pen, relocate it, then set the pen down at new location # d. Draw second eyebrow # 7. Draw some spikey hair # a. Lift the pen, relocate it, then set the pen down at new location # b. draw a spike of hair # c. Lift the pen, relocate it, then set the pen down at new location # d. draw a spike of hair # e. Lift the pen, relocate it, then set the pen down at new location # f. draw a spike of hair # g. Lift the pen, relocate it, then set the pen down at new location # h. draw a spike of hair # i. Lift the pen, relocate it, then set the pen down at new location # j. draw a spike of hair # 8. Draw an earring # a. Lift the pen, relocate it, then set the pen down at new location # b. Draw a circle # 9. Draw a nose # a. Lift the pen, relocate it, then set the pen down at new location # b. draw a circle # move the turtle out of the way up() goto(0,0) # allow user to view picture before terminating with a return. myValue = raw_input("Press return to end")
f9bf9633d75bf991e9bc17eb1dcc3c3ed672c2a1
donghL-dev/Info-Retrieval
/lecture-data/PythonBasics/003_list.py
577
3.59375
4
L=[] L=['a','b','c','d'] print(L) print(L[0]) print(L[-1]) print(len(L)) L.append('e') del L[0] s='-'.join(L) print(s) s='ZZZ ABC DEF GHI JKL' print(s) L=s.split() print(L) if 'ABC' in L: print('ABC is in L') else: print('ABC is not in L') for e in L: print(e) # end for print() for e in sorted(L): print(e) # end for print() for e in sorted(L,reverse=True): print(e) # end for print() for i in range(len(L)): print(i,L[i]) # end for print() for i in range(0,len(L),1): print(i,L[i]) # end for print() for i in range(len(L)-1,-1,-1): print(i,L[i]) # end for
9f113ee711350f75d8ad1cac6468a01265f900bb
xxpasswd/algorithms-and-data-structure
/other/binary_search_tree.py
2,340
3.875
4
""" 二叉搜索树: 插入 查找 删除 """ class BinaryTree: def __init__(self, value=None): self.value = value self.right = None self.left = None @property def root(self): return self.value def __str__(self): return "{{{},{},{}}}".format(self.value, str(self.left), str(self.right)) def insert(t, value): if t.value is None: t.value = value elif value < t.value: t.left = t.left if t.left else BinaryTree() insert(t.left, value) else: t.right = t.right if t.right else BinaryTree() insert(t.right, value) def find_pos(t, value): if t.value == None: return 'Not Fund' elif t.value == value: return t elif value < t.value: return find_pos(t.left, value) else: return find_pos(t.right, value) def find_max(t): if t.right is None: return t else: return find_max(t.right) def find_min(t): if t.left is None: return t else: return find_min(t.left) def delete(t, value): parent, del_t = find_delete_t(t, value) if del_t.left is None and del_t.right is None: if parent.left == del_t: parent.left = None else: parent.right = None elif del_t.left is None: if parent.left == del_t: parent.left = del_t.right else: parent.right = del_t.right elif del_t.right is None: if parent.left == del_t: parent.left = del_t.left else: parent.right = del_t.left else: min_parent, min_t = find_move_min(del_t.right, del_t) del_t.value = min_t.value delete(min_parent, value) def find_delete_t(t, value, parent_t=None): if t.value == None: return parent_t, None elif value == t.value: return parent_t, t elif value < t.value: return find_delete_t(t.left, value, t) else: return find_delete_t(t.right, value, t) def find_move_min(t, parent_t=None): if t.left is None: return parent_t, t else: return find_move_min(t.left, t) if __name__ == "__main__": t = BinaryTree(5) insert(t, 4) insert(t, 2) insert(t, 6) insert(t, 3) print(t) delete(t, 4) print(t)
5cd43e3bd4e1f56f7832cb245d0c1d0d3f6bd7b2
Sandhya-02/programming
/0 Python old/03_operators_rev.py
658
4.15625
4
# a = int(input("enter a number\n")) a=int(input("enter a number\n")) print("you have entered ",a) print("enter a number") a = int(input()) print("you have entered ",a) a = "enter a number" print(a) num= int(input()) print("you have enteredd ",num) #! ================================================= #* operators + - * / // % ** #* exponents a+b+c #* 2*b+c #* operands a,b,c,2 #? area of a reactangle l*b #? area of a square s*s #? perimeter of a square 4*s #? perimenter of a rectangle 2*(l+b) #? volume of a cylinder 3.14*r*r*h #? volume of a cone 0.33*3.14*r*r*h #? perimeter of a circle 2*3.14*r #? area of a cirlce 3.14*r*r
46bfc3a2574cb6235111f504071cbe6688d97a54
Adriskk/sorting-algorithm-visualization
/algorithms/heap_sort.py
847
4.125
4
# => HEAP SORT ALGORITHM FILE def heapify(arr, n, i, change): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[largest].size_Y < arr[l].size_Y: largest = l if r < n and arr[largest].size_Y < arr[r].size_Y: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # => UPDATE A WINDOW change(arr[i], arr[largest]) heapify(arr, n, largest, change) def heap_sort(elements, change): n = len(elements) for i in range(n // 2 - 1, -1, -1): heapify(elements, n, i, change) for i in range(n - 1, 0, -1): elements[i], elements[0] = elements[0], elements[i] # => UPDATE A WINDOW change(elements[i], elements[0]) heapify(elements, i, 0, change) return True
e3550cdad749c05a9cb133dc531c503d4860cc77
motasimmakki/Basic-Python-Programming
/SumUsingInput.py
128
3.890625
4
num1=input("Enter First Number") num2=input("Enter Second Number") sum=float(num1)+float(num2) print("{0}".format(sum))
5c48518c70e85dc4aec7635bd7bfc98d1e5b8e5f
athelia/make-pairs
/make_pairs.py
4,968
4.21875
4
""" Script to make pairs. Requirements: - Excluded pairs: never match this student with anyone in this list - Tech levels: prefer to pair students who are within 3 levels - Historical pairs: prefer to pair students who have not worked together Data structure: student_pairs = { student_name: { tech_level: int, excluded: set(student_name), past_pairs: list[student_name], ratings: set(student_name) }, ... } In: file with pairs dictionary Print: proposed pairs for today, star any repeats Ask for user approval for proposed pairs If yes, update pairs dictionary file with these new pairs (append to past_pairs) If no, rerun and get new pairs > Later: allow to fix specific pairs and reroll other pairs Out: list of student pairs for today > Way Later: send students a slack message with their pair for today """ FILE = 't1_pairs_dict.py' from t1_pairs_dict import STUDENT_PAIRS from pprint import pprint import random # import itertools import json def generate_pairs(): """Match students based on exclusion list and tech level""" students = set(STUDENT_PAIRS.keys()) pairs = {} specify_pair = input('Specify pairs? [Y]ES / [N]O: ') # if specify_pair.lower() in ['yes', 'y']: while specify_pair.lower() in ['yes', 'y']: student = input('Student 1: ') match = input('Student 2: ') students.remove(student) students.remove(match) pairs[student] = match specify_pair = input('Specify another pair? [Y]ES / [N]O: ') while students: student = students.pop() # The last unpaired student could be an excluded match, so this could fail try: ratings_pair = set(STUDENT_PAIRS[student].get('ratings', '')) # Set math excludes all historical pairs and excluded pairs match = (students - STUDENT_PAIRS[student]['excluded'] - set(STUDENT_PAIRS[student]['past_pairs']) - ratings_pair ).pop() # Is the difference in tech levels within 3? Otherwise prompt user if not abs(STUDENT_PAIRS[match]['tech_level'] - STUDENT_PAIRS[student]['tech_level']) <= 3: print(f"{student} tech level={STUDENT_PAIRS[student]['tech_level']} with {match} tech level={STUDENT_PAIRS[match]['tech_level']}") should_proceed = input('Okay to proceed? [Y]ES / [N]O: ') if should_proceed.lower() in ['no', 'n']: # TODO break out matching as a function so it can be # called until (1) no tech level issue, (2) user approves # match, or (3) run out of match options print('Quitting: try again') return else: while should_proceed.lower() not in ['yes', 'y', 'no', 'n']: should_proceed = input('Invalid key! [Y]ES / [N]O: ') # Set math creates a new set, so remove match from original pool students.remove(match) except: print(f'Failed: student={student} match={match} pairs={pairs} students={students}') return pairs[student] = match pprint(pairs) # should_write = input('Write to file? [Y]ES / [N]O: ') # if should_write.lower() in ['yes', 'y']: # update_global_var(pairs) # else: # while should_write.lower() not in ['no', 'n']: # should_write = input('Invalid key! [Y]ES / [N]O: ') return pairs # Not working def update_global_var(pairs): """Save generated pairs to global variable file""" with open(FILE, 'r') as f: x = json.load(f) for something in x: print(something) # for student in pairs: # pair = pairs[student] # STUDENT_PAIRS[student]['past_pairs'].append(pair) # STUDENT_PAIRS[pair]['past_pairs'].append(student) # print(f"Updated student={student}['past_pairs']: {STUDENT_PAIRS[student]['past_pairs']}") # print(f"Updated pair={pair}['past_pairs']: {STUDENT_PAIRS[pair]['past_pairs']}") def check_dict_update(pairs): """Verify that manual update of pairs dict has the pairs.""" all_ok = True for student in pairs: match = pairs[student] if STUDENT_PAIRS[student]['past_pairs'][-1] != match: all_ok = False print(f'Update student[\'past_pairs\']={student} match={match}') if STUDENT_PAIRS[match]['past_pairs'][-1] != student: all_ok = False print(f'Update match[\'past_pairs\']={match} student={student}') if all_ok: print('Success! No further updates needed.') pairs = generate_pairs() # # All permutations # def create_options(): # """ """ # pair_permutations = itertools.permutations(STUDENT_PAIRS.keys(), 2)
c31560e204ecac5a01e50ca5efba0a908af77be8
catlucht/learn-arcade-work
/Lab 12 - Final Lab/part_12.py
22,067
4.3125
4
class Room: """ This is the class for the room """ def __init__(self, description, north, south, east, west, up, down): self.description = description self.north = north self.south = south self.east = east self.west = west self.up = up self.down = down class Item: def __init__(self, room, name, description): self.room = room self.name = name self.description = description def main(): room_list = [] item_list = [] # Bedroom (Room 0) room = Room( "You are in a bedroom. It is dark and dusty.\nAll the windows are boarded shut. " "There are doors to the east and west. The door to the east has a combination lock.", None, None, None, 7, None, None) room_list.append(room) # Hall (Room 1) room = Room( "You are in a hallway. There are portraits hanging on the walls. " "\nThe eyes seem to follow you as you move. " "\nDoors surround you to the north, south, and west. " "\nThe door to the north is automated sliding doors. " "The screen says \"Enter the correct US state to pass.\" " "\nThere is a key lock on a door to go down to the basement.", None, 4, None, 0, None, None) room_list.append(room) # Basement (Room 2) room = Room( "You are in a dark basement. It is too dark to make anything out." "\nIt smells musty down here. The only exit you see is up the stairs.", None, 6, None, None, 1, None) room_list.append(room) # Garden (Room 3) room = Room( "You are in a garden of dead and rotted plants. There is a large menacing dog barking at you." "\nHe seems to be guarding something... There is a door to the south.", None, 1, None, None, None, None) room_list.append(room) # Living room (Room 4) room = Room( "You are in a living room. The television only tunes to static. The phone wire has been cut... " "\nAbove the landline you can make out the number 406-758-9031." "\nThere are doors to the north and south. The house's front door seems to be to the west." "\nIt's chained shut and missing the doorknob... Maybe there's a different way out.", 1, 5, None, None, None, None) room_list.append(room) # Kitchen (Room 5) room = Room( "You are in a kitchen. All the food is old and rotted. You better find a way out quick..." "\nThere is a door to the north.", 4, None, None, None, None, None) room_list.append(room) # Hidden Room (Room 6) room = Room( "You are in a hidden room. You wonder what the use of such a creepy room could be..." "\nThere is a door to the north.", 2, None, None, None, None, None) room_list.append(room) # Closet (Room 7) room = Room( "You are in a dark closet. It is so dusty you sneeze. There is a door to the east.", None, None, 0, None, None, None) room_list.append(room) # Outside (Room 10) room = Room( "", None, None, None, None, None, None) current_room = 0 # 0 Journal (Bedroom 0) journal = Item(0, "journal", "There is an old leather bound journal on the bed. There is a page sticking out...") item_list.append(journal) # 1 Shoebox (Bedroom 0) shoebox = Item(0, "shoebox", "There is a shoebox peaking out from under the bed.") item_list.append(shoebox) # 2 Key (Closet 7) key = Item(7, "key", "You see a little silver key.") item_list.append(key) # 3 Flashlight (Closet 7) flashlight = Item(7, "flashlight", "There is a powerful flashlight. That might be useful later...") item_list.append(flashlight) # 4 Notepad (Closet 7) notepad = Item(7, "notepad", "You see a notepad. There is some writing on it.") item_list.append(notepad) # 5 Bolt cutters (Garden 3) bolt_cutters = Item(None, "cutters", "There are a pair of bolt cutters next to the dog.") item_list.append(bolt_cutters) # 6 Bone (Kitchen 5) bone = Item(5, "bone", "There is a large bone on the table. Gross...") item_list.append(bone) # 7 Door knob (Hidden room 6) doorknob = Item(6, "doorknob", "You spot a shiny brass doorknob. Have you seen a door without a knob?...") item_list.append(doorknob) done = False found_door_knob = False used_bolt_cutters = False basement_unlocked = False garden_unlocked = False while not done: print() # Print room description print(room_list[current_room].description) # print items in current room for item in item_list: if item.room == current_room: print(item.description) # User action input action = input("What would you like to do? ") command_words = action.split(" ") # Moving north if action.lower() == "n" or action.lower() == "north" or action.lower() == "move north" \ or action.lower() == "go north" or action.lower() == "walk north": next_room = room_list[current_room].north if next_room is None: print() print("You can't go that way.") else: current_room = next_room # Moving south elif action.lower() == "s" or action.lower() == "south" or action.lower() == "move south" \ or action.lower() == "go south" or action.lower() == "walk south": next_room = room_list[current_room].south if next_room is None: print() print("You can't go that way.") else: current_room = next_room # Moving west elif action.lower() == "w" or action.lower() == "west" or action.lower() == "move west" \ or action.lower() == "go west" or action.lower() == "walk west": next_room = room_list[current_room].west if next_room is None: print() print("You can't go that way.") else: current_room = next_room # Moving east elif action.lower() == "e" or action.lower() == "east" or action.lower() == "move east" \ or action.lower() == "go east" or action.lower() == "walk east": next_room = room_list[current_room].east if next_room is None: print() print("You can't go that way.") else: current_room = next_room # Moving up elif action.lower() == "up" or action.lower() == "upstairs" or action.lower() == "go upstairs" or action.lower() == "go up"\ or action.lower() == "walk upstairs" or action.lower() == "walk up" or action.lower() == "move upstairs"\ or action.lower() == "move up": next_room = room_list[current_room].up if next_room is None: print() print("You can't go that way.") else: current_room = next_room # Moving down elif action.lower() == "down" or action.lower() == "downstairs" or action.lower() == "go downstairs" or action.lower() == "go down"\ or action.lower() == "walk downstairs" or action.lower() == "walk down" or action.lower() == "move downstairs"\ or action.lower() == "move down": next_room = room_list[current_room].down if next_room is None: print() print("You can't go that way.") else: current_room = next_room # Reading journal elif command_words[0].lower() == "read": if len(command_words) > 1: if command_words[1].lower() == "journal" or command_words[1].lower() == "page": if item_list[0].room == -1: print() print("\"... this house always gave me the creeps. I knew something was off about it. " "\n It feels like this house is alive... I don't even remember anymore how I got here. " "\n I miss my family... At least I think I have a family. I don't remember anymore." "\n I think I am going to try and escape. Wish me luck, journal...\"") else: print() print("You don't have that item.") elif command_words[1].lower() == "notepad": if item_list[4].room == -1: print() print("The only way out is to 'escape'") else: print() print("You don't have that item.") else: print() print("You can't read that.") else: print() print("Yes, reading is good. What would you like to read?") # Using shoe box elif command_words[0] == "open": if len(command_words) > 1: if command_words[1] == "shoebox": if item_list[1].room == -1: print() print("Inside the shoe box you find a note:" "\nA1 B2 C3 D4 E5 F6 G7 H8 I9 J10 K11 L12 M13 N14 O15 " "\nP16 Q17 R18 S19 T20 U21 V22 W23 X24 Y25 Z26") else: print() print("You don't have that item.") else: print() print("That can't be opened.") else: print() print("What would you like to open?") # --- Passcode locks --- elif command_words[0].lower() == "enter": if len(command_words) > 1: # Bedroom lock if current_room == 0: if command_words[1] == "51931165" or command_words[1] == "5-19-3-11-6-5": print() print("The door unlocked.") room_list[0].east = 1 room_list[0].description = "You are in a bedroom. It is dark and dusty." \ "\nAll the windows are boarded shut." \ "\nThere are doors to the east and west." else: print() print("The door is still locked. That was the wrong code...") elif current_room == 1: if command_words[1].lower() == "montana": print() print("The door blinked green and unlocked.") room_list[1].north = 3 garden_unlocked = True if basement_unlocked: room_list[1].description = "You are in a hallway. There are portraits hanging on the walls." \ "\nThe eyes seem to follow you as you move. " \ "\nDoors surround you to the north, south, and west. " \ "\nThere is a door to go down to the basement." else: room_list[1].description = "You are in a hallway. There are portraits hanging on the walls." \ "\nThe eyes seem to follow you as you move. " \ "\nDoors surround you to the north, south, and west. " \ "\nThere is a lock on the door to go down to the basement." else: print() print("The door is still locked. That was the wrong passcode.") else: print() print("That does nothing here.") # --- Use command --- elif command_words[0].lower() == "use": # Basement lock if len(command_words) > 1: if command_words[1] == "key": if item_list[2].room == -1: print() print("The basement door unlocked.") item_list[2].room = None room_list[1].down = 2 basement_unlocked = True if garden_unlocked: room_list[1].description = "You are in a hallway. There are portraits hanging on the walls." \ "\nThe eyes seem to follow you as you move. " \ "\nDoors surround you to the north, south, and west. " \ "\nThere is a door to go down to the basement." else: room_list[1].description = "You are in a hallway. There are portraits hanging on the walls. " \ "\nThe eyes seem to follow you as you move. " \ "\nDoors surround you to the north, south, and west. " \ "\nThe door to the north is automated sliding doors. " \ "\nThe screen says \"Enter the correct US state to pass.\" " \ "\nThere is a door to go down to the basement." else: print() print("You don't have the key for this door.") # Place door knob elif command_words[1].lower() == "doorknob": if item_list[7].room == -1: if current_room == 4: print() print("The door knob is now in place") item_list[7].room = None found_door_knob = True room_list[4].description = "You are in a living room. The television only tunes to static. The phone wire has been cut... " \ "\nAbove the landline you can make out the number 406-758-9031." \ "\nThere are doors to the north and south. " \ "\nThe house's front door seems to be to the west. It's chained shut..." else: print() print("There is nowhere to place a doorknob here.") if found_door_knob and used_bolt_cutters: print() print("It seems the door can be opened now...") room_list[4].west = 10 room_list[4].description = "You are in a living room. The television only tunes to static. The phone wire has been cut... " \ "\nAbove the landline you can make out the number 406-758-9031." \ "\nThere are doors to the north and south. The house's front door seems to be to the west." else: print() print("You don't have a doorknob.") elif command_words[1].lower() == "cutters": if item_list[5].room == -1: print() print("You cut the chain off of the door.") item_list[5].room = None used_bolt_cutters = True room_list[4].description = "You are in a living room. The television only tunes to static. The phone wire has been cut... " \ "\nAbove the landline you can make out the number 406-758-9031." \ "\nThere are doors to the north and south. The house's front door seems to be to the west." \ "\nIt is missing the doorknob." if found_door_knob and used_bolt_cutters: print() print("It seems the door can be opened now...") room_list[4].west = 10 room_list[4].description = "You are in a living room. The television only tunes to static. The phone wire has been cut... " \ "\nAbove the landline you can make out the number 406-758-9031." \ "\nThere are doors to the north and south. The house's front door seems to be to the west." else: print() print("You don't have that item.") elif command_words[1].lower() == "flashlight": if item_list[3].room == -1: if current_room == 2: print() print("You switch on the flashlight. You can now see that there is a door to the south.") room_list[2].description = "You are in a dark basement. It smells musty down here." \ "\nThere is a door to the south and an exit up the stairs." else: print() print("You switch on the flashlight. It doesn't help anything.") else: print() print("You don't have a flashlight.") else: print() print("That can't be used.") else: print() print("What would you like to use?") # Pet dog elif command_words[0].lower() == "pet": if command_words[1].lower() == "dog": print() print("That's a bad idea.") # Giving dog bone elif command_words[0].lower() == "give": if command_words[1].lower() == "bone": print() print("The dog gladly took the bone, wagging his tail." "\nHe seems very happy now.") room_list[3].description = "You are in a garden of dead and rotted plants. " \ "\nThere is a docile dog gnawing on a bone. There is a door to the south." item_list[5].room = 3 # Check Inventory elif action.lower() == "inventory" or action.lower() == "check inventory": print() print("Inventory:") for item in item_list: if item.room == -1: print(item.name) # Pick up items elif command_words[0].lower() == "get": picked_up = False for item in item_list: if command_words[1].lower() == item.name and item.room == current_room: item.room = -1 print() print("You have picked up", item.name) picked_up = True if not picked_up: print() print("That item doesn't seem to be here") # Drop items elif command_words[0].lower() == "drop": dropped = False for item in item_list: if command_words[1].lower() == item.name and item.room == -1: item.room = current_room print() print("You dropped", item.name) dropped = True if not dropped: print() print("You don't have that item.") # Quit action elif action.lower() == "q" or action.lower() == "quit": print() print("Goodbye.") done = True # Unknown input else: print() print("That is an invalid command.") # End of game if current_room == 10: print() print("A strong breeze overwhelms you as you open the front door. The sun is so bright, you have to squint to see." "\nBut you see it... freedom. You think of your parents, they have to be searching for you." "\nYou wonder what your friends have been up to since you've been gone. You miss them." "\nBut you have it, finally... freedom... sweet freedom...") print() print("Thanks for playing! Goodbye.") done = True main()
d42da86e51844053df950b6f890ef53c1c19fc28
Th3Lourde/l33tcode
/563.py
620
3.84375
4
''' Given the root of a binary tree, return the sum or every node's tilt The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values ''' from collections import deque class Solution: def findTilt(self, root): self.treeTilt = 0 def dfs(node): if not node: return 0 sumLeft = dfs(node.left) sumRight = dfs(node.right) self.treeTilt += abs(sumLeft - sumRight) return node.val + sumLeft + sumRight dfs(root) return self.treeTilt
0781721d53267a739e8f5bcd6638e13e27c54d57
RutujaKaushike/DigitRecognitionMNIST
/DigitRecognition.py
3,811
3.59375
4
################## # Digit Recognizer # Project by: Rutuja Kaushike (RNK170000) # For Machine Learning : CS6375.502 F18 by Prof. Anurag Nagar ################## #import packages keras from keras import utils from keras.layers import Dense, Reshape, Conv2D, Flatten,Dropout, MaxPool2D from keras.models import Sequential from keras.optimizers import RMSprop #import pacakages panda to read file import pandas as pd import numpy as np #import package matplot to plot the grap of accuracy and loss import matplotlib.pyplot as plt #import packages from sklearn to split train data into train and validation data from sklearn.model_selection import train_test_split #import package sys to read the CSV file path import sys #read training and test data CSV files train_file_path = sys.argv[1] test_file_path = sys.argv[2] output_file_path=sys.argv[3] data_training = pd.read_csv(train_file_path) data_test = pd.read_csv(test_file_path) #print frist 10 rows of the train and test data print(data_training.head(10)) print(data_test.head(10)) #seperate labels and predictors of training data train_X = data_training.iloc[:, 1:] train_Y = data_training.iloc[:, 0] #normalize the data to float and then divide by 255 to make it in the range of 0.0 -1.0 train_X = train_X.astype('float32') test_data = data_test.astype('float32') train_X = train_X/255 test_data = test_data/255 #change label f traiing data to vector train_Y = utils.to_categorical(train_Y, num_classes=10) #create training and validation data set by splitting the original training data train_X1,validation_x,train_Y1,validation_y = train_test_split(train_X,train_Y,test_size=0.2,random_state=42) #apply CNN & Maxpool model = Sequential() model.add(Reshape(target_shape=(1, 28, 28), input_shape=(784,))) model.add(Conv2D(32,kernel_size=(5, 5), padding="same",data_format="channels_first", kernel_initializer="uniform", use_bias=True)) model.add(MaxPool2D(pool_size=(2, 2), data_format="channels_first")) model.add(Conv2D(64,kernel_size=(5, 5),padding="same",data_format="channels_first", kernel_initializer="uniform", use_bias=True)) model.add(MaxPool2D(pool_size=(2, 2), data_format="channels_first")) #flatten data again and applying the activation function model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(100, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation='softmax')) #compile the model using RMSprop optimizer, the only parameter to change is learning rate i.e lr r_prop = RMSprop(lr=0.001) model.compile(loss='binary_crossentropy', optimizer=r_prop, metrics=['accuracy']) #train the model using training and validation data, no of epochs and batch size of the epoch is mentioned train_result = model.fit(train_X1, train_Y1,validation_data =(validation_x,validation_y), epochs=5, batch_size=64,verbose=1) #test the model by passing the test data to model len_test = test_data.shape[0] result = model.predict_classes(test_data) predict = {"ImageId":range(1, len_test+1), "Label":result} predict = pd.DataFrame(predict) predict.to_csv(output_file_path,header = True ,index = False) #plot the graph for accuracy #accuracy graph with epoch on X axis and acuracy on Y axis plt.plot(train_result.history['acc'], color = 'green', label = 'on training') plt.plot(train_result.history['val_acc'], color = 'red', label = 'on test') plt.title('Graph for accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend() plt.show() #loss graph with epoch on X axis and loss on Y axis plt.plot(train_result.history['loss'], color = 'green', label = 'on training') plt.plot( train_result.history['val_loss'],color ='red', label = "On test") plt.title('Graph for loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend() plt.show() print("Check the output") #End of file
8cfd11779e4b960b9624029650a159577a9219a6
vskdtc/python-samples
/src/if.py
569
4
4
x = int(input("Gebe eine Zahl ein: ")) if x == 2: print(x,'Ist eine Primezahl') elif x == 3: print(x,'Ist eine Primezahl') elif x == 5: print(x,'Ist eine Primezahl') elif x == 7: print(x,'Ist eine Primezahl') elif x%2 == 0: print(x,'Ist keine Primezahl, weil', x/2, 'A') elif x%3 == 0: print(x,'Ist keine Primezahl, weil', x/3, 'B') elif x%5 == 0: print(x,'Ist keine Primezahl, weil', x/5,'C') elif x%7 == 0: print(x,'Ist keine Primezahl, weil', x/7, 'D') elif x < 1000: print(x,'Ist eine Primezahl')
5b83db04a99f112dbe85931ffe4f58c5372e5ed7
Fireaxxe/CSCU9YE
/Lab/Solutions/lab3.py
5,045
3.71875
4
# The knapsack problem # Gabriela Ochoa import os import matplotlib.pyplot as plt import random as rnd # Single knapsack problem # Read the instance data given a file name. Returns: n = no. items, # c = capacity, vs: list of itmen values, ws: list of item weigths def read_kfile(fname): with open(fname, 'rU') as kfile: lines = kfile.readlines() # reads the whole file n = int(lines[0]) c = int(lines[n+1]) vs = [] ws = [] lines = lines[1:n+1] # Removes the first and last line for l in lines: numbers = l.split() # Converts the string into a list vs.append(int(numbers[1])) # Appends value, need to convert to int ws.append(int(numbers[2])) # Appends weigth, need to convert to int return n, c, vs, ws dir_path = os.path.dirname(os.path.realpath(__file__)) # Get the directory where the file is located os.chdir(dir_path) # Change the working directory so we can read the file knapfile = 'knap20.txt' nitems, cap, values, weights = read_kfile(knapfile) # Evaluates a solution. # input: solution binary string # ouptut: value and weight of the input solution def evaluate(sol): totv = 0 totw = 0 for i in range(nitems): totv = totv + sol[i]*values[i] totw = totw + sol[i]*weights[i] return totv, totw # Generates a random solution (binary string) # input: number of items # output: binary string with solutions def random_sol(n): sol = [] for i in range (n): sol.append(rnd.randint(0,1)) # Random binary string len = nitems return sol # Generates a valid random solution (binary string) # input: number of items # output: sol, binary string with solutions def random_sol_valid(n): binvalid = True while binvalid: s = random_sol(n) v, w = evaluate(s) binvalid = (w > cap) return s, v, w # Multiple iterations of generating valid random solutions # input: number of repetitions # output: Set of values obtained, binary string with solutions def random_search_valid(tries): values = [] best_sol = [] best_val = 0 best_wei = 0 print("Multi Random") for i in range (tries): sol, v, w = random_sol_valid(nitems) values.append(v) if (v > best_val): best_val = v best_wei = w best_sol = sol[:] return values, best_sol, best_val, best_wei # Return a random 1-bit flip neigbour # input: solution as binary vector # output: random solution in the 1-bit flip neighbourhood def random_valid_neig(sol): binvalid = True while binvalid: neig = sol[:] # copy solution i = rnd.randint(0,nitems-1) neig[i] = 0 if sol[i] else 1 # alter position i v, w = evaluate(neig) binvalid = (w > cap) return neig, v, w # First improvement random mutation, hill-climbing def hill_climbing(maxiter): trace = [] s, v, w = random_sol_valid(nitems) trace.append(v) for i in range (maxiter): s1, v1, w1 = random_valid_neig(s) if v1 > v: v = v1 w = w1 s = s1[:] trace.append(v) return s, v, w, trace # multiple tries, hill-climbig def multi_hc(tries, hc_iter): values = [] best_sol = [] best_trace =[] best_val = 0 best_wei = 0 print("Multi hill climbing") for i in range (tries): sol, v, w, trace = hill_climbing(hc_iter) values.append(v) if (v > best_val): best_val = v best_wei = w best_sol = sol[:] best_trace = trace[:] return best_trace, values, best_sol, best_val, best_wei # Calling functions s, v, w, trace = hill_climbing(10) # single run of hill-climbing print('After hill-climibing') print ('Sol.:' , s, 'V:', v, 'W:', w) print ('Trace:', trace) plt.figure() plt.plot(trace,'ro') # 'ro' indicates to plot as dots (circles) of red color plt.title('Trace ' + knapfile) plt.ylabel('Value') plt.show() times = 30 # number of tries by the random search and the multi HC # random search values_rnd, sol_rnd, val_rnd, wei_rnd = random_search_valid(times) print('Best Solution after Random Search:') print('Sol.:' , sol_rnd, 'V:', val_rnd, 'W:', wei_rnd) # Multi hill climbing hc_maxiter = 10 # set the maximun iterations for the hill-climebr b_trace, values_mhc, sol_mhc, val_mhc, wei_mhc = multi_hc(times, hc_maxiter) print('Best Solution after Multi-start hill-climbing:') print('Sol.:' , sol_mhc, 'V:', val_mhc, 'W:', wei_mhc) plt.figure() plt.plot(b_trace,'bo') # 'ro' indicates to plot as dots (circles) blue color plt.title('Best Trace ' + knapfile) plt.ylabel('Value') plt.show() # Comparing the performances of randon search against multiple hill-climbing results = [values_rnd, values_mhc] # combine solutions of two algorithms plt.figure() plt.boxplot(results,labels = ['random','hill-climbing']) plt.title('Comparison ' + knapfile) plt.ylabel('Value') plt.show()
86f7b42c38a16e9134f85d312dd420d8c8739ac1
NeSergeyNeMihailov436hdsgj/SummerP
/1A/15.py
360
3.703125
4
import datetime def printTimeStamp(name): print('Автор програми: ' + name) print('Час компиляції: ' + str(datetime.datetime.now())) a=list(map(int,input("Input numbers:").split(" "))) if a[0]==int(0): print("Error , first number can't be 0") elif int(0) in a: print(sum(a)/(len(a)-1)) printTimeStamp("Сергій Михайлов")
cdd8a90645d37b70a95c2389c891014053d9a4f2
denis-belagro/skillfactory-module-6.10
/B6.10/B6.10.2.py
200
3.578125
4
class Rectangle2: def __init__(self, width, height): self.width = width self.height = height p1 = Rectangle2(4, 7) print("width = ", p1.width) print("height = ", p1.height)
b1c80eec5f77e068f2e7fb765ad225de3b84c102
ProgFuncionalReactivaoct19-feb20/practica04-erickgjs99
/practica.py
1,232
3.734375
4
""" autor = erickgjs_99 file = practica,py """ import codecs import json # para abrir el archivo archivo = codecs.open("datos.txt", "r") # para leer todas las lineas de cadenas del archivo line_dic = archivo.readlines() # para que se guarde todas las cadenas en una lista line_dic = [json.loads(l) for l in line_dic] # funcion para los goles funcion = lambda x: list((x.items()))[1][1] > 3 #para que se guarde gol = list(filter(funcion, line_dic)) print(list(gol)) # JUgadores de nigeria funcion2 = lambda x: list((x.items()))[0][1] == "Nigeria" country = list(filter(funcion2, line_dic)) #impresion de los resultados de jugadores de nigeria print(list(country)) #el valor minimo #el valor maximo funcion3 = list(map(lambda x: list(x.items()) [2][1], line_dic)) minimo_p = min(funcion3) maximo_p = max(funcion3) funcion4 = lambda x: list(x.items())[2][1] == minimo_p funcion5 = lambda x: list(x.items())[2][1] == maximo_p est_min = list(filter(funcion4, line_dic)) est_max = list(filter(funcion5, line_dic)) print("jugador con minima estatura") #impresion de los resultados del minimo altura print((est_min)) #impresion de los resultados del maxima altura print(("jugador con maxima estatura ")) print((est_max))
89d74ea1d5e47a0f2f5bf4d95cd7dded36bd3f62
sotirisnik/projecteuler
/prob45.py
1,299
3.703125
4
import math def T( n ): return ( 0.5 * n * ( n + 1 ) ) def P( n ): return ( 0.5 * n * ( 3 * n - 1 ) ) def H( n ): return ( n * ( 2*n - 1 ) ) def inverseT( x ): """ n * ( n + 1 ) - 2*x = 0 n^2 + n - 2*x = 0 D = b^2 - 4*a*g = 1 - 4*1*(-2*x) = 1 + 8*x x1,2 = ( -b +- sqrt( D ) ) / 2*a = ( -1 +- sqrt( 1 + 8*x ) ) / 2 """ return ( 0.5 * ( -1 + math.sqrt( 1 + 8*x ) ) ) def inverseP( x ): """ n * ( 3*n - 1 ) - 2*x = 0 3*n^2 - n - 2*x = 0 D = b^2 - 4*a*g = 1 - 4*3*(-2*x) = 1 + 24*x x1,2 = ( -b +- sqrt( D ) ) / 2*a = ( 1 +- sqrt( 1 + 24*x ) ) / 6 """ return ( ( 1 + math.sqrt( 1 + 24*x ) ) / 6 ) def inverseH( x ): """ n * ( 2*n - 1 ) - x = 0 2*n^2 - n - x = 0 D = b^2 - 4*a*g = 1 - 4*2*(-x) = 1 + 8*x x1,2 = ( -b +- sqrt( D ) ) / 2*a = ( 1 +- sqrt( 1 + 8*x ) ) / 4 """ return ( 0.25 * ( 1 + math.sqrt( 1 + 8*x ) ) ) def isT( x ): tmp = inverseT( x ) return ( tmp == int( tmp ) ) def isP( x ): tmp = inverseP( x ) return ( tmp == int( tmp ) ) def isH( x ): tmp = inverseH( x ) return ( tmp == int( tmp ) ) n = 286 while True: tmp = T( n ) if isP( tmp ) and isH( tmp ): break n += 1 print "%d" % ( T(n) )
7cbd831519be43116a42b01129394c182d5413a8
haedal-programming/teachYourKidsToCode
/function/clickKaleidoscope.py
846
3.890625
4
import random import turtle cursor = turtle.Pen() cursor.speed(0) cursor.hideturtle() turtle.bgcolor("black") colors = ["red","yellow","blue","green", "orange","purple","white","gray"] # 반사 효과를 만드는 만화경 함수 def draw_kaleido(x,y): cursor.pencolor(random.choice(colors)) size = random.randint(10,40) draw_spiral(x,y,size) draw_spiral(-x,y,size) draw_spiral(-x,-y,size) draw_spiral(x,-y,size) # 나선형 그리는 함수 def draw_spiral(x,y,size): cursor.penup() cursor.setpos(x,y) cursor.pendown() for m in range(size): cursor.forward(m*2) cursor.left(92) # 클릭하는 위치에 나선형 그리기 turtle.onscreenclick(draw_kaleido) # 반사 효과를 만드는 만화경 함수 # 나선형 그리는 함수 # 클릭하는 위치에 나선형 그리기
67c5b04fc5d342b3cd72b6f250dee5016850309d
ggchangan/leetcodePython
/hamming_distance_461.py
405
3.515625
4
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x ^ y).count('1') def main(): assert bin(7).count('1') == 3 assert bin(1).count('1') == 1 assert Solution().hammingDistance(1, 4) == 2 assert Solution().hammingDistance(11, 4) == 4 if __name__ == '__main__': main()
865113ad5dcefdfb86821ef0066aa4c472110e8d
makuznet/hse
/lesson-2_list_comprehension/lesson-2-hard-mode-1-while.py
1,246
4.21875
4
# Напишите код, который проверяет делимость числа на 5. # Числа нужно выбрать из списка. Если число делится, # алгоритм должен выйти из цикла и вывести на экран искомое число и строку "делится на 5". # Если не делится, выводим на экран "это не делится на 5, продолжим поиск". # Продолжаем пока не найдем такое, которое бы делилось. # Проверяя числа на делимость, алгоритм также должен игнорировать число 45, не прервав на нем цикл. numbers = [2, 6, 7, 45, 1, 89, 678, 35, 11] index = 0 while index < len(numbers): index += 1 if numbers[index] % 5 != 0: print(numbers[index], 'не делится на 5. Продолжаем поиск!') elif numbers[index] == 45: print(numbers[index], 'делится на 5. Игнорируем!') continue elif numbers[index] % 5 == 0: print(numbers[index], 'делится на 5. Поиск закончен.') break
5f1fbacfab4c1c1a316c979426b377bbd936d7d2
mandycrose/module-02
/ch06_commandLine_Git/ch06_mandy.py
1,328
4.0625
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 6 10:05:27 2018 @author: 612436112 """ import sys class Animal(): def __init__(self, name, age): self.name = name self.age = age def eat(self): print('yum') class Dog(Animal): def bark(self): print('Woof!') class Robot(): def move(self): print('...move move move...') class CleanRobot(Robot): def clean(self): print('I vacuum dust') class SuperRobot(): def __init__(self,name,age): #This class contains 3 objects' self.name = name self.age = age self.o1 = Robot() self.o2 = Dog(name,age) self.o3 = CleanRobot() def playGame(self): print('alphago game') def move(self): return self.o1.move() #using robot class method def bark(self): return self.o2.bark() #using dog class method def eat(self): return self.o2.eat() #using dog class method def clean(self): return self.o3.clean() #using cleanrobot method #name = sys.argv[0] #input('pet\'s name: ') #age = sys.argv[1] #int(input('pet\'s age: ')) machineDog = SuperRobot('snoopy',7) machineDog.move() machineDog.bark() machineDog.eat()
da75ed7c95a045281cc627e1afbc30aa460718e6
AlanVenic/PythonExercicios
/ex040.py
677
3.953125
4
#crie um programa que leia duas notas de aluno e calcule sua media #mostrando uma msg final de acordo com a media atingida print('Verifique se você foi aprovado neste semestre.') num1 = float(input('Digite sua primeira nota: ')) num2 = float(input('Digite sua segunda nota: ')) media = (num1 + num2)/2 if media < 5.0: print('Sua média foi {}. Você foi reprovado pois sua média está abaixo de 5.0.'.format(media)) elif media > 5.0 and media < 6.9: print('Sua média foi {}. Você está de recuperação pois sua média está abaixo de 7.0.'.format(media)) else: print('Sua média foi {}. Você foi aprovado pois sua média está acima de 7.0.'.format(media))
85adb749e77f514bb44c0227401ffd301b141e07
runalb/Python-Problem-Statement
/PS-1/ps13.py
337
4.09375
4
# PS-12 WAP to check weather user inputted number is Armstrong or not num = int(input("Enter no: ")) res = 0 no = num len_no = len(str(num)) while(no!=0): d = no%10 res = res + d ** len_no no = no//10 if num == res: print(num,"is a Armstrong Number ") else: print(num,"is not a Armstrong Number ")
534b0dd96d7a7838d5cfe6367866a7dc898c8d4c
mrinxx/Pycharm
/FUNCIONES/1.py
941
4.03125
4
def raices(a,b,c): #abro la funcion discriminante=(b**2)-(4*a*c) #creo el discriminante para ver si es positivo o no (no puede ser menor que 0 una raiz) if discriminante >= 0: #si el discriminante es mayor o igual a 0 r1=(-b + (discriminante ** 0.5)) / (2 * a) #raices positivas r2=(-b - (discriminante ** 0.5)) / (2 * a) #raices negativas return r1,r2 #lo que va a salir fuera de la funcion if __name__ == "__main__": #bloque principal del programa #pido los 3 coeficientes de la ecuacion a=float(input("Introduce el coeficiente a: ")) b=float(input("Introduce el coeficiente b: ")) c=float(input("Introduce el coeficiente c: ")) if (b**2)-(4*a*c) < 0: #si el discriminante es menor a 0 print("No es posible calcular las raices") #error else: #si no raices=raices(a,b,c) #llamo a la funcion print("Las raices de la ecuación son:",raices) #la muestro pass
e6e62a024f0ff8eba13c5ada89cc6b6ae96e9e6c
NIKsaurabh/python_programs1
/programs/guessgame.py
506
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 14 10:01:23 2019 @author: saurabh """ import random cond=True count=0 t=(random.randint(1,100)) while(cond): user=int(input("Enter number : ")) if t>user: print("enter greater number") count+=1 elif t<user: print("enter less number") count+=1 else: print("Congratulations!!!!!!!") count+=1 print("You guessed in",count,"times") cond=False
96c310134b9dd83b318c2c7617da1950200bbed2
vxda7/end-to-end
/pre_learning/isitlower.py
204
3.78125
4
get = input() cnt_upper=0 cnt_lower=0 for i in get: if i.isupper(): cnt_upper+=1 elif i.islower(): cnt_lower+=1 print(f"UPPER CASE {cnt_upper}") print(f"LOWER CASE {cnt_lower}")
9762d5ef31d70684a2a181e1567ff0fc0588b814
sophialuo/CrackingTheCodingInterview_6thEdition
/1.1.py
1,399
4.0625
4
''' Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use a data structure? ''' #with data structure def is_unique(string): count = {} for char in string: if char in count: return False else: count[char] = 1 return True #without data structure def is_unique_v2(string): for i in range(len(string)): char = string[i] if char in string[i+1:]: return False return True #testing string1 = 'aaa' #should return False string2 = 'abc' #should return True string3 = 'aba' #should return False string4 = 'a' #should return True string5 = 'aab' #should return False string6 = 'baa' #should return False lst = [string1, string2, string3, string4, string5, string6] ans = [False, True, False, True, False, False] version = 1 while version < 3: count = 0 if version == 1: print('with data structure') else: print('without data structure') for i in range(len(lst)): string = lst[i] answer = ans[i] if version == 1: if is_unique(string) == answer: print('correct!') count += 1 else: print('incorrect for test case: ' + string) else: if is_unique_v2(string) == answer: print('correct!') count += 1 else: print('incorrect for test case: ' + string) if count == len(lst): print('all correct!') version += 1
20ac1e597e23bd7a970e210ce798bcfa56bef21f
Cowboys21/python
/confusing.py
205
3.984375
4
name = 'Jennifer' print(name [1:-1]) first = 'John' last = 'Smith' message = first + ' [' + last + '] is a coder' msg = f'{first} [{last}] is a coder' print(message) print(msg) print("python' in course")
f215130f504a80f7d62ffaf0ca949a25bc295536
phaynes52/Code-Samples
/Game Design/hw1-game-loop-phaynes52/Argh Matey/Island.py
10,750
3.625
4
#Island.py import Fight import config import Montauk def landho(): raw_input("Pirate in the Crow's Nest: 'LAND HO!!!' ") raw_input("Captain Blackbreath: 'All hands on deck! Head the masts toward the coast!' \nCaptain Blackbreath walks over to you.") raw_input("Captain Blackbreath: 'Unfortunately this is where I must let ye off matey. Our crew is headed toward Cifuentes - a dangerous free city on the other side of that island. If I brought ye there they'd eat you alive. On this side of the island is a small group of British soldiers. I'll ready a dingy and send you off to them. Hopefully their kind enough to help you.") theBritishAreComing() def theBritishAreComing(): raw_input("You thank the captain for all he's done for you and he walks off to prepare your transport.") raw_input("Captain Blackbreath: 'Good luck out there. The British have never been kind to us, but I've got a good feeling about you.'") business = raw_input("You row to the island, and as soon as you step on shore you are greeted by a British soldier. \nSoldier: 'You there! Stop! This land belongs to Dunstan Irving Cornelius Kinsington III Duke of Charles Island and you are trespassing. State your business.' \n Explain yourself: ") duel = raw_input("Soldier: ' \"{}\"? You really think I'd believe that? What do you think I am? French? I'm a damn Baron of the British Empire! I will have none of this nonsense. Come with me.' \n(Go with the soldier / Draw sword) ".format(business)).lower() while duel not in ["go with the soldier", "draw sword"]: duel = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Go with the soldier / Draw sword) ").lower() if duel == "go with the soldier" : raw_input("Soldier: 'Good choice sir. May the crown have mercy on your wayward life.' \nThe soldier slaps some iron handcuffs on you and takes your shoes just to be a dick. You walk behind his horse for a few miles until you reach a small encampment on the interior of the island with a sign that reads FORT MANTAUK.") raw_input("As you approach the compound, you can hear a very faint but familiar buzz.") raw_input("Before you enter, the soldier blindfolds you and puts you on the back of his horse. As he walks the horse though camp you can hear muffled conversation. The soldier drops you down in an unknown location and knocks you out with the butt of his sword.") Montauk.entry(0) elif duel == "draw sword" : raw_input("Soldier: 'Poor choice good sir. I shall vanquish you to the deepest rungs of Hell. Or maybe France.") Fight.fight(70, 6, 4) loot = raw_input("The soldier collapses to the ground bloodied from his wounds. \nSoldier: 'You shall rue the day you killed Edmund Kinsington Dingleberry IV Baron of... *cough*... *gargle*...' \n(Search body / Leave) ").lower() while loot not in ["search body", "leave"] : loot = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Search body / Leave) ").lower() if loot == "search body" : raw_input("You find a small gold piece and put it in your pocket. \nYou also take the soldiers gloves giving you a better grip on your sword. \n+1 strengh") config.inventory.append("gold piece") config.strength = config.strength + 1 raw_input("You look up and down the coast and see nothing in either direction. To the Northwest you see a small trail carved into the treeline and decide to follow that.") fork(0) return def fork(visit): if visit == 0: fork = raw_input("You walk through the jungle for about a quarter mile when you come across a fork in the road. There is nothing to indicate which direction to go. \n(Left / Right)").lower() else: fork = raw_input("You return to the fork in the road. \n(Left / Right)").lower() while fork not in ["left", "right"] : fork = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Left / Right) ").lower() if fork == "left" : forkleft() elif fork == "right" : forkright() return def forkleft(): fall = raw_input("You take the left path and walk about half a mile before you reach a clearing. In the middle is a small lake fed into by a magnificent waterfall. From the other end of the lake you think you see a small path leading behind the waterfall. \n(Investigate the path / Turn around) ").lower() while fall not in ["investigate the path", "turn around"]: fall = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Investigate the path / Turn around) ").lower() if fall == "investigate the path" : waterfall() elif fall == "turn around" : fork(1) return def forkright() : raw_input("You follow the path to the right. It seems to be worn down from frequent travel. After walking about a mile into the forest you start to hear a faint but familiar buzz.") raw_input("You pick up the pace heading in the direction of the sound. Slowly, you see a gap in the trees starting to appear as the buzz grows louder.") raw_input("As you approach the gap you veer off the path preferring the secrecy of the trees. From the edge of the clearing you see a tall wooden wall concealing a small emcampment.") entry = raw_input("British soldiers stand guard on the top of the wall, and you notice a sign that reads FORT MONTAUK. \n(Approach the fort / Look for another entrance) ").lower() while entry not in ["approach the fort", "look for another entrance"] : entry = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Approach the fort / Look for another entrance) ").lower() if entry == "look for another entrance" : raw_input("You walk the perimeter of the fort being careful to stay out of sight. On the backside of the fort you notice that one piece of the wall is starting to weather away.") raw_input("You think you can probably pry it open enough to get yourself inside.") if config.strength > 7 : raw_input("You pull at the boards and open a gap just large enough to slide into the fort.") Montauk.entry(1) else: raw_input("You pull at the boards but you are not strong enough to make an opening. You cut your losses and circle back to the front of the fort.") raw_input("You walk up to the front of the fort and shout to the soldiers on top of the wall") raw_input("'Excuse me! I seem to have gotten lost in the jungle. Would you be so kind as to help me find my way home?'") raw_input("Soldier: 'OY! You lost mate? We'll help you alright. *laughs* Let him in men!' ") raw_input("The soldiers open the gates and you walk into the fort. \n'Thank you all so much I don't know wha--'") raw_input("One of the soldiers smacks a baton across the back of your head and you collapse unconscious.") Montauk.entry(0) return def waterfall() : if config.bearSlain == False : raw_input("You follow the path and find a small cave behind the waterfall. Inside, the sunlight shines through a small hole in the ceiling illuminating an ornate sword.") bear = raw_input("As you apporach, you hear something rustle on the ground. You look down and realize that you were so focused on the sword that you failed to realize the giant bear in the cave. You can only assume that the English imported it and it escaped from their compound or something equally crazy to explain the carribean Grizzly Bear in front of you. You decide that despite the bear, you have to have that sword. \n(Sneak around / Attack) ").lower() while bear not in ["sneak around", "attack"]: bear = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Sneak around / Attack) ").lower() if bear == "sneak around" : raw_input("You try to sneak around the bear but accidentally step on it's paw. It roars awake and swipes at you, making a small gash in your left leg. \n-10 health") config.health = config.health - 10 if config.health < 1 : print("The strike from the bear is too much for you to handle. You succumb to your injuries as the bear feeds on your body then goes back to sleep. Thank you for playing. Goodbye.") quit() raw_input("The bear stands up. It turns to face you and lets out a roar directly into your face. You draw your sword and prepare for battle. \n(Press enter to begin fight)") Fight.fight(150, 10, 4) elif bear == "attack" : raw_input("You plunge your sword into the bear while it sleeps and land a strong hit. \n15 damage dealt") raw_input("The bear roars awake and stands up to face you. It stands up on its hind legs letting out another great roar. It comes down to face you, pawing at the ground as it prepares to fight. \n(Press enter to begin fight)") Fight.fight(135, 10, 4) raw_input("The bear lets out one final roar and falls to the ground. You step over the bear triumphantly and grab the sword. \n+2 strength") config.strength = config.strength + 2 config.bearSlain = True drink = raw_input("You exit the cave and take a minute to sit on the edge of the path near the waterfall and catch your breath. You're very thirsty. \n(Drink from the waterfall / Pass) ").lower() while drink not in ["drink from the waterfall", "pass"]: drink = raw_input("Shiver me timbers, who would try to do that??. Please enter a choice from the options provided. \n(Drink from the waterfall / Pass) ").lower() if drink == "drink from the waterfall" : config.health = min(100, config.health + 30) raw_input("*Glug* *Glug* *Glug* Ahhhhhhhhhh \nHealth restored to {}".format(config.health)) if drink == "pass" : config.health = min(100, config.health + 15) raw_input("You decide you're not that thirsty and take in the scenery. \nHealth restored to {}".format(config.health)) raw_input("You see the sun starting to set and figure it's time to get back on the road. You walk back the way you came.") else: raw_input("You walk up the path and see the cave you entered before. Inside sits the slain bear. You return back down the path.") raw_input("You decide you've seen all there is to see here and head back toward the main path.") fork(1)
7ea001b9def2b51bb8473f008b06a31a48e85da8
jjdblast/trafficLight
/trafficLight/geneticOptimization.py
5,411
3.640625
4
import random import numpy as np from trafficLight.visualization import showTrajectory from trafficLight.evaluation import score from trafficLight.simulation import Simulation import trafficLight.constants as constants import trafficLight.controller as controller class GeneticOptimization(object): """ Contains methods for the optimization of a given fitness function. The algorithm works as follows 1. Randomly create individuals with different properties (parameters) 2. Selectively cull the population such that only fit individuals survive 3. Create a new generation of individuals by mutation (randomly adjusting parameters) and by crossover between different individuals (mixing of parameters) Step 2. and 3. are then iterated a number of generations until (hopefully) a "steady-state" is reached. This algorithm works for a generalized class of individuals which can be generated by a factory method and provide the methods 1. mutate 2. crossbreed 3. fitness """ def __init__(self, params, individualFactory): self.params = params self.individualFactory = individualFactory # Constants self.numIndividuals = 100 self.numAfterCulling = 50 self.proportionGeneratedThroughMutation = 0.5 self.mutationParameter = 1.0 self.mutationDecay = 0.001 # How much the mutation parameter decreases with every timestep self.numIterations = 1000 self.numGeneration = 0 self.generation = [self.individualFactory() for n in range(self.numIndividuals)] # Visualization self.numToPlot = 10 self.printInterval = 10 self.plotInterval = 100 def iterate(self): self.generation.sort(key=lambda x : x.fitness, reverse=True) self.generation = self.generation[:self.numAfterCulling] self.outputInfo() numToReplenish = self.numIndividuals - self.numAfterCulling newIndividuals = [self.getNewIndividual() for i in range(numToReplenish)] self.generation = self.generation + newIndividuals assert len(self.generation) == self.numIndividuals self.mutationParameter *= 1 - self.mutationDecay def getNewIndividual(self): if random.random() < self.proportionGeneratedThroughMutation: randomIndividual = random.choice(self.generation) return randomIndividual.mutate(self.mutationParameter) else: randomIndividuals = random.sample(self.generation, 2) return randomIndividuals[0].crossbreed(randomIndividuals[1]) def optimize(self): for self.numGeneration in range(self.numIterations): self.iterate() def outputInfo(self): if self.numGeneration % self.printInterval == 0: print("Fittest individual: {}".format(max(self.generation, key=lambda individual: individual.fitness))) if self.numGeneration % self.plotInterval == 0: showTrajectory(self.params, [individual.sim for individual in self.generation[:self.numToPlot]]) class StrategyDriver(controller.Controller): def __init__(self, acceleration): self.acceleration = iter(acceleration) def act(self, pos, vel, time): return next(self.acceleration) class Strategy(object): """ Contains a generic strategy for approaching a traffic-light which is given by a discretized function a(t) """ def __init__(self, params, acceleration, trafficLight): self.params = params self.acceleration = acceleration self.trafficLight = trafficLight # Determine fitness by running the simulation driver = StrategyDriver(self.acceleration) self.sim = Simulation(params, driver, logging=True) self.sim.run() self.fitness = score(self.sim, self.trafficLight) def mutate(self, mutationParameter): """Create a new strategy by changing each value with probability mutationParameter. The changes are uniformly distributed between -maxChange and maxChange. (mutationParameter = 1 -> All values are changed mutationParameter = 0 -> No values are changed) Afterwards, truncate each value to physically plausible values (between MIN_ACC and MAX_ACC)""" maxChange = 0.1 doChange = np.random.binomial(n=1, p=mutationParameter, size=len(self.acceleration)) changeAmount = np.random.uniform(low=-maxChange, high=maxChange, size=len(self.acceleration)) effectiveChange = doChange * changeAmount newValues = self.acceleration + effectiveChange truncated = np.clip(newValues, a_min=self.params['min_acc'], a_max=self.params['max_acc']) return Strategy(self.params, truncated, self.trafficLight) def crossbreed(self, individual): acceleration = 0.5 * (individual.acceleration + self.acceleration) return Strategy(self.params, acceleration, self.trafficLight) def __str__(self): return str(self.fitness) def optimize(params, trafficLight): def strategyFactory(): acceleration = np.random.uniform( low=params['min_acc'], high=params['max_acc'], size=constants.NUM_STEPS ) return Strategy(params, acceleration, trafficLight) opt = GeneticOptimization(params, strategyFactory) opt.optimize()
28f9b9756fd285ae633a792d48bb49a95e9ad43a
jeremyponto/ITP_Assignments
/Practice_Assorted_Problem_Number_ 13_Jeremy_Ponto.py
475
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 17:10:25 2019 @author: user """ verbs = ["try", "brush", "run", "fix"] def makeForms(verbs): new_verbs = [] for verb in verbs: if verb[-1:] == 'y': new_verbs.append(verb[:-1] + "ies") elif verb[-1:] in ['o', 's', 'x', 'z'] or verb[-2:] in ["ch", "sh"]: new_verbs.append(verb + "es") else: new_verbs.append(verb + 's') print(new_verbs) makeForms(verbs)
b784e01c5b01a4193218e60ef87b4625fa4a92ff
GarvTambi/OpenCV-Beginners-to-Expert
/fetch_display_save.py
897
3.609375
4
import argparse # to pass the argument in the terminal import cv2 # to import the library # fetching the arguments and save in dictionary ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Enter path to the image") args = vars(ap.parse_args()) # loading and converting the image into numpy array # printing the corresponding values image = cv2.imread(args["image"]) # to read the image print("width of the image in pixels is: {}".format(image.shape[1])) print("height of the image in pixels is: {}".format(image.shape[0])) print("channels present the image is: {}".format(image.shape[2])) # load image into cv2 window # wait for key press # write image into another format cv2.imshow("Image Title", image) # to show the image cv2.waitKey(0) # wait until any key press from keyboard cv2.imwrite("newcat.jpg", image) # to save the image
bd53fc1b70a9efad6a0079f95ee760d0a1d78f0d
zilongxuan001/benpython
/ex19_0829.py
669
3.53125
4
def cheese_and_crackers(cheese_count, boxes_of_crackers): print("You have %d cheeses!" % cheese_count) print("You have %d boxes of crackers!" %boxes_of_crackers) print("Man that's enough for a party!") print("Get a blanket.\n") print("We can just give the function numbers directly:") cheese_and_crackers(20,30) print("OR, we can use variablse from our script:") amout_of_cheese = 10 amout_of_crackers = 50 cheese_and_crackers(amout_of_cheese,amout_of_crackers) print("We can enen do math inside too:") cheese_and_crackers(10 + 20, 5+ 6) print("And we can combine the two, variablse and math:") cheese_and_crackers(amout_of_cheese +100,amout_of_crackers+1000)
75c26ef2a199981ccbb3ccb9db10429a2fff4dce
LesterTremens/Trivia
/test.py
1,051
3.5625
4
pygame.init() #Inciamos todos los modulos de pygame pantalla = pygame.display.set_mode((0,0),pygame.FULLSCREEN) # Tamanio de la pantalla. salir= False #Finaliza el evento principal. reloj1 = pygame.time.Clock() #Reloj para actualizar los frames por segundo blanco =(255,255,255) #Color en formato RGB #Tipo de fuente a usar fuente1 = pygame.font.Font(None,100) #Texto que se mostrara texto1= fuente1.render("Hola",0,(0,0,0)) #Evento principal while salir != True: #Decide cada cuando se actualizara reloj1.tick(20) #Color de la pantalla pantalla.fill(blanco) #Colocamos donde se mostrara el texto colocando una nueva superficie pantalla.blit(texto1,(150,150)) #actualiza la ventaba constantemente pygame.display.update() #Evento que permite cerrar la ventana. for event in pygame.event.get(): if event.type == pygame.QUIT: salir = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: salir = True salir = True pygame.quit()
149dedafa32eac24e46908f55a0c8782ceba7b3f
aravindkoneru/Blackjack
/main.py
2,193
3.75
4
import dealer import deck import bank import playerCommands playingDeck = [] dealerHand = [] playerHand = [] totalAmount = 0 bet = 0 numDecks = 0 print "Welcome to blackjack. The ratio is 3:2" #Allows the user to choose the number of decks that they will play with while(numDecks == 0): print "How many decks would you like to play with? (enter a number): ", try: numDecks = int(raw_input()) except: numDecks = 0 continue #Allows the user to set up the bank for bets in the future while(totalAmount == 0): print "How much would you like to have in the bank? (enter a number): ", try: totalAmount = int(raw_input()) except: totalAmount = 0 continue print "You are playing with %d decks and have $%d to bet." % (numDecks, totalAmount) #Creates by playingDeck by adding and shuffling x number of decks as specified by the user for x in range(0, numDecks): playingDeck += deck.createDeck() playingDeck = deck.shuffle(playingDeck) #Makes the user place their bet while(bet == 0): print "How much would you like to bet? (enter a number): ", try: bet = int(raw_input()) except: bet == 0 continue dealerHand = dealer.init(playingDeck) playerCommands.hitMe(playingDeck, playerHand) playerCommands.hitMe(playingDeck, playerHand) dealer.showPartial(dealerHand) print "Value of Dealer Hand: ", playerCommands.valOfHand(dealerHand) playerCommands.readCards(playerHand) dealerVal = playerCommands.valOfHand(dealerHand) playerVal = playerCommands.valOfHand(playerHand) if(playerVal == 21): print "Black Jack! You win $%d!" % bet totalAmount += bet else: hit = True while(hit and playerVal < 22): print "Do you want to hit? (Y or N): ", try: answer = raw_input().upper() if not(answer == "Y" or answer == "N"): raise InvalidInputError() except: print "Invalid answer. Enter Y or N" continue if(answer == "Y"): playerCommands.hitMe(playingDeck, playerHand) playerVal = playerCommands.valOfHand(playerHand) playerCommands.readCards(playerHand) elif(answer == "N"): hit = False break if(playerVal > 21): print "BUSTED BITCH!" totalAmount -= bet
842229b243012d225c94d70ff50fd8cabcae57f6
ethanbar11/python_advanced_course1
/lecture_3/examples.py
375
3.640625
4
# how to read from file # file_stream = open('.\\text.txt', 'r') # data_read = file_stream.readlines() # print(data_read) # file_stream.close() # How to write to file s = open('.\\text.txt', 'w') s.writelines(['One\n', 'Two\n', 'Three']) s.flush() s.close() # Sugar syntax of with with open('.\\text.txt', 'r') as f: print(f.read()) print('Woho, Im out of the with!')
b6f4b1da9b05708856f0e61e3705bf68714ac3a1
mag389/holbertonschool-machine_learning
/pipeline/0x00-pandas/0-from_numpy.py
441
3.90625
4
#!/usr/bin/env python3 """ creates pd dataframe from numpy """ import pandas as pd def from_numpy(array): """ creates pd.DataFrame from np.ndarray array: np arr from which to create datafram columns of pd.DataFrame labeled in alphabetical and capitalized Returns: newly created pd.DataFrame """ alphabet = list(map(chr, range(65, 91))) return pd.DataFrame(array, columns=alphabet[0:array.shape[1]])
389eee775c643e3d7162be4d4af702c6c306b2f7
amandamorris/hw6-sales-report
/sales_report.py
1,896
3.640625
4
""" sales_report.py - Generates sales report showing the total number of melons each sales person sold. """ melon_sales = {} melon_report = open("sales-report.txt") for line in melon_report: line = line.rstrip() entries = line.split("|") salesperson = entries[0] dollars = entries[1] melons_sold = int(entries[2]) if melon_sales.get(salesperson): melon_sales[salesperson]["melons_sold"] += melons_sold else: melon_sales[salesperson] = {"dollars": dollars, "melons_sold": melons_sold} for salesperson in melon_sales: melons_sold = melon_sales[salesperson]["melons_sold"] print "{} sold {} melons.".format(salesperson, melons_sold) # below here is the bad code we were given, plus my comments on what each line is doing # salespeople = [] # melons_sold = [] # f = open("sales-report.txt") # open sales report file # for line in f: # for each line... # line = line.rstrip() # strip whitespace from right side of line # entries = line.split("|") # split line into list of components at | # salesperson = entries[0] # 1st element of list is the salesperson # melons = int(entries[2]) # 3rd element of list is number of melons # if salesperson in salespeople: # check to see if the salesperson is in the list of SP. If so... # position = salespeople.index(salesperson) # bind position to the index of the salesperson in the list # melons_sold[position] += melons # increment their melon sales in the same position in the melon list # else: # if not... # salespeople.append(salesperson) # add salesperson to the list # melons_sold.append(melons) # and add their melons sold to the list # for i in range(len(salespeople)): # for each salesperson... # print "{} sold {} melons".format(salespeople[i], melons_sold[i]) # print "salesperson sold X melons"
74fae66c32eaa98d357c3b2188c2b7707c0d3f7d
anilb0stanci/Solar
/satelite.py
3,588
3.546875
4
import math import numpy as np from numpy.linalg import norm mass_sun = 1.989 * 10 ** 30 G = 6.674e-11 class Satelite(object): def __init__(self, origin, target, color, size, mass, given_speed, angle, radius_planet, planets): self.color = color self.size = size self.mass = mass # The velocity of the planet of origin plus the given velocity # at the given angle. self.vel = (origin.vel + given_speed * np.array([np.cos(angle), np.sin(angle)])) # The position of the planet of origin plus the vector in the direction # of the given angle and length radius. self.pos = np.array([origin.pos[0] + radius_planet * np.cos(angle), origin.pos[1] + radius_planet * np.sin(angle)]) self.acc = self.update_acc(planets) self.origin = origin self.target = target self.min_distance = None self.old_acc = self.acc def update_pos(self, t): """Obtaining the new position using the Beeman's algorithm. Args: param1 (float): a small time step. """ self.pos = (self.pos + self.vel * t + (math.pow(t, 2) / 6.0) * (4.0 * self.acc - self.old_acc)) def update_minimal_distance(self): """Updates the minimal distance to the target if the Satelite has moved any closer. Writes the minimal distance in a text file named 'minimum-distance.txt.' """ dist = norm(self.pos-self.target.pos) # Distance to the target if self.min_distance: # If it's not the first iteration if self.min_distance > dist: # Update and overwrite self.min_distance = dist wr = open('minimum-distance.txt', 'w') wr.write("Minimal distance to " + self.target.name + ": " + str(round(self.min_distance / 1000, 2)) +" km.") else: self.min_distance = dist def update_vel(self, t, new_acc): """Obtaining the new velocity using the Beeman's algorithm. Args: param1 (float): a small time step needed for numerical integration. param2 (float): the acceleration at the next time step. """ self.vel = (self.vel + ((t / 6.0) * (2.0 * new_acc + 5.0 * self.acc - self.old_acc))) def update_acc(self, planets): """Calculating the acceleration due to the planets. The sum of all the Gm/r, where m is the mass of the planet and r is the radius separating them. Args: param1 (list): a list of all the planets. """ acc = np.zeros(2) for planet in planets: if planet is not self: dist = self.pos - planet.pos # Distance between planets # Using Newton's gravitational formula. acc = acc + (-G * planet.mass * dist) / math.pow(norm(dist), 3) return acc def update_vel_acc(self, t, planets): """Updates the velocity and the acceleration of the satelite. Args: param1 (float): a small time step needed for numerical integration. param2 (list): a list of all the planets. """ # First calculate the new acceleration. new_acc = self.update_acc(planets) # Calculate the velocity with it self.update_vel(t, new_acc) # Lastly, update the accelerations. self.old_acc, self.acc = self.acc, new_acc
1ee29032e3832aa3afa6ac5a7f84bd24c46fe327
SirMatix/Python
/Sentdex/timeit tutorial.py
322
3.53125
4
import timeit #print(timeit.timeit('1+3', number=50000)) input_list = range(100) def div_by_five(num): if num % 5 == 0: return True else: return False xyz = (i for i in input_list if div_by_five(i)) ##xyz = [i for i in input_list if div_by_five(i)] print(timeit.timeit('''''', number=5000))
42f9fb5933480956b867f4762411fea10a7e7e3f
midigo0411/Password-locker
/user.py
494
3.96875
4
class User: ''' Class to create user accounts and save their information ''' # Class Variables # global users_list users_list = [] def __init__(self,first_name,last_name,password): ''' Method to define the properties for each user object will hold. ''' # instance variables self.first_name = first_name self.last_name = last_name self.password = password def save_user(self): ''' Function to save a newly created user instance ''' User.users_list.append(self)
28f2c73d5a9e194f591a27aaf2b46ed3786e36a6
slideclick/pythonCode
/stackFrame.py
1,726
3.75
4
# -*- coding: UTF-8 -*- # http://www.pythontutor.com/ # python.exe -m doctest stackFrame.py # stackFrame.py is argv to doctest.script # from __future__ import print_function import argparse def foo(): """ simple funciton to demo LEGB and doctest foo() won't out put at console. To output you need print(foo()) which is 3 or python -i foo() which is '3'(Out) Example: (There must be a space char after >>> . The Expected result should be what in iPython: '3' not 3) However, if you have output in foo, it will also check the print result. You'd better separate output and return value and use doctest to check return value >>> foo() '3' """ x = 1 def bar(y): z = y + 2 # <--- (3) ... and the interpreter is here. return z print 7 return str(bar(x)) # <--- (2) ... which is returning a call to bar ... foo() def play(myInt, myLongInt, myList, myString): print 'START OF play Function:' print '\tmyInt=',myInt,'myLongInt=',myLongInt print '\tmyList=',myList,'myString=',myString myInt += 1 myLongInt += 1 myList.append(1) myString +='a' print 'END OF play Function:' print '\tmyInt=',myInt,'myLongInt=',myLongInt print '\tmyList=',myList,'myString=',myString return anInt = 10 aLongInt = 123456789012345678901234567890L aList = range(5) aString = 'hello' print 'BEFORE CALL:' print 'anInt=',anInt,'aLongInt=',aLongInt print 'aList=',aList,'aString=',aString print play(anInt, aLongInt, aList, aString) print print 'AFTER CALL:' print 'anInt=',anInt,'aLongInt=',aLongInt print 'aList=',aList,'aString=',aString if __name__ == '__main__': pass import doctest #doctest.testmod()
d5a9c6433d2390c541dafd49697014d6bf7f8d77
kjjudy/BIOL5153
/misc_lec/fib.py
1,085
4.375
4
#! /usr/bin/env python3 #import modules import argparse #define functions def get_args(): #create an ArgumentParser object ('parser') thtat will hild all info necessary to parse command line parser=argparse.ArgumentParser(description="This script returns the fibonacci number at a specified position in the fibonacci sequence") #define positional arguments parser.add_argument("num",help="The fibonacci number you wish to calculate", type = int) #define the optional arguments parser.add_argument("-v","--verbose", help="print verbose output", action='store_true') #parse the arguments return parser.parse_args() #function to calculate the fibonacci sequence def fib(n): #do the calculation a,b = 0,1 for i in range(n): a,b=b,a+b #return the value return a def main(): if args.verbose: print("The Fibonacci number for ",args.num," is ",fib(args.num)) else: #fib_num=fib(args.num) #above if num is wanted to be used for other stuff print(fib(args.num)) args=get_args() main()
03e1dc04d3a31ec4815b4ee56e4abb1378b45aa0
cybelewang/leetcode-python
/code944DeleteColumnsToMakeSorted.py
1,829
4.15625
4
""" 944 Delete Columns to Make Sorted We are given an array A of N lowercase letter strings, all of the same length. Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices. For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"], and the remaining columns of A are ["b","v"], ["e","y"], and ["f","z"]. (Formally, the c-th column is [A[0][c], A[1][c], ..., A[A.length-1][c]].) Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order. Return the minimum possible value of D.length. Example 1: Input: ["cba","daf","ghi"] Output: 1 Explanation: After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order. If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order. Example 2: Input: ["a","b"] Output: 0 Explanation: D = {} Example 3: Input: ["zyx","wvu","tsr"] Output: 3 Explanation: D = {0, 1, 2} Note: 1 <= A.length <= 100 1 <= A[i].length <= 1000 """ class Solution: def minDeletionSize(self, A): """ :type A: List[str] :rtype: int """ def increasing(t): # subfunction check if the sequence of t is in non-decreasing order N = len(t) for i in range(1, N): if t[i] < t[i-1]: return False return True ans = 0 for t in zip(*A): if not increasing(t): ans += 1 return ans #A = ["a"] #A = ["a", "b"] A = ["zyx", "wuv", "tsr"] print(Solution().minDeletionSize(A))