blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
aae78a1e1218f831fcb47fda26413f9705393c56
RichieSong/algorithm
/算法/分治/pow.py
1,088
3.96875
4
# -*- coding: utf-8 -*- # 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 # # 示例 1: # # 输入: 2.00000, 10 # 输出: 1024.00000 # # # 示例 2: # # 输入: 2.10000, 3 # 输出: 9.26100 # # # 示例 3: # # 输入: 2.00000, -2 # 输出: 0.25000 # 解释: 2-2 = 1/22 = 1/4 = 0.25 # # 说明: # # # -100.0 < x < 100.0 # n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 # # Related Topics 数学 二分查找 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float 1、递归 时间复杂度O(n) 代码忽略 2、分治(递归) 时间复杂度log(n) """ if n < 0: x = 1 / x n = -n return self.Pow(x, n) def Pow(self, x, n): if n == 0: return 1.0 half = self.Pow(x, n / 2) return half * half * x if n & 1 == 1 else half * half if __name__ == '__main__': s = Solution() print(s.myPow(2, -10))
74b8ad12cda25ee78b388d59be7aa22645e23550
rpsmith77/PythonForEverybody
/CH10_Exercise1.py
1,160
4.59375
5
# Ryan Smith # Python for Everybody Coursera # Exercise 1: Revise a previous program as follows: Read and parse the # “From” lines and pull out the addresses from the line. Count the number of # messages from each person using a dictionary. After all the data has been # read, print the person with the most commits by creating a list of (count, # email) tuples from the dictionary. Then sort the list in reverse order and # print out the person who has the most commits. f = open(input("Enter file name: ")) emailAddresses = {} for line in f: if line.startswith("From"): splitLine = line.split() emailAddress = splitLine[1] if emailAddress in emailAddresses: emailAddresses[emailAddress] += 1 else: emailAddresses[emailAddress] = 1 listOfTuples = [] for key, value in emailAddresses.items(): listOfTuples.append((key, value)) # cite: https://www.geeksforgeeks.org/python-program-to-sort-a-list-of # -tuples-by-second-item/ For showing me how to sort a list of tuples by the # second item in the tuple listOfTuples.sort(key=lambda x: x[1], reverse=True) print(*listOfTuples[0]) f.close()
ab8b31b22d065b834ae9e8e3ee33548202553428
gustmtofoli/DeepLearning
/lesson1/softmax.py
507
3.609375
4
import numpy as np import matplotlib.pyplot as plt # Using python3.6 scores = [3.0, 1.0, 0.2] # transforms the scores into probabilities def softmax(x): return np.exp(x) / np.sum(np.exp(x), axis = 0) x = np.arange(-2.0, 6.0, 0.1) scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)]) # print("scores: ", scores) scores_mult_10 = scores*10 scores_div_10 = scores/10 print("softmax: ", softmax(scores_div_10)) # plot a graphic plt.plot(x, softmax(scores_div_10).T, linewidth = 2) plt.show()
02cfe8d62938103c0bcb88873f128bc43f1c89d6
THUEishin/Exercies-from-Hard-Way-Python
/exercise3/ex3.py
302
4.15625
4
''' This exercise is to show easy operations between numbers. Nmaely, +, -, /, *, %, <, >, <=, >= ''' print("I will now count my chickens:") print("Hens",25+30/6) print("Roosters",100-25*3%4) print("How I will count the eggs:") print(3+2+1-5+4%2-1/4+6) print("Is it true that 3+2 < 5-7?", 3+2<5-7)
4bf31451f4b95815625493c17ccefdfa626f471a
DevanshSoni/Projects-on-Python
/Package Based Bank Application/Auth.py
1,549
3.59375
4
import os import json import time def sign_up(): os.system('cls') user_name=input("Enter User_Name") password=input("Enter Password") balance=int(input("Enter Initial Amount")) acc_no=None data=os.listdir('Bank') if data==[]: acc_no='1000' # Assign 1000 if there is no records in the history else: acc_no=str(int(max(data))+1) # otherwise increment to the next account Number data={'name':user_name,'Balance':balance,'Password':password} fp=open(f'Bank/{acc_no}','w') json.dump(data,fp) print("User Successfully Added") print(f"Your Account Number {acc_no} and Password {password}, needed at the time of login") fp.close() time.sleep(2) return True #Will return True after Successful Signing Up def login(id,password): data=os.listdir('Bank') if id in data: fp=open(f'Bank/{id}','r+') value=json.load(fp) if value['Password']==password: fp.close() return True #Return True if right password entered by the user else: fp.close() print("You've entered wrong password please try again!!!") return False #Return False if password is wrong else: print("No Such Record Exist Prefer Doing sign up") return False # Return False if user does not exists
da2ab8b944c469917752835185d397070600dc7c
shen-huang/selfteaching-python-camp
/19100202/nathanye/d4_exercise_control_flow.py
412
3.859375
4
# -*- coding: UTF-8 -*- # Filename : 9*9 table # author by : Nathanye # 九九乘法表 for i in range(1,10): # i 代表行数 for j in range(1,i+1): # j 代表列数 product=i*j print("%d*%d=%2d\t" % (i,j,i*j),end="") print () r=1 # r 代表行数 while r<10: c=1 # c 代表列数 while c<=r: print("%d*%d=%d\t" % (r,c,r*c),end="") c+=1 print() r+=2
d0557013f36be6f548917895a0cdb5b30820b33f
BRIANHG89/Python-Exercises-
/condicionalcompuesta/notasalumno.py
564
4
4
""" Confeccionar un programa que pida por teclado tres notas de un alumno, calcule el promedio e imprima alguno de estos mensajes: Si el promedio es >=7 mostrar "Promocionado". Si el promedio es >=4 y <7 mostrar "Regular". Si el promedio es <4 mostrar "Reprobado". """ nota1=int(input("Ingrese primera nota:")) nota2=int(input("Ingrese segunda nota:")) nota3=int(input("Ingrese tercera nota:")) prom=(nota1+nota2+nota3)/3 if prom>=7: print("Promocionado") else: if prom>=4: print("Regular") else: print("Respaldo")
715842ad8a37259ad9170257a66bf2d9dbda16d5
TorchAblaze/spooky_manor
/spooky_manor2.py
6,804
3.65625
4
from room import Room import locations def show_help(): print(""" HOW TO PLAY: Enter a verb (such as: 'take/get', 'drop', 'talk', 'kill', 'light', 'wear', 'use', 'enter/exit', 'go (direction)', 'north', 'south', 'east', 'west', 'up/down', 'shake', 'open', 'examine', 'eat', 'drink', 'give', 'read', 'play', 'look') and a noun that you would like to interact with. Enter 'inventory' to view your inventory. Enter 'score' to view your point total. Enter 'location' to view your current location. Enter 'help' for this help. Enter 'save' to save the game. Enter 'quit' to exit the game. """) ending = "Enter 'quit' to quit, enter 'save' to save or enter 'restart' to restart the game." # victory(end): # print("\nYou leave behind the manor and its secrets--another job well done.\nPerhaps one day you may pay another visit to Lord Spooky and Manfred,\nbut until then, only in your darkest dreams and nightmares will you return... \n\nto Spoooky Manor!\n\nTHE END.") # return end # points += 5 GATE = Room( "Gate", locations.GATE_COMMANDS, locations.GATE_INTRO ) FRONT_DOOR = Room( "Front Door", locations.FRONT_DOOR_COMMANDS, locations.FRONT_DOOR_INTRO ) VESTIBULE = Room( "Vestibule", locations.VESTIBULE_COMMANDS, locations.VESTIBULE_INTRO ) GREAT_HALL = Room( "Great Hall", locations.GREAT_HALL_COMMANDS, locations.GREAT_HALL_INTRO ) DINING_ROOM = Room( "Dining Room", locations.DINING_ROOM_COMMANDS, locations.DINING_ROOM_INTRO ) LOUNGE = Room( "Lounge", locations.LOUNGE_COMMANDS, locations.LOUNGE_INTRO ) KITCHEN = Room( "Kitchen", locations.KITCHEN_COMMANDS, locations.KITCHEN_INTRO ) DARK_CELLAR = Room( "Dark Cellar", locations.DARK_CELLAR_COMMANDS, locations.DARK_CELLAR_INTRO ) rooms = { 1: GATE, 2: FRONT_DOOR, 3: VESTIBULE, 4: GREAT_HALL, 5: DINING_ROOM, 6: LOUNGE, 7: KITCHEN, 8: DARK_CELLAR, # 9: Library(), # 10: SecretStudy(), # 11: BilliardRoom(), # 12: Conservatory(), # 13: Garden(), # 14: ReflectingPool(), # 15: HedgeMaze(), # 16: Graveyard(), # 17: FamilyCrypt(), # 18: Hallway(), # 19: Attic(), # 20: ServantsQuarters(), # 21: MasterSuite(), } game_name = "SPOOKY MANOR" print(f"\nWELCOME TO:\n{game_name}...") show_help() player_location = 1 points = 0 print(rooms[player_location].intro) while True: room_name = rooms[player_location] command = input("\n > ").upper() try: result = room_name.commands if type(result[command]) == dict: for key, value in result[command].items(): if key == "restriction in": if value in locations.inventory: print(result.get(command)["message1"]) elif value not in locations.inventory: print(result.get(command)["message2"]) player_location = result.get(command)["new location"] room_name = rooms[player_location] print(room_name.intro) continue elif key == "restriction out": if value not in locations.inventory: print(result.get(command)["message1"]) elif value in locations.inventory: print(result.get(command)["message2"]) player_location = result.get(command)["new location"] room_name = rooms[player_location] print(room_name.intro) continue elif key == "message": print(result.get(command)["message"]) elif key == "points": points += result.get(command)["points"] elif key == "add": if value not in locations.inventory: locations.inventory.append(value) elif value in locations.inventory: print("You already have that.") elif key == "remove": if value in locations.inventory: locations.inventory.remove(value) elif value not in locations.inventory: print("You don't have that.") elif key == "location": player_location = result.get(command)["location"] room_name = rooms[player_location] print(room_name.intro) continue elif command in result.keys(): print(result[command]) continue except KeyError as err: if command == 'HELP': show_help() continue elif command == 'SCORE': print("Score:", points) continue elif command == 'INVENTORY': for item in locations.inventory: print(item) continue elif command == 'SAVE': pass # Find way to save game elif command == 'LOOK': print(room_name.intro) continue elif command == 'QUIT': break elif command == 'LOCATION': room_name.print_location() continue elif command == 'RESTART': restart = input("Are you sure you want to restart the game? ('yes' or 'no')\n > ") if restart == 'YES': pass # Find a way to restart the game else: continue else: print("Hmm, I'm not sure what you mean. Please enter a verb and a noun to interect with your surroundings.") continue # class JoesPlace: # NORTH = { # "message": "You've gone north. You fool!", # "points": 2, # "location": 5 # } # commands = { # "GO NORTH": NORTH, # "GO UP": NORTH, # "LOOK FOR LAPTOP": { # "message": "You find a laptop. Now you have to do work. -5 points", # "points": -5 # } # } # # commands = { # # "GO NORTH": Command("You've gone north. You fool!", 2, 5), # # "LOOK FOR LAPTOP": Command("You find a laptop. Now you have to do work. -5 points", -5) # # } # # commands = [ # # Command(["GO NORTH", "GO UP"], "You've gone north. You fool!", 2, 5) # # ] # class Command: # def __init__(self, acceptable, message, points, location = 0): # self.message = message # self.points = points # self.location = location # self.acceptable_commands = acceptable # def match(self, input): # if input in self.acceptable_commands: # return True
c231ecd1858dc2968eec28b71e9d1aa557f7dd7b
gjq91459/mycourse
/15 Inheritance/01_inheritance.py
948
3.96875
4
############################################################ # # Inheritance # ############################################################ class Point: def __init__(self, x, y): self.x = x self.y = y def WhereAmI(self): print "Point(%i) is at %i,%i" % (id(self), self.x, self.y) def MoveBy(self, dx, dy): self.x += dx self.y += dy class ColoredPoint(Point): def __init__(self, x, y, color): Point.__init__(self, x, y) self.color = color def ChangeColor(self, newColor): self.color = newColor def Display(self): self.WhereAmI() print " ... and color is %s" % self.color def WhereAreYou(p): p.WhereAmI() p = Point(5,8) cp = ColoredPoint(15,25,"Blue") p.WhereAmI() cp.Display() cp.ChangeColor("Cyan") cp.MoveBy(5,15) cp.Display() WhereAreYou(p) WhereAreYou(cp)
9b08560ae55ee50e918e156d0040148204b7b7ed
nlpet/codewars
/Fundamentals/weird_string_case.py
776
4.21875
4
""" Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased. The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' '). """ def to_weird_case(string): wc = lambda p: p[1].upper() if p[0] % 2 == 0 else p[1] res = [] for word in string.split(" "): res.append("".join(list(map(wc, zip(range(len(word)), word.lower()))))) return " ".join(res)
46ff97c15baeaf88e3c399f9e404438a389d578e
kdveleva/SoftUni
/Python_Fundamentals/Dictionaries_Exercise/10. SoftUni Exam Results.py
951
3.546875
4
from collections import defaultdict results = defaultdict(int) submissions = defaultdict(list) while True: commands = input() if commands == "exam finished": break if "banned" in commands: command = commands.split('-') results.pop(command[0]) continue command = commands.split('-') username = command[0] language = command[1] points = int(command[2]) submissions[language].append(username) if username in results: if results[username] > points: continue else: results[username] = points else: results[username] = points results = dict(sorted(results.items(), key=lambda x: (-x[1], x[0]))) submissions = dict(sorted(submissions.items(), key=lambda x: (-len(x[1]), x[0]))) print("Results:") for k, v in results.items(): print(f'{k} | {v}') print('Submissions:') for k, v in submissions.items(): print(f'{k} - {len(v)}')
867c8f171a6d4f3e44e9dc4a40edbd244015affa
414190799/Yelp_Fake_reviews
/neuralnetwork.py
1,374
4
4
# coding: utf-8 # !/usr/bin/python3 """ Authors: Jiajun Bao, Meng Li, Jane Liu Classes: NN: Accepts the preprocessed data and trains a Multilayer Perceptron (MLP) classifier. Reports the accuracy of the MLP model. """ import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPClassifier from sklearn.preprocessing import StandardScaler class NN: #import the train dataset and validate dataset after feature generating def __init__(self,train,val): self._train = train self._val= val def train(self): dataMat = np.array(self._train) #assign x and y X=dataMat[:,1:-1] y = dataMat[:,0] #standarize and transform data scaler = StandardScaler() scaler.fit(X) X = scaler.transform(X) #train the model. hidden_layer_sizes=(50,20) which will get best results clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(50,20), random_state=1) clf.fit(X, y) #test the model valMat = np.array(self._val) X2=valMat[:,1:-3] y2 = valMat[:,0] scaler = StandardScaler() scaler.fit(X2) X2 = scaler.transform(X2) #return the accuracy result print("Neural Network accuracy score: ", clf.score(X2,y2))
4ded34b5d6c59a3c4a66981d583217ce9cdef85b
CSC-510-Team-31/CSC_510-Team-31_HW2345
/src/sym.py
697
3.5
4
import math from print import o class Sym: def __init__(self, c, s): self.n = 0 self.at = c or 0 self.name = s or "" self._has = {} def __repr__(self): return o({"at": self.at, "n": self.n, "name": self.name}) def add(self, v, nums = None, rand = None): if v == "?": return self.n += 1 self._has[v] = 1 + (self._has[v] if v in self._has else 0) def mid(self): most = -1 for k, v in self._has.items(): if v > most: mode, most = k, v return mode def div(self): def fun(p): return p * math.log(p, 2) e = 0 for n in self._has.values(): if n > 0: e -= fun(n / self.n) return e
992ca855937b774bae369131e60ffa7411c32a4a
bristolplodder/perudo
/throws.py
662
3.671875
4
import random #def int(): # x = random.randrange(1,6) # print(x) #int() #x, y, z = random.randrange(1,6), random.randrange(1,7), random.randrange(1,3) #print(x, y, z) def list(): ## player = [1,2,3] dice = [4,3,2] for cc in player: print("player "+str(cc)) #for bb in dice: for aa in range (0,dice[cc-1]): x = random.randrange(1,6) print(x) ## for x in player: ## print("player " + str(x)) ## for x in range(1, 11): ## for y in range(1, 11): ## print('%d * %d = %d' % (x, y, x*y)) ## z = random.randrange(1,6) ## print(z) ## print (" ") ## list()
a8c778c77066981d067e931b1e2d750107c6a8c1
jinurajan/Datastructures
/array/longest_common_suffix.py
855
3.953125
4
# -*- coding: utf-8 -*- def longest_common_suffix(string1, string2): if not string1 or not string2: # if either of one becomes null string return "" return "" st1, str1 = string1[-1], string1[:-1] st2, str2 = string2[-1], string2[:-1] if st1 == st2: # if the first element of each string is equal append to the result recursively return longest_common_suffix(str1, str2) + st1 else: # if they are not equal return "" # result_1 = longest_common_suffix(string1, str2) # result_2 = longest_common_suffix(str1, string2) # if len(result_1) > len(result_2): # return result_1 # else: # return result_2 if __name__ == "__main__": line = "CornField,outField " str1, str2 = line.strip().split(",") print longest_common_suffix(str1, str2)
6fec3ad707eee73c36b8d4c40c52fae0e6dde9a0
zhaochuanshen/leetcode
/Binary_Tree_Postorder_Traversal.py
868
4
4
''' Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. ''' # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): stack1 = [] stack2 = [] if not root: return stack1 stack1.append(root) while len(stack1) >0: current = stack1.pop() stack2.append(current.val) if current.left: stack1.append(current.left) if current.right: stack1.append(current.right) stack2.reverse() return stack2
ffd824831f7f99524d63178bea1b858a19dcc5af
naye0ng/Algorithm
/OnlineCodingTest/Midas/test03.py
1,398
3.734375
4
import copy # 가득 차있는 값 고르기 def findFull(board) : count = 0 for b in board : if sum(b) == len(b) : count +=1 return count def solution(block, board): answer = 0 if block == 0 : dy = [0,0,0] dx = [0,-1,-2] elif block == 1 : dy = [0,-1,-2] dx = [0,0,0] elif block == 2 : dy = [0,-1,-1] dx = [0,0,-1] elif block == 3 : dy = [0,0,-1] dx = [0,-1,0] elif block == 4 : dy = [0,0,-1] dx = [0,-1,-1] elif block == 5 : dy = [0,0,1] dx = [0,-1,-1] n = len(board) for x in range(n-1,-1,-1) : for y in range(n-1,-1,-1) : copy_board = copy.deepcopy(board) t = 0 for i in range(3) : if x+dx[i] >= n or x+dx[i] < 0 : break if y+dy[i] >= n or y+dy[i] < 0 : break if copy_board[x+dx[i]][y+dy[i]] == 0 : t += 1 if t == 3 : for i in range(3) : copy_board[x+dx[i]][y+dy[i]] = 1 count = findFull(copy_board) if answer == 0 or answer < count : answer = count return answer print(solution(0,[[1,0,0,0],[1,0,0,1],[1,1,0,1],[1,1,0,1]]))
74f851af2f32364e808334251921617ff8216dc6
tronghieu60s/python-dsa
/05_Queue/01_Static_Array_Queue/Queue.py
755
3.78125
4
class Queue: def __init__(self, maxSize): self.head = self.tail = -1 self.arr = [None] * maxSize def full(self): return self.tail == len(self.arr) - 1 def empty(self): return self.head == -1 def enqueue(self, value): if(self.full()): raise Exception("Full Queue!") if(self.empty()): self.head += 1 self.tail += 1 self.arr[self.tail] = value def dequeue(self): if(self.empty()): raise Exception("Empty Queue!") temp = self.arr[self.head] self.arr[self.head] = None if(self.head == self.tail): self.head = self.tail = -1 else: self.head += 1 return temp
d817a928197870c7c373ca17fad170a3232667d9
yshanstar/Leetcode_Shan_Python
/SwapNodesinPairs.py
620
3.71875
4
class ListNode: def __init__(self, x): self.val = x self.next = None class SwapNodesinPairs: def swapPairs(self, head): if head is None: return None if head.next is None: return head helper = ListNode(0) helper.next = head prev = helper cur = head while (cur is not None) and (cur.next is not None): tmp = cur.next.next cur.next.next = prev.next prev.next = cur.next cur.next = tmp prev = cur cur = prev.next return helper.next
a0fdd573551c3ab2b282d3b552730d5761f68f1e
chrisfischer/DontBuyMe
/predictionAPI.py
4,945
3.734375
4
import csv import random import math import operator import sys import argparse import json # Capital One Hackathon 1/11/2018 # hard coded cost prediction based on last 3 months of stock growth information def findCostMarketInvestment(cost, timeReference, determinantFundData, balance, interest, payment): data = [] days = int(timeReference) beforeInterest = getInterest(balance, interest, payment) afterInterest = getInterest(balance+itemCost, interest, payment) netInterest = afterInterest-beforeInterest with open(determinantFundData, 'r',encoding="utf8") as listing_file: csv_reader = csv.reader(listing_file) # creating list for line in csv_reader: stockPrice = line[1] date = line[0] data.append([stockPrice,date]) dataRecent = data[1:days] # print(dataRecent) percentGrowth = (float(dataRecent[0][0]) - float(dataRecent[len(dataRecent) -1][0])) / float(dataRecent[len(dataRecent) -1][0]) print("percent growth: " + str(percentGrowth)) print("Cost of the item based on 70 day percent growth of " + determinantFundData +" index fund") # print((float(cost) * percentGrowth) + cost ) return { "realCost": round((float(cost) * percentGrowth) + cost + netInterest,2), "interest": round(netInterest,2), "investmentReturn": round((float(cost) * percentGrowth),2)} # Determining cost of good based off of interest rate of credit card def getInterest(balance, interest, payment): total = 0; while(balance>0): balance=balance-payment if (balance<=payment): balance=0 balance= balance + balance*(interest/100/12) total += balance*(interest/100/12) return round(total,2) def getDate(date): # date: 2017-01-01 #print(date) year = int(date[2:4]) #print(year) month = int(date[5:7]) #print(month) day = int(date[8:]) #print(day) return [year, month, day] def getDatefromStock(date): #print(date) month = date[:2] monthLength=2 #print(month) if (month[1]=='/'): month=month[0] monthLength=1 #print(month) month=int(month) day = date[monthLength+1:monthLength+3] dayLength=2 #print(day) if (day[1]=='/'): day = day[0] dayLength=1 #print(day) day = int(day) year = int(date[(monthLength+dayLength+2):]) return [year, month, day] def actualRealCost(itemCost, purchaseDate, currentDate, stockData, balance, interest, payment): purchaseDate = getDate(purchaseDate) #print(purchaseDate) curDate = getDate(currentDate) #SUBJECT TO CHANGE #print(curDate) beforeStockPrice=0 afterStockPrice=0 counter=0; with open(stockData, 'r', encoding="utf8") as listing_file: csv_reader = csv.reader(listing_file) for line in csv_reader: if (line[0]=='date'): continue stockDate = getDatefromStock(line[0]) #print(stockDate) if (stockDate[0]>=purchaseDate[0] and stockDate[1]>=purchaseDate[1] and stockDate[2]>=purchaseDate[2]): beforeStockPrice = float(line[1]) if (afterStockPrice==0): for line in csv_reader: afterStockPrice=float(line[1]) break if (stockDate[0]>=curDate[0] and stockDate[1]>=curDate[1] and stockDate[2]>=curDate[2]): afterStockPrice = float(line[1]) rate = (afterStockPrice-beforeStockPrice)/beforeStockPrice beforeInterest = getInterest(balance, interest, payment) afterInterest = getInterest(balance+itemCost, interest, payment) netInterest= afterInterest-beforeInterest return { "realCost": round(rate*itemCost+itemCost+netInterest ,2), "interest":round(netInterest,2), "investmentReturn":round(rate*itemCost,2)} # handler for findCostMarketInvestment def findCostMarketInvestment_handler(event, context): # TODO implement print(json.dumps(event)) body = json.loads(event['body']) response = { "statusCode": 200, "isBase64Encoded": False, "headers": {}, "body": json.dumps({ "opportunityCost": findCostMarketInvestment(float(body['cost']),float(body['timeReference']),body['determinantFundData'], float(body['balance']), float(body['interest']), float(body['payment']) ) }) } return response # handler for actualRealCost def actualRealCost_handler(event, context): # TODO implement body = json.loads(event['body']) response = { "statusCode": 200, "isBase64Encoded": False, "headers": {}, "body": json.dumps({ "opportunityCost": actualRealCost(float(body['itemCost']),body['purchaseDate'],body['currentDate'], body['stockData'], float(body['balance']), float(body['interest']), float(body['payment']))}) } return response
be7f9045cae1ae52b5f4274b1cbbd8ba82bbf95a
Katherinaxxx/leetcode
/208. Implement Trie (Prefix Tree).py
1,821
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/11/18 下午1:57 @Author : Catherinexxx @Site : @File : 208. Implement Trie (Prefix Tree).py @Software: PyCharm """ # class Trie(object): # def __init__(self): # self.root = {} # self.end_of_word = "#" # def insert(self, word): # node = self.root # for char in word: # node = node.setdefault(char, {}) # node[self.end_of_word] = self.end_of_word # def search(self, word): # node = self.root # for char in word: # if char not in node: # return False # node = node[char] # return self.end_of_word in node # def startsWith(self, prefix): # node = self.root # for char in prefix: # if char not in node: # return False # node = node[char] # return True class Trie: def __init__(self): """ Initialize your data structure here. """ self.lookup = {} def insert(self, word: str) -> None: """ Inserts a word into the trie. """ tree = self.lookup for a in word: if a not in tree: tree[a] = {} tree = tree[a] # 单词结束标志 tree["#"] = "#" def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ tree = self.lookup for a in word: if a not in tree: return False tree = tree[a] if "#" in tree: return True return False def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ tree = self.lookup for a in prefix: if a not in tree: return False tree = tree[a] return True
ca6b9cfd33339565f09bcb59ddb71e1c24c42f47
crystalatk/python-algorithms
/Week 1/alg_2_Sum_Multiples.py
348
3.984375
4
# 2. Sum of All Multiples of 3 or 5 below 1000 # # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. r = 0 for n in range(1,1001): a = 3 b = 5 if n % a == 0 or n % b == 0: r += n print(r)
509b4250fe248c93ece92feb246bbe8bb7f882b2
Anishadahal/Assignmen2_tIW
/DataTypes/q25.py
212
4.25
4
# Write a Python program to check whether all dictionaries in a list are empty or # not. my_list = [{}, {}, {}] my_list1 = [{1, 2}, {}, {}] print(all(not d for d in my_list)) print(all(not d for d in my_list1))
6df51c80f494fd4e81a6d1c4917575714b2e3a88
apdaza/bookprogramming
/ejercicios/python/ejercicio085.py
731
3.640625
4
__size = 5 def llenado_usuario(m): for i in range(__size): n=[] for j in range(__size): num = int(input("ingrese el valor para la posicion (" + str(i) + "," + str(j) + ") : ")) n.append(num) m.append(n) def mostrar_matriz(m): for i in m: for j in i: print(j, end='\t') print("") if __name__ == "__main__": matriz=[] positivos = 0 negativos = 0 llenado_usuario(matriz) mostrar_matriz(matriz) for i in matriz: for j in i: if j > 0: positivos += j else: negativos += j print("positivos = " + str(positivos)) print("negativos = " + str(negativos))
940c0d41173004008ecd8513e86441f87dbfdb07
ProspePrim/PythonGB
/Lesson 6/task_6_4.py
3,012
3.78125
4
#Реализуйте базовый класс Car. # У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево). # А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда). # Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. # Добавьте в базовый класс метод show_speed, который должен показывать текущую скорость автомобиля. # Для классов TownCar и WorkCar переопределите метод show_speed. # При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение о превышении скорости. class Car: # atributes def __init__(self, speed, color, name, is_police): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): return f'{self.name} is started' def stop(self): return f'{self.name} is stopped' def turn_right(self): return f'{self.name} is turned right' def turn_left(self): return f'{self.name} is turned left' def show_speed(self): return f'Current speed {self.name} is {self.speed}' class TownCar(Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) def show_speed(self): print(f'Current speed of town car {self.name} is {self.speed}') if self.speed > 40: return f'Speed of {self.name} is higher than allow for town car' else: return f'Speed of {self.name} is normal for town car' class SportCar(Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) class WorkCar(Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) def show_speed(self): print(f'Current speed of work car {self.name} is {self.speed}') if self.speed > 60: return f'Speed of {self.name} is higher than allow for work car' class PoliceCar(Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) def police(self): if self.is_police: return f'{self.name} is from police department' else: return f'{self.name} is not from police department' ferarri = SportCar(140, 'Red', 'Ferarri', False) toyota = TownCar(39, 'Black', 'toyota', False) lada = WorkCar(50, 'Cherry', 'Lada', False) dodge = PoliceCar(140, 'Black', 'dodge', True) print(ferarri.show_speed()) print(dodge.police()) print(dodge.show_speed()) print(toyota.show_speed())
afe67941a477a69f43968c8637852734c7c43579
harveylabis/GTx_CS1301
/codes/CHAPTER_4/Chapter_4.5_Dictionaries/Lessson_2/AddingandRemovingfromaDictionary-1.py
331
3.578125
4
#Creates myDictionary with sprockets=5, widgets=11, cogs=3, and gizmos=15 myDictionary = {"sprockets" : 5, "widgets" : 11, "cogs" : 3, "gizmos": 15} print(myDictionary) #Creates the new key "gadgets" with value 1 myDictionary["gadgets"] = 1 print(myDictionary) del myDictionary["gadgets"] print(myDictionary)
480f07625738f0ad4c82494b5fcaa50783b41a06
tbjoern/adventofcode2017
/02/part2.py
387
3.515625
4
lines = [] with open("input.txt") as file: lines = file.readlines() sum = 0 for line in lines: numbers = list(map(lambda x: int(x), line.split())) for number1 in numbers: for number2 in numbers: if number1 != number2: if number1 > number2 and number1 % number2 == 0: sum += number1 / number2 print(sum)
7e46d5728b96ba9db4672f9d543c382baa92d82b
supriyo-pal/Python-Practice
/List/print all positive and negetive numbers in a list.py
340
3.75
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 3 10:41:08 2020 @author: Supriyo """ list=[34,5,-1,-5,-9,23,56,76,9,-64] list_pos=[] list_neg=[] for i in list: if i>=0: list_pos.append(i) else: list_neg.append(i) print("Positive Numbers ",list_pos) print("Negetive numbers ",list_neg)
894b08ed1dc3bc464f62e55e1ccfe81f3ff76eb0
nrmorciglio/digitalcrafts
/week1/day3/3intCalc.py
1,907
4.375
4
greeting = input('Welcome to this calculator program. What is your name?\n') print(f'Hello ' + greeting + ' ,lets begin!') print('This calculator is designed to compute up to three numbers. You will be asked if your equation requires a third number. Please follow the prompts to complete your calculation. PLEASE KEEP PEMDAS IN MIND WHEN ENTERING OPERATIONS') num1 = int(input('Please enter your first number\n')) op1 = input('enter an operation: + , - , * , /\n') num2 = int(input('Please enter your second number\n')) if op1 == '+': print(num1+num2) if op1 == '-': print(num1-num2) if op1 == '*': print(num1*num2) if op1 == '/': print(num1/num2) thirdintegerq = input('Does your equation require a third number? Enter Y for Yes or N for no\n') if thirdintegerq == 'N': op2 = '' print('Calculation complete - End of program') elif thirdintegerq == 'Y': op2 = input('enter another operation: + , - , * , /\n') num3 = int(input('Please enter your third number\n')) if op1 =='+' and op2 == '+': print(num1+num2+num3) if op1 =='-' and op2 == '-': print(num1-num2-num3) if op1 =='*' and op2 == '*': print(num1*num2*num3) if op1 =='/' and op2 == '/': print(num1/num2/num3) if op1 =='+' and op2 == '-': print(num1+num2-num3) if op1 =='+' and op2 == '*': print(num1+num2*num3) if op1 =='+' and op2 == '/': print(num1+num2/num3) if op1 =='-' and op2 == '+': print(num1-num2+num3) if op1 =='-' and op2 == '*': print(num1-num2*num3) if op1 =='-' and op2 == '/': print(num1-num2/num3) if op1 =='*' and op2 == '+': print(num1*num2+num3) if op1 =='*' and op2 == '-': print(num1*num2-num3) if op1 =='*' and op2 == '/': print(num1*num2/num3) if op1 =='/' and op2 == '+': print(num1/num2+num3) if op1 =='/' and op2 == '-': print(num1/num2-num3) if op1 =='/' and op2 == '*': print(num1/num2*num3)
0a5cb5be1d8f22a0c0a4174eb6e03954f8d6a894
smishra06/dynamicpage
/consecutive.py
376
3.578125
4
string="1AABBBCCCC1AA" #string="A" count=1 length="" if len(string)>1: for i in range(1,len(string)): if string[i-1]==string[i]: count+=1 else : length += string[i-1]+" occurs "+str(count)+", " count=1 length += (string[i]+" occurs "+str(count)) else: i=0 length += (string[i]+" occurs "+str(count)) print (length)
6f5b78d13ec7b8b9c72d92b96d923bc9dbbfe893
mazouri/EasyPython
/small_project/web/beautiful_soup/doc/09兄弟节点.py
2,454
3.515625
4
from bs4 import BeautifulSoup sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>") # print(sibling_soup.prettify()) # <html> # <body> # <a> # <b> # text1 # </b> # <c> # text2 # </c> # </a> # </body> # </html> # .next_sibling 和 .previous_sibling # 在文档树中,使用 .next_sibling 和 .previous_sibling 属性来查询兄弟节点 print(sibling_soup.b.next_sibling) # <c>text2</c> print(sibling_soup.c.previous_sibling) # <b>text1</b> # <b>标签有 .next_sibling 属性,但是没有 .previous_sibling 属性, # 因为<b>标签在同级节点中是第一个. # 同理,<c>标签有 .previous_sibling 属性,却没有 .next_sibling 属性 print(sibling_soup.b.previous_sibling) # None print(sibling_soup.c.next_sibling) # None # 实际文档中的tag的 .next_sibling 和 .previous_sibling 属性通常是字符串或空白 # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a> # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a> # 如果以为第一个<a>标签的 .next_sibling 结果是第二个<a>标签,那就错了, # 真实结果是第一个<a>标签和第二个<a>标签之间的顿号和换行符 index_soup = BeautifulSoup(open('index.html')) link = index_soup.a print(link) # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> print(link.next_sibling) # , # 第二个<a>标签是顿号的 .next_sibling 属性 print(link.next_sibling.next_sibling) # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> # .next_siblings 和 .previous_siblings # 通过 .next_siblings 和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出 print('------------------------') for sibling in index_soup.a.next_siblings: print(repr(sibling)) # ',\n' # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> # ' and\n' # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> # ';\nand they lived at the bottom of a well.' print('------------------------') for sibling in index_soup.find(id='link3').previous_siblings: print(repr(sibling)) # ' and\n' # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> # ',\n' # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> # 'Once upon a time there were three little sisters; and their names were\n'
b732b61c40007b986cc74d8031dcb45c552faba4
marianasoeiro/PythonIntro
/notebooks/exercicio6/exercicio6_3.py
752
4.09375
4
#Autor: Mariana Soeiro #About: Exercicio 6 - Lista 4 (Python) # - 6. Convert temperatures from Celsius to Fahrenheit [x] def toCelsius() : print("my converter from Celsius to Fahrenheit ") # 1.8c + 32 = F c = float(input("Choose a temperatura in Celsius degrees to convert in Fahrenheit degrees ")) f = c * 1.8 + 32 print("The temperature is {0} degrees Celsius is {1} degrees Fahrenheit".format(c,f)) toCelsius() def toFahrenheit() : print("my converter from Fahrenheit to Celsius") # (f - 32) * 1.8 f = float(input("Choose a temperatura in Fahrenheit degrees to convert in Celsius degrees ")) c = (f - 32)/1.8 print("The temperature is {0} degrees Fahrenheit is {1} degrees Celsius".format(f,c)) toFahrenheit()
c88c5f70605a11452f33d53b4329e6e1f7c9288b
AdamZhouSE/pythonHomework
/Code/CodeRecords/2397/60595/247461.py
134
3.765625
4
num=int(input()) for i in range(0,num*num*4): a=input() if(num==3): print(17) elif(num==7): print(15) else: print(num)
e48facdab72ab269869a7586fbed3c7bd85310f6
HelixAngler/Repos
/Python/simplcalculator.py
1,206
3.609375
4
def addi(g1, g2): return g1+g2 def subt(g1, g2): return g1-g2 def mult(g1, g2): return g1*g2 def divi(gi, g2): return g1/g2 def powe(g1, g2): return g1**g2 x=[0] while True: n=input("1st Number (ans for previous answer)") p=int(input("2nd Number ")) z=int(input("select calculation")) if n=="ans": k=x.pop() if (z == 1): k =addi(k, p) x.append(k) elif (z == 2): k =subt(k, p) x.append(k) elif (z == 3): k =k + mult(k, p) x.append(k) elif (z == 4): k =divi(k, p) x.append(k) elif (z == 5): k =powe(k, p) x.append(k) else: break else: l=int(n) x.pop() if (z == 1): k = addi(l, p) x.append(k) elif (z == 2): k = subt(l, p) x.append(k) elif (z == 3): k = mult(l, p) x.append(k) elif (z == 4): k = divi(l, p) x.append(k) elif (z == 5): k = powe(l, p) x.append(k) else: break print(x)
56155f457dd097e80b15ec6a6f4ac211d5733028
angelinn/HackBulgaria
/week0/fibonacci_lists.py
373
3.875
4
def fibonacci_lists(listA, listB, n): first = listA second = listB if n == 1: return first if n == 2: return second for i in range(2, n): result = first + second first = second second = result return result def main(): print(fibonacci_lists([1, 2], [3, 4], 5)) if __name__ == '__main__': main()
52b66daac98f4b790ddd9070905f007f19d4ad61
kharicha/hkarthikbabu
/python_problem_solved_100/code_chef.py
4,244
3.578125
4
# ''' # Input # # An input contains 2 integers A and B. # # # # Output # # Print a wrong answer of A-B. Your answer must be a positive integer containing the same number of digits # # as the correct answer, and exactly one digit must differ from the correct answer. Leading zeros are not # # allowed. If there are multiple answers satisfying the above conditions, anyone will do. # ''' # # n = input().split(' ') # s = int(n[0]) - int(n[1]) # print(s) # # si = str(s) # for i in range(len(si)): # # quote = ''' # When I see a bird # that walks like a duck # and swims like a duck # and quacks like a duck, # I call that bird a duck # ''' # def quote_words(quote): # d = {} # # for word in quote.split(): # print(word) # if word in d: # d[word] += 1 # else: # d[word] = 1 # return d # print(quote_words(quote)) # # cities = [1,2,3,4,5] # print(len(cities)) # name = 'karthik babu hari babu' # print(name[0].split()) # def convert(name): # print (' '.join(name).split()) # #return (name[0].split()) # # # # Driver code # name = ["karthik babu hari babu"] # print(convert(name)) # # name = 'karthik babu hari babu' # # n = name.split() # # print(n) # # nam = [] # # for na in n: # # print(na) # # nam.append(na) # # print(nam[2]) # # n = name [::-1] # print(n) #include <stdio.h> # no = [2,38,4857,1299,1,2,4,7] # no.sort() # print(no) # n = sorted(no) # print(n) # # Defining lists # L1 = [1, 2, 3] # L2 = [2, 3, 4] # # # L3 = [] # # for i in range(len(L1)): # # L3.append(L1[i]*L2[i]) # # print(L3) # # import operator # # a,b,c = map(operator.mul, L1, L2) # print(a,b,c) # def pal(s): # # rev = '' # # # # for c in reversed(s): # # rev += c # # # # if rev == s: # # return True # # else: # # return False # # print(pal('madam')) # import itertools # # # # c = itertools.count(5,10) # # print(next(c)) # # print(next(c)) # no = int(input("enter teh ni")) # s = 0 # temp = no # while temp > 0: # c = temp %10 # print(c) # s += c**3 # print(s) # temp = temp//10 # print(temp) # # if no == s: # print("armstrong") # else: # print("not armstrong") #pyramid # no = 5 # m = (2 * no) - 2 # # for i in range(0, no): # for j in range(0, m): # print(end=" ") # m = m - 1 # for j in range(0, i+1): # print("*", end=" ") # print(" ") #prime: # def pri(n): # # if n > 1: # # for i in range(2, n): # # if n % i == 0: # # print("not prime") # # break # # else: # # print(" prime") # # break # # else: # # print("not prime") # # # # pri(3) # ph = "1905" # # # # for p in ph: # # print(p) #!env python from lmconsole.client import * client = LMclient('kharicha').wait() print("client is", client) service = client.service("6hu-91t-yd7-qik") service.update_inventory().wait() print(service.inventory) shver = service.inventory['cat9k-24'].exec('show version').wait() print(shver.result.data) ship = service.inventory['cat9k-24'].exec('show ip int br').wait() print(shver.result.data) ddr = service.inventory['cat9k-24'] ses = ddr.ssh().wait() print(ses) cmd = "guestshell run python3 /home/guestshell/emre/runemre py --facts=/bootflash/guest-share/emre/tcam/emre-facts --rules=/bootflash/guest-share/emre/tcam/emre-rules" ses.write(cmd.encode()) out = ses.read(None, blocking=False).decode() print(out) client.terminate() while True: try: emre.wait(timeout=120) break except TimeoutError: print('not yet ready') print('done') emre = service.inventory['cat9k-24'].exec('guestshell run python3 /home/guestshell/emre/runemre.py --facts=/bootflash/guest-share/emre/tcam/emre-facts --rules=/bootflash/guest-share/emre/tcam/emre-rules').wait(timeout=120) emre = service.inventory['cat9k-24'] ses = emre.ssh().wait() cmd = "guestshell run python3 /home/guestshell/emre/runemre.py --facts=/bootflash/guest-share/emre/tcam/emre-facts --rules=/bootflash/guest-share/emre/tcam/emre-rules\n” ses.write(cmd.encode()) out = ses.read(None, blocking=False).decode() out | print emre = service.inventory['cat9k-24’] emre.interactive()
32531dea6cb7715d6fd5ad0562e850fd02390a07
pvenkatesh786/Python
/Programs/dictcount.py
150
3.703125
4
#!/bin/python dct = {} str = raw_input("Enter the string :") for elem in str: if elem not in dct: dct[elem] = 1 else: dct[elem] += 1 print dct
b82226026b94403a0a6881a91dc8fbb95a335ca7
Triple-Z/Python-Crash-Course
/C8/8.4.py
631
3.703125
4
# 8-9 def show_magicians(magicians): """ Show magicians function. :return: null """ for magician in magicians: print(magician) magicians = ['test1', 'test2', 'test3', 'test4', 'test5'] show_magicians(magicians) # 8-10 def make_great(magicians): for i in range(0, 5): magicians[i] = 'the Great ' + magicians[i] make_great(magicians) show_magicians(magicians) # 8-11 def make_great(magicians): for i in range(0, 5): magicians[i] = 'the Great ' + magicians[i] return magicians newMagicians = make_great(magicians[:]) show_magicians(newMagicians) show_magicians(magicians)
0e5274ac6da1bcae9d552c1a17c0b1c1741f5d65
MandragoraQA/Python
/Urok14-2.py
851
4.21875
4
#Игра крестики-нолики. Поля 3х3, реализуется через двухмерный массив (вложенные списки) #* - пустое поле #Х - крестик #0 - нолик pole = []#поле for a in range (3): row = [EMPTY for a in range(3)] pole.append(row) koordinati = []#координаты, которые будут меняться komanda = input("Перед вами поле 3х3. Введите команду: крест, ноль или стоп: ") if komanda = "крест" or komanda = "ноль": b = input("Введите координаты: ") koordinati.append(b) if len(koordinati)>3 or len(koordinati)<1: print("Таких координат не существует") elif komanda = "стоп": break
2983285e9a02e803370c3702e31f563dad47bc12
alexinf/AlgoritmosAvanzados
/python/python/kmp.py
611
3.765625
4
def partial(pattern): ret = [0] for i in range(1, len(pattern)): j = ret[i - 1] while j > 0 and pattern[j] != pattern[i]: j = ret[j - 1] ret.append(j + 1 if pattern[j] == pattern[i] else j) return ret def search(T, P): partialVar, ret, j = partial(P), [], 0 for i in range(len(T)): while j > 0 and T[i] != P[j]: j = partialVar[j - 1] if T[i] == P[j]: j += 1 if j == len(P): ret.append(i - (j - 1)) j = 0 return ret print(search("racadabraab", "ab")) print(search("racadabraab", "br"))
aada279be33c74c347bf36ede0ff5be80669bd66
ShrutiBalla9/ShrutiBalla7
/datatypes.py
757
4.125
4
A=['8','java','python','9','10',11,12,13,14,15] print("List A :",A[:]) print("List A : 2 to 5",A[2:6]) print("List A in reverse:",A[::-1]) A.append('12') print("List A after appending :",A[:]) A.insert(3,'oop') print("List A after inserting :",A[:]) A.pop(1) print("List A after poping :",A[:]) A.remove('python') print("List A after removing :",A[:]) del A[0] print("List A after deleteing :",A[:]) A.clear() print("List A after clearing :",A[:]) #Write a program to manipulate Tuple data B=(8,'java','python',9,10,11,12,13,14,15) print("Tuple B:",B) print("Tuple B: 2 to 5",B[2:6]) print("Tuple B in reverse:",B[::-1]) print("Count of java is :",B.count('java')) print("Index of java",B.index('java'))
3d3527c7e0fbb2ee7255fe3f2565803759af20ad
rosmoke/DCU-Projects
/week12/caesar-cypher.py
554
3.671875
4
import sys v = sys.argv[1] t = raw_input() def encrypt(alpha): alpha = "abcdefghijklmnopqrstuvwxyz" word = "" i = 0 while i < len(t): j = 0 while j < len(alpha): if t[i] == alpha[j]: if j > len(alpha)-4: word = word + alpha[j-23] else: word = word + alpha[j+int(v)] elif t[i] == alpha[j].upper(): if j > len(alpha)-4: word = word + alpha[j-23].upper() else: word = word + alpha[j+int(v)].upper() j = j + 1 if t[i].isalpha() == False: word = word + t[i] i = i + 1 return word print encrypt(t)
ba42788e18b755324b0b3fc72106f8664a6e2891
mattany/gomoku
/DynamicSpace.py
3,848
3.8125
4
import gym from gym.spaces import Discrete import numpy as np import math # You could also inherit from Discrete or Box here and just override the shape(), sample() and contains() methods class GomokuObservationSpace(Discrete): """ x where x in available actions {0,1,3,5,...,n-1} Example usage: self.action_space = spaces.Dynamic(max_space=2) """ def __init__(self, board, size = 15): cells = 15**2 super().__init__(3**cells) self.board = board # def enable_actions(self, row, col): # """ You would call this method inside your environment to enable actions""" # self.available_actions[row][col] = 0 # return self.available_actions def sample(self): illegal = True row, col = None, None if any(any((i == 0) for i in j) for j in self.board): while illegal: row = np.random.randint(len(self.board)) col = np.random.randint(len(self.board[row])) illegal = self.board[row][col] return row, col return -1 def contains(self, x): return not self.board[x[0]][x[1]] @property def numerical_representation(self): retval = int(''.join([''.join([str(i + 1) for i in j]) for j in self.board])) return convertToDecimal(retval) def __repr__(self): return np.asarray(self.board).__repr__() def __eq__(self, other): return self.board == other.board class GomokuActionSpace(Discrete): """ x where x in available actions {0,1,3,5,...,n-1} Example usage: self.action_space = spaces.Dynamic(max_space=2) """ def __init__(self, board, size=15): super().__init__(size ** 2) # initially all actions are available self.board = board def make_move(self, action, val): """ You would call this method inside your environment to remove available actions""" div = action // 15 self.board[div][action - (div * 15)] = val # def enable_actions(self, row, col): # """ You would call this method inside your environment to enable actions""" # self.available_actions[row][col] = 0 # return self.available_actions def sample(self): illegal = True row, col = None, None if any(any((i == 0) for i in j) for j in self.board): while illegal: row = np.random.randint(len(self.board)) col = np.random.randint(len(self.board[row])) illegal = self.board[row][col] return row * 15 + col return -1 def contains(self, x): div = x // 15 return not self.board[div][x - (div * 15)] def __repr__(self): return np.asarray(self.board).__repr__() def __eq__(self, other): return self.board == other.board def convertToTernary(N): # Base case if (N == 0): return # Finding the remainder # when N is divided by 3 x = N % 3 N //= 3 if (x < 0): N += 1 # Recursive function to # call the function for # the integer division # of the value N/3 convertToTernary(N) # Handling the negative cases if (x < 0): print(x + (3 * -1), end="") else: print(x, end="") def convertToDecimal(N): # If the number is greater than 0, # compute the decimal # representation of the number if (N != 0): decimalNumber = 0 i = 0 remainder = 0 # Loop to iterate through # the number while (N != 0): remainder = N % 10 N = N // 10 # Computing the decimal digit decimalNumber += int(remainder * math.pow(3, i)) i += 1 return decimalNumber else: return 0
96798540b7e0d8d4280e21da8d797ab5aaa6e0e6
FrancisPepito/practice-programming-problems
/maclaurin-series.py
233
4.0625
4
import math x=float(input("Enter value for x: ")) k=int(input("Enter value for k: ")) arctan=0.0 sign=1 ctr=1 for i in range(k): arctan=arctan+(sign*(x ** ctr)/ctr) ctr = ctr + 2 sign = sign * -1 print(arctan) print(math.atan(x))
feda51686359569e15146fe71f68c802676289c9
a12b4c3/advent_of_code1
/day4/d4p1-2.py
1,578
3.734375
4
import re guard_sleep_minutes = {} # outputs the laziest guard and how many minutes they are asleep, and # what minute they were asleep the most. def main(): laziest_guard = calculate_guard_sleep_minutes() # reads file line by line def calculate_guard_sleep_minutes(): with open("sorted_input.txt", "r") as problem_file: for line in problem_file: current_guard = 0 current_start_sleep = 0 line = line.rstrip() if line.find("Guard") is not -1: regex_pattern = "#(\d*)" guard_id = re.search(regex_pattern, line).group() # print(guard_id) continue if line.find("falls asleep") is not -1: regex_pattern2 = "(\d\d:\d\d)" current_start_sleep = re.search(regex_pattern2, line).group() # print(current_start_sleep) current_start_sleep = current_start_sleep.split(":")[1] # print(current_start_sleep) continue if line.find("wakes up") is not -1: regex_pattern3 = "(\d\d:\d\d)" wake_up_time = re.search(regex_pattern3, line).group() wake_up_time = wake_up_time.split(":")[1] # print(wake_up_time) # print(current_start_sleep) time_asleep = int(wake_up_time) - int(current_start_sleep) # print(time_asleep) continue def find_most_frequently_asleep_minute(): pass if __name__ == "__main__": main()
86f81150a82de79857a5ae3cc4c4e19ee406f72f
Yidna/elisa-fanclub
/libs/tokenizer.py
2,039
3.609375
4
from functionality.exceptions import IllegalInputException from libs.literals import LITERALS from libs.func_table import FUNC_TABLE class Tokenizer: tokens = [] cur = None def __init__(self, file_path): # Constructor self.cur = 0 with open(file_path, 'r') as f: self.file = f.read().splitlines() def tokenize(self): """ Split the input text into words and store in tokens. :return: void """ self.tokens = [word for line in self.file for word in line.split() if word] print("== TOKENS ==") print(self.tokens) def peek(self): if self.is_empty(): raise Exception("Reached end of token buffer.") return self.tokens[self.cur] def check_next(self, literal): """ Determine whether the next token is valid. :param literal: str | dict :return: boolean """ return (self.peek() in literal) if isinstance(literal, dict) else (self.peek() == literal) def get_next(self): """ Consume and return the next token. :return: str """ ret = self.peek() self.cur += 1 return ret def maybe_match_next(self, literal): """ Consume the next token only if it matches the given literal. :param literal: str :return: boolean """ return not self.is_empty() and self.check_next(literal) and self.get_next() def get_and_check_next(self, literal): """ Consume the next token and verify it matches the literal. :param literal: str | dict :return: str """ if not self.check_next(literal): raise IllegalInputException("Invalid token: expected {}, actual {}".format(literal, self.peek())) return self.get_next() def is_empty(self): return self.cur >= len(self.tokens) def is_next_reserved_keyword(self): return self.peek() in LITERALS or self.peek() in FUNC_TABLE
5ae06378645cd8f368b0d7a3c46c969f906e4cf6
Nmazil-Dev/PythonCrashCoursePractice
/More Exercises/10-11.py
743
4.09375
4
# Favorite number program import json #looks for the stored favorite number by looking at fav.json def stored(): filename = 'fav.json' try: with open(filename) as f_obj: fav = json.load(f_obj) except FileNotFoundError: return None else: return fav def new_fav(): filename = 'fav.json' fav = input('Enter your favorite number: ') with open(filename, 'w') as f_obj: json.dump(fav, f_obj) return fav def num(): fav = stored() if fav: print ('I remembered that your favorite number is ' + str(fav) + '!') else: fav = new_fav() print ("I'll remember that your fav number is " + str(fav) + "!") num()
d4d02cc965a3d29cb8a5a25644c7cf68965e9e38
somanmia/URI-Online-Judge-All-Problems-Solution-in-Python
/URI_1002.py
70
3.765625
4
pi= 3.14159 r=float(input()) result=pi*r*r print("A=%.4f"%result)
9b317912bd960e29a6c2d2967f51000a22046838
vaishnavi-ui/event-database-management
/Remove_Member.py
6,069
3.5
4
from tkinter import * import sqlite3 connection = sqlite3.connect("Event_Management.db") cursor = connection.cursor() def getId(val): global Id rem=val Id=val[0] def Del(): global e2,t,rowCount rem1=("DELETE FROM COMMITTEE_MEMBERS WHERE M_ID=?") cursor.execute(rem1,[(e2.get())]) remov=("DELETE FROM MEMBERS WHERE M_ID=?") cursor.execute(remov,[(e2.get())]) connection.commit() l8=Label(t,text="Member deleted from the committee",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 bproceed=Button(t,text="Exit",font="Times 12 bold",activebackground="red",bg="black",foreground="snow",command=lambda: t.destroy()).grid(row=rowCount,column=0) def dispYear(): global vari,e2,Id,t,rowCount,e4 countYear=0 rowCount+=1 lid=Label(t,text="ID",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) lname=Label(t,text="Name",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=1) lid=Label(t,text="Position",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=2) lid=Label(t,text="Date of joining",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=3) rowCount+=1 d=("SELECT M_ID,NAME,POSITION,DOJ FROM MEMBERS WHERE YEAR=? AND C_ID=?") cursor.execute(d,[(e4.get()),(Id)]) for row in cursor.fetchall(): for i in range(0,4): l9=Label(t,text=row[i],bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=i) rowCount+=1 countYear+=1 rowCount+=1 if countYear==0: lnodata=Label(t,text="No Member available for the year!",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) else: l7=Label(t,text="Enter the M_ID of the employee who you want to remove from the committee:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 e2=Entry(t) e2.grid(row=rowCount,column=0) rowCount+=1 b13=Button(t,text="Delete",command=Del,font="Times 12 bold",activebackground="red").grid(row=rowCount,column=0) rowCount+=1 def disp(): global e1,e2,Id,t,rowCount lid=Label(t,text="ID",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) lname=Label(t,text="Name",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=1) lid=Label(t,text="Position",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=2) lid=Label(t,text="Date of joining",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=3) rowCount+=1 sel=("SELECT M_ID,NAME,POSITION,DOJ FROM MEMBERS WHERE POSITION=? AND C_ID=?") cursor.execute(sel,[e1.get(),Id]) for row in cursor.fetchall(): for i in range(0,4): l6=Label(t,text=row[i],bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=i) rowCount+=1 print(row) l7=Label(t,text="Enter the M_ID of the employee who you want to remove from the committee:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 e2=Entry(t) e2.grid(row=rowCount,column=0) rowCount+=1 b6=Button(t,text="Delete",command=Del).grid(row=rowCount,column=0) rowCount+=1 def deletePosition(): global Id,t,e1,rowCount cnt=0 l3=Label(t,text="Following positions are availabe for deleting:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 find=("SELECT DISTINCT(POSITION) FROM MEMBERS WHERE C_ID=?") cursor.execute(find,[(Id)]) for row in cursor.fetchall(): l4=Label(t,text=row[0],bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 l5=Label(t,text="Please enter any one of the positions:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 e1=Entry(t) e1.grid(row=rowCount,column=0) rowCount+=1 b5=Button(t,text="Proceed",command=disp,font="Times 12 bold",activebackground="red").grid(row=rowCount,column=0) rowCount+=1 def deleteYear(): global e4,t,rowCount vari=IntVar() l9=Label(t,text="Enter the year from which you want to remove the employee from:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 find=("SELECT DISTINCT(YEAR) FROM MEMBERS WHERE C_ID=?") cursor.execute(find,[(Id)]) for row in cursor.fetchall(): l4=Label(t,text=row[0],bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 l5=Label(t,text="Please enter any one of the year:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=rowCount,column=0) rowCount+=1 e4=Entry(t) e4.grid(row=rowCount,column=0) rowCount+=1 b5=Button(t,text="Proceed",command=dispYear,font="Times 12 bold",activebackground="red").grid(row=rowCount,column=0) rowCount+=1 def RemoveMemberGUI(): global t,var,rowCount rowCount=5 t=Tk() t.configure(bg="black") t.title("Remove Member") l1=Label(t,text="REMOVE COMMITTEE MEMBERS",bg="black",foreground="snow",font="Baskerville 12 bold underline").grid(row=0,column=0) l2=Label(t,text="Select the parameter:",bg="black",foreground="snow",font="Baskerville 12 bold").grid(row=1,column=0) b1=Button(t,text="Position",command=deletePosition,font="Times 12 bold",activebackground="red",bg="black",foreground="snow").grid(row=2,column=0) b2=Button(t,text="Year",command=deleteYear,font="Times 12 bold",activebackground="red",bg="black",foreground="snow").grid(row=3,column=0)
995cd37b7a8c732eb2ee8838efd05832c6da1043
pierremayo/tutorials
/intro.py
160
3.8125
4
age = input("What is your age?") s1 = "You are {0} years old." s2 = "In 5 years you will be {0} years old." print(s1.format(age)) print(s2.format(int(age) + 5))
9eab4e148a47e13aac3df96583a80fdf6d80614b
pod1019/python_learning
/练习题/错误与调试.py
189
3.765625
4
#打印1到10的平方值 # for i in range(10): # print(i ** 2,end=',') #测试断点 a = 1.1 b = 2.2 if round(a+b,1) == 3.3: x = 5 y = 3 # z = x / y # print(z)
ff46ee54846e6653575491398ef9b1ca198ba733
pyslin/mypython
/my-func.py
929
3.9375
4
print(abs(-10)) print(abs) #abs(10)函数的调用 ,abs是函数 x = abs(10) #要获得函数调用结果,可以把结果赋值给变量 print(x) f = abs #函数本身也可以赋值给变量,变量指向函数,函数名就是指向函数的变量 print(f(-5)) def add(x,y,f): return f(x)+f(y) print(add(5,-6,abs)) def f(x): return x*x r = map(f,[1,2,3,4,5]) #map会返回一个惰性iterator,用list()函数把序列计算出来并返回list print(list(r)) r2 = list(map(str,[1,2,3,4,5])) #转换为字符返回惰性生成器,list(函数计算出来返回list print(r2) from functools import reduce def add(x,y): return x + y z = reduce(add,[1,2,3,4,5]) print(z) def fn(x,y): return x*10+y z2 = reduce(fn,[1,3,5,7,9]) print(z2) def char2num(s): digits = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} return digits[s] z3 = reduce(fn,map(char2num,'123456')) print(z3)
3f4a00a03125e424453e48cd1ec82ef91e422207
Stone1231/py-sample
/tests/oop_test.py
422
3.875
4
import unittest class Dog(): """Represent a dog.""" def __init__(self, name, heigh, weight): """Initialize dog object.""" self.name = name self.heigh = heigh self.weight = weight class OOPTestCase(unittest.TestCase): def setUp(self): self.dog = Dog('ccc',11,22) def test_dog(self): dogName = 'ccc' self.assertEqual(dogName, self.dog.name)
b3cb41c91541098f0c4198736e036385395838a3
C2L2C/userLogins
/userLogins.py
699
3.65625
4
import hashlib,sqlite3 con = sqlite3.connect('file:./db/ppab6.db?mode=rw', uri=True) cur = con.cursor() username = input("Please enter your username: ") password = input("Please enter your password: ") def is_valid_credentials(username,password): isUsernameValid= cur.execute("SELECT EXISTS(SELECT 1 FROM users WHERE username=?)",(username,)).fetchone()[0] retreivedPassword = cur.execute("SELECT password_hash FROM users WHERE username=?",(username,)).fetchone()[0] hashedPassword = hashlib.sha256(password.encode()).hexdigest() if isUsernameValid and retreivedPassword==hashedPassword: return True else: return False is_valid_credentials(username,password)
e0bcee7a38caa630bbeb0fe6059cd585578caf68
alexander-zw/mini-projects
/mnist.py
2,362
3.8125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data", one_hot=True) num_inputs = 784 num_classes = 10 num_layers = 4 # input layer, 3 hidden layers, output layer nums_in_layer = [num_inputs, 10, 10, 10, num_classes] batch_size = 100 # string of values, width 28x28 x = tf.placeholder("float", [None, 784]) # output, one hot y = tf.placeholder("float") def nn_predict(data): layers = [None, None, None, None] # does not include input layer # initialize hidden layers and output layer # nums_in_layer starts with the input layer, NOT the first hidden layer for i in range(num_layers): layers[i] = { "weights": tf.Variable(tf.random_normal( [nums_in_layer[i], nums_in_layer[i + 1]])), "biases": tf.Variable(tf.random_normal([nums_in_layer[i + 1]])) } # calculate result = data for i in range(num_layers - 1): result = tf.add(tf.matmul(result, layers[i]["weights"]), layers[i]["biases"]) result = tf.nn.relu(result) i += 1 result = tf.add(tf.matmul(result, layers[i]["weights"]), layers[i]["biases"]) return result def nn_train(data): prediction = nn_predict(data) cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=prediction, logits=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) num_epochs = 1 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(num_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples / batch_size)): epoch_x, epoch_y = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y}) epooch_loss += c print("Epoch ", epoch, " completed out of ", num_epochs, "; loss: ", epoch_loss) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, "float")) print("Accuracy: ", accuracy.eval({x: mnist.test.images, y: mnist.test.lables})) print("START TRAINING") nn_train(x)
b17563cf1ad0902bda26065475884c0d0575f086
iparedes/bugs2
/hop.py
2,098
3.578125
4
import sys, random, pygame from ocempgui.widgets import Button, Renderer, Constants # Used to see some action happending in the GUI. amount = 0 def _count_clicks (b): global amount amount += 1 b.text = "Clicked %d times" % amount # Initialize pygame window pygame.init () screen = pygame.display.set_mode ((200, 200)); screen.fill ((255, 200, 100)) # Create the Renderer to use for the UI elements. re = Renderer () # Bind it to a part of the screen, which it will use to draw the widgets. # Here we use the complete screen. re.screen = screen # Create a button, place it at x=10, y=30, bind a callback to its # clicking action and add it to the Renderer instance. button = Button ("Simple Button") button.topleft = 10, 30 button.connect_signal (Constants.SIG_CLICKED, _count_clicks, button) re.add_widget (button) # Some variables we will need in the main loop for drawing a rect. rnd = None color = None cnt = 100 while True: events = pygame.event.get () for ev in events: if ev.type == pygame.QUIT: sys.exit () # We could handle other events separately, too, but do not care. # Draw the rectangle on the screen. cnt -= 1 if cnt == 0: rnd = (random.randint (0, 5), random.randint (0, 5), \ random.randint (0, 5)) color = (rnd[0] * 340) % 255, (rnd[1] * 122) % 255, \ (rnd[2] * 278) % 255 pygame.draw.rect (screen, color, (60, 50, 50, 50)) cnt = 100 # Pass all received events to the Renderer. We also could pass only # a subset of them, but want it to get all. re.distribute_events (*events) # Force a refresh of the UI elements as our main screen changed and # we want them to be placed upon the changes (look at the # intersection with the rectangle). re.refresh () # We do not need to flip as it is done in the refresh() method of # the Renderer. If we assign just a part of the screen to the # Renderer, we would have to, of course. # pygame.display.flip () # Do not use 100% CPU. pygame.time.delay (15)
651ed5c361107016f8d8395c5eb139c2233acb2b
AvinashBonthu/Python-lab-work
/lab 1/lab1.2_19.py
100
3.71875
4
print 'Odd numbers between 0 and 100 are' for i in range(1,101): if i%2!=0: print i
19b65806990f1e43964e591f448683c4e59bfdb4
EdisonZhu33/Algorithm
/题型分类/双指针遍历AND滑动窗口/004-最接近的三数之和.py
1,294
3.703125
4
""" @file : 004-最接近的三数之和.py @author: xiaolu @time : 2020-05-11 """ ''' 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数, 使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). ''' from typing import List class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: n = len(nums) diff_value = float('inf') nums.sort() i = 0 while i < n: L = i + 1 R = n - 1 while L < R: if abs(nums[i] + nums[L] + nums[R] - target) < diff_value: diff_value = abs(nums[i] + nums[L] + nums[R] - target) result = [nums[i], nums[L], nums[R]] if nums[i] + nums[L] + nums[R] - target < 0: L += 1 else: R -= 1 i += 1 return sum(result) if __name__ == '__main__': nums = [-1, 2, 1, -4] target = 1 sol = Solution() result = sol.threeSumClosest(nums, target) print(result)
497abc78b47abb1ae87a3aeb42473fde50f31054
charan2108/pythonprojectsNew
/pythoncrashcourse/lists/changinglists/changelist.py
101
3.515625
4
#Modifyinglist bikes = ['Honda', "CBR", 'KTM', 'Ninja'] print(bikes) bikes[0] = 'Ducati' print(bikes)
0b54933b8a30ceccd9d9481372476241265d8ea7
LiuFang816/SALSTM_py_data
/python/Zeta36_Asynchronous-Methods-for-Deep-Reinforcement-Learning/Asynchronous-Methods-for-Deep-Reinforcement-Learning-master/Wrapped-Game-Code/dummy_game.py
1,324
3.546875
4
#!/usr/bin/python import cv2 import numpy as np ''' Dummy game to test the effectiveness of the DQN. The game starts out with a white screen, and will change to black if given input 1. A black screen turns white on input 2. Flipping the screen color gives reward 1, but the wrong input for a given screen will give -1 reward. Doing nothing always gives 0 reward. Every ten steps, a new episode starts. Ideally the DQN learns that the best strategy is to continually flip the screen color to maximize reward. ''' class GameState: def __init__(self): self.screen = np.ones((100, 100), np.float32) * 255 self.screen = cv2.cvtColor(self.screen, cv2.COLOR_GRAY2BGR) self.steps = 0 def frame_step(self, input_vec): reward = -1 if self.screen[0,0,0] == 255: if input_vec[1] == 1: reward = 1 self.screen *= (1./255.) elif input_vec[0] == 1: reward = 0 else: if input_vec[2] == 1: reward = 1 self.screen *= 255 elif input_vec[0] == 1: reward = 0 self.steps += 1 terminal = False if self.steps >= 10: self.steps = 0 terminal = True return self.screen, reward, terminal
6f7a8e0754f471a3d84529381c318dc129489edb
LeonDsouza/HackerRank
/pangrams.py
129
3.734375
4
if set(input().lower().replace(' ',''))==set('abcdefghijklmnopqrstuvwxyz'): print ("pangram") else: print("not pangram")
a3e7c4d23536d27f2c95eacb12bc0deba53501b2
dileepachuthan/Coursera-python-3.2-we
/we.py
368
3.96875
4
score = input("Enter Score:") f = float(score) try: if(f>0.0 and f<1.0): if(f >= 0.9): print('A') elif(f >= 0.8): print('B') elif(f >= 0.7): print('C') elif(f >= 0.6): print('D') else: print('F') except: print("Error..enter a value in the range")
3cdce236932573c4148b7985e3574fe23898e3ec
vifezue/PythonWork
/IT - 412/Week_1/week_1_functions_assignment/functions/enterAddress.py
1,064
4.34375
4
from checkForNull import checkfor_null from checkForValue import check_for_value def enter_address(): """Takes user entry and saves the address Returns: string -- Returns the Address or an empty string """ try: invalid_addressCharacters = ["!", "\"","'", "@", "$", "%", "^", "&", "*", "_", "=", "+", "<", ">", "?", ";", ":", "[", "]", "{", "}", ")","."] checkAddress = False while not checkAddress: #Entered address address = input("Please enter the Employee Address: ") #checks to see if address was entered if not checkfor_null(address): address = "None Provided" #Checks to see if address is alphnum if not address.isalnum: checkAddress = False break if not check_for_value(address,invalid_addressCharacters): print("Invalid entry....") checkEmail = False return address except: print("Invalid Entry") return ""
78e8b6a4f23aa8a78190fcbab45f3cd725863301
NBALAJI95/MapReduce_Project
/Extra requirements/Source Code/map_extra.py
1,957
3.546875
4
#! /usr/bin/env python import sys for line in sys.stdin: line = line.strip() words = line.split() for word in words: n = int(word[0:2]) if n >= 0 and n < 1: print 'Time_between_12_AM_AND_1_AM\t%s' % (1) if n >= 1 and n < 2: print 'Time_between_1_AM_AND_2_AM\t%s' % (1) if n >= 2 and n < 3: print 'Time_between_2_AM_AND_3_AM\t%s' % (1) if n >= 3 and n < 4: print 'Time_between_3_AM_AND_4_AM\t%s' % (1) elif n >= 4 and n < 5: print 'Time_between_4_AM_AND_5_AM\t%s' % (1) if n >= 5 and n < 6: print 'Time_between_5_AM_AND_6_AM\t%s' % (1) if n >= 6 and n < 7: print 'Time_between_6_AM_AND_7_AM\t%s' % (1) if n >= 7 and n < 8: print 'Time_between_7_AM_AND_8_AM\t%s' % (1) elif n >= 8 and n < 9: print 'Time_between_8_AM_AND_9_AM\t%s' % (1) if n >= 9 and n < 10: print 'Time_between_9_AM_AND_10_AM\t%s' % (1) if n >= 10 and n < 11: print 'Time_between_10_AM_AND_11_AM\t%s' % (1) if n >= 11 and n < 12: print 'Time_between_11_AM_AND_12_PM\t%s' % (1) elif n >= 12 and n < 13: print 'Time_between_12_PM_AND_1_PM\t%s' % (1) elif n >= 13 and n < 14: print 'Time_between_1_PM_AND_2_PM\t%s' % (1) elif n >= 14 and n < 15: print 'Time_between_2_PM_AND_3_PM\t%s' % (1) elif n >= 15 and n < 16: print 'Time_between_12_PM_AND_1_PM\t%s' % (1) elif n >= 16 and n < 17: print 'Time_between_4_PM_AND_5_PM\t%s' % (1) elif n >= 17 and n < 18: print 'Time_between_5_PM_AND_6_PM\t%s' % (1) elif n >= 18 and n < 19: print 'Time_between_6_PM_AND_7_PM\t%s' % (1) elif n >= 19 and n < 20: print 'Time_between_7_PM_AND_8_PM\t%s' % (1) elif n >= 20 and n < 21: print 'Time_between_8_PM_AND_9_PM\t%s' % (1) elif n >= 21 and n < 22: print 'Time_between_9_PM_AND_10_PM\t%s' % (1) elif n >= 22 and n < 23: print 'Time_between_10_PM_AND_11_PM\t%s' % (1) elif n >= 23 and n < 24: print 'Time_between_11_PM_AND_12_AM\t%s' % (1)
9d028705eacf3af310f02bd3afe08eb574101b18
G00364778/46887_algorithms
/assignment/contains_duplicates.py
795
3.703125
4
import time def contains_duplicates(elements): for i in range (0, len(elements)): for j in range(0, len(elements)): steps=(i+1)*(j+1) if i == j: # avoid self comparison continue if elements[i] == elements[j]: #return True, steps return steps #return False, steps return steps if __name__ == '__main__': #testarr=[i for i in range(0,5001)] #testarr[0]=1000 test1=[10,0,5,3,-19,5] test2=[0,1,0,-127,346,125] start = time.time() result = contains_duplicates(test2) end = time.time() #print("Duplicates found:", result, "- Execution Time:", (end-start)*1000, "ms") print("Duplicates found in stepcount:", result, "- Execution Time:", (end-start)*1000, "ms")
79ecbe86454e3ca6820662568c30f8a859727b8e
nikonura/theory_of_algorithms_2015_itmo_spo
/trees.py
4,084
3.90625
4
''' деревья T=<N,E> N=nodes(узлы) E=edges(ребра) у дерева всегда есть корень, причём только один. ели у дерева(корня) есть только 2 потомка, то оно называется бинарным. дерево называется пустым, если нет ни листов, ни ребер, или состоять из корня и нуля из более поддеревьев. ''' def binary_tree(value): return [value,[],[]] def get_left_child(node): return node[1] def get_right_child(node): return node[2] def get_root_value(node): return node[0] #вставка потомка влево def insert_left(root,value): child=root.pop(1) #выталкиваем первый элемент if len(child)>1: root.insert(1,[value,child,[]]) #меняем старый список на новый, попросту вставляем значение 1, значение и старый ребёнок как потомок else: root.insert(1,[value,[],[]]) #если список пустой, заменяем его на пустой [2, [9,[4,[],[]],[],[]] ] #вставка потомка вправо def insert_right(root,value): child=root.pop(2) if len(child)>1: root.insert(2,[value,[],child]) else: root.insert(2,[value,[],[]]) ''' [1,[2,[],[]].[3,[],[]]] хотим вставить левого потомка в левый потомок insert_left(get_left_child(tree),4) получим [1,[2,[4,[],[]],[]],[3,[],[]]] хотим вставить правого потомка в потомки потомка 4 insert_right(get_left_child(get_left_child(tree)),5) ''' #поиск элемента def find(tree,e): if not tree: return False if e==get_root_value(tree): return True return find(get_left_child(tree),e) or find(get_right_child(tree),e) '''ДЗ создать функцию binary_search_tree [1,[2,[3,[4,[],[]],[]],[]],[]]''' #есть корень, все левые элементы которого меньше правых def find1(tree,e): if not tree: return False if e==get_root_value(tree): return True if get_left_child<e: return find(get_left_child(tree),e) else: return find(get_right_child(tree),e) tree=binary_tree(21) insert_left(tree,13) insert_right(tree,33) insert_left(insert_left(tree,4)) insert_right(insert_left(tree,15)) insert_left(insert_right(tree,26)) insert_right(insert_right(tree,37)) print(find1(tree,15)) def foo(n,tabs=o): if n!=0: print(tabs*'\t',n) return foo(n-1,tabs+1) def preorder(tree,tabs=0): if tree: print(tabs*'\t',get_root_value(tree)) preorder(get_left_child(tree).tabs+1) preorder(get_right_child(tree).tabs+1) import operator "+"-add() "-"-sup() "*"-mul() "/"-truediv()} operator.add(3,5) ''' ops={'+': operator.add, \ '-': operator.sub, \ '*': operator.mul, \ '\': operator.truediv} ops['+'](3,5) словарь - это объекты типа слова-значения phones={'Mike':1111, 'john':2222, 'Pit':3333} phones['Mike'] ключами могут быть только строки и целые числа chars={'a':1, 'b':2, 'c':3, 'd':4} chars chars.keys() sorted(chars.keys()) sorted_chars=sorted(chars.keys()) ''' def evaluate(exp): left_op=get_left_child(exp) right_op=get_right_child(exp) if left_op and right_op: op=ops[get_root_value(exp)] return op(evaluate(left_op),evaluate(right_op)) else: return get_root_value(exp) def postorder_evaluate(exp): ops={'+': operator.add, '-': operator.sub, '*': operator.mul, '\': operator.truediv} left_op=get_left_child(exp) right_op=get_right_child(exp) if left_op and right_op: op=ops[get_root_value(exp)] left_op = postorder_evaluate(get_left_child(exp)) right_op = postorder_evaluate(get_right_child(exp)) return op((left_op),(right_op)) else: return get_root_value(exp)
9e1605304dca72bb6dc3f35a2f4cb15ee8653704
WarakornToey/All_Exercises_Python_3
/Exercise5_2_Warakorn_L.py
123
3.859375
4
v = int(input("Car Speed (km/hr) : ")) t = int(input("Time Speed (s/hr) : ")) result = v/t print("Result : ",result,"km/h")
51066b8d294ee8e090c3f9466f410bdd438925c3
FireinDark/leetcode_practice
/14_longest_common_prefix.py
1,219
3.78125
4
class Solution: # 暴力解决 def longestCommonPrefix(self, strs): if not strs: return "" i = 0 start = "" min_index = None for item in strs: if min_index is None: min_index = len(item) else: min_index = min_index if len(item) > min_index else len(item) if not min_index: return "" status = True while status and i < min_index: start = strs[0][i] for item in strs: if item[i] != start: status = False break if status: i += 1 return strs[0][:i] or "" # 仅需比较字符串中最短的与最长字符串最长公共前缀就是结果 def longestCommonPrefix(self, strs): if not strs: return "" mi = min(strs) ma = max(strs) if not mi: return "" for i in range(len(mi)): if ma[i] != mi[i]: return mi[:i] or "" return mi if __name__ == '__main__': print(Solution().longestCommonPrefix(["flower","flow","flight"]))
15d1b7a42f2ec0896a7362040bdf97db8d102e7a
Drlilianblot/tpop
/TPOP Python 3.x Practicals/exercise_booklet/coinwar.py
1,833
4.125
4
import random # these Constants are defined to facilitate code reading COIN_HEAD = 'HEAD' # represent the head of a coin COIN_TAIL = 'TAIL' # represent the tail of a coin def flipCoin(): ''' flip a coin randomly and return one of the two faces of a coin (e.g. COIN_HEAD, or COIN_TAIL). ''' flip = random.randint(0, 1) if (flip == 0): return COIN_HEAD else: return COIN_TAIL def coinwar(coins, maxIter): ''' Run a single game of the coin war. The game terminates when on of the player as no more coins or when we have reach maxIter rounds without a winner. The game is a draw if no winner is found after maxIter rounds have been done. @param coins: the initial number of coins for each player. @param maxIter: the maximum number of rounds before the game is declared a draw @return: 0 if it is a draw after maxIter iteration, 1 if DIFF wins, 2 if SAME wins. ''' same = diff = coins rounds = 0 while same > 0 and diff > 0 and rounds < maxIter: sameFlip = flipCoin() diffFlip = flipCoin() if(sameFlip == diffFlip): same += 1 diff -= 1 else: same -= 1 diff += 1 rounds += 1 if same == 0: return 2 elif diff == 0: return 1 else: return 0 def main(): ''' runs a simulation of 10,000 games and display the result. ''' sameWins = diffWins = draws = 0 for rounds in range(10000): gameResult = coinwar(20, 1000) if gameResult == 0: draws += 1 elif gameResult == 1: diffWins += 1 elif gameResult == 2: sameWins += 1 print("diff =%d, same = %d, draws = %d" % (diffWins, sameWins, draws)) main()
9e24a6b9a768acd71e55520c2a1ce6a89ad924bb
riddhinm5/myNumpy
/vector.py
4,237
3.5625
4
import math class Vector(): CANNOT_NORMALIZE_ZERO_VECTOR = 'Cannot normalize a zero vector' def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') def __str__(self): return 'Vector: {}'.format(self.coordinates) def __eq__(self, v): return self.coordinates == v.coordinates def __add__(self, v): try: if isinstance(v, int): expand = [] for _ in range(self.dimension): expand.append(v) v = Vector(expand) if isinstance(v, Vector): if self.dimension != v.dimension: raise ValueError sum_vec = Vector([self.coordinates[i] + v.coordinates[i] for i in range(self.dimension)]) return sum_vec else: raise TypeError except ValueError: raise ValueError('The coordiantes have a length mis-match') except TypeError: raise TypeError('Can perform addition only with another vector or a scalar') def __sub__(self, v): try: if isinstance(v, int): expand = [] for _ in range(self.dimension): expand.append(v) v = Vector(expand) if isinstance(v, Vector): if self.dimension != v.dimension: raise ValueError sub_vec = Vector([self.coordinates[i] - v.coordinates[i] for i in range(self.dimension)]) return sub_vec else: raise TypeError except ValueError: raise ValueError('The coordiantes have a length mis-match') except TypeError: raise TypeError('Can perform addition only with another vector or a scalar') def __mul__(self, v): try: if isinstance(v, (int, float)): expand = [] for _ in range(self.dimension): expand.append(v) v = Vector(expand) if isinstance(v, Vector): mul_vec = Vector([self.coordinates[i] * v.coordinates[i] for i in range(self.dimension)]) return mul_vec else: raise TypeError except TypeError: raise TypeError('Can only perform multiplication with a scalar with this function.\ To multiply 2 vectors use Vector.matmul()') __rmul__ = __mul__ def getMagnitude(self): ''' Magnitude of a vector is the measure of it's length rtype: Class 'vector' ''' magnitude = math.sqrt(sum([i**2 for i in self.coordinates])) return magnitude def normalize(self): ''' Normalizing a vector is the process of finding a unit vector i.e. a vector with magnitude 1 in the same direction as a given vector rtype: vector ''' magnitude = self.getMagnitude() try: unit_vecor = self * (1/magnitude) return unit_vecor except ZeroDivisionError: raise Exception(self.CANNOT_NORMALIZE_ZERO_VECTOR) def dot(self, v): ''' Calculating the dot product of 2 vectors i.e. v . w = v1*w1 + v2*w2 + ... + vn*wn ''' dot = sum([u*v for u, v in zip(self.coordinates, v.coordinates)]) return dot def angle(self, v, unit='radian'): try: v1 = self.normalize() w1 = v.normalize() angle = math.acos(v1.dot(w1)) if unit == 'degree': angle *= 180/math.pi return angle except Exception as e: if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR: raise Exception('Cannot comput an angle with a zero vector') else: raise e
2ce635527f3c26471448ef2fec19fbe05e0df76c
mikem2314/PythonExercises
/Mutations.py
285
3.859375
4
#Written to solve https://www.hackerrank.com/challenges/python-mutations/problem s = input("Please enter a string: ") t = input("Please enter an index and char to split on, separated by a space: ") index = int(t[0]) char = t[2] l = list(s) l[index] = char s = ''.join(l) print (s)
3fa859c1b3799fa403a8bf78a66d066a28bdf3e2
soumyaracherla/python-programs
/call by ref.py
267
3.609375
4
def updatelist(mylist): print("current data", mylist) mylist[1]= 11 print("updated data", mylist) list1= [1,2,3,4,5] updatelist(list1) def update(value): num=20 print("num is", num) return value result=update(10) print("num is ", result)
a99e996d8f1fa95e0b6bed7b1afc96dd2ed01896
HafizulHaque/Python-Practice-
/membership.py
464
3.9375
4
vowels = "aeiou" while(True): vowelCnt = 0 consCount = 0 other = 0 str = input("Enter a string (-1 to exit) :") try: if int(str) == -1: print("Thank you !") break except ValueError as error: pass for char in str: if char.isalpha(): if char.lower() in vowels: vowelCnt += 1 else: consCount += 1 else: other += 1 print("Total vowel : ", vowelCnt, ", Total consonent : ", consCount, ", Others : ", other)
401f8584675b314874c2b54a415a7f653925a780
18tbartecki/ITP-115
/ITP115_Project_Bartecki_Tommy/MenuItem.py
1,094
4.03125
4
# This file defines the MenuItem class # A MenuItem represents a single item that a diner can order from the restaurant’s menu class MenuItem: def __init__(self, name, itemType, price, description): self.name = name self.itemType = itemType self.price = price self.description = description # Prints a menu item and its price and description def __str__(self): return self.name + " (" + self.itemType + "): $" + str(self.price) + "\n\t" + self.description # All getters and setters to change and use the MenuItem variables in different classes def getName(self): return self.name def setName(self, name): self.name = name def getItemType(self): return self.itemType def setItemType(self, itemType): self.itemType = itemType def getPrice(self): return self.price def setPrice(self, price): self.price = price def getDescription(self): return self.description def setDescription(self, description): self.description = description
5601ad229d6ad66178d3e86959750b65c4028b1e
kabirbansod/EMmodelling
/a6.py
11,545
3.609375
4
# Unitless 1D FDTD solution to wave equation. # Author- Kabir Bansod # Date: 10/09/14 import numpy as np # Loading required libraries. import matplotlib.pyplot as plt import time import matplotlib.animation as animation class FdTd: def __init__(self): self.time_tot = 500 # Time for which the simulation runs. # Stability factor self.S = 1 #Speed of light self.c = 299792458 #defining dimensions self.n_x = 300 self.n_xsrc = self.n_x/6 # Location of the source. self.epsilon0 = 8.854187817*10**(-12) self.mu0 = 4*np.pi*10**(-7) self.sigma = np.ones(self.n_x)*4*10**(-4) self.sigma_star = np.ones(self.n_x)*4*10**(-4) self.get_epsilon() self.source_choice = self.get_source() # Get the type of source to be used from the user. if (self.source_choice==1): fr = input("Enter the frequency of the source in THz:") self.freq = fr*10**(12) min_wavelength = self.c/(self.freq*np.sqrt(np.amax(self.epsilon)/self.epsilon0)) #print min_wavelength #print np.sqrt(np.amax(epsilon))*freq self.delta = min_wavelength/30 else: self.delta = 10**(-6) self.deltat = self.S*self.delta/self.c # Time step. print self.deltat self.h_frequency = 0.5/(self.deltat) self.number_steps_freq = 1001 self.ar = np.zeros(self.n_x) self.dum1 = 0 self.dum2 = 0 return def get_epsilon(self): """ Returns an array containing the permittivity values of the medium""" a =input("Enter Refractive index:") self.epsilon=np.ones(self.n_x)*self.epsilon0 self.epsilon[self.n_x/3:2*self.n_x/3] = self.epsilon[self.n_x/3:2*self.n_x/3]*a self.mu = self.mu0*np.ones(self.n_x) self.mu[self.n_x/3:2*self.n_x/3] = self.mu[self.n_x/3:2*self.n_x/3]*2 return def get_source(self): """Gets the source to be used in the calculations from the user""" print ("Pick a source to be used in 1D FDTD simulation of wave prpogation in vacuum.") print ("1: Sinusoidal source of frequency 1Hz.") print ("2: Impulse.") print ("3: Gaussian source.") return input("Enter your choice: ") def plotFields(self): xdim = self.n_x xsrc = self.n_xsrc Ez = np.zeros(xdim) # Arrays that hold the values of Electric field Hy = np.zeros(xdim) # and magnetic field respectively. A = ((self.mu-0.5*self.deltat*self.sigma_star)/(self.mu+0.5*self.deltat*self.sigma_star)) B=(self.deltat/self.delta)/(self.mu+0.5*self.deltat*self.sigma_star) C=((self.epsilon-0.5*self.deltat*self.sigma)/(self.epsilon+0.5*self.deltat*self.sigma)) D=(self.deltat/self.delta)/(self.epsilon+0.5*self.deltat*self.sigma) H_src_correction = -np.sqrt((self.epsilon[xsrc]/self.epsilon0)/(self.mu[xsrc]/self.mu0)) n_src = np.sqrt(self.epsilon[xsrc]/self.epsilon0) delay_half_grid = n_src*self.delta/(2*self.c) half_time_step = self.deltat/2 h_f = self.h_frequency n_steps = self.number_steps_freq frequencies = np.linspace(0,h_f,n_steps) exp_terms = np.exp(-1j*2*np.pi*self.deltat*frequencies) ref = np.ones(n_steps)*(0+0j) trn = np.ones(n_steps)*(0+0j) src = np.ones(n_steps)*(0+0j) fig , axes = plt.subplots(2,1) # Figure with 2 subplots- one for E field and one for H. axes[0].set_xlim(len(Ez)) axes[0].set_title("E Field") axes[1].set_xlim(len(Hy)) axes[1].set_title("H Field") line, = axes[0].plot([],[]) # Get line objects of the axes in the plot in order to modify it line1, = axes[1].plot([],[]) # from animate function. def init(): """ Initializes the plots to have zero values.""" line.set_data([],[]) line1.set_data([],[]) return line, if (self.source_choice==1): # When the source is sinusoidal of frequency 1Hz. def sine_src(n): source = np.sin(2*np.pi*self.freq*self.deltat*n) return source def animate(n, *args, **kwargs): """ Animation function that sets the value of line objects as required. Argument n refers to the frame number: time step in our case. """ Esrc = sine_src(n) Hsrc = H_src_correction*sine_src(n + delay_half_grid + half_time_step) Ez[xsrc] = Ez[xsrc] + Esrc # Sinusoidal source. Hy[0:xdim-1] = A[0:xdim-1]*Hy[0:xdim-1]+B[0:xdim-1]*(Ez[1:xdim]-Ez[0:xdim-1]) Hy[xsrc-1] = Hy[xsrc-1] - B[xsrc-1]*Esrc Ez[1:xdim]= C[1:xdim]*Ez[1:xdim]+D[1:xdim]*(Hy[1:xdim]-Hy[0:xdim-1]) #Ez[xsrc] = Ez[xsrc] - D[xsrc]*Hsrc ylims1 = axes[0].get_ylim() ylims2 = axes[1].get_ylim() e_max = abs(np.amax(Ez)) h_max = abs(np.amax(Hy)) Ez[xdim-1]= self.dum2+((self.S-1)/(self.S+1))*(Ez[xdim-2]-Ez[xdim-1]) Ez[1]= self.dum1+((self.S-1)/(self.S+1))*(Ez[1]-Ez[0]) Ez[0]= Ez[2] self.dum1 = Ez[2] self.dum2 = Ez[xdim-2] ref[0:n_steps] = ref[0:n_steps] + (exp_terms[0:n_steps]**(n))*Ez[0] trn[0:n_steps] = trn[0:n_steps] + (exp_terms[0:n_steps]**(n))*Ez[xdim-1] src[0:n_steps] = src[0:n_steps] + (exp_terms[0:n_steps]**(n))*Esrc if (e_max > ylims1[1]): # Scaling axes. axes[0].set_ylim(-(1.2*e_max),1.2*e_max) if ((h_max)>ylims2[1]): # Scaling axes. axes[1].set_ylim(-(1.2*h_max),1.2*h_max) line.set_data(np.arange(len(Ez)),Ez) # Sets the updated values of fields. line1.set_data(np.arange(len(Hy)),Hy) #time.sleep(0.01) return line, ani = animation.FuncAnimation(fig, animate, init_func=init, frames= self.time_tot, interval=10, blit=False, repeat =False) # Note: We assign a reference to the animation, otherwise the # animation object will be considered for garbage collection. fig.show() return ref, trn, src elif (self.source_choice==2): # When the source is an impulse of height 1 unit. #axes[0].set_ylim(-0.1,0.1) axes[1].set_ylim(-0.002,0.002) def animate(n, *args, **kwargs): """ Same as above.""" if (n==0): Esrc = 1 else: Esrc = 0 Hsrc = H_src_correction*0 Ez[xsrc] = Ez[xsrc] + Esrc Hy[0:xdim-1] = A[0:xdim-1]*Hy[0:xdim-1]+B[0:xdim-1]*(Ez[1:xdim]-Ez[0:xdim-1]) Hy[xsrc-1] = Hy[xsrc-1] - B[xsrc-1]*Esrc Ez[1:xdim]= C[1:xdim]*Ez[1:xdim]+D[1:xdim]*(Hy[1:xdim]-Hy[0:xdim-1]) Ez[xsrc] = Ez[xsrc] - D[xsrc]*Hsrc ylims1 = axes[0].get_ylim() ylims2 = axes[1].get_ylim() e_max = abs(np.amax(Ez)) h_max = abs(np.amax(Hy)) Ez[xdim-1]= self.dum2+((self.S-1)/(self.S+1))*(Ez[xdim-2]-Ez[xdim-1]) Ez[1]= self.dum1+((self.S-1)/(self.S+1))*(Ez[1]-Ez[0]) Ez[0]= Ez[2] self.dum1 = Ez[2] self.dum2 = Ez[xdim-2] ref[0:n_steps] = ref[0:n_steps] + (exp_terms[0:n_steps]**(n))*Ez[0] trn[0:n_steps] = trn[0:n_steps] + (exp_terms[0:n_steps]**(n))*Ez[xdim-1] src[0:n_steps] = src[0:n_steps] + (exp_terms[0:n_steps]**(n))*Esrc if (e_max > ylims1[1]): # Scaling axes. axes[0].set_ylim(-(1.2*e_max),1.2*e_max) if ((h_max)>ylims2[1]): # Scaling axes. axes[1].set_ylim(-(1.2*h_max),1.2*h_max) line.set_data(np.arange(len(Ez)),Ez) line1.set_data(np.arange(len(Hy)),Hy) if n==0: Ez[xsrc] = Ez[xsrc] + 0 # Impulse source. return line, ani = animation.FuncAnimation(fig, animate, init_func=init, frames=(self.time_tot), interval=10, blit=False, repeat =False) fig.show() return ref, trn, src elif (self.source_choice==3): # When the source is gaussian. def gauss_src(n): source = 1.0*(1/np.sqrt(2*np.pi))*np.exp(-((n-80.0)*self.deltat)**2/(5*self.deltat)**2) return source def animate(n, *args, **kwargs): """Same as earlier.""" Esrc = gauss_src(n) Hsrc = H_src_correction*Esrc Ez[xsrc] = Ez[xsrc] + Esrc Hy[0:xdim-1] = A[0:xdim-1]*Hy[0:xdim-1]+B[0:xdim-1]*(Ez[1:xdim]-Ez[0:xdim-1]) Hy[xsrc-1] = Hy[xsrc-1] - B[xsrc-1]*Esrc Ez[1:xdim]= C[1:xdim]*Ez[1:xdim]+D[1:xdim]*(Hy[1:xdim]-Hy[0:xdim-1]) Ez[xsrc] = Ez[xsrc] - D[xsrc]*Hsrc ylims1 = axes[0].get_ylim() ylims2 = axes[1].get_ylim() e_max = abs(np.amax(Ez)) h_max = abs(np.amax(Hy)) Ez[xdim-1]= self.dum2+((self.S-1)/(self.S+1))*(Ez[xdim-2]-Ez[xdim-1]) Ez[1]= self.dum1+((self.S-1)/(self.S+1))*(Ez[1]-Ez[0]) Ez[0]= Ez[2] self.dum1 = Ez[2] self.dum2 = Ez[xdim-2] ref[0:n_steps] = ref[0:n_steps] + (exp_terms[0:n_steps]**(n))*Ez[0] trn[0:n_steps] = trn[0:n_steps] + (exp_terms[0:n_steps]**(n))*Ez[xdim-1] src[0:n_steps] = src[0:n_steps] + (exp_terms[0:n_steps]**(n))*Esrc if (e_max > ylims1[1]): # Scaling axes. axes[0].set_ylim(-(1.2*e_max),1.2*e_max) if ((h_max)>ylims2[1]): # Scaling axes. axes[1].set_ylim(-(1.2*h_max),1.2*h_max) line.set_data(np.arange(len(Ez)),Ez) line1.set_data(np.arange(len(Hy)),Hy) return line, ani = animation.FuncAnimation(fig, animate, init_func=init, frames=(self.time_tot), interval=5, blit=False, repeat =False) fig.show() return ref, trn, src else : print (" The choice entered is not valid. Please enter a valid choice and try again.\n") def main(): simulation = FdTd() ref ,trn, src = simulation.plotFields() fig2 , ax = plt.subplots(3,1) frequencies = np.linspace(1,simulation.h_frequency,simulation.number_steps_freq) ref = (ref)*simulation.deltat trn = (trn)*simulation.deltat src = (src)*simulation.deltat ref = (abs(ref/src))**2 trn = (abs(trn/src))**2 #print ref[1:10] #print np.amax(trn) ax[0].plot(frequencies, ref.real ) ax[0].set_title("FFT of relection coefficient") ax[1].plot(frequencies, trn.real ) ax[1].set_title("FFT of Transmission coefficient") ax[2].plot(frequencies, src.real) ax[2].set_title("FFT of Source") plt.show() fig3, axis = plt.subplots(1,1) axis.plot(frequencies,ref+trn) #axis.set_ylim(0,2) plt.show() if __name__ == "__main__": main()
cf59bd73ce18bb69146cce53401615931f800ead
utgupta27/Utext
/test.py
351
3.921875
4
def check(num): if num%2!=0: print('Weird') else: if num>=2 or num<=5 : print('Not Weird') elif num>=6 or num<=20: print('Weird') elif num>20: print('Not Weird') else: pass if __name__ == '__main__': n = int(input().strip()) check(n)
b14baac35f52e7b222387e5f877727859d04be5c
liusska/Python-Basic-Sept-2020-SoftUni
/FirstSteps/lab/9.YardGreening.py
217
3.5625
4
yard = float(input()) price_yard = float(yard * 7.61) discount = float(price_yard * 0.18) price = float(price_yard - discount) print(f"The final price is: {price} lv.") print(f"The discount is: {discount} lv.")
966cc62351bc90450c1769d3d6fa0f33c366de3c
mborbola/adventofcode
/2018/11/1.py
1,164
3.890625
4
def read_input(): with open('input', 'r') as f: grid_serial_number = int(f.readline()) return grid_serial_number def hundred(power): return int(str(power)[-3]) # First I created this to generate the cell's power based on x,y and serial number def calc_power(x, y, grid_serial_number): rack_id = x + 10 power = y * rack_id power += grid_serial_number power *= rack_id power = hundred(power) power -= 5 return power def get3by3power(grid, x, y): sum = 0 for i in range(3): for j in range(3): sum += grid[x + i][y + j] return sum def main(): grid_serial_number = read_input() grid = [[calc_power(x, y, grid_serial_number) for y in range(1, 300)] for x in range(1, 300)] max_power = -100 max_coord = (0,0) for x in range(0, 297): for y in range(0, 297): power = get3by3power(grid, x, y) if power > max_power: max_power = power max_coord = (x, y) # anwser assumes a 1-300 grid but I have a 0-299 print(f'The max power is: {max_power} at <{max_coord[0]+1},{max_coord[1]+1}>') main()
bb45aad9636411b3da7087c888a4923c25ef6ac8
transferome/Simulations
/fst/avgfst.py
2,785
3.53125
4
""" Finds the average fst value for each simulated region """ import fst.listfst as lister import numpy as np def fstopen(fstfile): with open(fstfile) as f: fstlist = [float(line.rstrip('\n').split(',')[1]) for line in f] return fstlist # function finds the average Fst within a between or within .txt file def avgfst_between(fstfile): """Return the mean fst from an fst file""" fstlist = fstopen(fstfile) return str(round(sum(fstlist)/len(fstlist), 8)) def varfst_between(fstfile): """Return the variance in fst from an fst file""" fstlist = fstopen(fstfile) return str(round(float(np.var(fstlist, ddof=1)), 8)) def avgfst_within(fst1, fst2): fstlist1 = fstopen(fst1) fstlist2 = fstopen(fst2) fstlist = fstlist1 + fstlist2 return str(round(sum(fstlist)/len(fstlist), 8)) def varfst_within(fst1, fst2): fstlist1 = fstopen(fst1) fstlist2 = fstopen(fst2) fstlist = fstlist1 + fstlist2 return str(round(float(np.var(fstlist, ddof=1)), 8)) # this will take the blueprint object, which holds the information on the # original window and contig class AvgFst: """Calculates Average Fst for each region file and adds it to a list Methods for working with that list object into a data file""" def __init__(self, contig, pos1, pos2): """Sets up an id tag simulation_window given the blueprint, also a keyword argument that will be within or between""" self.contig = contig self.window = (pos1, pos2) self.simulation_window = '{}_{}-{}'.format(self.contig, str(self.window[0]), str(self.window[1])) self.repAwithins = None self.repBwithins = None self.betweens = None self.regions = None self.fst_data = ['region,withinFst_mean,betweenFst_mean,withinFst_var,betweenFst_var\n'] def files_regions(self): """ Gets the files""" self.repAwithins = lister.withinfiles(replicate='A') self.repBwithins = lister.withinfiles(replicate='B') self.betweens = lister.betweenfiles() self.regions = [s.split('_')[0] for s in self.betweens] def gather_data(self): for w, x, y, z in zip(self.regions, self.repAwithins, self.repBwithins, self.betweens): self.fst_data.append('{}\n'.format(','.join([w, avgfst_within(x, y), avgfst_between(z), varfst_within(x, y), varfst_between(z)]))) def write_sum(self): """Writes out fstdata, 1 is repa within, 1 is repb within, final is between""" with open('{}_Simulation_Fst.dat'.format(self.simulation_window), 'w+') as output: for line in self.fst_data: output.write(line) if __name__ == '__main__': pass
9c0b92bf205ad514856f0bd44af2555e6c2c4e90
tekjar/flying-car
/fcnd.exercises/3d/astar.py
4,781
4.125
4
import numpy as np from enum import Enum from queue import PriorityQueue # breadth-first search is to keep track of visited cells and all your partial plans # and always expand the shortest partial plan first # now we add the notion of cost function. which is the total cost of all the actions in a partial plan # this helps in expansion to optimize the search process for lowest cost # note that by expanding by bringing next lowest cost node to the front of the queue before analyzing same # level neighbours, we'll start analyzing next level before analyzing all current level nodes and hence loose # shortest path class Action(Enum): LEFT = ((0, -1), 1) RIGHT = ((0, 1), 1) UP = ((-1, 0), 1) DOWN = ((1, 0), 1) def __str__(self): ''' returns string representation of this action ''' if self == self.LEFT: return '>' elif self == self.RIGHT: return '<' elif self == self.UP: return '^' elif self == self.DOWN: return 'v' def move_value(self): ''' returns (row, column) value to add to current position to perform this action ''' return self.value[0] def cost(self): ''' returns cost of current action ''' return self.value[1] class Astar: def __init__(self, graph): self.graph = graph self.start = None self.goal = None def heuristic(self, current_position): ''' Returns euclidian heuristic ''' sub = np.subtract(self.goal, current_position) return np.linalg.norm(sub) def valid_actions(self, current_position): current_row, current_column = current_position[0], current_position[1] up_index = current_row - 1 down_index = current_row + 1 left_index = current_column - 1 right_index = current_column + 1 max_row_index, max_column_index = self.map_matrix_shape() valid = [Action.UP, Action.DOWN, Action.LEFT, Action.RIGHT] # print('row = ', current_row, 'column = ', current_column) # upward movement out of map if up_index < 0 or self.map[up_index][current_column] == 1: valid.remove(Action.UP) # downward movement out of map if down_index > max_row_index or self.map[down_index][current_column] == 1: valid.remove(Action.DOWN) # leftside movement out of map if left_index < 0 or self.map[current_row][left_index] == 1: valid.remove(Action.LEFT) # rightside movement out of map if right_index > max_column_index or self.map[current_row][right_index] == 1: valid.remove(Action.RIGHT) return valid def move(self, current, action): ''' moves the current position based on action and returns position after movement ''' drow, dcolumn = action.move_value() return current[0] + drow, current[1] + dcolumn def travel(self, start, goal): self.start = start self.goal = goal # {currnt_position: (parent, action)} paths = {} visited = set() queue = PriorityQueue() found = False queue.put((0, start)) # there are still nodes to traverse through while not queue.empty(): current_total_cost, current_node = queue.get() if current_node == goal: found = True break for neighbour in self.graph[current_node]: neighbour_cost = self.graph.edges[current_node, neighbour]['weight'] heuristic_cost = self.heuristic(current_node) total_cost = current_total_cost + neighbour_cost + heuristic_cost # print('current = ', current, ' action = ', action, ' after action = ', neighbour) if neighbour not in visited: visited.add(neighbour) queue.put((total_cost, neighbour)) paths[neighbour] = (total_cost, current_node) return found, paths def trace_back(self, paths): path = [] # trace back from goal next = self.goal while next != self.start: cost, next = paths[next] path.append(next) path = path[::-1] return path def axis_points(self, path): ''' :param path: path from start to goal :return: x, y coordinate points for plotting ''' sgrid_row = [] sgrid_column = [] pos = self.start for i in range(len(path)): pos = path[i] sgrid_row.append(pos[0]) sgrid_column.append(pos[1]) return sgrid_column, sgrid_row
e52553a913da8472c30b6fea6b177c0bb8d7a906
MiguelOrellanaR/PROGRAMAS_PROYECTOS
/Factorial.py
2,117
4.0625
4
def pedir_numero_menú(): correcto = False num = 0 while (not correcto): try: num = int(input("\n>Ingrese una opción del menú:")) print() correcto = True except ValueError: print("Error, Ingrese un número que corresponda a una opción del menú\n") return num def pedir_numero(): correcto = False num = 0 while (not correcto): try: num = int(input("Ingrese número:")) if (num >= 0): print() correcto = True else: print("Los factoriales de números negativos están indefinidos. Ingrese un entero positivo") print() except ValueError: print("Error, Ingrese un número entero positivo.\n") return num salir = False opcion = 0 while (not salir): print('-------MENÚ-------') print("1. Ingresar número") print("2. Historial") print("3. salir") opcion = pedir_numero_menú() if opcion == 1: archivo = open("Prog1.txt", "a") fac = pedir_numero() factorial=1 fac1=str(fac) archivo.write("El número ingresado es: " + fac1); archivo.write("\n"); if (fac % 7 ==0): for n in range(fac): factorial = factorial * (n + 1) factorial1=str(factorial) print("El factorial es: ", factorial) print() archivo.write("El factorial es: 1"+factorial1); archivo.write("\n"); archivo.write("\n") else: print("Error. Ingrese un número divisible entre 7.\n") archivo.write("No es un número divisible entre 7."); archivo.write("\n"); archivo.write("\n") archivo.close() elif opcion == 2: archivo = open("Prog1.txt", "r") historial = archivo.read() archivo.close() print(historial) elif opcion == 3: salir = True else: print("Ingrese un número que corresponda a una opción del menú\n") print(' ** Miguel Antonio Orellana Ruíz**')
92b8816d81c3edb5f94a0a1deacb42d00bc70032
MrAttoAttoAtto/CircuitSimulatorC2
/components/Diode.py
5,601
3.71875
4
import math from typing import List, Tuple from components.Component import Component from general.Circuit import Circuit from general.Environment import Environment class Diode: """ A basic diode using the Schottky Diode Equation """ def __init__(self, breakdownVoltage: float = 40, saturationCurrent: float = 1e-12, ideality: float = 1): """ Creates a diode, setting all the nodes to None before the resistor is connected :param breakdownVoltage: The voltage (in Volts) at which the diode breaks down when in reverse bias :param saturationCurrent: The current (in Amps) allowed to flow when the diode is in reverse bias :param ideality: The ideality (n) of the diode as modelled by the Schottky Diode Equation """ # Basic diode properties self.breakdownVoltage = breakdownVoltage self.saturationCurrent = saturationCurrent self.ideality = ideality # The objects that will hold the voltage at the anode and cathode nodes of the resistor # These are the values corresponding to the anode and cathode nodes in the INPUT VECTOR self.anodeVoltage = None self.cathodeVoltage = None # The objects that will hold the current at the anode and cathode nodes of the resistor # These are the values corresponding to the anode and cathode nodes in the RESULT VECTOR self.anodeCurrent = None self.cathodeCurrent = None # The objects that will hold the conductances at the anode and cathode nodes in the resistor: in essence # the derivatives of the currents with respect to the anode and cathode voltages # These are the values corresponding to the anode and cathode nodes in the JACOBIAN MATRIX self.anodeConductanceByAnodeVoltage = None self.anodeConductanceByCathodeVoltage = None self.cathodeConductanceByAnodeVoltage = None self.cathodeConductanceByCathodeVoltage = None # noinspection PyMethodMayBeStatic def getRequiredCrossNodes(self, nodes: List[int], identifier: int) -> List[Tuple[int, int, int]]: """ Returns an empty list as cross-node entries are not required for a diode :param nodes: The nodes this diode is connected to (anode, cathode) :param identifier: This diode's identifier :return: An empty list """ return [] def connect(self, circuit: Circuit, nodes: List[int]): """ Connects the diode to its specified nodes Sets the matrix/vector reference objects as defined above :param circuit: The circuit :param nodes: A list of the (2) nodes this diode is connected to, with the anode being first :return: None """ anodeNode, cathodeNode = nodes self.anodeVoltage = circuit.getInputReference(anodeNode) self.cathodeVoltage = circuit.getInputReference(cathodeNode) self.anodeCurrent = circuit.getResultReference(anodeNode) self.cathodeCurrent = circuit.getResultReference(cathodeNode) self.anodeConductanceByAnodeVoltage = circuit.getJacobianReference(anodeNode, anodeNode) self.anodeConductanceByCathodeVoltage = circuit.getJacobianReference(anodeNode, cathodeNode) self.cathodeConductanceByAnodeVoltage = circuit.getJacobianReference(cathodeNode, anodeNode) self.cathodeConductanceByCathodeVoltage = circuit.getJacobianReference(cathodeNode, cathodeNode) def stamp_static(self, environment: Environment): """ Amends the values at its nodes to affect the circuit as the diode would, after infinite time. :param environment: The environment of the circuit when this diode is operating :return: None """ thermalVoltage = environment.k * environment.temperature / environment.q idealityTemperatureModifier = self.ideality * thermalVoltage voltageAcross = self.anodeVoltage.value - self.cathodeVoltage.value try: # If the diode is in reverse bias more strong than the breakdown voltage, it's broken down! if voltageAcross < -self.breakdownVoltage: reverseBiasVoltage = -self.breakdownVoltage - voltageAcross current = -(self.saturationCurrent * math.exp(reverseBiasVoltage / idealityTemperatureModifier)) conductance = self.saturationCurrent * \ math.exp(reverseBiasVoltage / idealityTemperatureModifier) / idealityTemperatureModifier else: current = self.saturationCurrent * (math.exp(voltageAcross / idealityTemperatureModifier) - 1) conductance = self.saturationCurrent * \ math.exp(voltageAcross / idealityTemperatureModifier) / idealityTemperatureModifier except OverflowError: # It's probably wrong if there's a math range error, so to save ourselves from pain, make it a smol resistor conductance = 1 / environment.gMin current = voltageAcross * conductance self.anodeCurrent += current self.cathodeCurrent -= current conductance += environment.gMin self.anodeConductanceByAnodeVoltage += conductance self.anodeConductanceByCathodeVoltage -= conductance self.cathodeConductanceByAnodeVoltage -= conductance self.cathodeConductanceByCathodeVoltage += conductance def stamp_transient(self, environment: Environment, delta_t: int): self.stamp_static(environment) Component.register(Diode)
ee4497f47d5b3d3f120cdd589db4c394464faebe
vmred/codewars
/katas/6kyu/Mix Fruit Juice/solution.py
1,147
4.0625
4
# Story # Jumbo Juice makes a fresh juice out of fruits of your choice. # Jumbo Juice charges $5 for regular fruits and $7 for special ones. # Regular fruits are Banana, Orange, Apple, Lemon and Grapes. # Special ones are Avocado, Strawberry and Mango. # Others fruits that are not listed are also available upon request. # Those extra special fruits cost $9 per each. # There is no limit on how many fruits she/he picks. # The price of a cup of juice is the mean of price of chosen fruits. # In case of decimal number (ex. $5.99), output should be the nearest integer # (use the standard rounding function of your language of choice). # Input # The function will receive an array of strings, each with the name of a fruit. # The recognition of names should be case insensitive. There is no case of an enmpty array input. # Example # ['Mango', 'Banana', 'Avocado'] //the price of this juice bottle is (7+5+7)/3 = $6($6.333333...) def mix_fruit(arr): fruits = {'banana': 5, 'orange': 5, 'apple': 5, 'lemon': 5, 'grapes': 5, 'avocado': 7, 'strawberry': 7, 'mango': 7} return round(sum(fruits.get(i.lower(), 9) for i in arr) / len(arr))
56a7e682f1d8634b1df7a3f914e25bf32ec31e56
preneetho/ML
/Capstone Project/house-prediction/src/processing.py
13,519
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 9 17:18:57 2020 @author: preneeth """ import pandas as pd import numpy as np import pickle #dataframe to hold input data from a excel. This is for testing the moldel with data from excel (1 row) df = pd.DataFrame() #this df holds the processed input data. final_df = pd.DataFrame() #this df holds the actual data for preprocessing inout data. masterDataDF = pd.read_csv('../data/innercity.csv') # Derive Age of the house at the time of sale from dayhours. def processDayhours(): df["yr_sold"] = df["dayhours"].apply(lambda x:x[:4]).astype(int) df["age_sold"] = df.yr_sold - df.yr_built # Set Categorical columns def setCategoricalColumns(): df.coast = pd.Categorical(df.coast) df.condition = pd.Categorical(df.condition, ordered=True) df.quality = pd.Categorical(df.quality, ordered=True) df.furnished = pd.Categorical(df.furnished) df.zipcode = pd.Categorical(df.zipcode) df.yr_built = pd.Categorical(df.yr_built) df.yr_sold = pd.Categorical(df.yr_sold) # Method to Mean encoding of categorical columns def addMeanEncodedFeature (indFeatureName): global df grpDF = pd.read_csv('../data/'+indFeatureName+'.csv') grpDF.rename(columns = {indFeatureName:'key', 0:"val"}, inplace = True) grpDF.set_index("key", inplace = True) lookup = str(df.loc[0,indFeatureName]) if ((indFeatureName == 'furnished') or (indFeatureName == 'coast')): lookup = df.loc[0,indFeatureName] lookupval = grpDF.at[lookup, 'val'] df.loc[:,indFeatureName+'_enc'] = lookupval # Method for processing Age Sold Feature def binAgeSold(): df['age_sold_quantile_bin'] = df.apply(lambda val: round((val['age_sold'] / 10))*10, axis=1 ) #masterDataDF['age_sold_quantile_bin'] = masterDataDF.apply(lambda val: round((val['age_sold'] / 10))*10, axis=1 ) addMeanEncodedFeature(df['age_sold_quantile_bin'].name) # Method for processing Lat and long Feature def binLatLong(): lat_long_df = pd.read_csv('../data/lat_long_df.csv') lat_long_df.rename(columns = {0:"val"}, inplace = True) lat_long_df.set_index("key", inplace = True) lat_long_df["val"]= lat_long_df["val"].astype(str) longmin = float(lat_long_df.at['longmin', 'val'] ) latmin = float(lat_long_df.at['latmin', 'val'] ) df['long_bin'] = df['long'].apply(lambda val: round(( abs(longmin) - abs(val)) /.2)) df['lat_bin'] = df['lat'].apply(lambda val: round(( abs(val) - abs(latmin) )/.2)) df['region'] = df.apply (lambda row: str(row['long_bin'])+'-'+str(row['lat_bin']), axis=1) #df.region = pd.Categorical(df.region).codes df['Region_name']= df.apply (lambda row: "Region"+'-'+str(row['region']), axis=1) addMeanEncodedFeature(df['Region_name'].name) # Method for processing condition Feature def binCondition(): conditions_df = [ df['condition'] == 1, df['condition'] == 2, df['condition'] == 3, df['condition'] == 4, df['condition'] == 5 ] choices = ['Bad', 'Bad', 'Average', 'Average', 'Good'] df['condition_bin'] = np.select(conditions_df, choices) addMeanEncodedFeature(df['condition_bin'].name) # Method for processing Quality Feature def binQuality(): conditions_df = [ df['quality'] < 7, df['quality'] == 7, df['quality'] == 8, df['quality'] == 9, df['quality'] == 10, df['quality'] > 10 ] choices = ['Bad', 'Average','Average','Average','Average', 'Good'] df['quality_bin'] = np.select(conditions_df, choices) addMeanEncodedFeature(df['quality_bin'].name) # Method for processing bed room Feature def binBedRooms(): conditions_df = [ df['room_bed'] < 3, df['room_bed'] == 3, df['room_bed'] == 4, df['room_bed'] == 5, df['room_bed'] == 6, df['room_bed'] > 6] choices = ['Small','Average','Average','Large','Large','Large'] df['room_bed_bin'] = np.select(conditions_df, choices) addMeanEncodedFeature(df['room_bed_bin'].name) #method to return bath type def getBathType(x): if (x < 2): return "1_Bath" elif (x >= 2 and x <3): return "2_Bath" elif (x >= 3): return "3_Bath" else : return # Method for processing bath room Feature def binBath(): df['room_bath_bin'] = df['room_bath'].apply(lambda val: getBathType(val)) addMeanEncodedFeature(df['room_bath_bin'].name) def getCeilType(x): if (x <= 1): return "1_Floor" elif (x > 1 and x <= 2): return "2_Floor" elif (x > 2): return "3_Floor" else : return def binCeil(): df['ceil_bin'] = df['ceil'].apply(lambda val: getCeilType(val)) addMeanEncodedFeature(df['ceil_bin'].name) def getSightType(x): if (x == 0): return "No_Visits" elif (x >= 1 and x <= 3): return "Few_Visits" elif (x > 3): return "More_Visits" else : return def binSight(): df['sight_bin'] = df['sight'].apply(lambda val: getSightType(val)) addMeanEncodedFeature(df['sight_bin'].name) def getYrBuilt(val): if str(val).find("1875, 1900") > 0: return "1900s" elif str(val).find("1900, 1925") > 0: return "1925s" elif str(val).find("1925, 1950") > 0: return "1950s" elif str(val).find("1950, 1975") > 0: return "1975s" elif str(val).find("1975, 2000") > 0: return "2000s" elif str(val).find("2000, 2025") > 0: return "2025s" else : return "Others" def binYrBuilt(): df['yr_built_tmpbin'] = pd.cut(df.yr_built, bins=[1875,1900,1925,1950,1975,2000,2025]) df['yr_built_bin'] = df['yr_built_tmpbin'].apply(lambda val: getYrBuilt(val) ) df.drop(['yr_built_tmpbin'], axis=1, inplace=True) addMeanEncodedFeature(df['yr_built_bin'].name) def getYrRenovated(val, year): if (year == 0 or year == 1890): return "Not Renovated" elif str(val).find("1875, 1900") > 0: return "1900s" elif str(val).find("1900, 1925") > 0: return "1925s" elif str(val).find("1925, 1950") > 0: return "1950s" elif str(val).find("1950, 1975") > 0: return "1975s" elif str(val).find("1975, 2000") > 0: return "2000s" elif str(val).find("2000, 2025") > 0: return "2025s" else: return "Others" def binYrRenovated() : df.loc[(masterDataDF.yr_renovated == 0), "yr_renovated"]=1890 df['yr_renovated_tmpbin'] = pd.cut(df.yr_renovated, bins=[1875,1900,1925,1950,1975,2000,2025]) df['yr_renovated_bin'] = df.apply(lambda val: getYrRenovated(val['yr_renovated_tmpbin'], val['yr_renovated']), axis=1 ) addMeanEncodedFeature(df['yr_renovated_bin'].name) def getZipcode(val): if str(val).find("98000, 98025") > 0: return "ZIPGRP1" elif str(val).find("98025, 98050") > 0: return "ZIPGRP2" elif str(val).find("98050, 98075") > 0: return "ZIPGRP3" elif str(val).find("98075, 98100") > 0: return "ZIPGRP4" elif str(val).find("98100, 98125") > 0: return "ZIPGRP5" elif str(val).find("98125, 98150") > 0: return "ZIPGRP6" elif str(val).find("98150, 98175") > 0: return "ZIPGRP7" elif str(val).find("98175, 98199") > 0: return "ZIPGRP8" else: return "Others" def binZipcode(): global df df['zipcode_tmpbin'] = pd.cut(df.zipcode, bins=[98000, 98025, 98050,98075, 98100,98125, 98150, 98175, 98199]) df['zipcode_bin'] = df.apply(lambda val: getZipcode(val['zipcode_tmpbin']), axis=1 ) df.drop(['zipcode_tmpbin'], axis=1, inplace=True) encoded_columns = pd.get_dummies(df['zipcode_bin'], prefix="zipcode") df = df.join(encoded_columns) def binFurnished(): addMeanEncodedFeature (df.furnished.name) def binCoast(): addMeanEncodedFeature (df.coast.name) def dataLogTransformation(): df['lot_measure_log'] = (df['lot_measure']+1).transform(np.log) df['ceil_measure_log'] = (df['ceil_measure']+1).transform(np.log) df['basement_log'] = (df['basement']+1).transform(np.log) #Function to drop attributes def dropAttributes (columns_list): for col in columns_list: if col in df.columns: df.drop(col, axis=1, inplace=True) print ("Dropped Attribute : "+ col) def dropFeatures(): dropCols = ['living_measure15','lot_measure15'] dropAttributes (dropCols) dropCols = ['cid','living_measure','total_area', 'dayhours'] dropAttributes (dropCols) dropCols = ['room_bed','room_bath', 'lot_measure', 'ceil', 'coast', 'sight', 'condition',\ 'quality', 'ceil_measure', 'basement', 'yr_built', 'yr_built_bin', 'zipcode_bin',\ 'yr_renovated', 'yr_renovated_bin', 'zipcode', 'lat', 'long', 'furnished', 'yr_sold', \ 'long_bin', 'lat_bin', 'region', 'Region_name', 'condition_bin', 'quality_bin', \ 'room_bed_bin', 'room_bath_bin', 'ceil_bin', 'sight_bin', 'age_bin','age_sold', \ 'age_sold_bin','age_sold_quantile_bin' ] dropAttributes (dropCols) dropCols=['zipcode_ZIPGRP1','zipcode_ZIPGRP7','zipcode_ZIPGRP6', 'zipcode_ZIPGRP4'] dropAttributes (dropCols) #Function to replace outliers lying outside IQR range with median value. def fixOutlier (col): global masterDataDF Q1 = col.quantile(0.25) Q3 =col.quantile(0.75) IQR = Q3 - Q1 max_value = Q3+(1.5*IQR) min_value = Q1-(1.5*IQR) masterDataDF.loc[( col < min_value) | (col > max_value), col.name] = col.median() def fixOutliers (): global masterDataDF fixOutlier(masterDataDF.basement) fixOutlier(masterDataDF.lot_measure) fixOutlier(masterDataDF.ceil_measure) fixOutlier(masterDataDF.room_bath) #Method to set the data types of all features def setDataTypes(): global df convert_dict = {'cid': object, 'dayhours': object, 'room_bed': float, 'room_bath': float, 'living_measure': float, 'lot_measure': float, 'ceil': float, 'coast': int, 'sight': int, 'condition': int, 'quality': int, 'ceil_measure': float, 'basement': float, 'yr_built': int, 'yr_renovated': int, 'zipcode': int, 'lat': float, 'long': float, 'living_measure15': float, 'lot_measure15': float, 'furnished': int, 'total_area': float } df = df.astype(convert_dict) #Method for pre processing and feature engg of input data def preProcessing(inputData): global df cols = ['cid', 'dayhours', 'room_bed', 'room_bath', 'living_measure',\ 'lot_measure', 'ceil', 'coast', 'sight', 'condition', 'quality',\ 'ceil_measure', 'basement', 'yr_built', 'yr_renovated', 'zipcode',\ 'lat', 'long', 'living_measure15', 'lot_measure15', 'furnished',\ 'total_area'] df = pd.DataFrame([inputData], columns=cols) setDataTypes() print ("DataTypes Set for all Features") processDayhours() print ("Derived age and year sold feature.") fixOutliers() print ("Fixed outliers") binAgeSold () print ("Age Sold - Processed") binLatLong () print ("Lat & Long - Processed") binCondition () print ("Condition- Processed") binQuality() print ("Quality- Processed") binBedRooms () print ("Bed Rooms- Processed") binBath () print ("Bath Rooms- Processed") binCeil() print ("Ceil- Processed") binSight () print ("Sight- Processed") binYrBuilt() print ("Yr Built- Processed") binYrRenovated() print ("Yr Renovated- Processed") binZipcode() print ("Zipcode- Processed") binFurnished() print ("Furnished- Processed") binCoast() print ("Coast- Processed") dataLogTransformation() print ("Data Log Transformation completed") setCategoricalColumns() print ("Set Categorical Features ") dropFeatures() model_cols=['furnished_enc', 'Region_name_enc', 'quality_bin_enc', 'ceil_measure_log', 'lot_measure_log', 'sight_bin_enc', 'basement_log', 'coast_enc', 'yr_built_bin_enc', 'yr_renovated_bin_enc', 'zipcode_ZIPGRP3', 'age_sold_quantile_bin_enc', 'room_bed_bin_enc', 'room_bath_bin_enc', 'zipcode_ZIPGRP5', 'ceil_bin_enc', 'zipcode_ZIPGRP2', 'condition_bin_enc'] for col in model_cols: if col in df.columns: final_df[col]=df[col] else: final_df[col]=0 processedData = list(final_df.loc[0]) return processedData #Method to test the code as standalone def test(): #A simple method to read a input data and pass it to the #processing method tempDf = pd.DataFrame() tempDf = pd.read_csv('../data/input.csv') inputData = list(tempDf.loc[0]) model = pickle.load(open('../model/HousePrediction.pkl', 'rb')) print (inputData) processedData = preProcessing(inputData) output = np.round(model.predict([processedData]),2) print ("Predicted Value ===> "+ str(output)) test()
0c92a853c41fe7ca55c8de03a7fe42c7217c93ab
314H/Data-Structures-and-Algorithms-with-Python
/Dictionaries/Maps/Longest subset zero sum.py
1,144
3.671875
4
""" Longest subset zero sum Given an array consisting of positive and negative integers, find the length of the longest subarray whose sum is zero. NOTE : You have to return the length of longest subarray . #### Input Format : Line 1 : Contains an integer N i.e. size of array Line 2 : Contains N elements of the array, separated by spaces #### Output Format Line 1 : Length of longest subarray #### Constraints: 0 <= N <= 10^8 #### Sample Input : 10 95 -97 -387 -435 -5 -70 897 127 23 284 #### Sample Output : 5 """ def subsetSum(l): #Implement Your Code Here n=len(l) sum=[0]*n sum[0]=l[0] m={l[0]:0} start, end=-1,-2 if sum[0]==0: start, end=0,0 for i in range(1,n): sum[i]=sum[i-1]+l[i] if sum[i]==0: start, end=0,i elif sum[i] in m: if i-m[sum[i]]>end-start+1: start,end=m[sum[i]]+1,i else: m[sum[i]]=i return start,end n=int(input()) l=list(int(i) for i in input().strip().split(' ')) #finalLen= subsetSum(l) #print(finalLen) start,end=subsetSum(l) print(end-start+1)
533ae9683cadaa42071508458f5cba79b58c5d1d
ajylee/cryptopals-challenges
/pkcs1.py
1,225
3.671875
4
def pad(data_block, second_byte, block_size): """ This is the rigorous PKCS#1 described in Bleichenbacher 98. """ padding_string_len = block_size - len(data_block) - 3 return chr(0) + second_byte + padding_string_len * chr(0xff) + chr(0) + data_block def check_and_remove_padding(plaintext_signature, second_byte, min_padding_string_len=8): """If valid padding, removes padding and returns tuple (True, ASN.1 HASH) Otherwise returns (False, None) This is the actual PKCS#1 described in Bleichenbacher 98. Not necessary for Cryptopals, but interesting for testing. """ # NOTE: we cannot directly match the hash content using a regex group # because of possible newline chars (\n). fail = (False, None) for ii, cc in enumerate(plaintext_signature): if ((ii == 0 and cc == chr(0)) or (ii == 1 and cc == second_byte) or (2 <= ii and cc != chr(0))): continue elif ii >= (2 + min_padding_string_len) and cc == chr(0): data_block = plaintext_signature[ii + 1:] return (True, data_block) else: return fail else: return fail
c2a22bc62026ce277253c51f2dbdcd60a8274a3f
loganyu/leetcode
/problems/1925_count_square_sum_triples.py
762
3.953125
4
''' A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n. Example 1: Input: n = 5 Output: 2 Explanation: The square triples are (3,4,5) and (4,3,5). Example 2: Input: n = 10 Output: 4 Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10). Constraints: 1 <= n <= 250 ''' class Solution: def countTriples(self, n: int) -> int: count = 0 for a in range(1, n+1): for b in range(1, n+1): total = a**2 + b**2 c = int(math.sqrt(total)) if (c**2 == total and c <= n): count += 1 return count
e85fa0c74ec3f0ce036426975f8440f7383d68e3
bastiandg/adventofcode
/2016/day09.py
1,586
3.765625
4
#!/usr/bin/env python3 import sys def recursiveUncompression(length, multiplier, substring): index = 0 decompressedLength = 0 subCompression = False additionalCharacters = 0 while index < len(substring): if substring[index] == "(": for j in range(3, 10): if (index + j) < len(substring) and substring[index + j] == ")": subCompression = True compressionInstruction = substring[index + 1:index + j].split("x") subLength = int(compressionInstruction[0]) subMultiplier = int(compressionInstruction[1]) decompressedLength += recursiveUncompression(subLength, subMultiplier, substring[index + j + 1:index + j + 1 + subLength]) index = index + j + subLength break else: additionalCharacters += 1 index += 1 if subCompression: return decompressedLength * multiplier + additionalCharacters else: return length * multiplier def iterativeUncompression (input): decompressedLength = len(input) index = 0 while index < len(input): if input[index] == "(": for j in range(3, 10): if (index + j) < len(input) and input[index + j] == ")": compressionInstruction = input[index + 1:index + j].split("x") length = int(compressionInstruction[0]) multiplier = int(compressionInstruction[1]) instructionLength = j + 1 decompressedLength += (multiplier - 1) * length - instructionLength index = index + j + length break index += 1 return decompressedLength input = open("day09.txt", "r").read().split("\n")[0] print(iterativeUncompression(input)) print(recursiveUncompression(1, 1, input))
57bcf1d1d7a123424fec4cf54180e3b9a2e897f0
thinthinhtet22/Python-Class
/variable.py
801
3.578125
4
>>> 2 + 2 4 * / % + - (operator) adddition = 75 + 25 substraction = 204 - 204 multiplication = 100 * 0.5 division = 90 / 9 power of 2 = 3 ** 2 the remainder of the division = 10 % 3 int - integer - 1, 2, 3, ---> 308930 etc float - - 1.0, 5.9, 6.0, 63.23, etc string - - 'Hello', "World", "A", "B", a =1 a (variable) = (assign) 1 (value) width = 20 height = 5 * 9 vol = width * height vol sale = 1500 tax = 5 / 100 total_tax = slae * tax total_tax total_price = sale + total_tax total_price print('spam eggs') print('don\'t') print("doesn't") print('"Yes"') print("\"Yes,\" they said.") print('"Isn\'t," they said') print('"Isn\'t, they said"') s = 'First Line.\nSecondLIne' print(s) print("""\ Usage : thingy -a -b -c """) """...""" or '''...'''
ca2dfb54ab832ef74ebb3a59b40ab2fbde518cf2
vinayakgajjewar/bioinformatics
/hw2/2_1.py
5,121
3.65625
4
## no tree/graph/tries libraries allowed ## code adapted from https://nbviewer.jupyter.org/gist/BenLangmead/6665861 class SuffixTree(object): class Node(object): def __init__(self, lab): self.lab = lab # label on path leading to this node self.out = {} # outgoing edges; maps characters to nodes def traverse(self,level): """ Traverse the suffix tree in DFS order and prints the label on the edges with their level number """ for x in self.out: # x is the first letter of the outgoing edge, if self.out=={} we are in a leaf and the for loop is not executed child = self.out[x] # out[x] gives the pointer to the children with an edge that starts with x #print(child.lab) print(level,child.lab) child.traverse(level+1) # visit recursively the child def longestRepeat(self, s): global longest """ Returns the longest repeated string by finding the internal node in the suffix tree that corresponds to the longest string from the root""" ## YOUR CODE HERE for x in self.out: print("////////") child = self.out[x] #print(s, child.lab) print(child.lab) child.longestRepeat(s + child.lab) def __init__(self, s): """ Make suffix tree, without suffix links, from s in quadratic time and linear space """ s += '$' self.root = self.Node(None) self.root.out[s[0]] = self.Node(s) # trie for just longest suf # add the rest of the suffixes, from longest to shortest for i in range(1, len(s)): # start at root; we’ll walk down as far as we can go cur = self.root j = i while j < len(s): if s[j] in cur.out: child = cur.out[s[j]] lab = child.lab # Walk along edge until we exhaust edge label or # until we mismatch k = j+1 while k-j < len(lab) and s[k] == lab[k-j]: k += 1 if k-j == len(lab): cur = child # we exhausted the edge j = k else: # we fell off in middle of edge cExist, cNew = lab[k-j], s[k] # create “mid”: new node bisecting edge mid = self.Node(lab[:k-j]) mid.out[cNew] = self.Node(s[k:]) # original child becomes mid’s child mid.out[cExist] = child # original child’s label is curtailed child.lab = lab[k-j:] # mid becomes new child of original parent cur.out[s[j]] = mid else: # Fell off tree at a node: make new edge hanging off it cur.out[s[j]] = self.Node(s[j:]) def followPath(self, s): """ Follow path given by s. If we fall off tree, return None. If we finish mid-edge, return (node, offset) where 'node' is child and 'offset' is label offset. If we finish on a node, return (node, None). """ cur = self.root i = 0 while i < len(s): c = s[i] if c not in cur.out: return (None, None) # fell off at a node child = cur.out[s[i]] lab = child.lab j = i+1 while j-i < len(lab) and j < len(s) and s[j] == lab[j-i]: j += 1 if j-i == len(lab): cur = child # exhausted edge i = j elif j == len(s): return (child, j-i) # exhausted query string in middle of edge else: return (None, None) # fell off in the middle of the edge return (cur, None) # exhausted query string at internal node def hasSubstring(self, s): """ Return true iff s appears as a substring """ node, off = self.followPath(s) return node is not None def hasSuffix(self, s): """ Return true iff s is a suffix """ node, off = self.followPath(s) if node is None: return False # fell off the tree if off is None: # finished on top of a node return '$' in node.out else: # finished at offset 'off' within an edge leading to 'node' return node.lab[off] == '$' def traverse(self): return self.root.traverse(0) def longestRepeat(self): global longest longest = '' self.root.longestRepeat('') return longest # MAKE THE SUFFIX TREE f = open("test_input.txt", "r") text = f.readline().strip() stree = SuffixTree(text) stree.longestRepeat()
d3417a0e6c6f6e5545849ac1387a37cb6c120a3d
human-doodle/Airline-Management-Application
/Flight.py
620
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 13 18:56:26 2020 @author: Shivani """ class Flight: def __init__(self, num, f, t, d, q): self.__num= num self.__to=t self.__from=f self.__date=d self.__quota=q def display(self): print("\n") print("Flight num: ",self.__num) print("Source: ",self.__from) print("Destination: ",self.__to) print("Date: ",self.__date) print("Quota: ",self.__quota) print("\n") def retinfo(self): return self.__num,self.__from, self.__to,self.__date, self.__quota
de94430dbb18b7816e16cfffde7f265ac720c3f2
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4472/codes/1594_2426.py
208
3.5625
4
tempo = float(input("Tempo de viagem: ")) velocidade = float(input("Velocidade media: ")) distancia = velocidade * tempo quantidade = distancia / 12 print (round(distancia, 1)) print (round(quantidade, 1))
8826dbbabfec1f7a8b041b0a022d36cbea40132f
hcketjow/Trips-with-python3
/zaawansowe_TYPY/krotki-slownik.py
525
3.84375
4
krotka = 1,2,3,4 # krotka nie posiada nawiasów i nie można zmienić wartości krotki # --------------------------------------SŁOWNIK----------------------------------------- imie = str(input("Podaj imie i nazwisko: ")) number = str(input("Podaj number pokoju: ")) pokoje = { 49:"Wojciech Chodasiewicz", 69:"Zuzanna Trytek", } pokoje.update({number:imie}) print(pokoje) # del() - do usuwnaia # pop() - usuwa i zwraca wartość # update() - dodaje element # popitem() - usuwa ostatni element i go zwraca # clear() - czyści słownik
8eba6e56a0c8db1ee168366737df8083114f423d
Varobinson/python101
/celsius-or-fahrenheit.py
408
4.5625
5
#Prompt the user for a number in degrees Celsius, #and convert the value to degrees in Fahrenheit and #display it to the user. #prompt user try: degrees_celsius = int(input('What is the degrees celcius? ')) except ValueError: print('Enter Valid Temp! ') #convert celsius to fahrenheit degrees_fahrenheit = (degrees_celsius * 9/5) + 32 #return fahrenheit to user print(f'{degrees_fahrenheit} F ')
af500bbb7ea9ea46690003c32a87da436ca3bf53
jacob31/python_files
/time_clock.py
2,305
4.21875
4
#!/usr/bin/python import time class NotIntegerError(ValueError): pass class MakeScheduler(): def set_work_hours(self, work_hours=1): ''' sets the number of hours you plan on working defaults to 8 hours. ''' self.work_hours = work_hours if int(work_hours) != work_hours: raise NotIntegerError('non-integers can not be converted') def set_work_interval(self, work_interval=5): ''' max work interval with out a break is 50 minutes. defaults to 50 minutes. Minimum of 5 -10 minute break helps keep you eyes healthy. ''' self.work_interval = work_interval if int(work_interval) != work_interval: raise NotIntegerError('non-integers can not be converted') def set_break_interval(self, break_interval=1): ''' break interval is to remind you to look away from your computer This helps protect your eyes. default is 10 minutes ''' self.break_interval = break_interval if int(break_interval) != break_interval: raise NotIntegerError('non-integers can not be converted') # intervals are based off seconds 50min. == 3000sec. def work_hour(work_interval, break_interval): intervals = [to_seconds(work_interval), to_seconds(break_interval)] print("Starting interval timer...") for interval in intervals: timer(interval) # requires seconds if interval == work_interval: print("Take a break!\a") elif interval == break_interval: print("Time is up! Back to work...\a") else: print('error!!!') def timer(seconds): timer_count = 0 while timer_count < seconds: time.sleep(1) timer_count += 1 pass def to_seconds(min): return min * 1 def make_scheduler(): def scheduler(): for i in range(work_hours): work_hour(work_interval, break_interval) pass return scheduler # work_hours = 1 # work_interval = 10 # break_interval = 2 # my_schedule = make_scheduler(work_hours, work_interval, break_interval) # my_schedule()
4d93c77d64256530155ae0b293915f440d662aaa
jobu95/euler
/src/pr006.py
579
3.890625
4
# compute the sum of squares of the first n natural numbers def sqsum(n): if n < 1: return 0 def iter(cur, acc): if cur == 0: return acc else: return iter(cur - 1, acc + cur**2) return iter(n, 0) # compute the square of the sum of the first n natural numbers def sumsq(n): if n < 1: return 0 def iter(cur, acc): if cur == 0: return acc else: return iter(cur - 1, acc + cur) return iter(n, 0)**2 if __name__ == "__main__": print(sumsq(100) - sqsum(100))
5cb0ed9991399a5b63294be53f305e6aa21b037f
qiuyunzhao/python_basis
/g_if语句/g0_if语句.py
1,915
4.0625
4
# 代码块 # 代码块中保存着一组代码,同一个代码块中的代码,要么都执行要么都不执行,代码块就是一种为代码分组的机制 # 代码块语句就不能紧随在:后边,而是要写在下一行 # 代码块以缩进开始,直到代码恢复到之前的缩进级别时结束 # # 缩进有两种方式,一种是使用tab键,一种是使用空格(四个) Python的官方文档中推荐我们使用空格来缩进 # Python代码中使用的缩进方式必须统一 否则 "translate_tabs_to_spaces": true, # 单行 num = 11 if num > 20: print('num比10大!') print('不受if控制') # 多行代码块 if num < 20: print(123) print(456) print('不受if控制') # 可以使用逻辑运算符来连接多个条件 if num > 10 and num < 20: print('num比10大,num比20小!') # ------------------------------------------------------------------------ # 获取用户输入的用户名 # ageStr = input('请输入你的年龄:') # 返回字符串 # age = int(ageStr) age = 18 if age > 17: print('你已经成年了~~') else: print('你还未成年~~') # ------------------------------------------------------------------------ age = 68 if 18 <= age < 30: print('你已经成年了!') elif 30 <= age < 60: print('你已经中年了!') elif age >= 60: print('你已经退休了!') else: print('你还未成年~~') # ------------------------------------------------------------------------ # 打印分割线 print("=" * 30) # 获取小明的成绩 score = float(input('请输入你的期末成绩(0-100):')) if 0 <= score <= 100: if score == 100: print('宝马,拿去玩!') elif score >= 80: print('苹果手机,拿去玩!') elif score >= 60: print('参考书,拿去玩!') else: print('棍子一根!') else: print('你输入的内容不合法')
12f59801d2533eb8e9736003f5ab721a438ce02d
Tapan-24/python
/longest_word_string.py
220
3.984375
4
str = input("Insert Different String: ") first = str.split() len_str = len(first) longest = 0 for i in range(len_str-1): if len(first[longest])< len(first[i]): longest = i print(first[longest])
50a13f82d5c1bb6d1e13286bef3525446a5c2cc7
Raymond0620/Interview
/算法笔试/腾讯3/1.py
599
3.515625
4
''' @Descripttion: 柠檬的选择 @Author: daxiong @Date: 2019-09-20 20:38:01 @LastEditors: daxiong @LastEditTime: 2019-09-20 20:53:07 ''' s = input().strip().split() n, m = int(s[0]), int(s[1]) lemonA = [int(x) for x in input().strip().split()] lemonB = [int(x) for x in input().strip().split()] lemonA.sort() lemonB.sort() a, b, c, d = lemonA[0],lemonA[1], lemonA[-2], lemonA[-1] m, n = lemonB[0], lemonB[-1] maxAB = max(a*m, a*n, d*m, d*n) if a*m == maxAB or a*n == maxAB: # 这种情况去掉a print(max(b*m, b*n, d*m, d*n)) else: #这种情况去掉a print(max(a*m, a*n, c*m, c*n))
169e31885d91ae9d9f1a5ad28d500a0b4c225548
slobodaPolina/ML_Lab2
/_gradient_descent.py
5,286
3.53125
4
import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from metrics import NRMSE from parameters import gradient_descent as parameters import prepare_data # случайным образом делим наши данные на тернировочные и часть для кросс-валидации. k - какую (1/k) часть отделить def cross_validation_split(data, k): np.random.shuffle(data) features = data[:, :-1] labels = data[:, -1] split_point = len(labels) // k training_features = np.array(features[split_point:]) cross_val_features = np.array(features[:split_point]) training_labels = np.array(labels[split_point:]) cross_val_labels = np.array(labels[:split_point]) return training_features, cross_val_features, training_labels, cross_val_labels # предсказываем ответы для нескольких запросов, пользуясь существующими весами def predict(features, weights_vector): return [sum([weight * feature_val for weight, feature_val in zip(weights_vector, features[i])]) for i in range(len(features))] def gradient_descent(parameters): train_losses, test_losses = [], [] training_object_count, feature_count, training_features, training_labels, test_features, test_labels = prepare_data.read_from_file() training_features = preprocessing.normalize(training_features, axis=0) test_features = preprocessing.normalize(test_features, axis=0) # merge features with their own labels to get a normal array of vectors ^) train_data = np.hstack((training_features, np.reshape(training_labels, (-1, 1)))) # array of random initial weights from 0 to 1 weights = np.random.rand(feature_count + 1) cross_val_parameter = parameters['cross_val_parameter'] for iteration in range(parameters['num_iterations']): print('Iteration {}'.format(iteration + 1)) # разделяем данные, по части из них будет проходить кросс-валидация cross_val_training_features, cross_val_test_features, cross_val_training_labels, cross_val_test_labels = cross_validation_split(train_data, cross_val_parameter) # добавляю к массиву фич столбик единичек, для тренировочной и тестовой кросс-валидационной части cross_val_training_features = np.hstack(( cross_val_training_features, np.ones((cross_val_training_features.shape[0], 1), dtype=cross_val_training_features.dtype) )) cross_val_test_features = np.hstack(( cross_val_test_features, np.ones((cross_val_test_features.shape[0], 1), dtype=cross_val_test_features.dtype) )) predicted_values = predict(cross_val_training_features, weights) # абсолютные значения ошибок - разница между тем, что было значением cross_val_training и тем, что предсказали по cross_val_training_features absolute_error = [predicted_value - cross_val_training_label for predicted_value, cross_val_training_label in zip(predicted_values, cross_val_training_labels)] # T.dot перемножение матриц cross_val_training_features и absolute_error # градиент считается по cross_val_training_features, проверки будут по cross_val_test_features gradient = cross_val_training_features.T.dot(absolute_error) / cross_val_training_features.shape[0] + parameters['regularization_strength'] * weights # и обновляю веса на правильные weights = weights * (1 - parameters['learning_rate'] * parameters['regularization_strength']) + parameters['learning_rate'] * (-gradient) predicted_labels = predict(cross_val_test_features, weights) train_loss = NRMSE(predicted_labels, cross_val_test_labels) train_losses.append(train_loss) # и по всему тестовому набору predicted_labels = predict(test_features, weights) test_loss = NRMSE(predicted_labels, test_labels) test_losses.append(test_loss) print('Cross validation loss: {}, Test loss: {}'.format(train_loss, test_loss)) return train_losses, test_losses best_test_losses = [] best_train_losses = [] for max_iterations in range(parameters['num_iterations']): print("-------------Max iterations {} out of {} -----------------------".format(max_iterations + 1, parameters['num_iterations'])) train_loss, test_loss = gradient_descent({ 'learning_rate': parameters['learning_rate'], 'regularization_strength': parameters['regularization_strength'], 'cross_val_parameter': parameters['cross_val_parameter'], 'num_iterations': max_iterations + 1 }) best_test_losses.append(min(test_loss)) best_train_losses.append(min(train_loss)) plt.plot(best_test_losses) plt.xlabel('maximum iterations') plt.ylabel('best_test_NRMSE') plt.show() plt.plot(best_train_losses) plt.xlabel('maximum iterations') plt.ylabel('best_train_NRMSE') plt.show()