blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
3109cb7b7d3c93fe59714b4ac898ce797f2cc6ea
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/hgxkon001/question3.py
1,361
4.46875
4
#Konrad Hugo #assignment 8 question 3 #2014-05-09 message = input("Enter a message:\n") encrypt = '' length = len(message) def encryptor(message,encrypt): #function that encrypts a message inserted if len(encrypt) == length: #This is the condition to be met/break print("Encrypted message:\n",encrypt,sep = '') else: position = ord(message[0]) #converts the letter taken into account into the integer representing it on the table of ASCII if 97 <= position <= 122: if position == 32: # This makes sure ' ' is not changed new_char = chr(position) elif position == 122: new_char = chr(position-25) #ensures z is swapped to a else: new_char = chr(position+1) #Acts as the encryptor, changing the letter inputed by one further in the alphabet eac time return encryptor(message[1:],encrypt + new_char) else: encrypt += chr(position) return encryptor(message[1:],encrypt) #acts as the loop, feeding in message's string as one less each time, and encrypt's string as one more each time encryptor(message,encrypt) #initiation germination
f28134193251136a8c691bca4596fd3e0369a63b
ldgeao99/Algorithm_Study
/Test_Basic_Codes/1-1. bubble sort.py
1,172
3.859375
4
"""<버블정렬> @ 시간복잡도 Best : O(n^2) Avg : O(n^2) Worst : O(n^2) @ 알고리즘 로직 - 크기가 2인 윈도우를 맨 뒤까지 움직이면서 비교하고, 작은건 앞으로 큰건 뒤로 옮긴다. - 이를 리스트의 크기 - 1 번 만큼 반복한다. (한번을 마칠 때 마다 정렬이 완료된 숫자가 맨 뒤에 fix 된다.) """ # 오름차순 정렬 def bubble_sort_ascending_order(lst): new_list = lst.copy() for i in range(len(new_list)-1): for j in range(len(new_list)-1-i): if new_list[j] > new_list[j+1]: new_list[j], new_list[j+1] = new_list[j+1], new_list[j] return new_list # 내림차순 정렬 def bubble_sort_descending_order(lst): new_list = lst.copy() for i in range(len(new_list)-1): for j in range(len(new_list)-1-i): if new_list[j] < new_list[j+1]: new_list[j], new_list[j+1] = new_list[j+1], new_list[j] return new_list lst = [3, 2, 5, 1] print(lst) # [3, 2, 5, 1] print(bubble_sort_ascending_order(lst)) # [1, 2, 3, 5] print(bubble_sort_descending_order(lst)) # [1, 2, 3, 5]
b4486b006d62473edb014067e50286ccf7d79c68
supercatex/EightQueensPuzzle
/main1.py
2,104
3.546875
4
import app import time # check the new position whether is valid. def checking(new, pieces, size): # check bounding. if new.x < 0 or new.y < 0 or new.x >= size or new.y >= size: return False for piece in pieces: # check same position. if new.x == piece.x and new.y == piece.y: return False # check x and y if new.x == piece.x or new.y == piece.y: return False # check cross if abs(new.x - piece.x) == abs(new.y - piece.y): return False # all pass return True # get the next position. def nextPiece(piece, size): # next column x = piece.x + 1 y = piece.y # if over bounding, next row. if x >= size: x = 0 y = y + 1 # the end. if y >= size: return None # new piece with new position. return app.Piece(x, y, piece.t) def setQueen(board, x, y, deep): global _counting_solutions # find the next valid position to prepare setting a queen. new = app.Piece(x, y, app.PieceType.QUEEN) while new != None and checking(new, board.pieces, board.row) == False: new = nextPiece(new, board.row) # if not found, do nothing. if new == None: return if new.y != deep: return # performance optimize # set a queen. board.pieces.append(new) # if the queen is the last one, found a solution. if deep == board.row - 1: _counting_solutions += 1 print('Solution ' + str(_counting_solutions) + str(board)) # else set the next one. else: setQueen(board, new.x, new.y, deep + 1) # if found solution or no solution, pick up the last queen. prev = board.pieces.pop() # set the queen to next position to try another solutions. new = nextPiece(prev, board.row) if new == None: return setQueen(board, new.x, new.y, deep) _size = 8 _counting_solutions = 0 if __name__ == '__main__': ts = time.time() setQueen(app.Board(_size), 0, 0, 0) te = time.time() print('Solutions: ' + str(_counting_solutions)) print('Cost: ' + str(round(te - ts, 2)) + ' sec')
241527beadb3bf318ee4cedc46dcbc689c33cbab
joyer7/CDSW-Demos-KOLON
/Example12-PolyReg-Demo/poly_reg_scipy.py
2,214
3.671875
4
# # Polynomial Regression - python, scipy # We have a couple options we could use to solve [Polynomial Regression](https://en.wikipedia.org/wiki/Polynomial_regression) using [SciPy](https://www.scipy.org/). Below is one appraoch. import numpy as np import pandas as pd from scipy import optimize # ## Generate Data # We'll generate sample sample data with known coefficients and randomly generated error. Specifically; # $$ y = \beta_0 + \sum_i (\beta_i x_i) + \epsilon \thinspace \thinspace \thinspace \thinspace \thinspace \forall i \in {1..3}$$ # $$ \beta_0: 4 $$ # $$ \beta_1: 6 $$ # $$ \beta_2: 2 $$ # $$ \beta_3: -1 $$ x1 = np.random.uniform(low=-2.0, high=4.0, size=10000) x2 = np.power(x1,2) x3 = np.power(x1,3) y0 = 4 + 6*x1 + 2*x2 - 1*x3 + np.random.normal(0,4,10000) # ## Initialize & Run Optimizer # SciPy optimize can solve problems more general that [linear regression](https://en.wikipedia.org/wiki/Linear_regression). While we are technically solving the same problem when minimizing squared residuals, this form of the analysis is more commonly refer to as [linear least squares](https://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)). # Our solutions invovles definining the function we want to minimize, residual. The optimizer leastsq function will solve for a solution which minimizes the residual sum of squares. predict = lambda b, x1, x2, x3: b[0] + b[1]*x1 + b[2]*x2 + b[3]*x3 residual = lambda b, y,x1,x2,x3: predict(b, x1,x2,x3) - y # This appraoch requires that we initialize our coefficients, we'll choose to randomly initialize. b0 = np.random.normal(0,1,4) b, success = optimize.leastsq(residual, b0[:], args=(y0,x1,x2,x3)) # That's it. **b** is an array of our coefficients and it closely matches our known true values. dat = pd.DataFrame(data=np.dstack((b, [4,6,2,-1]))[0]) dat.columns = ['scipy_coef', 'true_coef'] dat # ## Plot Predict Function Over Observations # Now, let's take a look at a plot of our trained parameters. We'll use bokeh so you can interactively see how slight changes in the coefficient can produce very bad results. Running [create_bokeh_poly_reg.py](../files/py/create_bokeh_poly_reg.py). execfile('py/create_bokeh_poly_reg.py')
d64ec20d9a3a046380df6823a2adc1393d25d53f
aakash0610/Practice-
/Step 44.py
1,072
4.09375
4
TUPLE = [54,76,32,14,29,12,64,97,50,86,43,12] def main_menu(): display = int(input(("1 – Display minimum \n2 – Display maximum \n3 – Display total \n4 – Display average \n5 – Quit")) ax = max(TUPLE) mini = min(TUPLE) tot = total(TUPLE) avg = vg(TUPLE) if display =='2': print (ax) elif display == '1': print(mini) elif display == '3': print(tot) elif display == '4': print(avg) elif display == '5': print("Goodbye and Thank you") else: print("invalid input") while display != 5: display = int(input(("1 – Display minimum \n2 – Display maximum \n3 – Display total \n4 – Display average \n5 – Quit")) def max(TUPLE): TUPLE.sort() out1 = print("the largest number is: " + TUPLE[-1]) return out1 def min(TUPLE): TUPLE.sort() out2 = print("the smallest number is: "+TUPLE[0]) return out2 def total(TUPLE): tot = sum(TUPLE) return tot def vg(TUPLE): vg = sum(TUPLE)/len(TUPLE) return vg main_menu()
31290772c88b4a9ecfee34a2152b22166ba73722
mlesigues/Python
/everyday challenge/day_56.py
669
3.578125
4
#Task: Missing Number from Leetcode #src: https://www.tutorialspoint.com/missing-number-in-python class Solution: def missingNumber(self, nums: List[int]) -> int: #strategy: arithemtic series! ==> n(n+1)/2 or binary search #binary search: sort list, length of the list = high, low = 0 nums.sort() low = 0 high = len(nums) while low < high: mid = low + (high-low)//2 #floor division if nums[mid] > mid: #search high side high = mid else: #search low side low = mid + 1 return low
06d831bdfe88c48846a0230006e81c439890eeb2
swaraj1999/python
/chap 2 string/variable_more.py
253
3.75
4
# taking one or more variables in one line name, age=" swaraj","19" #dont take 19, take 19 as string "19",otherwise it will give error print("hello " + name + " your age is " + age) # hello swaraj your age is 19 XX=YY=ZZ=1 print(XX+YY+ZZ) #ANS 3
e2bd4e7ede37958dddd801bd523cf0e0eb2a8e41
HifzaZaheer96/Assessment
/Code/example.py
228
4.125
4
#!/usr/bin/env python3 def endsPy(input): for i in range(len(input)): if input[i-1] == "y" or input[i-1] == "Y" and input[i-2] == "p" or input[i-2] =="P": return True else: return False
13d69d2f3826f9a2a5c0554471c82ebc52a3ca80
AYAN-AMBESH/learning-Python
/ex20.py
295
4.25
4
# Write a Python program to get the difference between a given number and 17, # if the number is greater than 17 return double the absolute difference. def number(): x = 17 y = int(input("enter a number: ")) if y>17: return 2*abs(y-x) return (x-y) print(number())
4967eac3757336224e3c1af0ba7acabf5ba2ec86
dictator-x/practise_as
/algorithm/leetCode/0166_fraction_to_recurring_decimal.py
795
3.640625
4
""" 166. Fraction to Recurring Decimal """ class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return "0" ret = ["-"] if numerator*denominator else [] numerator = abs(numerator) denominator = abs(denominator) div, mod = divmod(numerator, denominator) ret.append(str(div)) if mod == 0: return "".join(ret) record = {} ret.append(".") while mod != 0: # TODO: circuit break. if mod in record: ret.insert(record[mod], "(") ret.append(")") return "".ret record.put(mod, len(ret)) div, mod = divmod(mod*10, denominator) record.put(div)
c4fd2a20674f3b35b3de6894641d65686a98fbb9
cassiebodin/ComputationalPhysics_phys305
/Homeworks/Homework4/problem1_hwk4.py
2,137
3.828125
4
def Problem1(): #import libraries import numpy as np import matplotlib.pyplot as plt #euler method def Euler1(): def f(T,t): return (-K*(T-T_out)) #initial parameters T = 85 T_out = 25 K=.1 t=0 #set up parameters for graph xarr = [] yarr =[] #step size 1 h = 1e-1 for t in np.arange(0,15,h): #rest of loop for euler method T+=h*f(T,t) #piece of loop for graphing xarr.append(h) yarr.append(T) print("for step size h=", h," After 15 sec T =",T) h = 1e-2 T = 85 for t in np.arange(0,15,h): #rest of loop for euler method T+=h*f(T,t) #piece of loop for graphing xarr.append(h) yarr.append(T) print("for step size h=", h," After 15 sec T =",T) h = 1e-3 T = 85 for t in np.arange(0,15,h): #rest of loop for euler method T+=h*f(T,t) #piece of loop for graphing xarr.append(h) yarr.append(T) print("for step size h=", h," After 15 sec T =",T) h = 1e-4 T = 85 for t in np.arange(0,15,h): #rest of loop for euler method T+=h*f(T,t) #piece of loop for graphing xarr.append(h) yarr.append(T) print("for step size h=", h," After 15 sec T =",T) h = 1e-5 T = 85 for t in np.arange(0,15,h): #rest of loop for euler method T+=h*f(T,t) #piece of loop for graphing xarr.append(h) yarr.append(T) print("for step size h=", h," After 15 sec T =",T) #now plot fig, ax = plt.subplots() #ax.plot (xarr,yarr,'red',linestyle='-', marker=',') #set both to a log scale ax.loglog(xarr,yarr,'red',linestyle='-', marker=',') ax.set(title='Euler', xlabel='log(h)', ylabel='log(T)') #other way? #ax.set_yscale('log') #ax.set_xscale('log') #add a grid ax.grid() fig.savefig('euler1.png') # uncomment to save plot plt.show() Euler1() Problem1()
244bc08f0ce4cce2befe7299d886cebfb2a2a377
rpalo/advent-of-code-2018
/python/src/day12.py
2,728
4.15625
4
"""Day 12: Subterranean Sustainability Conway's game of life with plants! See which plants will live or die each generation. """ from collections import deque from itertools import islice from typing import List, Dict class Plants(deque): """A row of plants centered around zero""" def __init__(self, *args): deque.__init__(self, *args) self.zero = 0 def score(self) -> int: """Sums up all the indices (including negative) that have a plant""" return sum(i - self.zero for i, pot in enumerate(self) if pot == '#') def __getitem__(self, key) -> islice: """Allows slicing a deque""" if isinstance(key, slice): return islice(self, key.start, key.stop, key.step) else: return deque.__getitem__(self, key) def copy(self): result = Plants(self) result.zero = self.zero return result def next_generation(plants: Plants, rules: Dict[str, str]) -> Plants: """Given a row of pots with/without plants and some rules, creates the next generation of plants. The only rules that could increase the length in either direction require 3 dots on the end to check, so this makes sure there are 3 dots on each end just in case. """ this_generation = plants.copy() if any(c == '#' for c in this_generation[:3]): this_generation.extendleft(['.']*3) this_generation.zero += 3 if any(c == '#' for c in this_generation[len(this_generation) - 3:]): this_generation.extend(['.']*3) next_generation = this_generation.copy() for i in range(2, len(this_generation) - 2): next_generation[i] = rules.get("".join(this_generation[i-2:i+3]), '.') return next_generation def parse_rules(text: str) -> Dict[str, str]: """Parses the conversion rules from a block of text""" rules = {} for line in text.splitlines(): pattern, _, output = line.partition(" => ") rules[pattern] = output return rules def age(plants: Plants, generations: int, rules: Dict[str, str]) -> Plants: """Ages a set of plants n generations""" for i in range(generations): plants = next_generation(plants, rules) return plants if __name__ == "__main__": with open("python/data/day12.txt", "r") as f: rules = parse_rules(f.read()) initial_plants = Plants( "##..#..##....#..#..#..##.#.###.######..#..###.#.#..##.###.#.##..###..#.#..#.##.##..###.#.#...#.##..") # Part 1 plants = age(initial_plants, 20, rules) print(plants.score()) # Part 2: Wherein it's #@%!# linear above about 300 plants = age(initial_plants, 300, rules) print(plants.score() + (50000000000 - 300)*86)
5a20f7346625f5775540b1f8321d75fa5a40328f
malimahar/Assignments
/Assignment 5.py
1,178
4.375
4
#Arithmetic operators a = 2 print(a+a) print(a-a) print(a*a) print(a/a) print(a%a) print(a**a) print(a//a) #Assignment operators a = 5 print(a) #a = a+2 same for all a += 2 print(a) a -= 2 print(a) a *= 2 print(a) a /= 2 print(a) a %= 2 print(a) a = 5 a **= 2 print(a) a //= 2 print(a) #Bitewise operators a = 5 a &= 2 print(a) a = 5 a |= 2 print(a) a = 5 a ^= 2 print(a) a = 5 a >>= 2 print(a) a = 5 a <<= 2 print(a) #Logical Operators print(a<=a and a>=a) print(a==a or a>a) print(not(a<=a and a>=a)) #Identity Operatos veg = ["potota", "carrot", "onion"] x = veg print(x is veg) print(x is not veg) #Membership Operators print("potato" in veg) print("onion" not in veg) # Comparison Operators a = 6 print(a==a) print(a!=a) print(a>a) print(a<a) print(a>=a) print(a<=a) # ---------------------------->Conditional Expressions<--------------------------- a = 15 b = 20 if a>=b: print("a is greater than b") else: print("b is greater than a") #----------------------------->Chained Operators<------------------------------- a = 38 b = 65 c = 15 print(a<b<c) print(a<=b<=c) print(a<b*c/a%b//c)
d247aa0b1b28a9e53991bc665dc0626dbe13e23d
Copenhagen-EdTech/Discere
/intelligentQuestion.py
746
4.125
4
### This script takes a string that defines the subject, ### and prompts back a question for the user to explain. from random import randint #from X import X as subject # ## Defining vocabularies # vocab = "abcdefghijklmnopqrstuvwxuz" # vowls = "aeiouy" # consonants = "bcdfghjklmnpqrstvwxz" ## Defining predetirmined questions in dictionary QD ={1:"Can you elaborate on _?_", 2:"Please explain _?_", 3:"What do you mean by _?_", 4:"could you further describe _?_"} #S = "the spanish inquisition" ## Function that takes a given string input, checks for def firstQuestionMaker(subject): Q = QD[randint(1,len(QD))] # Selects one of the questions at random question = Q.replace("_?_", subject) return question
50b9e5fdac3842b7c768a14c255463678118ef89
jz33/LeetCodeSolutions
/T-1090 Largest Values From Labels.py
1,650
3.8125
4
''' 1090. Largest Values From Labels https://leetcode.com/problems/largest-values-from-labels/ We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S. Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item. ''' class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: arr = sorted(zip(values, labels), reverse=True) picked = collections.Counter() # {label : used count} totalSum = 0 totalCount = 0 for value, label in arr: if picked[label] < use_limit: totalSum += value totalCount += 1 picked[label] += 1 if totalCount == num_wanted: break return totalSum
99000109d6235c50d7e1c85e39f4bb58a5ad0f80
amolgadge663/LetsUpgradePythonBasics
/Day3/D3Q1.py
195
4.15625
4
#Question 1 : #Find sum of n numbers with help of while loop. n = eval(input("Enter N number: ")) sum = 0 while(n>0): sum += n n -= 1 print("Sum of N number is: ", sum)
f893633980a03d6187f826f42951aa2049b440c4
derekpa2/Advent_of_code_2019
/aoc_day2_2.py
1,807
3.703125
4
def Intcode(cmdinput,noun,verb): #begin Intcode function. # #This function takes a cmdinput string, replaces index 1 with noun, #replaces index 2 with verb, and returns the output at 0 # # cmdinput[1] = noun cmdinput[2] = verb index = 0 while index < len(cmdinput): if cmdinput[index] == 1: cmdinput[cmdinput[index + 3]] = cmdinput[cmdinput[index + 1]] + cmdinput[cmdinput[index + 2]] index = index + 4 elif cmdinput[index] == 2: cmdinput[cmdinput[index + 3]] = cmdinput[cmdinput[index + 1]] * cmdinput[cmdinput[index + 2]] index = index + 4 elif cmdinput[index] == 99: index = len(cmdinput) else: index = index + 1 return cmdinput if __name__ =="__main__": #read the numbers in readfile = open('aoc_day2_1.txt') fileinput = [] #read each line of the text file for line in readfile: fileinput.append(line) #splits the string up and makes it into a list of integers #map(x,y) assigns the list y to a type x, and returns a list object #list(map(x,y)) converts that list object to a list cmdinput = list(map(int,fileinput[0].split(','))) #the output is at position 0. find which pair (noun,verb) of numbers (0-99) will #produce the reult of 19690720. What is 100*noun*verb? solution = [] for noun in range(100): for verb in range(100): inputlist = cmdinput.copy() result = Intcode(inputlist,int(noun),int(verb)) if result[0] == 19690720: print("It workded!") solution.append(noun) solution.append(verb) del inputlist[:] print(solution) print(100*solution[0]+solution[1])
7c5611901dff7995d8e58174fb70164d53f58af8
AMuscularMoose/CSV-Project
/sitka_2.py
1,128
3.84375
4
import csv from datetime import datetime open_file = open("sitka_weather_07-2018_simple.csv", "r") csv_file = csv.reader(open_file, delimiter = ",") header_row = next(csv_file) #skip the first record since the first row is just the header #The enumerate() function returns both the index of each iteam and the value of each # item as you loop through a list for index, column_header in enumerate(header_row): print("Index:", index, "Column Name:", column_header) highs = [] dates = [] # we call the method striptime() using the string #as an example #somedate = '2017-07-01' #converted_date = datetime.strptime(somedate,'%Y-%m-%d') #print(converted_date) for row in csv_file: highs.append(int(row[5])) converted_date = datetime.strptime(row[2],'%Y-%m-%d') dates.append(converted_date) #print(highs) import matplotlib.pyplot as plt fig = plt.figure() plt.plot(dates, highs, c="red") plt.title("Daily high temperatures, July 2018", fontsize=16) plt.xlabel("", fontsize=12) plt.ylabel("Temperature (F)", fontsize=12) plt.tick_params(axis="both", labelsize=12) fig.autofmt_xdate() plt.show()
e53cfd3686b4c7658a8288eb8552be526b32f0fd
dkpats/CS50Lectures
/Lecture2Python/exceptions.py
315
3.890625
4
import sys try: x = int(input("Enter X: ")) y = int(input("Enter Y: ")) except ValueError: print("Value Error: Something went wrong with you inputs.") sys.exit(1) try: result = x/y except ZeroDivisionError: print("Error: Cannot divide by 0.") sys.exit(1) print(f"{x}/{y} = {result}")
ad846536c59102e9eb11af8eae4d1fa7c36c83e9
hdjsjyl/LeetcodeFB
/316.py
1,219
3.796875
4
""" 316. Remove Duplicate Letters Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Input: "bcabc" Output: "abc" """ # solution1: time complexity: O(n), memory complexity: O(n) # using a auxiliary stack and build a increasing order stack # using a set to judge whether the current element is in the stack or not # using a dictionary to compute the frequency of each element class Solution: def removeDuplicateLetters(self, s: str) -> str: if not s: return "" dicts = {} for ss in s: dicts[ss] = dicts.get(ss, 0) + 1 stack = [s[0]] sets = set() sets.add(s[0]) dicts[s[0]] -= 1 for i in range(1, len(s)): dicts[s[i]] -= 1 if s[i] in sets: continue else: while stack and ord(s[i]) < ord(stack[-1]) and dicts[stack[-1]] > 0: sets.remove(stack.pop(-1)) stack.append(s[i]) sets.add(s[i]) return ''.join(stack)
704ed3364f1b2c9f85c407a9c83d8cb5051d5945
bgranella/2020.01
/59158.Prieto.Agustin/enunciado2/test_employee.py
605
3.5
4
import unittest from employee import Employee class TestEmployee(unittest.TestCase): def test_employee(self): person1 = Employee("Agustin", 19, 40000) self.assertEqual(Employee.get_employee(person1), ["Agustin", 19, 40000]) def test_pay_tax_pay(self): person1 = Employee("Agustin", 19, 40000) self.assertEqual(Employee.pay_tax(person1), 'Paga impuestos') def test_pay_tax_no_pay(self): person1 = Employee("Agustin", 19, 20000) self.assertEqual(Employee.pay_tax(person1), 'No paga impuestos') if __name__ == '__main__': unittest.main()
00b6d6f0b28fd1ab9609171d3ce97b072ca541c8
luisSantamariaCOL/PythonCompetitiveProgramming
/Codeforces/800/anton_and_danik.py
244
3.609375
4
def main(): number = input() s = input() D = s.count('D') A = s.count('A') if D > A: print("Danik") elif A > D: print("Anton") else: print("Friendship") if __name__ == '__main__': main()
2723988567cf961e539b2462c1dfb2c0bb96a444
jty-cu/LeetCode
/Algorithms/226-翻转二叉树.py
1,641
4.21875
4
## solution1: traverse ''' 写一个 traverse 函数遍历每个节点,让每个节点的左右子节点颠倒过来就行了。 单独抽出一个节点,需要让它做什么?让它把自己的左右子节点交换一下。 需要在什么时候做?好像前中后序位置都可以 ''' class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def traverse(root): if not root: return tmp = root.left root.left = root.right root.right = tmp traverse(root.left) traverse(root.right) traverse(root) return root ## solution2: 分解问题 / 递归 ''' 对于某一个二叉树节点 x 执行 invertTree(x),你能利用这个递归函数的定义做点啥? 我可以用 invertTree(x.left) 先把 x 的左子树翻转,再用 invertTree(x.right) 把 x 的右子树翻转,最后把 x 的左右子树交换, 这恰好完成了以 x 为根的整棵二叉树的翻转,即完成了 invertTree(x) 的定义。 **这种「分解问题」的思路,核心在于你要给递归函数一个合适的定义,然后用函数的定义来解释你的代码;如果你的逻辑成功自恰,那么说明你这个算法是正确的。** ''' class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return ## 翻转左右子树 left = self.invertTree(root.left) right = self.invertTree(root.right) ## 重新连接根节点 root.left = right root.right = left return root
7a4f613bec6bbcc0ed70dc592a19a7b463d0da4e
kola1197/abalonserver
/Board.py
1,806
3.59375
4
from Ball import * from tkinter import * from Logger import Logger class Board: def __init__(self): self.Logger=Logger() self.balls = [] self.draw_array = [] self.fill() self.white_is_move=1 self.white=14 self.black=14 self.cmove=0 self.num = [[0 for i in range(j)] for j in range(5, 10)] + [[0 for i in range(13 - j)] for j in range(5, 9)] for i in range(5): for j in range(9 - i): self.num[i + 4][j] = i + j for i in range(4): for j in range(8 - i): self.num[3 - i][j] = j def fill(self): for i in range(5): b = Ball(-1, i, 0) self.balls.append(b) for i in range(6): b = Ball(-1, i, 1) self.balls.append(b) for i in range(3): b = Ball(-1, i+2, 2) self.balls.append(b) for i in range(5): b = Ball(1, i, 8) self.balls.append(b) for i in range(6): b = Ball(1, i, 7) self.balls.append(b) for i in range(3): b = Ball(1, i+2, 6) self.balls.append(b) def update_draw_array(self): self.draw_array = [[0 for i in range(j)] for j in range(5, 10)] + [[0 for i in range(13 - j)] for j in range(5, 9)] for b in self.balls: self.draw_array[b.coord.Y][b.coord.X] = b.color # self.draw_in_console() def draw_in_console(self): print(self.draw_array) def count(self): self.white = 0 self.black = 0 for list in self.draw_array: for color in list: if color == 1: self.white += 1 if color == -1: self.black += 1
468aeb1f3a4fe6ac745e751a0cf8fac341d0d672
wanziforever/console_config_tool
/console.py
12,615
3.53125
4
#!/usr/bin/env python # encoding: utf-8 """ handle the main console constructor and rendering. the whole console will draw a layout frame, including the toppest header, lowest footer, and the body in the middle, body part will have a main window and a main interactor. the main window is used to show the menu and form, main window is a simple place holder with nothing actuall widget, and console logic will control when to show menu or to show form by replacing the placeholder's original_widget main interactor is mainly controled by user, parsing the user input and do layout or console level work, including the menu/form switch, menu navigation. the menus and forms navigation will use a path algorithom, the menu manager will build a console model for menu and form information including all the item with path information like following: 1: submenu aaaa 2: submenu bbb 1.1: form cccc 1.2: form dddd so the path is the string concated with the index and '.', each time, user input a index, an switcher will record it and make new a new path base on the path which currerntly is located in. for exmaple, if you are in the submenu aaaa, you currently will see the sub items form cccc, and form dddd, and your current path is '1', when user enter 2, a new path '1.2' will be generated and user will navigated to form 1.2 dddd. now the form dddd view will in front of you. there are several levels of controlers, the controlers are used to control the most behavior, the toppest level one is ConsoleControler which receive every event, and distribute it to its child controlers. for example, the ConsoleControler accept the user main interactor command, and have a check whether it is a `quit` command, if it is not, ConsoleControler send it to its child controler main panel controler, main panel controler currently has nothing to do except transfer it to view controler (maybe the main panel will do some further action later), view controler will determine the menu and form view switching and do the switch. """ import urwid as uw from log import log palette = [ ("underline", "underline", "black"), ("reverse", "light gray,standout", "black"), ('title', 'light gray', 'black'), ('redfont', 'dark red,bold', 'black'), ('normal', '', ''), ('bold', 'bold', ''), ('blue', 'bold', 'dark blue'), ('highlight', 'black', 'dark blue'), ('body', 'black', 'light gray', 'standout'), ('button normal', 'light gray', 'dark blue', 'standout'), ('button select', 'white', 'dark green'), ('button disabled', 'dark gray', 'dark blue'), ('edit', 'light gray', 'dark blue'), ('bigtext', 'white', 'black'), ('exit', 'white', 'dark cyan') ] class MenuView(uw.ListBox): """show menu item information in the menu view :type rows: list of tuple :param rows: member is a tuple (index, menu_title_text) """ def __init__(self, rows): body = uw.SimpleListWalker(self._wrap_rows(rows)) super(MenuView, self).__init__(body) def _wrap_rows(self, rows): """the text cannot directly add to listbox, use Text widget wrap :type rows: list of tuple :param rows: member is a tuple (index, menu_title_text) """ return [uw.Text("%-3s%s" % (str(index)+".", txt)) for index, txt in rows] def change_items(self, rows): """change the menu content which is showed on the console urwid.Text list cannot directly add to listbox, use simpleListWalker wrap :type rows: list of tuple :param rows: member is a tuple (index, menu_title_text) """ self.body = uw.SimpleListWalker(self._wrap_rows(rows)) class MenuViewControler(object): """menu view controler, normally the content of the menu change is triggered by a key press by user navigation operation. provide a do method to accept the uplevel controler command and do view navigation :type model: class `menumgr.ConsoleModel` :param model: menu model data containing the path and menu mapping """ def __init__(self, model): self._view = None self._model = model def get_view(self): """"return the Menu view widget in urwid :return type: class 'urwid.Widget' """ if self._view is not None: return self._view return self._view def do(self, path): """execute the path navigation :type path: str :param path: the internal path to a menu item :return type: Boolen, if cannot find the route target, return False """ menu = self._model.find_by_path(path) if menu is None: return False rows = [(index, item.get_title()) for index, item in menu.get_items()] if not self._view: self._view = MenuView(rows) else: self._view.change_items(rows) return True class FormViewControler(object): """form view controler, mainly use to cordinate the form generator to retrieve the form base on the specified path :type model: class `menumgr.ConsoleModel` :param model: menu model data containing the path and form mapping """ def __init__(self, model): self._view = None self._model = model def get_view(self): return self._view def do(self, path): """execute the path navigation :type path: str :param path: the internal path to a form item :param model: menu model data containing the path and form mapping """ form = self._model.find_by_path(path) log(form) if form is None: return False self._view = form.gen_view() return True class ViewSwitcher(object): """a status control object, control the switcher between menu view and form view, the switcher will consider the current status (current path located) and determine the next view. switcher will also in charge of generated new paths. :type menctl: class `console.MenuViewControler` :param menctl: the menu controler instance :type formctl: class `console.FormViewControler` :param formctl: the menu controler instance """ menu_upward = ['U', 'u'] root_menu = ['', 'root'] def __init__(self, menuctl, formctl): self._current_path = '' self._menuctl = menuctl self._formctl = formctl def startup_view(self): self._current_path = path = 'root' self._menuctl.do(path) return self._menuctl def do(self, cmd): """accept the uplevel controler command, and ask low level controler to do something. here let the menu controler or form controler to navigate its menu or form. firstly try to do menu navigation, and if fail, then do form navigation. :type cmd: str :param cmd: the command send from upper level controler :return type: `console.MenuViewControler` or `console.FormViewControler` None for nothing to go """ path = "" if cmd in self.menu_upward: if self._current_path not in self.root_menu: tokens = self._current_path.split(".") if len(tokens) <= 1: path = "root" else: path = ".".join(tokens[-1]) else: if self._current_path in self.root_menu: path = cmd else: path = self._current_path + "." + cmd if self._menuctl.do(path): self._current_path = path return self._menuctl if self._formctl.do(path): self._current_path = path return self._formctl return None class MainPanelControler(object): """main panel view control, use view switcher to determine which view to show, manager the main panel widget. :type main_panel: urwid.Widget :param main_panel: the view widget of the main panel :type menctl: class `console.MenuViewControler` :param menctl: the menu controler instance :type formctl: class `console.FormViewControler` :param formctl: the menu controler instance """ def __init__(self, main_panel, menuctl, formctl): self._main_panel = main_panel self._viewswitcher = ViewSwitcher(menuctl, formctl) self._current_ctl = None def switch_view(self, newctl): if newctl is None: return if newctl == self._current_ctl: return self._current_ctl = newctl self._main_panel.original_widget = newctl.get_view() def do(self, cmd): newctl = self._viewswitcher.do(cmd) self.switch_view(newctl) def get_view(self): """get the main panel view widget in urwid :return type: `urwid.Widget` """ return self._main_panel def startup_view(self): ctl = self._viewswitcher.startup_view() self.switch_view(ctl) class ConsoleControler(object): """top level controler, accept the user key press, and transfer comamnd to every sub controlers """ console_exit = ['Q', 'q'] def __init__(self): self._mainctl = None def set_main_panel_controler(self, ctl): self._mainctl = ctl def do(self, cmd): if cmd in self.console_exit: raise uw.ExitMainLoop() if not self._mainctl.do(cmd): return # someother sub controler do one by one ... def get_header(): """frame header""" txt = (u'Highgo Purog瀚高集群软件V2.0 配置工具') return uw.Text(txt, align="center") def get_footer(): """frame footer""" txt = (u'Press u to upward, q to quit') return uw.Text(txt) class MainPanel(uw.WidgetPlaceholder): """control how to show the form and menu""" def __init__(self, *args): super(MainPanel, self).__init__(uw.SolidFill('^')) def show_form(self, form): self.original_widget = form def show_menu(self, menu): """use a unified interface to set the menu with padding""" self.original_widget = uw.Padding(menu, left=2) def get_main_panel(): #return uw.WidgetPlaceholder(uw.SolidFill()) #menu = get_menu(menuitems) return MainPanel() class MainInteractor(uw.Edit): """the main interactor interface to user, handle the key press, and send it to top controler """ def __init__(self, *args): self._controler = None super(MainInteractor, self).__init__(*args) def keypress(self, size, key): if key == 'enter': self._controler.do(self.get_edit_text()) self.set_edit_text("") super(MainInteractor, self).keypress(size, key) def set_controler(self, control): self._controler = control class Console(object): def __init__(self): self._controler = ConsoleControler() self._loop = None self._menu_model = None self._form_model = None self._menuctl = None self._formctl = None self._mainctl = None self._maininteractor = None self._frame = None def set_menu_model(self, model): self._menu_model = model def set_form_model(self, model): self._form_model = model def _make_layout(self): pile = uw.Pile( [ (1, uw.SolidFill()), self._mainctl.get_view(), (1, uw.Filler(self._maininteractor, valign="bottom")), ((1, uw.SolidFill('-'))) ]) self._frame = uw.Frame(pile, header=get_header(), footer=get_footer()) def _run(self): self._loop = uw.MainLoop(self._frame, palette) #main.show_menu(menu) self._loop.run() def startup(self): """related resource creation and do assignment""" self._menuctl = MenuViewControler(self._menu_model) self._formctl = FormViewControler(self._form_model) self._mainctl = MainPanelControler(get_main_panel(), self._menuctl, self._formctl) self._maininteractor = MainInteractor("choice: ") self._maininteractor.set_controler(self._controler) self._controler.set_main_panel_controler(self._mainctl) self._make_layout() # for startup, firstly swith to menu view #self._mainctl.switch_view(self._menuctl) self._mainctl.startup_view() self._run() if __name__ == "__main__": pass
6ec1095584fe04c5028e478984918830e53691b5
lichobaron/Numerico
/Parcial1/punto3a.py
643
3.609375
4
from math import * from sympy import * import time gx="8**x -25" #funcion inversa transformada g1x=str(diff(gx)) x=1 tolerancia=0.0001 N=50 i=1 print('iteracion\tg(f(x))\t\terror\t\tderivada') starttime = time.time() while i<=N: d= float(eval(g1x)) if d == 0: print ("El metodo no aplica") x0=x-float(eval(gx))/d er=abs(x0-x) print("%d\t\t%.5f\t\t%.5f\t\t%.5f"%(i,x0,er,d)); if er<tolerancia: endtime = time.time() - starttime print("La raiz es ",x0) print ("El tiempo de ejecucion fue : %.4f Sg" % endtime) break i=i+1 x=x0 if i>=N: print("El metodo no converge ")
57245a5ef489b2ccfbee3402313096c97ddd864a
super1947/AICourse
/DAY04/variantArgs02.py
379
3.609375
4
# variantArgs02.py # minval : 튜플 요소에서 가장 큰 수와 가장 작은 수를 반환하는 함수 만들기 def minval(*args): return min(args), max(args) print(minval(3, 5, 8, 2, 4)) # 튜플은 sort() 함수가 불가능. list만 가능 def minval2(*args): mylist = [i for i in args] mylist.sort() return mylist[0], mylist[-1] print(minval2(3, 5, 8, 2, 4))
8e017d72a03e0b374d779efb1c08191ad7614f11
prajithpipt/python
/sumtk.py
531
4.0625
4
from tkinter import * root=Tk(className='addition') def add(event): n1=int(num1.get()) n2=int(num2.get()) sum=n1+n2 res.delete(0,"end") res.insert(0,sum) Label(root,text="enter first number :").grid(row=0,sticky=W,padx=5) num1=Entry(root).grid(row=0,column=1,sticky=E,padx=5) Label(root,text="enter second number :").grid(row=1,sticky=W,padx=5) num2=Entry(root).grid(row=1,column=1,sticky=E,padx=5) btn=Button(root,text="add").grid(row=3) btn.bind("<Button-1>",add) res=Entry(root).grid(row=5,sticky=E) root.mainloop()
c4c420b2f2eda8c6572958eda73df6c483f7b50f
villejacob/interview-prep
/InterviewBit/RemoveDuplicatesFromSortedArray.py
781
4.0625
4
''' Remove duplicates from Sorted Array Given a sorted array, remove the duplicates in place such that each element appears only once and return the new length. Note that even though we want you to return the new length, make sure to change the original array as well in place Do not allocate extra space for another array, you must do this in place with constant memory. Example: Given input array A = [1,1,2], Your function should return length = 2, and A is now [1,2]. ''' A = [-6, -7, -7, 2, 3, 3, 3, 3, 4, 4, 5, 6, 7, 7, 7] def removeDuplicates(A): i = 0 j = i + 1 while j < len(A): if A[i] == A[j]: j += 1 else: i += 1 A[i] = A[j] j += 1 return len(A[:i+1]) print removeDuplicates(A), A
dd57cf9eb7b9182ab8ce957b534a9d3eee8750b9
J1ng06/4dn4_Advanced_Internet_Communications
/Lab 2/4DN4_LAB2_JC_WZ/4DN4_LAB2_JC_WZ/Client_Code/FTPClient.py
4,447
3.59375
4
import socket import sys import os import time # Create a TCP/IP socket sock = None # Connect the socket to the port where the server is listening server_address = '' amount_received = 0 file_found = False # client always running unless break while True: message = raw_input('Enter your command.\n') if(message.startswith("CONNECT")): server_address = (message.split(',')[1],int((message.split(',')[2]))) print >>sys.stderr, 'connecting to %s port %s' % server_address # setup socket object sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to a server with address and port provided sock.connect(server_address) elif(sock == None): print "Connect to a server first" else: if(message == "QUIT"): quit() elif(message == "BYE"): print 'Bye..' # send BYE to server and close the socket sock.sendall(message) sock.close() sock = None elif(message.startswith("LIST")): # send list to the server and print out its response sock.sendall(message) data = sock.recv(1028) print >>sys.stderr, 'received "\n%s"' % data elif(message.startswith("READ")): if(len(message.split(',')) == 2): # Send data sock.sendall(message) # the next receive will be the file size from the server data = sock.recv(64) # if the next received data is ERROR: then something went wrong on the server side if(data.startswith("ERROR:")): print >>sys.stderr, '"%s"' % data else: filesize = int(data) amount_received = 0 # open the file for writing in bytes f1 = open(message.split(',')[1], 'wb') while amount_received <= filesize: # keep receving the writing to the file untill amount received is greater or equal to the file size try: data = sock.recv(64) f1.write(data) amount_received = len(data) + amount_received print str(data) except: f1.close() os.remove(f1.name) sock = None break #print len(data) # if (time.time() > timeout): # print "time out" # break if(amount_received == filesize): print >>sys.stderr, 'File Received.' f1.close() else: print '\nSeparate the file name and READ with comma' elif(message.startswith("WRITE")): if(len(message.split(',')) == 2): file_found = False # loop the directory to find the file given using os.listdirt for files in os.listdir(os.getcwd()): if(files == message.split(',')[1]): file_found = True # file is found, get the filesize to server for error handling sock.sendall(message + ','+ str(os.path.getsize(os.getcwd() + "\\" + files))) # open the file for reading, and send each line to the server f1 = open(message.split(',')[1],'rb') for line in f1: sock.sendall(line) # close the file, the next recevied data will include whether the transfer was succesful or not f1.close() data = sock.recv(1028) if(data != ""): print >>sys.stderr, '%s' % data if(file_found == False): # file not found print back error message print "\nFile is not in the current directory and include the extension" else: print "\nSeparte the file name and Write with comma"
f931608262f3e658bce92988e8583200c8dad3bf
malavikasreekumar/HackerRank_Problem_Solving
/Grading Students.py
482
3.546875
4
def gradingStudents(grades): newgrade=[] for i in range(len(grades)): if grades[i] > 40 and grades[i] <=100: if ((((grades[i]//5)+1)*5)-grades[i]< 3 ): newgrade.append(((grades[i]//5)+1)*5) else: newgrade.append(grades[i]) else: if grades[i]>=38 and grades[i] < 40: newgrade.append(40) else: newgrade.append(grades[i]) return newgrade
9552e4e01b36680f0e2bdd915d6705f78903c771
jordiae/PAR-MAI
/lab/s2_moving_target_planner/problem_gen.py
4,022
3.921875
4
import sys import collections import random nums2names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'] Pos = collections.namedtuple('Pos', 'x y t') def usage(): print('USAGE FOR PRE-DEFINED BOARDS: python3.6 <problem_name> robot <x> <y> target <x> <y> [x1, y1] > <problem_name>.pddl') print('with x, y in [0-3]') print('USAGE FOR RANDOM BOARDS: python3.6 <problem_name> random <seed> <n_steps> > <problem_name>.pddl') def random_non_equal_pairs(n=2, start=0, end=3, seed=0): random.seed(seed) pairs = [] for i in range(0, n): pair = random.randint(start, end), random.randint(start, end) while pair in pairs: pair = random.randint(start, end), random.randint(start, end) pairs.append(pair) return pairs def random_consecutive_coords(start, n=6, seed=0): random.seed(seed) trajectory = [Pos(nums2names[start.x], nums2names[start.y], nums2names[start.t])] current_x = start.x current_y = start.y for i in range(n): moved = False while not moved: mov = random.randint(0,4) if mov == 0: # left if current_x > 0: current_x = current_x - 1 moved = True else: continue if mov == 1: # right if current_x < 3: current_x = current_x + 1 moved = True else: continue if mov == 2: # up if current_y > 0: current_y = current_y - 1 moved = True else: continue if mov == 3: # down if current_y < 3: current_y = current_y + 1 moved = True else: continue if mov == 4: # stay moved = True trajectory.append(Pos(nums2names[current_x], nums2names[current_y], nums2names[i])) return trajectory def main(): try: problem_name = sys.argv[1] if sys.argv[2] == 'random': [robot, target] = list(map(lambda coords: Pos(coords[0], coords[1], 0), random_non_equal_pairs(seed=int(sys.argv[3])))) if int(sys.argv[4]) > 7 or int(sys.argv[4]) < 1: sys.exit() trajectory = random_consecutive_coords(start=target, n=int(sys.argv[4]), seed=int(sys.argv[3])) else: args = sys.argv[2:] if args[0] != 'robot': sys.exit() robot = Pos(nums2names[int(args[1])], nums2names[int(args[2])], 'zero') if args[3] != 'target': sys.exit() target = Pos(nums2names[int(args[4])], nums2names[int(args[5])], 'zero') trajectory = [target] for index, x in enumerate(args[6:]): if index % 2 == 0: trajectory.append(Pos(nums2names[int(x)], nums2names[int(args[6+index+1])], nums2names[index+1])) robot = Pos(nums2names[robot.x], nums2names[robot.y], nums2names[robot.t]) trajectory_preds = f'(locatedAt {trajectory[0].x} {trajectory[0].y} {trajectory[0].t})\n' for coords in trajectory[1:]: trajectory_preds += f' (locatedAt {coords.x} {coords.y} {coords.t})\n' except BaseException as e: print(e) usage() exit() PROBLEM_TEMPLATE =\ f'''(define (problem {problem_name}) (:domain moving_target) (:objects zero one two three four five six - Coord ) (:init (exactlyOneLessThan zero one) (exactlyOneLessThan one two) (exactlyOneLessThan two three) (exactlyOneLessThan three four) (exactlyOneLessThan four five) (exactlyOneLessThan five six) (locatedAt {robot.x} {robot.y} {robot.t}) (= (cost) 0) ) (:goal (or {trajectory_preds} )) (:metric minimize (cost) ) )''' print(PROBLEM_TEMPLATE) if __name__ == '__main__': main()
26c7b23f68b5294a460444792ed78a60b61ead91
osnipezzini/PythonExercicios
/desafio03.py
218
3.8125
4
print('==== DESAFIO 03 ====') n1 = int(input('Digite o primeiro número ')) n2 = int(input('Digite o segundo número ')) calculo = n1 + n2 print('A soma entre os dois números digitados é de : {} '.format(calculo))
b1e8063a35aef029559742284ec3337b4e5523e6
raowaqarakram/Waqar-Akram-Assignments
/Quiz_App.py
2,161
4.34375
4
#Student: Waqar Akram #email: raobscs@gmail.com #This is a small quiz app for pyhton students using dictionaries in pyhton #You can add 100 of questions in this dictionary quiz=[ { "sr_no":1, "question":"Which of the following are true of Python dictionaries:", "options":["All the keys in a dictionary must be of the same type.","Dictionaries can be nested to any depth.","A dictionary can contain any object type except another dictionary.","Items are accessed by their position in a dictionary."], "answer":"2" }, { "sr_no":2, "question":"d = {'foo': 100, 'bar': 200, 'baz': 300}\nWhat is the result of this statement:\nd['bar':'baz']", "options":["It raises an exception","[200, 300].","200 300.","(200, 300)"], "answer":"1" }, { "sr_no":3, "question":"In a Python program, a control structure:", "options":["Directs the order of execution of the statements in the program","Dictates what happens before the program starts and after it terminates","Defines program-specific data structures","Manages the input and output of control characters"], "answer":"1" }, { "sr_no":4, "question":"What signifies the end of a statement block or suite in Python?", "options":["A comment","A line that is indented less than the previous line","}","end"], "answer":"2" }, { "sr_no":5, "question":"What does a threading.Lock do?", "options":["Allow only one thread at a time to access a resource","Pass messages between threads","SHIFT TO ALL CAPS","Wait until a thread is finished"], "answer":"1" }, ] score=0 for question in quiz: i=1 print(str(question["sr_no"])+" "+question["question"]) for item in question["options"]: print(i,item) i+=1 its_answer=input("Write Correct Option No Here like 1,2,3: ") if (its_answer==question["answer"]): score+=1 pcntg=(score/len(quiz))*100 print("Your Result Score is ",score) print("Your Percentage is "+str(pcntg)+"%") resume=input()
ca4f8ef738a3e3a35b484afb130a98b80776d8ec
yusufkhan004/DSA-Problems
/Array/2reversealgoarrrotation.py
526
4.125
4
def reverseArray(arr, start, end): while (start < end): temp = arr[start] arr[start] = arr[end] arr[end] = temp start += 1 end = end - 1 def leftrotate(arr, d, n): if d == 0: return # incase d is greater than n d = d % n reverseArray(arr, 0, d-1) reverseArray(arr, d, n-1) reverseArray(arr, 0, n-1) def printArray(arr): for i in arr: print(i, end=" ") arr = [1, 2, 3, 4, 5, 6, 7] d = 8 n = 7 leftrotate(arr, d, n) printArray(arr)
47eeaf49d16ec392b24eb0955a9936e86ec98bcb
srf6413/DecisionTree_Adaboost_Language_Classifier
/trainAdaBoost.py
10,953
3.5
4
""" Submitted by: Rahul Golhar(rg1391@rit.edu) """ import math import pickle import pandas import random col_names = ['hasZ', 'avgWordLen', 'dutchDiphtongs', 'englishStopWords', 'dutchStopWords', 'englishCommonWords', 'dutchCommonWords', 'repeatedVowels', 'repeatedConsonants', 'ratioVowelsConsonants', 'language', 'weight'] totalNoOfEntriesValues = 0 class AdaModel: """" This class represents a trained AdaBoost model. The hypothesis vector and hypothesis weight vector are the 2 attributes of AdaBoost model. """ def __init__(self,hypothesisVector, hypothesisWeightVector): self.hypothesisVector = hypothesisVector self.hypothesisWeightVector = hypothesisWeightVector def weightOfStump(totalError): """" This functions is used to calculate the total say a stump will have based on the errors it committed. :param totalError the total error of a stump :return weight a stump will have based on error """ if totalError == 0: return 99999 if totalError == 1: return -99999 return (math.log((1 - totalError) / totalError)) / 2 def exponentValue(value): """" This functions is used to calculate the value of e raised to the value passed. :param value the value to raise with :return result of e^value """ try: return math.exp(value) except OverflowError: if value>=0: return float('inf') else: return float("-inf") def entropy(q): """" Function to return the entropy value of the probability passed. @:param q the probabilty of certain condition @:return the entropy of the value passed """ if q == 0 or q == 1: return 0 else: return -1 * (q * math.log(q, 2) + (1 - q) * math.log((1 - q), 2)) def getMostImportant(currentDataFrame): """" Function to return the most important attribute that can define te result. @:param currentFeatures the dataframe to find the attribute in @:return mostImportant the most important feature in the data frame passed """ sampleSpaceSize = len(currentDataFrame) maxGain = -999999 mostImportant = '' noOfEnglish = len(currentDataFrame[currentDataFrame['language'] == 'en']) entropyEnglish = entropy(noOfEnglish / sampleSpaceSize) for currFeature in currentDataFrame.columns: if currFeature == 'language': continue if currFeature == 'weight': continue # Calculate all required values trueValuesEnglish = len( currentDataFrame[(currentDataFrame[currFeature] == True) & (currentDataFrame['language'] == 'en')]) trueValuesDutch = len( currentDataFrame[(currentDataFrame[currFeature] == True) & (currentDataFrame['language'] == 'nl')]) falseValuesEnglish = len( currentDataFrame[(currentDataFrame[currFeature] == False) & (currentDataFrame['language'] == 'en')]) falseValuesDutch = len( currentDataFrame[(currentDataFrame[currFeature] == False) & (currentDataFrame['language'] == 'nl')]) totalTrue = trueValuesEnglish + trueValuesDutch totalFalse = falseValuesEnglish + falseValuesDutch if totalTrue == 0 or totalFalse == 0: remainderEnglish = entropyEnglish else: # (pk+nk/p+n) B(pk/(pk+nk)) probTrue = totalTrue / sampleSpaceSize probFalse = totalFalse / sampleSpaceSize probTrueEnglish = trueValuesEnglish / totalTrue probFalseEnglish = falseValuesEnglish / totalFalse # Calculate the remainder remainderEnglish = entropy(probTrueEnglish) * (probTrue) + entropy(probFalseEnglish) * (probFalse) currGain = entropyEnglish - remainderEnglish # Check whether the gain is maximum if currGain > maxGain: maxGain = currGain mostImportant = currFeature # Return the attribute which has maximum gain return mostImportant def learningAlgo(currentFeatures): """" This functions represents the learning algorithm used to find important attribute and assign weights and create a stump. :param currentFeatures the data to use for creating a stump :return created stump data, mostImportantFeature of stump and amt Of Say Of the Stump """ # *************************** Select best feature ********************** mostImportantFeature = getMostImportant(currentFeatures) print("Most Important feature selected: " + mostImportantFeature) trueWithDutch = currentFeatures[ (currentFeatures[mostImportantFeature] == True) & (currentFeatures['language'] == 'nl')] falseWithEnglish = currentFeatures[ (currentFeatures[mostImportantFeature] == False) & (currentFeatures['language'] == 'en')] trueWithDutchWeights = (trueWithDutch['weight']).sum() falseWithEnglishWeights = (falseWithEnglish['weight']).sum() totalIncorrectWeightSum = trueWithDutchWeights + falseWithEnglishWeights # *************************** Find Amount of say ********************** amtOfSayOfCurrentStump = weightOfStump(totalIncorrectWeightSum) print("Sum of total incorrect weights: " + str(totalIncorrectWeightSum)) print("\t\t\t\tAmount of say for current stump: " + str(amtOfSayOfCurrentStump)) newWeightFactorForIncorrect = exponentValue(amtOfSayOfCurrentStump) newWeightFactorForCorrect = exponentValue(-amtOfSayOfCurrentStump) print("New Weight Factor For Incorrect values: " + str(newWeightFactorForIncorrect)) print("New Weight Factor For Correct values: " + str(newWeightFactorForCorrect)) tempFeatures = currentFeatures # *************************** Assign new weights ********************** for index in range(len(tempFeatures)): if (tempFeatures.iloc[index, col_names.index(mostImportantFeature)] == True and tempFeatures.iloc[index, col_names.index('language')] == "en") or \ (tempFeatures.iloc[index, col_names.index(mostImportantFeature)] == False and tempFeatures.iloc[index, col_names.index('language')] == "nl"): tempFeatures.iloc[index, col_names.index('weight')] = tempFeatures.iloc[index, col_names.index('weight')] \ + newWeightFactorForCorrect else: tempFeatures.iloc[index, col_names.index('weight')] = tempFeatures.iloc[ index, col_names.index('weight')] \ + newWeightFactorForIncorrect currentFeatures = tempFeatures totalWeightBeforeNormalization = (currentFeatures['weight']).sum() print("Total Weight Before Normalization: " + str(totalWeightBeforeNormalization)) # *************************** Normalize the weights ********************** for index in range(len(tempFeatures)): tempFeatures.iloc[index, col_names.index('weight')] = tempFeatures.iloc[index, col_names.index('weight')] \ / totalWeightBeforeNormalization currentFeatures = tempFeatures print("After normalization total weight: " + str((currentFeatures['weight']).sum())) return currentFeatures, mostImportantFeature, amtOfSayOfCurrentStump def createNewFrameFromStump(decisionStump): """" This functions creates new data frame using a stump and gives more priority for classifying incorrect values predicted by current stump. :param decisionStump the decision stump to use :return new data based on incorrect classification of previous stump """ newDataFrame = pandas.DataFrame(columns=col_names) # ********************* Adding incorrect predictions to new frame ************************* for externalIndex in range(len(decisionStump)): randomNumberToCheck = random.random() cumulativeValue = 0 for internalIndex in range(len(decisionStump)): cumulativeValue = cumulativeValue + decisionStump.iloc[internalIndex, col_names.index('weight')] if cumulativeValue >= randomNumberToCheck: newDataFrame.loc[externalIndex] = (decisionStump.iloc[internalIndex]) break # ********************* Re-assigning weights in new frame ************************* for index in range(len(newDataFrame)): newDataFrame.iloc[index, col_names.index('weight')] = 1/len(newDataFrame) return newDataFrame def generateAdaBoost(currentDataFrame): """" This functions creates stumps one by ond comes up with a hypothesis vector and hypothesis weight vector. :param currentDataFrame the data to use :return hypothesis vector and hypothesis weight vector based on data """ hypothesisVector = list() hypothesisWeightVector = list() # ************************ Create stumps one by one ********************** for i in range(1, 6): print("Creating Stump: " + str(i)) dataAfterStump, mostImportantFeature, amtOfSayOfCurrentStump = learningAlgo(currentDataFrame) hypothesisVector.append(mostImportantFeature) hypothesisWeightVector.append(amtOfSayOfCurrentStump) if i != 5: print("Updating data for next stump.") currentDataFrame = createNewFrameFromStump(dataAfterStump) print("\n\n") return hypothesisVector, hypothesisWeightVector def trainAdaBoost(initialData, writeFile): """" Train the Ada Boost algorithm by calling functions and save it to a file specified. @:param initialData the data read from the file @:param writeFile the file to store results on @:return none """ hypothesisVector, hypothesisWeightVector = generateAdaBoost(initialData) adaBoostModel = AdaModel(hypothesisVector, hypothesisWeightVector) print("Generated AdaBoost Model.") # Save AdaBoost model file = open(writeFile, 'wb') pickle.dump(adaBoostModel, file) print("\n\nAdaBoost model Saved.") return def trainDataAdaBoost(allTrainData, resultFile): global totalNoOfEntriesValues totalNoOfEntriesValues = len(allTrainData) initialWeights = [1 / totalNoOfEntriesValues] * totalNoOfEntriesValues allTrainData['weight'] = initialWeights trainAdaBoost(allTrainData, resultFile)
11835d477444887237b4496087acb70086ae987d
AchimGoral/DI_Bootcamp
/DI_Bootcamp/Week_5/Day_3/test.py
695
4.125
4
# __init__: called when an object is instantiated # __repr__: called when you dump an object variable on screen # __str__: called when you print a variable # # str is more informal than repr # class Person: # def __init__(self, weight, height, facebook_friends): # self.weight = weight # self.height = height # self.facebook_friends = facebook_friends # def __gt__(self, other): # if self.facebook_friends > other.facebook_friends: # return True # return False # print(dir(Person)) # see all the different methods possible # p1 = Person(100, 1, 200) # p2 = Person(50, 2, 199) # print(p1 > p2) # call dunder __gt__(greater than)
766f7a715b4834b94b3d033207565e9ad0027ac2
lilsweetcaligula/sandbox-online-judges
/lintcode/easy/swap_nodes_in_pairs/py/swap_nodes_in_pairs.py
1,002
3.6875
4
# coding:utf-8 ''' @Copyright:LintCode @Author: lilsweetcaligula @Problem: http://www.lintcode.com/problem/swap-nodes-in-pairs @Language: Python @Datetime: 17-02-16 00:32 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def swapPairs(self, head): if head == None: return None dummy = ListNode(0) dummy.next = head prev = dummy first = dummy second = None while first.next != None and first.next.next != None: first = first.next second = first.next temp = second.next second.next = first first.next = temp prev.next = second prev = first return dummy.next
4a5e26127a77a2ced658add317dda8df25800968
SamuelCody/hackerrank
/algorithms/implementation/Counting Valleys/counting-valleys.py
317
3.875
4
# Counting Valleys # https://www.hackerrank.com/challenges/counting-valleys/problem def countingValleys(n, s): valleys = 0 elevation = 0 for char in s: if char == 'U': elevation += 1 else: elevation -= 1 if (elevation == 0 and char == 'U'): valleys += 1 return valleys
c953d688cf4d99ad6078f38f1827e557b351b90e
quocthinh1102/QuocThinh
/swap.py
145
4.03125
4
#!usr/bin/python a = input("a = ") b = input("b = ") def swap(a,b): a,b = b,a return a,b print('Hoan doi cua 2 so a va b: ') print swap(a,b)
307780d1faca934c9556c9bfae32208bbe89a7c2
sklee16/lexicographic
/problem_set_2.py
4,850
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 07:58:00 2019 Problem Set 2 #1 Lex index as a linear order of input #2 Weight of a Word @author: sl288 """ from nose.tools import ok_ # ============================================================================= # Problem 1 # This program finds the lexicographically index as a linear order in which the # list is passed as a linear order on [0, 1, ... , n - 1] # ============================================================================= import math def lin_lex_index(word): length = len(word) lex_index = 0 k = 0 for word_index in range(length): k = base_k(word, word_index) lex_index += k * math.factorial(length - word_index - 1) return lex_index """ Sub-function of lin_lex_index() Calculates the k digit that is changed in each places. """ def base_k (word, word_index): k = 0 for next_letter in word[word_index :]: if next_letter < word[word_index]: k += 1 return k #Code Test ok_(17 == lin_lex_index([3, 6, 2, 1])) ok_(13 == lin_lex_index([9, 2, 10, 5])) ok_(1 == lin_lex_index([4, 3])) ok_(2 == lin_lex_index([2, 1, 3])) ok_(35 == lin_lex_index([1, 2, 4, 3, 0])) ok_(0 == lin_lex_index(list(range(0, 1000)))) lin_lex_index(list(range(500, 0, - 1))) #checked by factorial of 500 in calculator # ============================================================================= # Problem 2 # This program finds all the cominbation of words by starting with weight_word # function which the word_find will make new words during enumeration, which # the weight() will check the weight of the word before prepending the word in # the list. # Note: Empty word has a weight of zero. # ============================================================================= """ Pass n twice, for word_find for n as a counter and the limit of the n to check satisfy the conidition of weight of a word when a word of length n is created """ def weight_words(l, n, w): assert (n >= 0) return word_find(l, n, w, n) """ Sub-function of weight_word() Prepends the element to the list if the weight() function is True for satisfying its weight parameter """ def prepend (words, element, w, n): word_prepend = [] for word in words: if(weight([element] + word, w, n)): word_prepend.append([element] + word) return word_prepend """ Sub-function of weight_word() Checks the weight of the word passed as a parameter. Returns the boolean value to the calling function, prepend() (above), to determine whether to include the word in the list or not. """ def weight(word, w, n): weight_calc= sum(word) # since the word is still increasing, the weight can be less than the expected weight w if(len(word) < n): if(weight_calc <= w): return True # for the final check, when the word is composed with n letters, # the word has to have weight of w before it is decided to be prepended # to a list elif(len(word) == n): if(weight_calc == w): return True else: return False """ Sub-function of weight_word() Prepending the words to the list. """ def word_find(l, n, w, k): if n == 0: return [[]] list_weighted = [] words = word_find(l, n - 1, w, k) for element in l: new_words = prepend(words, element, w, k) list_weighted.extend(new_words) return list_weighted #Code Test ok_([] == weight_words([4, 25], 3, 5)) ok_([[90, 13], [13, 90]] == weight_words([90, 13], 2, 103)) ok_([] == weight_words([2, 9, 13], 3, 0)) ok_([[16]] == weight_words([16], 1, 16)) #Note that the following two cases are in inverse order of each other. ok_([[10, 10, 6], [10, 6, 10], [6, 10, 10]] == weight_words([1, 5, 10, 2, 6, 4, 7], 3, 26)) ok_([[6, 10, 10], [10, 6, 10], [10, 10, 6]] == weight_words([7, 4, 6, 2, 10, 5, 1], 3, 26)) ok_([[10, 10, 5, 5, 5, 5], [10, 5, 10, 5, 5, 5], [10, 5, 5, 10, 5, 5], [10, 5, 5, 5, 10, 5], [10, 5, 5, 5, 5, 10], [5, 10, 10, 5, 5, 5], [5, 10, 5, 10, 5, 5], [5, 10, 5, 5, 10, 5], [5, 10, 5, 5, 5, 10], [5, 5, 10, 10, 5, 5], [5, 5, 10, 5, 10, 5], [5, 5, 10, 5, 5, 10], [5, 5, 5, 10, 10, 5], [5, 5, 5, 10, 5, 10], [5, 5, 5, 5, 10, 10]] == weight_words([20, 14, 10, 5], 6, 40))
f5eca5c781ed155ed466ec8bf0fbcb03b0e11c04
XrossFox/nltk_tests
/nltk_analysis_test/input_nltk_test.py
1,061
4.03125
4
#Read user input #Clean string #Analyze sentiment #Output result from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from textblob import TextBlob def clean_my_string(a_string): a_string = word_tokenize(a_string) not_stop_words = [word for word in a_string if word not in stopwords.words("english")] clean_string = " ".join(not_stop_words) return clean_string def analyze(string_to_analyze): an = TextBlob(string_to_analyze) sentiment = lambda x: "Positive" if an.sentiment.polarity > 0 else "Neutral" if an.sentiment.polarity == 0 else "Negative" return "'{string_to_analyze}' is a {sentiment} comment with a polarity of {polarity}".format( string_to_analyze=string_to_analyze, sentiment=sentiment(an.sentiment.polarity), polarity=str(an.sentiment.polarity)) def main(): user_input = input("Key something! ") clean_words = clean_my_string(user_input) print(analyze(clean_words)) if __name__ == "__main__": main()
f460cdb418e70cd792cfe6aecb9ec659966e59cb
cianobrady/CSU44061_ML
/linreg.py
2,165
3.515625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as seabornInstance from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import LabelEncoder from sklearn import metrics import csv #read in data from csv files df = pd.read_csv('tcd ml 2019-20 income prediction training (with labels).csv') df_test = pd.read_csv('tcd ml 2019-20 income prediction test (without labels).csv') df_test = df_test.drop('Income', axis=1) # Remove income as headings are different #concatenate datasets and keep track of the index where they meet total = df.append(df_test) index = len(total) - len(df_test) #Replace empty values and remove unused columns df = total.replace(np.NaN, 0) X = df.drop(['Instance', 'Profession', 'Hair Color'], axis=1) #One hot encoding to handle categorical data Xohe = X.select_dtypes(include=['object']) Xohe = pd.get_dummies(Xohe, columns=['University Degree', 'Country', 'Gender']) X = X.drop(['University Degree', 'Country', 'Gender'], axis=1) #concatenate numerical and categorical data data = pd.concat([X,Xohe], axis=1) #train data is set to training file, test data is set to test file training_data = data[:index] test_data = data[index:] trainy = training_data['Income in EUR'].astype('int') trainx = training_data.drop(['Income in EUR'], axis=1) test = test_data.drop(['Income in EUR'], axis=1) #train model X_train, X_test, y_train, y_test = train_test_split(trainx, trainy, test_size=0.3, random_state=0) regressor = LinearRegression() regressor.fit(X_train, y_train) #training the algorithm y_pred = regressor.predict(X_test) #local tests #make predictions y_testpred = regressor.predict(test) #write back to file subf = pd.read_csv('tcd ml 2019-20 income prediction submission file.csv') i = 0 while (i < len(y_testpred)): subf.Income[i] = y_testpred[i] i += 1 subf.to_csv('out.csv', index=False, sep=',') print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
c41de0b93b20480a5c8b13086b9d49acc43688a8
GrethellR/-t06_rodriguez.santamria
/santamaria/simple07.py
199
3.734375
4
#Programa7:Dado un número import os #Declaración num=0 #Input vis os num=int(os.sys.argv[1]) #Processing #mostrar: El número es impar if (num%2 != 0): print("El número es impar") #fin_if
4610faf6f08a234090f9becf7e48179a304327cc
7deathmaster7/pythonlearn
/example2.py
1,334
4.125
4
import argparse def Func (valor): if valor == 1 or valor == 0: result = valor return result else: result = valor * Func(valor - 1) return result def Funciter(valor): result = 1 for x in range(valor,1,-1): result *= x return result def Funciter2(valor): result = 1 while 1 < valor: result *= valor valor = valor -1 return result def main(valor,metodo): print('************************************Fatorial************************************\n\n Digite 1 para cálculo com fatorial recursivo;\n 2 para cálculo fatorial com for;\n ou 3 para cálculo fatorial com while\n\n\n') result = 0 x = valor if metodo == 1: result = Func(x) print('O valor do fatorial é: %d \n\n' % result) elif metodo ==2: result = Funciter(x) print('O valor do fatorial iterativo é: %d \n\n' % result) elif metodo ==3: result = Funciter2(x) print('O valor do fatorial iterativo com while é: %d \n\n' % result) else: print('O valor de tipo de calculo é inferior a 1 ou superior a 3\n\n' ) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("valor",type=int,help = "entrada de dados para calculo do fatorial") parser.add_argument("metodo",type= int,help = "método") args = parser.parse_args() main(args.valor,args.metodo)
9f0a63a203a3f358625b28396be41b0e7c33d104
YasirChoudhary/Python-Basics
/DataStructure/List/list_11.py
431
4.21875
4
courses=['History', 'Maths', 'ML', 'Physics', 'CompSci'] # remove method takes one argument courses.remove('Art') print(courses) ''' output: ValueError: list.remove(x): x not in list ''' ''' suppose if we have a large list of items and we want to remove a item which is not present in the list we will get ValueError. If the item is present remove method will remove the element. ValueError: list.remove(x): x not in list '''
5b18b6328c5094e915a59a278cb1e174c5b60e94
sainihimanshu1999/Dynamic-Programming
/IsSubsequence.py
242
3.578125
4
''' In this solution we are using two pointer approach, ''' def subSequence(self,s,t): pos_s,pos_t = 0,0 while pos_s<len(s) and pos_t<len(t): pos_s,pos_t = pos_s + (s[pos_s]==t[pos_t]), pos_t + 1 return pos_s == len(s)
b75323905d823f4f4246df1691478b0245a3db89
amithKadasur/python-scraps
/python-scraps/nesting_examples.py
785
3.984375
4
# '''dictionary''' # from datetime import datetime # # alien_0 = {'color': 'green', 'points': 5} # alien_1 = {'color': 'yellow', 'points': 10} # alien_2 = {'color': 'red', 'points': 15} # # print(datetime.now()) # aliens = [alien_0, alien_1, alien_2] # print(aliens) # # print(aliens[0]['color']) # print(datetime.now()) # # '''input from user''' # prompt = "tell me your name and" # prompt += " I will say it back: " # # print(input(prompt)) # # # prompt = "loop will run till you type 'exit'" # message = "" # while message != "exit": # message = input(prompt) # print(message) square = [x**2 for x in range(10)] print(square) compare = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] print(compare) compare = [(x, y) for x in [1,2,3] for y in [3,1,4]] print(compare)
6ac12a5e160a1451de4275d02dd2db075613c6e6
orenlivne/euler
/algorithms/mergesort.py
1,114
3.96875
4
''' ============================================================ Merge sort: O(n log n) time. ============================================================ ''' def mergesort(a): '''Sorts the array a in non-decreasing order.''' n = len(a) return a if n == 1 else list(merge(mergesort(a[:n / 2]), mergesort(a[n / 2:]))) # Note: the two sub-sorts can be performed in parallel! def merge(a, b): '''Merges two non-decreasing lists into one non-decreasing list.''' i, j, na, nb = 0, 0, len(a), len(b) while i < na and j < nb: min_a, min_b = a[i], b[j] if min_a < min_b: yield min_a i += 1 else: yield min_b j += 1 i, a = (j, b) if i == na else (i, a) for k in xrange(i, len(a)): yield a[k] if __name__ == "__main__": import timeit, numpy as np for n in 2 ** np.arange(20): print n, timeit.timeit(stmt='mergesort(a)', setup='import numpy as np; from __main__ import mergesort; \ a = np.random.randint(0, %d, %d)' % (n, n), number=1)
8e8364be5d82f6fd145d829e6801c10ce7641f1a
hibfnv/Python-learning
/compare03.py
166
3.875
4
#!/usr/bin/env python name=raw_input('Enter your name: ') if 'on' in name: print "your name contained words 'on'" else: print "Sounds your name have no 'on' in it"
ff535325e96c9ed9980674cb14298f601962504b
bosgithub/Dynamic_Programing
/1.fibonacci_sequence.py
1,074
4
4
""" Here is the one and only "Fibonacci sequence" where the result of the current number is the sum of the previous 2 """ # Fibonacci: def fib(n): if n == 0: result = 0 elif (n == 1) or (n == 2): result = 1 # this step calls fib for the previous two elements else: result = fib(n-1) + fib(n-2) return result # Memoization: runs above algorithm, with a notebook writting # down every result from fib(n) up to fib(n-1) def fib2(n, memo): if memo[n]: return memo[n] elif n == 0: result = 0 elif (n == 1) or (n == 2): result = 1 else: result = fib(n-1) + fib(n-2) memo[n] = result return result def memo(n): memo = [None] * (n + 1) return fib2(n, memo) def fib_bottom_up(n): if n == 0: return 0 elif (n == 1) or (n == 2): return 1 bottom_up = [None] * (n+1) bottom_up[1] = 1 bottom_up[2] = 1 for i in range(3, n+1): bottom_up[i] = bottom_up[i-1] + bottom_up[i-2] return bottom_up[n]
709639f298ddc5c48143f7d67876bf3bb4da6b3c
gabriellaec/desoft-analise-exercicios
/backup/user_277/ch128_2020_04_01_16_46_26_258715.py
447
3.828125
4
pergunta_1=input("Está se movedo? (n/s)"): if pergunta_1=="n": pergunta_2=input("Deveria estar parado? (n/s)") if pergunta_2=="n": print("WD-40") elif pergunnta_2=="s": print("Sem problemas!) elif pergunta_1=="s": pergunta_3=input("Deveria se mover? (n/s) if pergunta_3=="n": print("Silver tape") elif pergunta_3=="s": print("Sem problemas!")
e5465da977e9c4f77eede9b40fab5cad653dbd7a
pebongue/wtc_bootcamp
/ex1.py
444
4.0625
4
import datetime #method to calculate the year someone turns 100 given their age def your_centenary(age): current_year = datetime.datetime.now().year return current_year + (100 - age) #Ask user for their name and age name = input("what is your name? :") age = abs(int(input("How old are you? :"))) #personal message for when the user turns 100 print("Hello "+name+ "! You will turn 100 in {}.".format(your_centenary(age)))
11ee69ae1175077912fd45a8ee69135e68631da7
bruninhamax/pythonfundamentals
/Exercicios/oldbank.py
2,351
4.0625
4
class ContaBancaria(): def __init__(self, cliente, conta, ag=8, banco=999, saldo=0): self.cliente = cliente self.conta = conta self.ag = ag self.banco = banco self.saldo = saldo def depositar(self): try: deposito = float(input('Digite o valor para depósito: R$ ')) print(f'Saldo anterior: R$ {self.saldo}') print(f'Deposito: R$ {deposito}') self.saldo += deposito print(f'Novo saldo: R$ {self.saldo}') print('-'*20) except ValueError: print('Digite apenas números') print('-'*20) def sacar(self): try: saque = float(input('Digite o valor para saque: R$ ')) if saque <= self.saldo: print(f'Saldo anterior: R$ {self.saldo}') print(f'Saque: R$ {saque}') self.saldo -= saque print(f'Novo saldo: R$ {self.saldo}') print('-'*20) else: print('Saldo insuficiente') print(f'Saldo atual: R$ {self.saldo}') print('-'*20) except ValueError: print('Digite apenas números!') print('-'*20) def extrato(self): print('Extrato') print('=' * 20) print(f'Agência: 0{self.ag} Conta: {self.conta}') print(f'Cliente: {self.cliente}') print(f'Saldo: {self.saldo}') print('-'*20) op = 1 cliente = ContaBancaria(input('Digite o nome do cliente: '), input('Digite o número da conta: ')) print('============== OldBank =============') print('========= Seja bem-vindo(a) ========') while op > 0: try: print('Selecione uma opção:') print('Para fazer um depósito, digite 1') print('Para fazer um saque, digite 2') print('Para ver o extrato, digite 3') print('Para finalizar, digite 0') op = int(input('> ')) if op > 3: raise ValueError elif op == 1: cliente.depositar() elif op == 2: cliente.sacar() elif op == 3: cliente.extrato() except ValueError as t: print('Digite apenas números de 0 a 3') print('-'*20) print(f'Obrigada por usar nosso banco, {cliente.cliente}!')
aca3706c29ca085c9b6603661180ddb53fa28ba8
Hyferion/Leetcode
/zigzagconversion.py
665
3.515625
4
class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s difference = numRows - 1 + numRows - 2 print(difference) new_str = '' k = difference while len(new_str) != len(s): for i in s: print(i) print(k) print(new_str) if k == difference: k = 0 new_str = new_str + i else: k += 1 difference = difference - 1 return new_str sol = Solution() print("Solution: " + sol.convert("PAYPALISHIRING", 3))
b4e9b33b89c83485fe323a39a50c7dbfc4dc66ad
xiaomiaoright/Auto-Price-Prediction
/DataPreparationForModeling.py
6,379
3.9375
4
# Data Visualization Continued # The distribution of the variables and relationship of variablees has been studies in the VisulizationData Part # This document will prepare the data for ML modeling # Load the dataset import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import numpy.random as nr import math %matplotlib inline auto_prices = pd.read_csv('Automobile price data _Raw_.csv') auto_prices.head(20) # Recode Columns Names auto_prices.columns = [str.replace('-', '_') for str in auto_prices.columns] # Treat missing values # Failure to deal with missing values before training a machine learning model will lead to biased training at best """ Deal with Missing Values Remove features with substantial numbers of missing values. In many cases, such features are likely to have little information value. Remove rows with missing values. If there are only a few rows with missing values it might be easier and more certain to simply remove them. Impute values. Imputation can be done with simple algorithms such as replacing the missing values with the mean or median value. There are also complex statistical methods such as the expectation maximization (EM) or SMOTE algorithms. Use nearest neighbor values. Alternatives for nearest neighbor values include, averaging, forward filling or backward filling. """ (auto_prices.astype(np.object) == '?').any() auto_prices.dtypes # the columns with missing values have an object (character) type as a result of using the '?' code # Count missing values for col in auto_prices.columns: if auto_prices[col].dtype == object: count = 0 count = [count + 1 for x in auto_prices[col] if x == '?'] print(col + ' ' + str(sum(count))) #The normalize_losses column has a significant number of missing values and will be removed ## Drop column with too many missing values auto_prices.drop('normalized_losses', axis = 1, inplace = True) ## Remove rows with missing values, accounting for mising values coded as '?' cols = ['price', 'bore', 'stroke', 'horsepower', 'peak_rpm'] for column in cols: auto_prices.loc[auto_prices[column] == '?', column] = np.nan auto_prices.dropna(axis = 0, inplace = True) auto_prices.shape # Transform column data type # five columns in this dataset which do not have the correct type as a result of missing values for column in cols: auto_prices[column] = pd.to_numeric(auto_prices[column]) auto_prices[cols].dtypes ### Feature engineering and transforming variables """ 1. Aggregating categories of categorical variables to reduce the number. 2. Transforming numeric variables to improve their distribution properties to make them more covariate with other variables. Some common transformations include, logarithmic and power included squares and square roots. 3. Compute new features from two or more existing features. interaction terms. """ ## Aggregating categorical variables ## num_of_cylinders Feature auto_prices['num_of_cylinders'].value_counts() # only one car with three and twelve cylinders cylinder_categories = {'three':'three_four', 'four':'three_four', 'five':'five_six', 'six':'five_six', 'eight':'eight_twelve', 'twelve':'eight_twelve'} auto_prices['num_of_cylinders'] = [cylinder_categories[x] for x in auto_prices['num_of_cylinders']] auto_prices['num_of_cylinders'].value_counts() # Check out the box plots of the new cylinder categories def plot_box(auto_prices, col, col_y = 'price'): sns.set_style("whitegrid") sns.boxplot(col, col_y, data=auto_prices) plt.xlabel(col) # Set text for the x axis plt.ylabel(col_y)# Set text for y axis plt.show() plot_box(auto_prices, 'num_of_cylinders') # the price range of these categories is distinctive! Yeah!! ## body_style feature auto_prices['body_style'].value_counts() # hardtop and convertible have a limited number of cases body_cats = {'sedan':'sedan', 'hatchback':'hatchback', 'wagon':'wagon', 'hardtop':'hardtop_convert', 'convertible':'hardtop_convert'} auto_prices['body_style'] = [body_cats[x] for x in auto_prices['body_style']] auto_prices['body_style'].value_counts() # Check out the box plots of the new body_style categories plot_box(auto_prices, 'body_style') # hardtop_convert category does appear to have values distinct from the other body style ## Transforming numeric variables # to make the relationships between variables more linear # to make distributions closer to Normal, or at least more symmetric # logarithms, exponential transformations and power transformations # examine a histogram of the label def hist_plot(vals, lab): ## Distribution plot of values sns.distplot(vals) plt.title('Histogram of ' + lab) plt.xlabel('Value') plt.ylabel('Density') #labels = np.array(auto_prices['price']) hist_plot(auto_prices['price'], 'prices') # price label: skewed to the left and multimodal # no values less than or equal to zero --->> log transformation auto_prices['log_price'] = np.log(auto_prices['price']) hist_plot(auto_prices['log_price'], 'log prices') # The distribution of the logarithm of price is more symmetric ## Examine the relationship between variables after transformation def plot_scatter_shape(auto_prices, cols, shape_col = 'fuel_type', col_y = 'log_price', alpha = 0.2): shapes = ['+', 'o', 's', 'x', '^'] # pick distinctive shapes unique_cats = auto_prices[shape_col].unique() for col in cols: # loop over the columns to plot sns.set_style("whitegrid") for i, cat in enumerate(unique_cats): # loop over the unique categories temp = auto_prices[auto_prices[shape_col] == cat] sns.regplot(col, col_y, data=temp, marker = shapes[i], label = cat, scatter_kws={"alpha":alpha}, fit_reg = False, color = 'blue') plt.title('Scatter plot of ' + col_y + ' vs. ' + col) # Give the plot a main title plt.xlabel(col) # Set text for the x axis plt.ylabel(col_y)# Set text for y axis plt.legend() plt.show() num_cols = ['curb_weight', 'engine_size', 'horsepower', 'city_mpg'] plot_scatter_shape(auto_prices, num_cols) # relationships are more linear with log_price compared with price auto_prices.to_csv('Auto_Data_Preped.csv', index = False, header = True)
55d4999fa6d7650af5c5e9b7e9e35ec2bb4d17ce
KaueGuimaraes/Python-Begin-Exercises
/ex010.py
1,121
4.09375
4
print('========= DESAFIO 010 =========\n') reais = float(input('Digite quantos reais você tem: R$')) dolar = 3.27 resultado = reais / dolar print('\nVocê pode comprar ${:.4} dolares com R${} reais'.format(resultado, reais)) #Na época que eu fiz esse exercício(2018) o dolar valia R$3.27 reais print('\nFIM!!') #Hoje em dia quando eu estou revisando esse meu exercício antigo(final de 2020) o Dolar está valendo R$5.09 reais ''' English Version print('========= CHALLENGE 010 =========\n') reais = float(input('Type how much reais you have: R$')) #Reais = Brazilian money dolar = 3.27 result = reais / dolar print('\nYou can buy ${:.4} dolars with R${} reais'.format(result, reais)) #When I did this exercise(2018) one dolar cost R$3.27 reais print('\nEND!!') #Nowadays when i am reviewing this old exercise(final de 2020) one dolar está costs R$5.09 reais ''' ''' Desafio: Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dolares ela pode comprar. Challenge: Make a program that reads how much reais a people have, and shows how much dolars the user can buy. '''
6833a5845a7cdc5b806658598dd4fd43b3ca5e73
maheshlalu/PythonBasics
/CalculateAreaOfTriangel.py
388
3.984375
4
import random # formula #s = a+b+c/2 # area = √s(s-a)*(s-b)*(s-c) a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) #RANDOM Number print(random.randint(1,9))
57e6061c3e7acaaa32abb8284b9f71e7a66de055
VetoPlayer/TaxSalesApp
/src/main/python/tax/utils.py
239
3.828125
4
from decimal import Decimal, ROUND_UP ROUND_PRECISION='.1' def round_up(num): "Rounds up the given number to match up to the nearest 0.05" return float(Decimal(num * 2).quantize(Decimal(ROUND_PRECISION), rounding=ROUND_UP) / 2)
337913c6b73da1771c453f3017aed23d0e1467e0
Ledz96/ML_Project_1
/Alessandro_funcs/split_data.py
458
3.71875
4
# -*- coding: utf-8 -*- """Exercise 3. Split the dataset based on the given ratio. """ import numpy as np def split_data(x, y, ratio, seed=1): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # split the data based on the given ratio: TODO p = np.random.permutation(len(y)) y = y[p] x = x[p] limit = int(len(y)*ratio) return x[:limit],y[:limit],x[limit:],y[limit:]
99299285c23e906c23ffc4a0306a5eb470c11807
hushaoqi/LeetCode
/70.py
1,719
3.625
4
import math class Solution: # 很明显递归会超出时间限制 def climbStairs(self, n: int) -> int: if n == 1: return 1 if n == 2: return 2 return self.climbStairs(n-1) + self.climbStairs(n-2) # 递归改进 def climbStairs1(self, n: int) -> int: self.res = [0] * (n + 1) return self.helper(n) def helper(self, n: int): if n <= 1: return 1 if self.res[n] > 0: return self.res[n] self.res[n] = self.helper(n - 1) + self.helper(n - 2) return self.res[n] # 一维动态规划,记录前两次的结果 def climbStairs2(self, n: int) -> int: if n <= 1: return 1 dp = [0]*n dp[0] = 1 # 一步台阶 dp[1] = 2 # 两步台阶 for i in range(2, n): dp[i] = dp[i-1] + dp[i-2] return dp.pop() # 进一步优化,我们只用两个整型变量a和b来存储过程值 def climbStairs3(self, n: int) -> int: a = 1 b = 1 while n > 0: b += a a = b - a n -= 1 return a # 神仙操作:分治法 Divide and Conquer 的解法 def climbStairs4(self, n: int) -> int: if n <= 1: return 1 return self.climbStairs4(n // 2) * self.climbStairs4(n - n // 2) + self.climbStairs4(n // 2 - 1) * self.climbStairs4(n - n // 2 - 1) # 神仙操作:通项公式 def climbStairs5(self, n: int) -> int: root5 = math.sqrt(5) return int((1 / root5) * (pow((1 + root5) / 2, n + 1) - pow((1 - root5) / 2, n + 1))) if __name__=='__main__': s = Solution() print(s.climbStairs1(6))
d5a29794d7d461a8f71c73b28ae372f2fd7d4a92
daytonpe/mit-6.00
/ps05/ps5_ghost.py
2,920
4.03125
4
# Problem Set 5: Ghost # Name: # Collaborators: # Time: # import random # ----------------------------------- # Helper code # (you don't need to understand this helper code) import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print('Loading word list from file...') # inFile: file inFile = open(WORDLIST_FILENAME, 'r', encoding='ascii') # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print(" ", len(wordlist), "words loaded.") return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # Actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program. wordlist = load_words() # TO DO: your code begins here! def word_ends_game(word, word_list): if len(word)<4: return False else: if word.lower() in word_list: return True else: return False def word_can_be_formed(word, word_list): for entry in word_list: if word.lower() == entry[0:len(word)]: return True return False def play_game(word_list): print() print() turn = 1; word = '' while (True): if turn%2==1: letter = input("Player 1: ") else: letter = input("Player 2: ") if letter not in string.ascii_letters: print("That's not a letter. Please Try again.") continue turn = turn + 1 word = word+letter if word_can_be_formed(word, word_list)==False: print('GAME OVER! ' +str(word.upper())+' does not start a word') word = '' return 0 print() print(word.upper()) if(word_ends_game(word, word_list)): print('GAME OVER! ' +str(word.upper())+' is a word.') word = '' return 0 def play_ghost(word_list): print() print('GHOST') while True: cmd = input('n: new game\ne: end game\n') if cmd == 'n' or cmd == 'N': play_game(word_list) print() elif cmd == 'e' or cmd == 'E': break else: print("Invalid command.") play_ghost(wordlist)
d0cb3686eae1adc28ea7cd9359da06d561770f83
MichalStachnik/guessingGame
/guessingGame.py
824
4.09375
4
#Small guessing game, play the computer to see if you can guess from random import randint #TODO - make a case for 0 correct & input validation def game(): computer_digits = [str(randint(0,9)), str(randint(0,9)), str(randint(0,9))] print("computers numbers: ") print(computer_digits) isTrue = True while isTrue: user_guess = list(input("What is your guess? ")) i = 0 numCorrect = 0 for compdigit in computer_digits: if compdigit == user_guess[i]: numCorrect += 1 if numCorrect == 3: print("You won!") isTrue = False i += 1 if numCorrect == 1: print("Just one, try again") elif numCorrect == 2: print("Close, almost there!") game()
9f162668d8aa7c72adcedd01b2a2317a34a0c34f
yunzc/cv_notes
/part1.py
3,625
3.890625
4
# Yun Chang CV notes part 1 # Edge detections and Hough transform import cv2 import numpy as np """ Edge detection is done by calculating the gradient then thresholding the calculated gradient and keeping the places where the gradient is above a certain value. In other words, edges are where there are significant change in pixel value (talking gray-scale) where the significance is determined by coder. The often used Canny filter Gaussian filters the picture before gradient calculation -> but by linear properties (associative) it turns out to be just filtering with the derivative of the gaussian. Canny: 1. filter with derivative of gaussian 2. threshold to find significant gradient area 3. thinning (find the maximum in a local area) 4. linking (if there are weak pixels linking strong pixels: edge) most common kernel used to find gradient (discrete): Sobel """ # img = cv2.imread('stata.jpg') # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # # arg Canny(image, low_thresh, high_thresh, sobel_kernel_size) # edges = cv2.Canny(gray,100,200,5) # cv2.imshow('edges', edges) # cv2.waitKey(0) """ Hough transform is based on the concept of voting: easiest way to think about it is such: let's say the normal space is x y space, now we can characterize each line by d the closest distance from line to origin, and theta the angle between d and the x axis. x*cos(theta) + y*sin(theta) = d; now we define a Hough space of d and theta. A line in xy space is now a point in Hough space, and a point in Hough space is now sinusoids. So we take each points in the edge image, "plot" them in Hough space, and find the intersections to the sinusoids (the maximums) to find the points that define lines in xy space. """ # # implementation with cv2.HoughLines # lines = cv2.HoughLines(edges,1,np.pi/180,175) # # arg: (edge_img, d accuracy, theta accuracy, threshold) # img1 = img # for i in range(len(lines)): # for rho,theta in lines[i]: # a = np.cos(theta) # b = np.sin(theta) # x0 = a*rho # y0 = b*rho # x1 = int(x0 + 1000*(-b)) # y1 = int(y0 + 1000*(a)) # x2 = int(x0 - 1000*(-b)) # y2 = int(y0 - 1000*(a)) # cv2.line(img1,(x1,y1),(x2,y2),(255,0,0),5) # print(x1,y1,x2,y2) # cv2.imshow('HoughLines', img1) # cv2.waitKey(0) # to implement this from scratch, create array and discretize line to points. Add to an index of array everytime # a line "hits" the point --> then find those above threshold # probabilistic Hough Line transform: HoughLinesP """ Similar idea for a circle: for each point vote for the points along the circle around the point with a certain radius (but this time have to iterate over different radii): polling, find max """ # implementation with cv2.HoughCircles img2 = cv2.imread('pool.jpg') gray2 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) gray2 = cv2.medianBlur(gray2, 5) circles = cv2.HoughCircles(gray2,cv2.HOUGH_GRADIENT,1,20, param1=200,param2=45,minRadius=0,maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0,:]: # draw the outer circle cv2.circle(img2,(i[0],i[1]),i[2],(0,255,0),2) # draw the center of the circle cv2.circle(img2,(i[0],i[1]),2,(0,0,255),3) cv2.imshow('detected circles',img2) cv2.waitKey(0) """ Generalized Hough transform for arbitrary shape First, generate the Hough table. Go around boundary of shape, pick a reference point, and store the displacement indexed by the angle. Sometimes for one angle there might be multiple displacements, just store all in table. The on subject image, go backwards and vote. (get lines usually)
f7dc87b190c64eb2b1f9c5671230ee424f0ae865
chickenLags/imageRecognition-old-
/learning1.py
1,052
3.84375
4
# learning how to use openCV in this document. import cv2 import numpy as np import matplotlib.pyplot as plt # this imports an image and the argument makes it grayscale. # not specifying arg2 makes it read it as a colored image but # it removes the alpha channel. grayscale is prefered since its # simpler / easier. (less channels, less processing) img = cv2.imread('roy.jpeg', cv2.IMREAD_GRAYSCALE) #IMG_GRAYSCALE -> 0 #IMREAD_COLOR -> 1 #IMRED_UNCHANGED -> -1 ''' # this code creates a window where arg0 is the window title and # arg1 is the image used. waitkey, waits for a key and destroy, closes it. cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() ''' ''' # shows the image with matplotlib. it also allows for drawing / plotting # on the image. imshow will be the prefered way though. plt.imshow(img, cmap='gray', interpolation='bicubic') plt.plot([50, 100], [80,100], 'c', linewidth=5) plt.show() ''' ''' # this saves the image to the root directory cv2.imwrite('roygray.png', img) '''
236e0b6f19a5915afeb9a44a7739cb27342be98c
kliner/leetcode
/239.py
1,053
3.546875
4
import collections class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ q = collections.deque() ans = [] for i, num in enumerate(nums): if len(q) == 0 or num > q[-1]: q.clear() q.append(num) else: if num < q[0]: q.appendleft(num) else: while num > q[0]: q.popleft() q.appendleft(num) if i >= k and q[-1] == nums[i-k]: q.pop() if i >= k-1: ans.append(q[-1]) return ans if __name__ == '__main__': test = Solution() print test.maxSlidingWindow([1,3,2,1,0,5], 3) print test.maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3) print test.maxSlidingWindow([1,5,2,3,4,3,2,1], 3) print test.maxSlidingWindow([1,-1], 1) print test.maxSlidingWindow([-7,-8,7,5,7,1,6,0], 4)
4b2f1bd834b6ea2fd67ac8ad3e6b016670ef95d4
warmslicedbread/mini-projects
/kindergarten-garden/kindergarten_garden.py
1,046
3.8125
4
class Garden: def __init__(self, diagram, students = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]): self.diagrams = diagram.split("\n") self.students = students def plants(self, student): all_plants = [] plant_names = [] name_index = self.students.index(student) for diagram in self.diagrams: all_plants.append(diagram[name_index*2: name_index*2 + 2]) for row in all_plants: for plant in row: plant_names.append(self.plant_name(plant)) return plant_names def plant_name(self, letters): for letter in letters: if letter == "G": return "Grass" elif letter == "C": return "Clover" elif letter == "R": return "Radishes" else: return "Violets" classroom = Garden("VCRRGVRG\nRVGCCGCV", students=["Samantha", "Patricia", "Xander", "Roger"]) print(classroom.plants("Xander"))
9e1143e7f05f92b61f83423e060cc13c8b5ae7ae
Sai-Sindhu-Chunduri/Python-programs
/oddpositioned.py
143
4.3125
4
#Program to print all odd positioned characters in a string. s=input() for i in range(len(s)): if i%2!=0: print(s[i],end=" ")
75589ffd8aa2ce4911b1c69e4e49565e164ea054
justinzuo/myp
/day2/myljust.py
487
3.78125
4
if __name__ == '__main__': num = "10" nb = num.rjust(10,"-") print(nb) for i in range(1,10) : nstr = "" for j in range(1,i+1) : nstr="{0}*{1}={2}".format(j,i,i*j) print("{0}*{1}={2}".format(j,i,i*j).rjust(8,"-"),end=" ") print("\n") print("-------------------------------------------") for i in range(1,101) : num = str(i) print(num.rjust(3,"-"),end=" ") if i%10==0 : print("\n")
1aec65af10c743b52981fe20ae5bf2909d5681d2
fengbaoheng/leetcode
/python/257.binary-tree-paths.py
1,229
3.828125
4
# # @lc app=leetcode.cn id=257 lang=python3 # # [257] 二叉树的所有路径 # # https://leetcode-cn.com/problems/binary-tree-paths/description/ # # algorithms # Easy (57.36%) # Total Accepted: 6.8K # Total Submissions: 11.8K # Testcase Example: '[1,2,3,null,5]' # # 给定一个二叉树,返回所有从根节点到叶子节点的路径。 # # 说明: 叶子节点是指没有子节点的节点。 # # 示例: # # 输入: # # ⁠ 1 # ⁠/ \ # 2 3 # ⁠\ # ⁠ 5 # # 输出: ["1->2->5", "1->3"] # # 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 # # # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if root is None: return [] if root.left is None and root.right is None: return [str(root.val)] results = [] for p in self.binaryTreePaths(root.left): results.append(str(root.val)+"->"+p) for p in self.binaryTreePaths(root.right): results.append(str(root.val)+"->"+p) return results
886c52e2478b292f1c6a96820afb50e01b973154
PurpleMyst/porcupine
/porcupine/plugins/autoindent.py
1,867
3.75
4
"""Indenting and dedenting automatically.""" # without this, pressing enter twice would strip all trailing whitespace # from the blank line above the cursor, and then after_enter() wouldn't # do anything setup_before = ['rstrip'] from porcupine import get_tab_manager, tabs, utils def leading_whitespace(string): r"""Return leading whitespace characters. Ignores trailing '\n'. >>> leading_whitespace('\t \t lel') '\t \t ' >>> leading_whitespace(' \n') ' ' """ count = len(string) - len(string.lstrip()) return string[:count].rstrip('\n') def after_enter(textwidget): """Indent or dedent the current line automatically if needed.""" lineno = int(textwidget.index('insert').split('.')[0]) prevline = textwidget.get('%d.0 - 1 line' % lineno, '%d.0' % lineno) textwidget.insert('insert', leading_whitespace(prevline)) # we can't strip trailing whitespace before this because then # pressing enter twice would get rid of all indentation # TODO: make this language-specific instead of always using python stuff prevline = prevline.strip() if prevline.endswith((':', '(', '[', '{')): # start of a new block textwidget.indent('insert') elif (prevline in {'return', 'break', 'pass', 'continue'} or prevline.startswith(('return ', 'raise '))): # must be end of a block textwidget.dedent('insert') def on_new_tab(event): if isinstance(event.data_widget, tabs.FileTab): textwidget = event.data_widget.textwidget def bind_callback(event): textwidget.after_idle(after_enter, textwidget) textwidget.bind('<Return>', bind_callback, add=True) def setup(): utils.bind_with_data(get_tab_manager(), '<<NewTab>>', on_new_tab, add=True) if __name__ == '__main__': import doctest print(doctest.testmod())
812c4e08f0d0786062b2ee3476a4c68cebbdbf3b
ThiaudioTT/EmbaralhadordePalavras
/embaralhadordepalavras.py
2,131
3.84375
4
from time import sleep def traco(): #uso estilístico# print("-"*50) def banner(): traco() print("Bem vindo ao embaralhador de palavras!;)") traco() #menu def menu(): while True: try: option = int(input("\nVocê deseja:\n\n[1] Inverter palavras de trás pra frente\n[2] Embaralhar palavras\n[3] Inverter palavras (espelho)\nOpcão: ")) except ValueError: traco() print("\nERRO: Escolha uma OPÇÃO entre 1 e 2.\n") except: print("ERRO: ") raise else: if option <= 3: return option elif option > 2: traco() print("Escolha uma opção entre 1 e 2.\n") #inverte(de tras pra frente) palav def dtf(palavras): palavras.reverse() print("\nSeu texto de trás pra frente:\n") for p in palavras: print("{} ".format(p), end = "") print("\n") traco() #embaralha def embaralhar(palavras): from random import shuffle shuffle(palavras) print("\nSeu texto:\n") for p in palavras: print("{} ".format(p), end = "") print("\n") traco() #programa def main(): print("Bem vindo ao embaralhador de palavras! ;)") while True: # #fazer o banner aqui option = menu() # try: # palavras = str(input("Digite as palavras: ").lower()).split() # except ValueError: # print("\nApenas letras são permitidas! (por enquanto)\n") # except: # print("Erro: ") # raise if option == 1: palavras = str(input("Digite as palavras: ").lower()).split() dtf(palavras) sleep(3) elif option == 2: palavras = str(input("Digite as palavras: ").lower()).split() embaralhar(palavras) sleep(3) elif option == 3: palavras = str(input("Digite as palavras: ").lower()) print("\n{}\n".format(palavras[::-1])) traco() sleep(3) #executa if __name__ == "__main__": main()
7c2925e2cb6839af355d5d0b443ed56104d048ca
cleitonkn/CursoemVideo
/Desafio018.py
171
3.9375
4
import math x = int(input('\nDigite um angulo qualquer: ')) print('\nO seno de {}° é {}'.format(x, math.sin(x))) print('\nO coseno de {}° é {}'.format(x, math.cos(x)))
ef666432d78f2b2979e3efc44fb62229206e8fba
MaksimKatorgin/module17
/task9.py
705
4.09375
4
#Дан вот такой (уже многомерный!) список: #nice_list = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]] #Напишите код, который «раскрывает» все вложенные списки, то есть оставляет только внешний список. #Для решения используйте только list comprehensions. #Ответ: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] nice_list = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]] flat = [num for row in nice_list for row_i in row for num in row_i] print('Ответ: ', flat)
0a586eca0a737597811b32f35aad18af299f768d
jayjanodia/LeetCode
/Medium/82. Remove Duplicates from Sorted List II/Solution.py
2,165
3.75
4
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head): # Node to handle the case in case we just have one root node and the elements after that are all the same as the root node sentinel = Node(0, head) # Predecessor node that will always be a distinct value pred = sentinel while head: if head.next and head.val == head.next.val: while head.next and head.val == head.next.val: head = head.next pred.next = head.next else: pred = pred.next head = head.next return sentinel.next # Directly Implementable Solution # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: # Creating a sentinel node # This node is for handling the case where we just have the same number in the linked list # eg 9-->9-->9-->null sentinel = ListNode(0, head) # Create a predecessor node that will act as the last node before the sublist of duplicates # comes in pred = sentinel while head: # if the current node value and the next node value are the same, then while the current #value and the next value are the same, keep going to the next node if head.next and head.val == head.next.val: while head.next and head.val == head.next.val: head = head.next # Point the predecessor node to the next node, so now the predecessor node is linked to a new node value pred.next = head.next # Else if the current node value and the next node value are not the same then go to the next value in the linked list. else: pred = pred.next head = head.next return sentinel.next
6d939f1a3890db50e130817a4cb52ae7b9854664
unicorn111/Battelship_lab1
/field/field_to_str.py
953
3.96875
4
import read_file def field_to_str(): '''(list) -> (str) Converts list into str and writes it in a file 0 is for ' ' 1 is for '*' 2 s for 'X' ''' board = read_file.read_file('field.txt') board_str1 = "" board_str = [] for i in board: if 0 in i: board_str1 += " " elif 1 in i: board_str1 += "*" elif 2 in i: board_str1 += "X" for i in range(0, 91, 10): board_str.append(board_str1[i:i + 10]) print('Do you want to see a field here', end='') print(' or you want to write it in a file field1.txt?') control = int(input('Print 1 to see a field or 2 to write in a file ')) if control == 1: for i in board_str: print(i) elif control == 2: with open('field1.txt', 'w') as file: for i in board_str: file.write(i + '\n') else: print('You are cheating!') field_to_str()
f764c0be326457a1290e872b77a0a89827e5351a
Xalitor/Gilyazor_Emil
/lesson_04/Rectangle.py
263
4.09375
4
def perimeter(): return((lenght + width)*2) def display(): print("Your rectangle is {:.5f} square feet".format(perimeter())) lenght = float(input("Please, enter rectangle's leght " )) width = float(input("Please, enter rectangle's width " )) display()
47bbb47a7eb3bb23ca8c9e3ea1df3e86999e969b
VMBailey/Ops301
/ops-301d3Challenge11.py
646
3.625
4
# Script Name: Python File Handling # Author: Vincent Bailey # Date of Latest Revision: 9/14/2021 # Purpose: This script writes a haiku into a text file, prints the first # line into the user's terminal and then deletes the text file. from os import remove newfile = open("newtextfile.txt", "w") newfile = open("newtextfile.txt", "a") newfile.write("A dance of salt and sweet, \n") newfile.write("Betwixt two mountains of yeast. \n") newfile.write("The Fountain of Youth.") print ("A dance of salt and sweet,") remove("newtextfile.txt")
eb944658df0d7b0dbab779983cc4c4dbc2641ffb
Keerthijan3/NBA-Analytics
/AnalyzeHeightWeight.py
2,119
3.609375
4
''' This script will output plots based on player heights and weights over the years. This can shed some insight how the ideal bodytype of NBA players has changed over the years To filter by player position, pass it in as an argument. Positions are C, SG, PF, SF, PG ''' import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from PIL import Image def Plot(x, y, title, filename, ylabel): ''' Function to create plots and save ''' fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111) ax.plot(x, y, color="#d1ae45") ax.set_facecolor("#2E2E2E") ax.set_title(title, fontsize=16) ax.set_xlabel('Year', labelpad=15, fontsize=12) ax.set_ylabel(ylabel, labelpad=15, fontsize=12) plt.grid(True, color="#93a1a1", alpha=0.1) plt.savefig(filename) plt.close() players = pd.read_pickle('Data/Players.pkl') seasons = pd.read_pickle('Data/Seasons_Stats.pkl') try: pos = sys.argv[1] seasons = seasons[seasons['Pos'] == pos] naming = "( " + pos + " )" except: pos = "" naming = "" height_arr = list() weight_arr = list() year = list() stddevh = list() stddevw = list() for i in range(1950, 2018): season_players = seasons[seasons['Year'] == i] season_players = season_players['Player'].values player_data = players.loc[players['Player'].isin(season_players)] heights = player_data['height'].values weights = player_data['weight'].values height_arr.append(np.mean(heights)) weight_arr.append(np.mean(weights)) stddevh.append(np.std(heights)) stddevw.append(np.std(weights)) year.append(i) Plot( year, height_arr, 'Avg Height vs Year for NBA Players' + naming, pos+'heightvsyear.png', 'Height(cm)' ) Plot( year, stddevh, 'Height Std. Dev. vs Year for NBA Players' + naming, pos+'heightstdvsyear.png', 'Height (cm)' ) Plot( year, stddevw, 'Weight Std. Dev. vs Year for NBA Players' + naming, pos + 'weightstdvsyear.png', 'Weight (kg)' ) Plot( year, weight_arr, 'Avg Weight vs Year for NBA Players' + naming, pos + 'weightvsyear.png', 'Weight (kg)' )
4c8d3b6ddc0559780ea0c478e7ee1a16b9a7b259
shashanka-adiga/Algorithims-and-datascrtures
/LinkedList/MergeSortedLL.py
1,381
4.0625
4
class LinkedList: def __init__(self, data): self.value = data self.next = None def append(self, head, data): if head is None: head = LinkedList(data) temp = head while temp.next is not None: temp = temp.next new_node = LinkedList(data) new_node.next = None temp.next = new_node def merge(self, head1, head2): fake = LinkedList(-1) last = fake while head1 is not None and head2 is not None: if head1.value < head2.value: last.next = head1 last = head1 head1 = head1.next else: last.next = head2 last = head2 head2 = head2.next if head1 is None: last.next = head2 if head2 is None: last.next = head1 return fake.next def print_list(self, head): if head is None: return temp = head while temp is not None: print(temp.value, end=' ') temp = temp.next head1 = LinkedList(6) head1.append(head1, 8) head1.append(head1, 10) head2 = LinkedList(1) head2.append(head2, 7) head2.append(head2, 9) head2.append(head2, 11) head2.append(head2, 13) ref = head2.merge(head1, head2) head1.print_list(ref)
b8f45dfb5a1a1612f195c424525c3aa55032ce2f
G-itch/Projetos
/Ignorância Zero/050Exercício1.py
507
3.78125
4
txt = input("Digite algo:") txt2 = input("Digite novamente: ") def find(): global txt,txt2 for i in range(len(txt)+1 - len(txt2)): meh = False if txt[i:i+len(txt2)] == txt2: print("OK BOOMER") break else: meh = True if meh: print("Meh") def index(): global txt,txt2 lista = [] for i in range(len(txt)+1 -len(txt2)): if txt[i:i+len(txt2)] == txt2: lista.append(i) print(lista) find() index()
4d680e19b164f498b237e8ab77cbfaebb2f4b4f9
abreens/sn
/les11/unsuccessfulguesses.py
3,549
4.03125
4
##### # # Les 11 - Add unsuccessful guesses # # Every good game needs to store the best score, so that you can try to best it. # # During the game, collect user's unsuccessful guesses and then store them in the dictionary # under the name "wrong_guesses". Hint: you can store a list in a dictionary. ;) ##### # Nodige external packages importeren import random import json import datetime # FUNKTIE - Inlezen van een geheel getal tussen 1 en 30 def lees_geheel(): while True: invoer = input("\nGuess the secret number (between 1 and 30): ") try: getal = int(invoer) except ValueError: print("Jammer genoeg was dit geen (geheel) getal. Probeer aub opnieuw...") else: if 1 <= getal <= 30: print("Dit was een correcte invoer! Wij analyseren nu het resultaat...") # De lus breken break else: print("Het getal moet tussen 1 en 30 liggen. Probeer aub opnieuw...") return getal # FUNKTIE - Inlezen van de naam van de speler def lees_naam(): while True: name = input("Wat is Uw naam? ") # Empty strings return False! if not name: print("Naam mag niet leeg zijn. Gelieve opnieuw Uw naam in te voeren.\n") else: print("Dat was een correcte invoer. We gaan verder met het spel...\n") # De lus breken break return name # 1. Initialisaties secret = random.randint(1, 30) attempts = 0 dts = str(datetime.datetime.now()) # dts = Date Time Stamp wrong_guesses = [] # 2. Welcome print("Dit is het 'Guess the Secret Number' spel!\n") # 3. Naam van de speler inlezen naam = lees_naam() print("Welkom, " + naam + "!\n") # 4. De huidige top scores uitlezen en afdrukken with open("score_list.txt", "r") as score_file: score_list = json.loads(score_file.read()) # Empty lists return False if not score_list: print("Er zijn nog geen top scores opgeladen!") else: print("De huidige top scores zijn:") for score_dict in score_list: print("On " + score_dict.get("date") + ", player " + score_dict.get("speler") + " needed " + str(score_dict.get("attempts")) + " attempts to guess the secret number " + str(score_dict.get("secret")) + ". Wrong guesses were: " + str(score_dict.get("wrong_guesses"))) # 5. Een geheim getal tussen 1 en 30 raden while True: guess = lees_geheel() attempts += 1 # Het antwoord analyseren if guess == secret: print("\nYou've guessed it - congratulations! It's number " + str(secret)) print("Attempts needed: " + str(attempts)) print("Dit waren Uw verkeerde keuzes: ", wrong_guesses) # De score_list.txt file updaten en wegschrijven score_list.append({"attempts": attempts, "date": dts, "speler": naam, "secret": secret, "wrong_guesses": wrong_guesses}) with open("score_list.txt", "w") as score_file: score_file.write(json.dumps(score_list)) # De lus breken break # Het getal werd niet geraden. Tips voor de speler meegeven. elif guess > secret: print("Sorry, your guess is not correct... Try something smaller") else: print("Sorry, your guess is not correct... Try something bigger") # De huidige guess dynamisch opslaan in lijst wrong_guesses wrong_guesses.append(guess) # 6. Afscheid print("\nBedankt voor het spelen. Hope to see you soon...")
f8151429d7d6f1352e5d5a8d0a70b27abaeaaabd
tnGithub069/tsuneSite
/app001_projectManagement/process/C050_StringUtil.py
671
3.59375
4
""" 共通クラス C050_StringUtil セッション関連の共通メソッドを格納する """ def isNull(_str_): result = False if _str_ == None: result = True return result def isEmpty(_str_): result = False if _str_ == None or _str_ == "": result = True return result def isAllSpace(_str_): result = False if _str_ == None or _str_ == "": result = True else: _str_.replace(" ","") _str_.replace(" ","") if _str_ == "": result = True return result def isSameCharacter(str1,str2): result = False if str1 == str2: result = True return result
0de56e3e4336ff020956282e9cb6a1fbd4d0324c
weitaishan/PythonPractice
/Base/Finished/Test32.py
336
3.703125
4
# *_*coding:utf-8 *_* ''' 题目:按相反的顺序输出列表的值。 ''' list = [32, 'name', '土豆',999, 110] #方法一 ''' for i in range(1, len(list)+1): print(list[len(list)-i], end =" ") ''' #方法二 list.reverse() # 注意:reverse()方法是修改列表,而不是返回一个新的列表 print(list)
2e486f52ebb15be5c213789aab954adebfc2948a
hrz123/algorithm010
/Week08/知识性/python实现归并排序.py
16,933
3.625
4
# python实现归并排序.py from typing import List class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums: List[int], l: int, r: int): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) self.merge(nums, l, mid, r) def merge(self, nums, l, mid, r): res = [0] * (r - l + 1) i, j, k = l, mid + 1, 0 while i <= mid and j <= r: if nums[i] < nums[j]: res[k] = nums[i] i += 1 else: res[k] = nums[j] j += 1 k += 1 if i <= mid: res[k:] = nums[i:mid + 1] else: res[k:] = nums[j:r + 1] nums[l:r + 1] = res def merge1(self, nums, l, mid, r): res = nums[l:r + 1] i, j, k = l, mid + 1, 0 while i <= mid and j <= r: if nums[i] < nums[j]: res[k] = nums[i] i += 1 else: res[k] = nums[j] j += 1 k += 1 if i <= mid: res[k:] = nums[i:mid + 1] nums[l:r + 1] = res # 以下为自我练习 class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums: List[int], l: int, r: int): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) self.merge(nums, l, mid, r) def merge(self, nums, l, mid, r): res = [0] * (r - l + 1) i, j, k = l, mid + 1, 0 while i <= mid and j <= r: if nums[i] < nums[j]: res[k] = nums[i] i += 1 else: res[k] = nums[j] j += 1 k += 1 if i <= mid: res[k:] = nums[i:mid + 1] else: res[k:] = nums[j:r + 1] nums[l:r + 1] = res class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) self.merge(nums, l, mid, r) def merge(self, nums, l, mid, r): cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] < nums[j]: cache[c] = nums[i] i += 1 c += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] i += 1 c += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums: List[int], l: int, r: int): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums: List[int], l: int, r: int): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums: List[int], l: int, r: int): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums: List[int], l: int, r: int): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): return self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] += nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + ((r - l) >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + (r - l >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + (r - l >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) i, c = l, 0 cache = [0] * (r - l + 1) for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums: List[int]): return self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + (r - l >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + (r - l >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l:r + 1] = cache class Solution: def mergeSort(self, nums): self.mergeSortHelper(nums, 0, len(nums) - 1) def mergeSortHelper(self, nums, l, r): if l >= r: return mid = l + (r - l >> 1) self.mergeSortHelper(nums, l, mid) self.mergeSortHelper(nums, mid + 1, r) cache = [0] * (r - l + 1) i, c = l, 0 for j in range(mid + 1, r + 1): while i <= mid and nums[i] <= nums[j]: cache[c] = nums[i] c += 1 i += 1 cache[c] = nums[j] c += 1 while i <= mid: cache[c] = nums[i] c += 1 i += 1 nums[l: r + 1] = cache def main(): sol = Solution() nums = [3, 2, 4, 1, 5] sol.mergeSort(nums) print(nums) nums = [3, 2] sol.mergeSort(nums) print(nums) nums = [5] sol.mergeSort(nums) print(nums) nums = [] sol.mergeSort(nums) print(nums) if __name__ == '__main__': main()
8490a028b499891eca56d1a66a3262d534d7f014
goelhardik/programming
/leetcode/clone_graph/bfs_sol.py
1,249
3.9375
4
# Definition for a undirected graph node # class UndirectedGraphNode(object): # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution(object): def cloneGraph(self, node): """ :type node: UndirectedGraphNode :rtype: UndirectedGraphNode """ if (node == None): return None copies = {} queue = [] source_copy = UndirectedGraphNode(node.label) copies[node] = source_copy queue.append(node) """ Solve using BFS. If a node has been visited, then it will have a copy in the map. So if the copy is there, we just need to update the current node's neighbors. Otherwise we create a copy and add the node to the map. """ while (len(queue) > 0): node = queue.pop(0) copy = copies[node] for neighbor in node.neighbors: if neighbor not in copies: neighbor_copy = UndirectedGraphNode(neighbor.label) copies[neighbor] = neighbor_copy queue.append(neighbor) copy.neighbors.append(copies[neighbor]) return source_copy
bb38954cba7e551b79c11a511455e784e62fa83c
marcosjrvrael/airflowsandbox
/source/python/src/simplefunction.py
735
3.75
4
import argparse import logging def get_count(input_str: str) -> int: """ Função responsável por fazer a contagem de vogais em uma palavra """ num_vowels = 0 lista = [i for i in input_str if i in 'aeiou'] num_vowels = len(lista) return num_vowels def run (word: str) -> None: logging.info(f'Vowels count: {get_count(word)}') if __name__ == '__main__': logger = logging.getLogger() logger.setLevel(logging.INFO) parser = argparse.ArgumentParser() parser.add_argument( '--word', type=str, help='Word to have vowels count', required=True ) args = parser.parse_args() logging.info(f"Execution arguments: {args}") run(args.word)
8b0a8af9b8787cce3abb69447ee297359fd4e64d
18sby/python-study
/vippypython/chap9/demo14.py
530
3.71875
4
# 字符串的编码转换 s = '春风不动柳如纱' # 编码 # 在 GBK 编码中,一个中文占两个字节 print(s.encode('GBK')) # b'\xb4\xba\xb7\xe7\xb2\xbb\xb6\xaf\xc1\xf8\xc8\xe7\xc9\xb4' # UTF-8 中,一个中文占三个字节 print(s.encode(encoding='UTF-8')) # 解码 # byte 代表的就是一个二进制数据 print(s.encode('GBK').decode(encoding="GBK")) print(s.encode('UTF-8').decode(encoding="utf-8")) # print(s.encode('GBK').decode(encoding="UTF-8")) # 解不了,编码格式和解码格式要相同
d8ae6403657e71ac9e6c0539983af43273332c3d
gme5k/advanced-heuristics
/Oude Algoritmes/randomNewAlgorithm.py
2,520
3.71875
4
import random from nationLoader import * from visualization import * Russia = nationLoader("TXT/Russia.txt") def randomNewAlgorithm(nation): ''' NOG NIET AF Start with 'truly' random province ''' options = [1, 2, 3, 4, 5, 6, 7] # Select random province from nation firstRandom = random.choice(nation.keys()) firstNeighbors = nation[firstRandom][0] rand = random.choice(options) #low = min(options) nation[firstRandom][1] = rand print "Random province is", firstRandom, "and its neighbors are", firstNeighbors print "Its transmitter nr is", nation[firstRandom][1] print "-------------------" # Iterate over neighbors and assign valid transmitters def assignNeighborTransmitters(province): neighbors = nation[province][0] # Remove own transm from options try: options.remove(nation[province][1]) except ValueError: print "Probably already removed" for neighbor in neighbors: LocalOptions = options[:] print "transmitterOptions:", options #neighborTransmitter = nation[neighbor][1] print "Neighbor is", neighbor, "and", neighbor, "'s neighbors are", nation[neighbor][0] # Find common neighbors commonNeighbors = set(neighbors) & set(nation[neighbor][0]) print "Common neighbors are ", commonNeighbors # Remove transmitters of adjacent neighbors from options for commonNeighbor in commonNeighbors: print commonNeighbor, "transmitter:", nation[commonNeighbor][1] if nation[commonNeighbor][1] in options and nation[commonNeighbor][1] != 0: try: LocalOptions.remove(nation[commonNeighbor][1]) except ValueError: print "Probably already removed" print "tranmitterOptionsLocal:", LocalOptions rand = random.choice(LocalOptions) #lowest = min(LocalOptions) # Assign random from transmitterOptions if nation[neighbor][1] == 0: nation[neighbor][1] = rand print neighbor, "; transmitter assigned:", nation[neighbor][1], "\n" #checkNeigborsOfNeighbor(firstRandom) assignNeighborTransmitters(firstRandom) print "Continue with: ", random.choice(firstNeighbors) return nation randomNewAlgorithm(Russia) colorNation(Russia, "Russia")
d4e3d1490a77c8a2481b663e06ad180613839dec
andrecrocha/Fundamentos-Python
/Fundamentos/Aula 14 - Laço de repetição While/exercicio57.py
514
4.25
4
""" Desafio 57. Faça um programa que leia o sexo de uma pessoa e só aceite 'M' ou 'F'. Peça o sexo até que a pessoa digite um sexo válido """ sex = input("Escreva o seu sexo. Só M e F são válidos: ").upper().strip()[0] # o zero só pega a primeira letra da palavra while sex not in "MF": print("Código inválido. Tente novamente") sex = input("Escreva o seu sexo. Só M e F são válidos: ").upper().strip()[0] # o zero só pega a primeira letra print("Sexo registrado com sucesso! Obrigado!")
0099063a412795fd2c1a067dfd4cb2f1d55db23a
ianhom/Python-Noob
/Note_3/Example_100.py
171
3.96875
4
#!/bin/usr/python # -*- coding: UTF-8 -*- ''' 题目:列表转换为字典。 ''' i = ['a', 'b'] l = [1, 2] print dict([i,l]) # Result ''' {'a': 'b', 1: 2} '''
10eb11b4bfe4e0e892a7ffae2ac4f1f18d4ab876
Glittering/pythonLearn
/jinYuan/doWork/3_15_赵士诚/figer_guessing_game.py
438
3.90625
4
#!/usr/bin/python3 #coding:utf-8 import random def compare(enter): com_enter=random.choice([1,2,3]) if com_enter == enter: print 'same' elif com_enter == enter+1 or com_enter == 1 and enter == 3: print 'you lose,the computer is{}'.format(com_enter) else: print 'you won,the computer is{}'.format(com_enter) while(1): enter = input('enter,1,2,3 for 剪刀,石头,布') compare(enter)
1dd47d6c09f6b2b52d4c5cab1d845eaa7f7db928
AlekEl/Python-Game-statistics-reports
/reports.py
3,499
3.578125
4
# Report functions def open_file(file_name): """Opens the file and returns content in form of a list""" try: with open(file_name, "r") as f: content = f.readlines() content = [game for game in content if game] content = [game.split("\t") for game in content] return content except FileNotFoundError as err: raise err def count_games(file_name): """Returns number of lines in a file (games)""" content = open_file(file_name) return len(content) def decide(file_name, year): """Returns True if there is a game from given year in a file. Otherwise returns False""" if type(year) != int: raise ValueError("Not a valid year") content = open_file(file_name) for game in content: if str(year) in game: return True return False def get_latest(file_name): """Returns title of the latest game in the file""" content = open_file(file_name) game_name = content[0][0] game_year = int(content[0][2]) latest = [game_name, game_year] for game in range(1, len(content)): game_name = content[game][0] game_year = int(content[game][2]) if latest[1] < game_year: latest[0] = game_name latest[1] = game_year return latest[0] def count_by_genre(file_name, genre): """Returns the number of games from given genre from the file""" if type(genre) != str: raise TypeError("Invalid genre") content = open_file(file_name) genre_index = 3 count = 0 for game in content: if genre.lower() == game[genre_index].lower(): count += 1 return count def get_line_number_by_title(file_name, title): """Returns the number of line of a given game(title) from the file""" if type(title) != str: raise TypeError("Invalid title") content = open_file(file_name) title_index = 0 titles = [game[title_index] for game in content] try: line = titles.index(title) + 1 except ValueError as err: raise err return line def quick_sort(lst): """Sorting algorithm""" if not lst: return [] return (quick_sort([x for x in lst[1:] if x < lst[0]]) + [lst[0]] + quick_sort([x for x in lst[1:] if x >= lst[0]])) def sort_abc(file_name): """Sort and return title list""" content = open_file(file_name) title_index = 0 arr = [game[title_index] for game in content] arr = quick_sort(arr) return arr def get_genres(file_name): """Return sorted genre list without duplicates""" content = open_file(file_name) genre_index = 3 genres = list(set([game[genre_index] for game in content])) genres = quick_sort(genres) return genres def when_was_top_sold_fps(file_name): """Return year of a top selling fps game""" content = open_file(file_name) copies_sold_index = 1 year_index = 2 genre_index = 3 best_selling_fps = [] for game in content: if game[genre_index] == "First-person shooter": if len(best_selling_fps) == 0: best_selling_fps = [float(game[copies_sold_index]), game[year_index]] elif best_selling_fps[0] < float(game[copies_sold_index]): best_selling_fps = [float(game[copies_sold_index]), game[year_index]] if len(best_selling_fps) == 0: raise ValueError("No fps game in the file") return int(best_selling_fps[1])
d0ec407d9985fbe8980c6644a27142b3de883e58
Anju-PT/pythonfilesproject
/collections/list/length.py
365
3.78125
4
lst=[10,20,30,40,50,60,70,80,90,100] #len #print(len(lst)) print("there are {0} items".format(len(lst))) #sorted ls=[6,7,3,9,10,5,4,2,1] print(sorted(ls)) # ls=sorted(ls) # st=0 # st=ls[::-1] # print(st) ls.sort(reverse=True) print(ls) words=["big","Blue","seven","glass","Green","anju","Antartica"] print(sorted(words)) words.sort(key=str.lower) print(words)
bc1a7c95557df44fd8b140d6f5ec54f4bb02096e
clevercoderjoy/tik_tak_toe
/tik_tak_toe.py
8,784
4.09375
4
# idea # we need a board to play the game # a function to display the board # a function to play the game # a function to ask what player 1 wants, i.e. 'x' or 'o' # a funtion to handle turn # a funtion to take input from user # a funtion to check if input is valid or not # a function to display the updated values on the board after every turn # a funtion to switch between players # a function to keep taking turns until the game is over # a function to check game status # a function to check rows # a function to check columns # a function to check diagonals # a function to check if game is tie # a function to display winner # a function to clear board #=================================Global Variables============================= #variable to hold bool value on if game is still being played or not game=True #variable to hold the player which is the winner winner=None #variable to check if the player wants to play again or not replay=True #variable to check if the game is a tie or not tie=False #variable to take position where the 'x' or 'o' will be placed on the board as an input position_input=None #variable to hold the current player current_player=None #game board board=['-', '-', '-', '-', '-', '-', '-', '-', '-'] #a function to display board def display_board(): #an empty line for neater look print() #printing the elements of the board print(board[0] + ' | ' + board[1] + ' | ' + board[2]) print(board[3] + ' | ' + board[4] + ' | ' + board[5]) print(board[6] + ' | ' + board[7] + ' | ' + board[8]) print() #a function to play the game def play(): #calling the global variables global current_player global game global tie #displaying the board before starting the game display_board() #checking who wants to go first current_player=input("Who wants to go first? x or o:\n") #valid choices of pieces to be played valid_list=['x', 'X', 'o', 'O'] #checking if player entered a valid choice while current_player not in valid_list: print("Invalid choice. Try again.") #calling the function to play the game again if player enters an invalid choice play() while game: #calling the function to handle each turn handle_turn() #calling the function to check if players want to play the game again play_again() #a function to handle turn def handle_turn(): #calling the function to take input from the player take_input() #calling the function to update the game board update_board() #calling the function to check status of the game check_status() #calling the function to display the game board display_board() #calling the function to switch between player 1 and player 2 switch_players() #taking input from the player def take_input(): #calling the global variables global position_input #taking input from the current player position_input=int(input("Enter a position between 1-9: ")) #switching to actual position on the board #position_input-=1 #calling the function to check if the position input is valid or not check_valid_input() #a function to check if input is valid or not def check_valid_input(): #calling the global variables global position_input #a list containing all the valid inputs allowed for entering the positions valid_input=[1,2,3,4,5,6,7,8,9] if position_input not in valid_input: print("Invalid choice. Try again.") take_input() #calling the function to check if the position is already taken or not position_already_taken() #updating game board def update_board(): #calling the global variables global position_input global current_player #updating the board with current player's coice board[position_input-1]=current_player #a function to check if the position on the board is already taken or not def position_already_taken(): #calling the global variables global position_input global current_player if board[position_input-1]!='-': print("This position is already taken. Enter a position that is not taken.") take_input() #a function to switch between players def switch_players(): #calling the global variables global current_player if current_player=='x' or current_player=='X': current_player='o' else: current_player='x' #a function to check game status def check_status(): #calling the global variables global tie #calling function to check for winner if any check_winner() if winner!=current_player and tie==False: #calling function to check if the game is a tie check_tie() #a function to chech if the game is a tie def check_tie(): #calling the global variables global tie global game if '-' not in board: tie=True game=False print("\nThis match is a tie.") #a function to check winner def check_winner(): #calling the global variables global game #calling the function to check if there is a winner in any of the rows check_rows() #calling the function to check if there is a winner in any of the columns check_columns() #calling the function to check if there is a winner in any of the diagonals check_diagonals() #condition to check if there is a winner or not if winner==current_player: #setting win status to true game=False #calling the function to display the winner if there is a winner display_winner() #a function to display winner def display_winner(): #calling the global variables global current_player print("\n"+current_player.capitalize()+ " is the winner.") #a function to check rows def check_rows(): #calling the global variables global game global winner row_1=board[0]==board[1]==board[2] !='-' row_2=board[3]==board[4]==board[5] !='-' row_3=board[6]==board[7]==board[8] !='-' if row_1 or row_2 or row_3: game=False if row_1 or row_2 or row_3: winner=current_player #a function to check columns def check_columns(): #calling the global variables global game global winner column_1=board[0]==board[3]==board[6] !='-' column_2=board[1]==board[4]==board[7] !='-' column_3=board[2]==board[5]==board[8] !='-' if column_1 or column_2 or column_3: game=False if column_1 or column_2 or column_3: winner=current_player #a function to check diagonals def check_diagonals(): #calling the global variables global game global winner diagonal_1=board[0]==board[4]==board[8] !='-' diagonal_2=board[2]==board[4]==board[6] !='-' if diagonal_1 or diagonal_2: game=False if diagonal_1 or diagonal_2: winner=current_player #a function to clear the board def clear_board(): board[0]='-' board[1]='-' board[2]='-' board[3]='-' board[4]='-' board[5]='-' board[6]='-' board[7]='-' board[8]='-' #a function to check if players wants to play again or not def play_again(): #calling the global variables global replay #terminal message print("Do you want to play again?\n") #a variable to hold player's choice if they want to play again or not choice=input("Enter 'Y' or 'y' for yes and 'n' or 'N' for no:\n") #checking if valid choice entered play_choice=['Y', 'y', 'N', 'n'] while choice not in play_choice: print("Invalid choice. Try again.\n") #if invalid choice is entered then the same function is called again to take the correct input play_again() #checking if the players want to play again or not if choice=='y' or choice=='Y': replay=True else: replay=False #game is being played until the player enteres 'n' on 'N' while replay: #setting the choice variable as none to remove previous entries choice=None #calling the function to clear the board to start a new game clear_board() #calling the function to reset the global values before starting a new game reset() #function is called to play the game again play() #a function to reset the values for a new game def reset(): #calling the global variables global game global winner global replay global tie global position_input global current_player game=True winner=None replay=False tie=False position_input=None current_player=None #calling the function to play the game play()
d65d8ae0cbdc34e2b63c3edf56cae9abc9876135
CArielSanchez/CC5114-Redes-Neuronales
/Sigmoid/sigmoid.py
1,330
3.78125
4
import numpy as np from random import randint import math #Create a perceptron: #opcional weigth,bias and lr(weigth of learning) class Sigmoid: def __init__(self,w=[],b=0,lr=0.1): self.w=w self.b=b self.lr=lr self.large=len(w) def set_lr(self,lr): self.lr=lr def set_b(self,b): self.b=b def set_w(self,w): self.w=w #Set a perceptron on ramdom values #large: large of the input recived for the perceptron. def random_init(self,large): self.large=large w=[] for x in range(0,large): w.append(randint(-2,2)) b = (randint(-2,2)) self.set_b(b) self.set_w(w) #Ejecuta un perceptron #input: data recived by the perceptron def run(self,input): #Multiplica el input con sus pesos w_mult_input= np.multiply(self.w,input) sumatory= sum(w_mult_input) + self.b r = 1/(1 + math.exp(-sumatory)) return r #Algoritm of learning #real_output: ouput real #disered_output: output disered #input: data recived by the perceptron def learn(self,real_output,disered_output,input): diff=disered_output-real_output self.w = np.add(self.w , (np.array(input) * self.lr * diff)) self.b= self.b + (self.lr * diff)
90888e8bfc8ff868072e2e1db11a49f37f64e5f6
anoop123gupta/saral_debugging_code
/more_exercise/exercise9.py
175
3.625
4
x=int(raw_input("Enter a number ")) y=list(str(x)) s=0 for i in range(len(y)): s=s+int(y[i]) if x%s==0: print x,"harshad number hai" else: print x,"harshad number nahi hai"
ea1bca34a821b2617f4e4ed7e467f99f0861a897
sandysql05/Python
/Certification 2/Files/Assignment7.py
395
3.59375
4
#filename=input("enter file name:") #fhand= open(filename,'r') fhand= open('Assignment72.txt','r') cnt=0 total=0.00 for line in fhand: if line.startswith('X-DSPAM-Confidence:'): value = float(line[len('X-DSPAM-Confidence:'):len(line)].strip()) cnt=cnt+1 total=total+value print('Average spam confidence:', total/cnt) #print(line.rstrip().upper())
e6dc56afa4414aaf765a2ecc588488d2ab650a35
dimasiklrnd/python
/highlighting numbers, if, for, while/Queen's move.py
1,259
3.5
4
'''Шахматный ферзь может ходить на любое число клеток по горизонтали, по вертикали или по диагонали. Даны две различные клетки шахматной доски, определите, может ли ферзь попасть с первой клетки на вторую одним ходом. Для простоты можно не рассматривать случай, когда данные клетки совпадают. Формат входных данных Программа получает на вход четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки, потом для второй клетки. Формат выходных данных Программа должна вывести YES, если из первой клетки ходом ферзя можно попасть во вторую. В противном случае - NO''' x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if abs(x1 - x2) == abs(y1 - y2) or x1 == x2 or y1 == y2: print('YES') else: print('NO')
4a9d631ae5f9291b5977b089198e80fce31ed4af
pbaranay/hearthstone-stars
/hearthstone_stars.py
3,534
4.15625
4
""" Hearthstone is a popular online collectible card game (CCG). One of its play modes, Ranked, features a monthly progression where users earn "stars" and advance up a ladder of "ranks," usually striving to reach the ultimate rank, Legend. Winning a game nets you a star, while losing a game usually results in losing a star. Winning several games in a row generally merits an extra star. This program simulates how many games a player needs to play in order to reach Legend, given a particular average win rate. Other configuration variables can be specified as well, although the defaults match Hearthstone's standard implementation. """ from collections import OrderedDict import math import random import statistics def build_star_map(): """ The star map is a dictionary that translates how many total stars you have into a rank. """ # total number of stars: rank d = OrderedDict() ranks = range(1, 26) # The range [1, 25]; i.e. the numbers 1 to 25, inclusive. ranks.reverse() num_stars = 0 stars_per_rank = 2 d[0] = 25 for current_rank in ranks: # At rank 20, 15, and 10, the number of stars per rank increases by 1. if current_rank in [20, 15, 10]: stars_per_rank += 1 for _ in xrange(stars_per_rank): num_stars += 1 d[num_stars] = current_rank d[num_stars+1] = 0 # Legend return d def play_game(win_rate): """ Returns True if win, False otherwise. """ return random.random() < win_rate DEFAULT_RANK_FLOORS = (25, 20, 15, 10, 5) def climb_to_legend( win_rate, start_stars=0, no_streaks_above_rank=5, rank_floors=DEFAULT_RANK_FLOORS ): """ Use a random number generator to simulate how many games are needed to reach Legend. :param win_rate: How likely the player is to win an individual game. :param start_stars: How many stars the player begins with. :param no_streaks_above_rank: The rank at which players no longer receive an extra star for a win streak. :param rank_floors: Once a player passes one of these ranks, they cannot fall back below it, even with multiple losses. :return: The number of simulated games played. :rtype: int """ star_map = build_star_map() current_stars = start_stars star_rank_floors = [min(k for k, v in star_map.items() if v == floor) for floor in rank_floors] no_streaks_above = min(k for k, v in star_map.items() if v == no_streaks_above_rank) wins_in_row = 0 games = 0 legend = star_map.keys()[-1] while current_stars < legend and games < 5000: games += 1 if play_game(win_rate): wins_in_row += 1 if wins_in_row >= 3 and current_stars < no_streaks_above: current_stars += 2 else: current_stars += 1 else: wins_in_row = 0 if current_stars not in star_rank_floors: current_stars -= 1 return games def simulate(n, *args, **kwargs): average = statistics.mean(climb_to_legend(*args, **kwargs) for _ in xrange(n)) return average if __name__ == "__main__": print("Welcome to the Hearthstone Legend Climb Simulator!") while True: win_rate = input("What is your average win rate? (Example: 0.5) ") avg = int(math.ceil(simulate(100, win_rate))) print("With a win rate of {}, it will take an average of {} games to reach Legend.".format( win_rate, avg ))