blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7a617992719556abf958d1eedfba4d87ffca38c9
atiktanim/Python
/Project Quiz Test/Quiz.py
1,754
3.59375
4
import random Zilla = {'Chandpur': 'Ilish', 'Dhaka': 'Biriany', 'Rajshahi': 'Mango', 'Comilla': 'Roshmalai', 'ChapaiNababganz': 'pera', 'Bogura': 'Doi', 'Nator': 'kachagolla', 'Chittagong': 'Shutki', 'Khulna': 'Modhu', 'Barisal': 'Guazava' } # Generates 5 quiz files: for quizNum in range(5): # creates the quiz and answer key files quizFile = open('Zillasquiz%s.txt' % (quizNum + 1), 'w') answerKeyFile = open('Zillasquiz_answers%s.txt' % (quizNum + 1), 'w') quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n') quizFile.write((' ' * 20) + 'Zilla favourite things quiz (Form %s)' % (quizNum + 1)) quizFile.write('\n\n') # shuffle the orders of the state. zillaName = list(Zilla.keys()) random.shuffle(zillaName) # Loop through all 10 states,making a question for each. for questionNum in range(10): correctAnswer = Zilla[zillaName[questionNum]] wrongAnswers = list(Zilla.values()) del wrongAnswers[wrongAnswers.index(correctAnswer)] wrongAnswers = random.sample(wrongAnswers, 3) answerOptions = wrongAnswers + [correctAnswer] random.shuffle(answerOptions) # Write the question and the answer options to the quiz file. quizFile.write('%s.What is the famous thing of %s?\n' % (questionNum + 1, zillaName[questionNum])) for i in range(4): quizFile.write(' %s. %s\n'%('ABCD'[i],answerOptions[i])) quizFile.write('\n') # Write answer key to File answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)])) quizFile.close() answerKeyFile.close()
afc8d6c466837c5ee1bc781bc6ca70ab55de5e6e
AIA2105/A_Practical_Introduction_to_Python_Programming_Heinold
/Python sheets/7.13.py
181
3.53125
4
x = [1, 1, 2, 3, 4, 3, 0, 0] new = [] index = 0 for i in range(len(x)): if not new.__contains__(x[i]): new.insert(index, x[i]) index += 1 print(new)
2f7dee5f68f1676e2195f33be0a47b82ad7528f1
basimsahaf-zz/Coding-Challenges
/anagram.py
1,140
4.15625
4
""" Q: Given two strings, check whether they are anagrams of each other. Example: "public relations" is an anagram of "crap built on lies." You are also given a testing client to check the correctness of your function.""" #Testing client for anagram class AnagramTesting(object): def Client(self,sol): assert(sol('go go go','gggooo')==True) assert(sol('abc','cba')==True) assert(sol('hi man','hi man')==True) assert(sol('aabbcc','aabbc')==False) assert(sol('123','1 2')==False) print("ALL TEST CASES PASSED") #Solution: def anagram(s1,s2): s1 = s1.replace(' ','').lower() s2 = s2.replace(' ','').lower() if len(s1) != len(s2): return False count = {} for letter in s1: if letter in count: count[letter] +=1 else: count[letter] = 1 for letter in s2: if letter in count: count[letter] -=1 else: count[letter] = 1 for keys in count: if count[keys] !=0: return False return True #Test the function t = AnagramTesting() t.Client(anagram)
15326c1a2c5e91b06fdab113e1981d27ceda7262
LRegan666/Athene_Leetcode
/Search_in_Rotated_Sorted_Array.py
1,262
3.671875
4
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums: return -1 start, end = 0, len(nums)-1 while start+1 < end: mid = int((start + end) / 2) if nums[start] > nums[end]: avg = int((nums[start] + nums[end]) / 2) if avg <= nums[mid]: if nums[end] < target <= nums[mid]: end = mid else: start = mid else: if target <= nums[mid] or target > nums[end]: end = mid else: start = mid else: mid = int((start + end) / 2) if target <= nums[mid]: end = mid else: start = mid if nums[start] == target: return start elif nums[end] == target: return end else: return -1 if __name__ == '__main__': nums = [4,5,6,7,0,1,2] target = 4 finder = Solution() index = finder.search(nums, target) print(index)
d4fee27a4dd7540de232c5206f211afaa28429ec
rjovelin/Rosalind
/Armory/ORFR/longest_ORF.py
1,631
3.796875
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 30 22:02:52 2015 @author: Richard """ # use biopython to translate DNA sequences and manipulate sequences from Bio.Seq import Seq def find_longest_ORF(input_file): ''' (file) -> str Given a DNA string S in input file, return the longest protein string that can be translated from an ORF of S. (return any protein if multiple proteins with longest length exist) Note: an ORF starts with the initiation codon, and ends either with a stop codon or with the end of the DNA sequence ''' # open file for reading infile = open(input_file, 'r') # get DNA sequence and create a SeqObject DNA = Seq(infile.readline().rstrip()) # close file infile.close() # create variable for protein length size = 0 # check translations of all DNA sequences for i in range(len(DNA)): # stop translation at the first stop codon protein = DNA[i:].translate(to_stop = True) # keep if peptide length > size and peptide starts with M if protein.startswith('M') and len(protein) > size: longest = protein size = len(protein) # check ORF on the reverse strand DNArc = DNA.reverse_complement() for i in range(len(DNArc)): # stop translation at the first stop codon protein = DNArc[i:].translate(to_stop = True) # keep if peptide length > size and peptide starts with M if protein.startswith('M') and len(protein) > size: longest = protein size = len(protein) return longest
baec9cdecfafca3eecd3689c6e0d847adff07cb7
Crazyinfo/Python-learn
/try/习题/twosum.py
337
3.765625
4
# 网摘 def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic = {} for i, num in enumerate(nums): if target - num in dic: return [dic[target - num], i] dic[num] = i m = twoSum([2, 7, 11, 15], 9) print(m) print(twoSum([2, 7, 11, 15], 18))
ec6885140e83aee6daf8c713e8fd0687b9a1330c
hs634/algorithms
/python/arrays/move_zeros_to_end.py
328
3.53125
4
__author__ = 'hs634' arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9] def move_zeros_to_end(arr): count = 0 for i, item in enumerate(arr): if item != 0: arr[count] = arr[i] count += 1 while count < len(arr): arr[count] = 0 count += 1 print arr move_zeros_to_end(arr)
054d28f6fbfa9cc5421bd77c78e361f46374c534
i-aditya-kaushik/geeksforgeeks_DSA
/Bitwise Magic/Codes/rightmost_diff_bit.py
1,343
4.25
4
""" Rightmost different bit Given two numbers M and N. The task is to find the position of rightmost different bit in binary representation of numbers. Input Format: The input line contains T, denoting the number of testcases. Each testcase follows. First line of each testcase contains two space separated integers M and N. Output Format: For each testcase in new line, print the position of rightmost different bit in binary representation of numbers. If both M and N are same then print -1 in this case. User Task: The task is to complete the function posOfRightMostDiffBit() which takes two arguments m and n and returns the position of first different bits in m and n. Constraints: 1 <= T <= 100 1 <= M <= 103 1 <= N <= 103 Example: Input: 2 11 9 52 4 Output: 2 5 Explanation: Tescase 1: Binary representaion of the given numbers are: 1011 and 1001, 2nd bit from right is different. Testcase 2: Binary representation of the given numbers are: ‭110100‬ and 0100, 5th bit fron right is different. ** For More Input/Output Examples Use 'Expected Output' option ** """ import math def posOfRightMostDiffBit(m,n): ans = m^n return(int(math.log((ans & -ans),2)+1)) assert posOfRightMostDiffBit(11,9) == 2 assert posOfRightMostDiffBit(52,4) == 5 assert posOfRightMostDiffBit(8,0) == 4 print('The code ran Correctly')
be3112a86d8dab7211dd0a03ae4061509e64d2bb
lzjzx1122/FaaSFlow
/src/function_manager/port_controller.py
412
3.59375
4
# a really simple port controller allocating port in a range class PortController: def __init__(self, min_port, max_port): self.port_resource = list(range(min_port, max_port)) def get(self): if len(self.port_resource) == 0: raise Exception("no idle port") return self.port_resource.pop(0) def put(self, port): self.port_resource.append(port)
dc9ddd28d806e42f96838dd2995ee0fbbaf03fe5
Broozer29/Utrecht_HBO_ICT
/While-loop & numbers.py
345
3.765625
4
def main(): totaal = 0 aantalGetallen = 0 user_input = int(input("Enter number: ")) while user_input != 0: totaal += user_input aantalGetallen += 1 user_input = int(input("Enter number: ")) if user_input == 0: print("Er zijn ",aantalGetallen," getallen ingevoerd, de som is: ",totaal) main()
dd2a94d2c5b58c0ae302cae772edbb9729b1b903
rajkn1212/Practice-Python
/Strings/q16.py
482
4.28125
4
# Write a Python program to remove the nth index character from a nonempty string. def removeChar(givenString, pos): newString = "" if givenString == "": print("empty string") else: list1 = list(givenString) for i in range(len(list1)): if pos == i: del list1[i] for char in list1: print(char) newString += char return newString value = removeChar("vipin", 2) print(value) #viin
8cd7def10aa3dd1ba478f1eca091bd606943bc80
Code-Institute-Submissions/python-2
/run.py
2,117
4.125
4
from random import randint board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): for row in board: print(" ".join(row)) """ starting the game and printing the board """ print ("The hunt in on!") print_board(board) """ generating random positions for the ships """ ships = 4 while ships > 0: def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) """ function to check if a ship is already present in that specific point""" if (board[ship_row][ship_col]) == "O": board[ship_row][ship_col] = "@" ships = ships + 1 for turn in range(9): print ("Turn"), turn """ checks in input is correct""" input = False def isNumber(s): for i in range(len(s)): if s[i].isdigit() != True: return False return True while input == False: guess_row = int(input("Guess Row:")) guess_col = int(input("Guess Col:")) if isNumber(guess_row) and isNumber(guess_col): print("Target aquired") input = True else: print("Those coordinates don't look correct, sir") """this part checks if the coordinates inouted by the player have a corispondence with the ships location on the board""" if guess_row == ship_row and guess_col == ship_col: print("Nice hit captain!") ships = ships - 1 else: if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5): print("You're probably aiming for another dimension mate!") elif(board[guess_row][guess_col] == "X"): print("We already check that area sir !") else: print("You will get them the next time !!") board[guess_row][guess_col] = "X" if turn == 8: print("Game Over") if ships == 0: print("Congratultions ! We've wipped out the enemy!") break turn = +1 print_board(board)
cff144d4c6ae304b790ec511975dfe4bdcfbc035
RESHMA-KRISHNAN/PYTHON-PROGRAMMING
/CO4/comparison.py
784
4.09375
4
class distance: def __init__(self, x=5,y=5): self.ft=x self.inch=y def __eq__(self, other): if self.ft==other.ft and self.inch==other.inch: return "both objects are equal" else: return "both objects are not equal" def __lt__(self, other): in1=self.ft*12+self.inch in2=other.ft*12+other.inch if in1<in2: return "first object smaller than other" else: return "first object not smaller than other" def __gt__(self, other): in1=self.ft in2=other.ft if in1<in2: return "first object greater than other" else: return "first object not greater than other" d1=distance(5,5) d2=distance(10,5) print (d1>d2) d3=distance() d4=distance(6,10) print (d1<d2) d5=distance(3,11) d6=distance() print(d5<d6)
e4197b72b91ab68ab48d34a0a280254cef57ef51
EddyGharib/delta-robot-application
/delta_kinematics.py
4,005
3.6875
4
""" Python implementation of the direct (forward) and inverse kinematic equations of a delta robot with special dimensions. R, r, l and d. """ import numpy as np from math import * import time from matplotlib.pyplot import * # Some other constants sqrt3 = sqrt(3) sin120 = sqrt(3) / 2 cos120 = -0.5 tan60 = sqrt(3) sin30 = 0.5 tan30 = 1 / sqrt(3) default_drob_dimensions = {'R':0.40941, 'r':0.4, 'l':0.8, 'd':0.07845} c_default_drob_dimensions = {'R':0.40941, 'r':0.4, 'l':0.8, 'd':0.07845} # Main functions def fwd_kinematics(theta1, theta2, theta3, drob_dimensions = default_drob_dimensions): """ Takes the angles in degrees and gives the position if existing else it returns False """ # Robot dimensions d = drob_dimensions['d'] R = drob_dimensions['R'] r = drob_dimensions['r'] l = drob_dimensions['l'] e = 2 * sqrt(3) * d f = 2 * sqrt(3) * R re = l rf = r t = (f - e) * tan30 / 2 dtr = pi / 180 theta1 *= dtr theta2 *= dtr theta3 *= dtr y1 = -(t + rf * cos(theta1)) z1 = -rf * sin(theta1) y2 = (t + rf * cos(theta2)) * sin30 x2 = y2 * tan60 z2 = -rf * sin(theta2) y3 = (t + rf * cos(theta3)) * sin30 x3 = -y3 * tan60 z3 = -rf * sin(theta3) dnm = (y2 - y1) * x3 - (y3 - y1) * x2 w1 = y1 * y1 + z1 * z1 w2 = x2 * x2 + y2 * y2 + z2 * z2 w3 = x3 * x3 + y3 * y3 + z3 * z3 a1 = (z2 - z1) * (y3 - y1) - (z3 - z1) * (y2 - y1) b1 = -((w2 - w1) * (y3 - y1) - (w3 - w1) * (y2 - y1)) / 2.0 a2 = -(z2 - z1) * x3 + (z3 - z1) * x2 b2 = ((w2 - w1) * x3 - (w3 - w1) * x2) / 2.0 a = a1 * a1 + a2 * a2 + dnm * dnm b = 2 * (a1 * b1 + a2 * (b2 - y1 * dnm) - z1 * dnm * dnm) c = (b2 - y1 * dnm) * (b2 - y1 * dnm) + b1 * b1 + dnm * dnm * (z1 * z1 - re * re) d = b * b - 4.0 * a * c; if (d < 0): return False z0 = -0.5 * (b + sqrt(d)) / a; x0 = (a1 * z0 + b1) / dnm y0 = (a2 * z0 + b2) / dnm return [x0, y0, z0] def s_inv_kinematics(x0, y0, z0, drob_dimensions = default_drob_dimensions): """ Takes the position of the end effector as input and returns the corresponding angle in degree if existing else it returns False """ # Robot dimensions d = drob_dimensions['d'] R = drob_dimensions['R'] r = drob_dimensions['r'] l = drob_dimensions['l'] e = 2 * sqrt(3) * d f = 2 * sqrt(3) * R re = l rf = r y1 = -0.5 * 0.57735 * f y0 -= 0.5 * 0.57735 * e a = (x0 * x0 + y0 * y0 + z0 * z0 + rf * rf - re * re - y1 * y1) / (2 * z0) b = (y1 - y0) / z0 d = -(a + b * y1) * (a + b * y1) + rf * (b * b * rf + rf) if (d < 0): return False yj = (y1 - a * b - sqrt(d)) / (b * b + 1) zj = a + b * yj if (yj > y1): toadd = 180 else: toadd = 0 theta = 180 * atan(-zj / (y1 - yj)) / pi + toadd return theta def inv_kinematics(x0, y0, z0, drob_dimensions = default_drob_dimensions): """ Takes the position of the end effector as input and returns the 3 angles in degree if existing else it returns False """ # Robot dimensions d = drob_dimensions['d'] R = drob_dimensions['R'] r = drob_dimensions['r'] l = drob_dimensions['l'] e = 2 * sqrt(3) * d f = 2 * sqrt(3) * R re = l rf = r theta1 = s_inv_kinematics(x0, y0, z0, drob_dimensions) theta2 = s_inv_kinematics(x0 * cos120 + y0 * sin120, y0 * cos120 - x0 * sin120, z0, drob_dimensions) theta3 = s_inv_kinematics(x0 * cos120 - y0 * sin120, y0 * cos120 + x0 * sin120, z0, drob_dimensions) if ( theta1 == False or theta2 == False or theta3 == False): return False return [theta1, theta2, theta3] def mesure_inv_kin_speed(): start_time = time.clock() inv_kinematics(0, 0, -0.941) print("--- %s seconds ---" % (time.clock() - start_time)) if __name__ == "__main__": # mesure_inv_kin_speed() # print(inv_kinematics(0.5, 0.5, -0.8)) pass
f4a57ebbddea08efd079691627117d318f60d7f2
Aliebs/GCTA
/custom_func.py
2,270
3.671875
4
import statistics, time, random def help(): print("\n\n") print(""" |---------------------------------------------------------| | GCTA - Help guide | | | | Commands: What does it do: | | | | - fight Fight the closest enemy (if possible) | | - run Run away from enemy | | - heatlh Check hero's health | | - change name Change your hero's name | | | | Good luck hero. You're gonna need it. | | | |---------------------------------------------------------| """) print("\n\n") def fight(enemy_name, enemy_health, enemy_damage, fight_status): global hero_health global rat_fight global ratboss_health while enemy_health > 0 and statistics.hero_health > 0: enemy_health = enemy_health - statistics.hero_damage print("You strike " + enemy_name + " for a total of " + str(statistics.hero_damage) + " damage") time.sleep(1) statistics.hero_health = statistics.hero_health - enemy_damage print(enemy_name + " Strikes " + statistics.username + " For a total of " + str(enemy_damage) + " damage") time.sleep(1) if enemy_health > 0: print("You died. The end.") sys.exit() else: statistics.rat_fight = "done" print(enemy_name + " Was defeated!") def run(enemy_name): global hero_health global rat_fight avoid_chance = random.randint(1, 20) if avoid_chance > 10: print("You get away!") statistics.rat_fight = "done" else: statistics.hero_health = statistics.hero_health / 2 print(enemy_name + " chases after you and catches you, landing a critical hit dealing HALF your health") def health(): print("\n Your hero has " + str(statistics.hero_health) + " Health.\n") def change_name(): global username print("\nChoose a new username!") Username_change = input("\n---> ") username = Username_change
2580f3db9e3c7993f4c5d5f475852222d18c5a4a
ryancey1/python-data-science
/01-python-basics/05-working-with-web-data/jsondata_start.py
1,986
3.875
4
# # Example file for parsing and processing JSON # import urllib.request import json def printResults(data): # Use the json module to load the string data into a dictionary theJSON = json.loads(data) # now we can access the contents of the JSON like any other Python object if "title" in theJSON["metadata"]: print(theJSON["metadata"]["title"]) # output the number of events, plus the magnitude and each event name if "count" in theJSON["metadata"]: print(theJSON["metadata"]["count"], "\n") print("** All Events **") # for each event, print the place where it occurred for feature in theJSON["features"]: print(feature["properties"]["place"]) print("\n--------------\n") print("** Events >4.0 magnitude **") # print the events that only have a magnitude greater than 4 for f in theJSON["features"]: mag, place = float(f["properties"]["mag"]), f["properties"]["place"] if mag >= 4: print(mag, place, sep="\t|\t") print("\n--------------\n") print("** Events with more than 1 reporting **") # print only the events where at least 1 person reported feeling something for f in theJSON["features"]: felt, place, mag = f["properties"]["felt"], f["properties"]["place"], f["properties"]["mag"] if felt != None and int(felt) > 0: print(f'{felt} person reported', "%2.2f" % mag, place, sep="\t|\t") def main(): # define a variable to hold the source URL # In this case we'll use the free data feed from the USGS # This feed lists all earthquakes for the last day larger than Mag 2.5 urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson" # Open the URL and read the data webUrl = urllib.request.urlopen(urlData) if webUrl.getcode() == 200: printResults(webUrl.read()) else: print("Received an error. Cannot parse.") if __name__ == "__main__": main()
154e4ac9846cf99c0b5b8ca4af4f1a77b5ec877f
gear/learn
/codeforfun/python/s-cs97si/linear_algebra.py
1,328
3.875
4
"""coding=utf-8 python=3.5.2 """ import numpy as np def solve(mat, y): """Solve a system of linear equations given by `mat` and y. The rows represent coefficients of each equation.""" reduced = gaussian_elim(mat) sol = np.zeros(shape=(mat.shape[0])) S = 0 for i in reversed(range(len(sol))): sol[i] = (y[i]-S) / reduced[i][i] S += y[i] - S return sol def gaussian_elim(mat): """Perform gaussian elimination on matrix `mat`. The result is a new upper triangle matrix. `mat` must be a n-by-n 2d numpy array.""" up_mat = np.array(mat, dtype=float) n = up_mat.shape[0] for r in range(0,n-1): for rr in range(r+1, n): try: ratio = up_mat[rr][r] / up_mat[r][r] except ZeroDivisionError: print("zero") continue for i in range(r,n): up_mat[rr][i] -= up_mat[r][i] * ratio return up_mat def test(): print("Testing gaussian elimination...") matrix = np.array([[1,2,3,4], [7,5,3,3], [6,3,7,3], [8,1,9,2]]) print(gaussian_elim(matrix)) print("Testing system of linear equations...") sol = solve(matrix, [1,2,3,4]) print(sol) print("Correct result:") print(np.matmul(matrix, sol)) if __name__ == '__main__': test()
5174b45a4744d830fe4e5d7938ef951208a06be2
Sulorg/Python
/Self-taught-programmer-Althoff/ООП2.py
1,112
4.03125
4
#Задание1 class Shape(): def what_am_i(self): print("Я - фигура.") class Square(Shape): square_list = [] def __init__(self, s1): self.s1 = s1 self.square_list.append(self) def calculate_perimeter(self): return self.s1 * 4 def what_am_i(self): super().what_am_i() print("Я - фигура.") a_square = Square(29) print(Square.square_list) another_square = Square(93) print(Square.square_list) #Задание2 class Shape(): def what_am_i(self): print("Я - фигура.") class Square(Shape): square_list = [] def __init__(self, s1): self.s1 = s1 self.square_list.append(self) def calculate_perimeter(self): return self.s1 * 4 def what_am_i(self): super().what_am_i() print("Я - фигура.") def __repr__(self): return "{} на {} на {} на {}".format(self.s1, self.s1, self.s1, self.s1) a_square = Square(29) print(a_square) #Задание3 def compare(obj1, obj2): return obj1 is obj2 print(compare("а", "б"))
c59c99cf9a269e7bae4515bcca9104cf70fa7163
nsmedira/MIT-6_01
/python-tutorial/if-else-while/problems/perfectSquare.py
371
3.546875
4
import math def perfectSquare(n): if not isinstance(n, int) or n <= 0: return "argument must be a positive integer" if n == 1: return True # assuming that this problem wants a loop instead of the square root function i = math.floor(n/2) while i > 1: if i ** 2 == n: return True i -= 1 return False
484aae30f2f5d92daf20002f6133502314ade821
physics91si/sblankenAtStanford-lab5
/trig.py~
458
3.84375
4
#!/usr/bin/python #The following statements are used to import numpy and matplotlib. import numpy as np import matplotlib.pyplot as plt # TODO fill in this function def integrate(y, dx): return np.sum(y*dx) # TODO write code here to setup arrays x and y = sin(x) and then plot them. # After this is done implement your integrate function above integrate y def plot(): x = np.arange(0, np.pi, 0.01) y = sin(x) plt.plot(x,y) plt.show()
361aaf44f0078ce022ac48c0f6496f010c69d70e
CharmingCheol/python-algorithm
/백준/그래프/2668(숫자고르기).py
589
3.546875
4
import sys # 사이클 문제 def DFS(start, current): # 현재 위치가 1인 경우 if visited[current]: # 시작값과 현재값이 같은 경우(사이클인 경우) if start == current: result.append(start) else: visited[current] = 1 DFS(start, nums[current]) size = int(sys.stdin.readline()) nums = [0] + [int(sys.stdin.readline()) for _ in range(size)] visited = [0] * (size + 1) result = [] for i in range(1, size + 1): DFS(i, i) visited = [0] * (size + 1) print(len(result)) for item in result: print(item)
15b7f3dd05e387ad3cf64a7941acd41a3b6fa52b
Tutu0027/Max_entropy
/100/24.py
700
4.125
4
# -*- coding: utf-8 -*- #!/usr/bin/env python # 题:Python有许多内置函数,如果您不知道如何使用它,您可以在线阅读文档或查找一些书籍。 但是Python为每个内置函数都有一个内置的文档函数。 #      请编写一个程序来打印一些Python内置函数文档,例如abs(),int(),raw_input() #      并为您自己的功能添加文档 #      # 提示:内置文档方法是__doc__ print(abs.__doc__) print(int.__doc__) print(input.__doc__) def square(num): '''Return the square value of the input number. The input number must be integer. ''' return num ** 2 print(square(2)) print(square.__doc__)
9e81e19d09330022f115c82de55d99ba72d474b7
santiagopemo/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
5,231
3.5
4
#!/usr/bin/python3 """Base Module""" import json import csv from os import path import turtle import random class Base: """Base Class""" __nb_objects = 0 def __init__(self, id=None): """Initializtes a Base class instance""" if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = Base.__nb_objects @staticmethod def to_json_string(list_dictionaries): """Returns the JSON string representation of list_dictionaries""" if list_dictionaries is None or len(list_dictionaries) == 0: return "[]" return json.dumps(list_dictionaries) @classmethod def save_to_file(cls, list_objs): """Writes the JSON string representation of list_objs to a file""" filename = "{}.json".format(cls.__name__) with open(filename, mode="w") as f: if list_objs is None: f.write("[]") else: dict_list = [] for obj in list_objs: dict_list.append(obj.to_dictionary()) f.write(cls.to_json_string(dict_list)) @staticmethod def from_json_string(json_string): """returns the list of the JSON string representation json_string""" if json_string is None or len(json_string) == 0: return [] return json.loads(json_string) @classmethod def create(cls, **dictionary): """Returns an instance with all attributes already set""" if cls.__name__ == "Rectangle": dummy = cls(1, 1) if cls.__name__ == "Square": dummy = cls(1) dummy.update(**dictionary) return dummy @classmethod def load_from_file(cls): """Returns a list of instances""" filename = "{}.json".format(cls.__name__) try: with open(filename, mode="r") as f: dict_list = Base.from_json_string(f.read()) obj_list = [] for dic in dict_list: obj_list.append(cls.create(**dic)) return obj_list except FileNotFoundError: return [] @classmethod def save_to_file_csv(cls, list_objs): """Serializes in CSV format""" filename = "{}.csv".format(cls.__name__) with open(filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) if cls.__name__ == "Rectangle": for o in list_objs: values = [o.id, o.width, o.height, o.x, o.y] writer.writerow(values) if cls.__name__ == "Square": for o in list_objs: values = [o.id, o.size, o.x, o.y] writer.writerow(values) @classmethod def load_from_file_csv(cls): """Deserializes in CSV format""" filename = "{}.csv".format(cls.__name__) if not path.isfile(filename): return [] with open(filename, newline='') as csvfile: reader = csv.reader(csvfile) if cls.__name__ == "Rectangle": rect_list = [] for row in reader: r_dict = {} r_dict["id"] = int(row[0]) r_dict["width"] = int(row[1]) r_dict["height"] = int(row[2]) r_dict["x"] = int(row[3]) r_dict["y"] = int(row[4]) rect_list.append(cls.create(**r_dict)) return rect_list if cls.__name__ == "Square": sq_list = [] for row in reader: s_dict = {} s_dict["id"] = int(row[0]) s_dict["size"] = int(row[1]) s_dict["x"] = int(row[2]) s_dict["y"] = int(row[3]) sq_list.append(cls.create(**s_dict)) return sq_list @staticmethod def draw(list_rectangles, list_squares): """Draw squares""" t1 = turtle.Turtle() t1.screen.bgcolor("#ffffff") t1.hideturtle() t1.pensize(4) t1.shape("turtle") sf = 5 h_x = (-1 * turtle.window_width() / 2) + 5 h_y = (-1 * turtle.window_height() / 2) + 10 t1.up() t1.goto(h_x, h_y) for i in range(2): if i == 0: seq = list_rectangles if i == 1: seq = list_squares for r in seq: tur_color = "#{:06x}".format(random.randint(0, 0xaaaaaa)) t1.color(tur_color) t1.showturtle() t1.up() t1.forward(r.x * sf) t1.left(90) t1.forward(r.y * sf) t1.down() t1.forward(r.height * sf) t1.right(90) t1.forward(r.width * sf) t1.right(90) t1.forward(r.height * sf) t1.right(90) t1.forward(r.width * sf) t1.up() t1.goto(h_x, h_y) t1.right(180) t1.down() turtle.exitonclick()
bace5e222fbd54a2976a260f9481945a792f0171
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/kngtho005/boxes.py
906
3.9375
4
# boxes.py # print_square() # prints 5x5 box on the screen # print_rectanle(width,height) # prints a box on screen with given width and height # get_rectangle(width,height) # returns a string containing box with given width and height # Thomas Konigkramer # 29 March 2014 def print_square(): print("*****\n" "* *\n" "* *\n" "* *\n" "*****") def print_rectangle(width,height): print(width * "*") for i in range(height-2): print("*", "*", sep = (width-2) * " ") print(width * "*") def get_rectangle(width,height): line = "*" * width ledge = "*" redge = "*" emptybox = (width - 2) * " " newline = "\n" rect = line + newline + (height - 2) * (ledge + emptybox + redge + newline) + line return rect
df29039e97adc18924893074cac7f743aa14cdf2
xenonyu/leetcode
/buildTree.py
840
3.984375
4
# Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def preTraverse(preStart, preEnd, inStart, inEnd): if preStart > preEnd or inStart > inEnd: return # print(preStart, preEnd) root = TreeNode(preorder[preStart]) inRoot = inorder.index(root.val) numsLeft = inRoot - inStart root.left = preTraverse(preStart + 1, preStart + numsLeft, inStart, inRoot - 1) root.right = preTraverse(preStart + numsLeft + 1, preEnd, inRoot + 1, inEnd) return root return preTraverse(0, len(preorder) - 1, 0, len(inorder) - 1)
410ee8bfa76491d0536823bb5d55b99c254d7c7c
noah-hixon/COS
/hixon_project1.py
9,493
4.15625
4
import random #checks to see if the user inputs a valid response def validatePlayers(numOfPlayers): while numOfPlayers != "y" and numOfPlayers != "n": print("INVALID INPUT") numOfPlayers = input("Do you want the computer to be one player?[y/n]") if numOfPlayers == "y": print("You will play the computer.") return True elif numOfPlayers == "n": print("Both players will come from human input.") return False # gets input from the user and validates it def getInput(): print("Welcome to Connect 4!\nCode By Noah Hixon\nThis game is for 2 players") numOfPlayers = str(input("Do you want the computer to be one player?[y/n]")) if numOfPlayers != "y" and numOfPlayers != "n": # validates computer player input validatePlayers(numOfPlayers) elif numOfPlayers == "y": print("You will play the computer.") return "y" elif numOfPlayers == "n": print("Both players will come from human input.") return "n" # gets the size of the board (number of rows and columns) from the user def getBoardSize(): global ROWS # will be global variable global COLUMNS # will be global variable print("*The default board has 6 rows and 7 columns*") ROWS = int(input("How many rows would you like? Please enter a number greater than or equal to 5:")) while ROWS < 5: # validates ROWS input print("You did not enter a valid number.") ROWS = int(input("How many rows would you like? Please enter a number greater than or equal to 5:")) COLUMNS = int(input("How many columns would you like? Please enter a number greater than or equal to 5:")) while COLUMNS < 5: # validates COLUMNS input print("You did not enter a valid number") COLUMNS = int(input("How many columns would you like? Please enter a number greater than or equal to 5:")) # creates board and returns it def createBoard(rows, columns): board = [] for i in range(ROWS): temp = [] for j in range(COLUMNS): temp.append("_ ") board.append(temp) return board # prints the board in the correct orientation def printBoard(board,COLUMNS): for row in range(len(board)- 1, -1, -1): print(board[row], "\n") # checks to see if the user input a valid number for column def validateColumns(columns): while columns > COLUMNS: print("That number is not valid") columns = int(input("Please choose a column to place your piece(1-" + str(COLUMNS) + "):")) return columns # places the user's piece in the desired column def dropPiece(board, row, col, piece): board[row][col - 1] = piece # checks the slot the user wants to put a piece and sees if there is a piece already there; # finds the first empty slot and returns it, if none are empty it returns -1 def slotFull(board, ROWS, column): for row in range(ROWS): if board[row][column-1] == "_ ": return row return -1 # checks the board for a winner(4 cases) def checkWin(board, playPiece): for col in range(COLUMNS-3): # this checks horizontally for win for row in range(ROWS): if board[row][col] == playPiece and board[row][col + 1] == playPiece and board[row][col+2] == playPiece and board[row][col + 3] == playPiece: return True for col in range(COLUMNS): # this check vertically for win for row in range(ROWS - 3): if board[row][col] == playPiece and board[row + 1][col] == playPiece and board[row + 2][col] == playPiece and board[row + 3][col] == playPiece: return True for col in range(COLUMNS -3): # this checks diagonally (positive) for win for row in range(ROWS - 3): if board[row][col] == playPiece and board[row + 1][col + 1] == playPiece and board[row + 2][col + 2] == playPiece and board[row + 3][col + 3] == playPiece: return True for col in range(COLUMNS - 3): # this checks diagonally(negative) for win for row in range(3, ROWS): if board[row][col] == playPiece and board[row - 1][col + 1] == playPiece and board[row - 2][col + 2] and board[row - 3][col + 3]: return True return False # main loop for a game with both players coming from human input def twoPlayer(): gameWon = False turn = 0 board = createBoard(ROWS, COLUMNS) printBoard(board, COLUMNS) while not gameWon: # while none of the win conditions are met # player 1 input if turn%2 == 0: piece = "X" print("Player 1, what is your choice?") choice = int(input("Choose a column to drop your piece:")) if choice < 1 or choice > COLUMNS: # validating column choice choice = validateColumns(choice) #row = slotFull(board, ROWS, choice) #dropPiece(board, row, choice, piece) #printBoard(board, COLUMNS) else: while slotFull(board, ROWS, choice) == -1: choice = int(input("COLUMN FULL\nEnter a new column:")) else: row = slotFull(board, ROWS, choice) dropPiece(board, row, choice, piece) printBoard(board, COLUMNS) gameWon = checkWin(board, "X") turn += 1 # player 2 input elif turn%2 == 1: piece = "O" print("Player 2, what is your choice?") choice = int(input("Choose a column to drop your piece:")) if choice < 1 or choice > COLUMNS: choice = validateColumns(choice) else: while slotFull(board, ROWS, choice) == -1: choice = int(input("COLUMN FULL\nEnter a new column:")) else: row = slotFull(board, ROWS, choice) dropPiece(board, row, choice, piece) printBoard(board, COLUMNS) gameWon = checkWin(board, "O") turn += 1 # turn - 1 will be the winner if turn%2 == 1: print("Player 1 wins!") else: print("Player 2 wins!") # main loop for a game versus computer def computerPlayer(): gameWon = False turn = 0 board = createBoard(ROWS, COLUMNS) printBoard(board, COLUMNS) while not gameWon: # while none of the win conditions are met # player 1 input if turn%2 == 0: piece = "X" print("Player 1, what is your choice?") choice = int(input("Choose a column to drop your piece:")) if choice < 1 or choice > COLUMNS: choice = validateColumns(choice) else: if slotFull(board, ROWS, choice) == -1: choice = int(input("COLUMN FULL\nEnter a new colum:")) else: row = slotFull(board, ROWS, choice) dropPiece(board, row, choice, piece) printBoard(board, COLUMNS) gameWon = checkWin(board, "X") turn = turn + 1 # computer input (pseudo-random) else: piece = "O" compChoice = random.randrange(1, COLUMNS) # the computer's choice is a random number between 1 and amount of columns if slotFull(board, ROWS, compChoice) == -1: compChoice = random.randrange(1, COLUMNS) else: row = slotFull(board, ROWS, compChoice) dropPiece(board, row, compChoice, piece) printBoard(board, COLUMNS) print("The computer chooses..." + str(compChoice) + "\n" + "------------------------------------" + "\n") gameWon = checkWin(board, "O") turn += 1 # deciding winner(same as two player) if turn % 2 ==1: print("Player 1 wins!") else: print("The computer wins!") # asks the player if they want to play the game again and returns the answer def playAgain(): playAgain = input("Do you want to play again? [y/n]") while playAgain != "y" and playAgain != "n": playAgain = input("Do you want to play again? [y/n]") return playAgain # main game loop def main(): userInput = getInput() # calls input function if userInput == "y": getBoardSize() computerPlayer() while playAgain() == "y": userInput = getInput() if userInput == "y": getBoardSize() computerPlayer() else: getBoardSize() twoPlayer() elif userInput == "n": getBoardSize() twoPlayer() while playAgain() == "y": userInput = getInput() if userInput == "y": getBoardSize() computerPlayer() else: getBoardSize() twoPlayer() main()
5665e54089f010b48819e72dadddc890fb50820c
Alexander30/PythonTheHardWay
/ex11.py
291
3.8125
4
print "How old are you?", age = raw_input('-->' ) print "How tall are you?", height = raw_input() print "How much do you weight?", weight = raw_input() print "aky mas oblubene cislo?", x = eval(raw_input()) print x print 'So, you\'re %r old, %r tall and %r heavy.' %\ (age, height, weight)
9764e46fe07ac0954eca41e85297a8dfb4ba961f
nickrye/HEM4EPA
/com/sca/hem4/writer/Writer.py
863
3.609375
4
from abc import abstractmethod, ABC class Writer(ABC): def __init__(self): self.outputs = None self.filename = None self.headers = None self.data = None self.dataframe = None self.batchSize = 10000000 def write(self, generateOnly=False): if not generateOnly: self.writeHeader() for data in self.generateOutputs(): if data is not None: if not generateOnly: self.appendToFile(data) self.analyze(data) @abstractmethod def writeHeader(self): pass @abstractmethod def appendToFile(self): pass @abstractmethod def getHeader(self): pass @abstractmethod def generateOutputs(self): pass @abstractmethod def analyze(self, data): pass
1791957bdd295ad76b10a73065faae6342ccdb6c
nathanlo99/dmoj_archive
/done/a20.py
193
3.71875
4
for i in range(int(input())): value = int(input().strip(), 16) if (value >> 20) & 1 != 0: print("{:08X} ".format(value & ~(1 << 20)), end = "") print("{:08X}".format(value))
a921c14ea3cce56c08a14fb1c6a20fd54e100582
amdonatusprince/The-Classic-Snake-Game
/snake.py
1,652
3.921875
4
from turtle import Turtle STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake: def __init__(self): self.snake_list = [] self.create_snake() self.head = self.snake_list[0] self.move_speed = 0.1 def create_snake(self): for position in STARTING_POSITION: self.add_length(position) def add_length(self, position): snake = Turtle(shape="square") snake.color("white") snake.penup() snake.goto(position) self.snake_list.append(snake) def reset(self): for snake in self.snake_list: snake.goto(x=1000, y=1000) self.snake_list.clear() self.create_snake() self.head = self.snake_list[0] self.move_speed = 0.1 def extend(self): #extend the length of the snake self.add_length(self.snake_list[-1].position()) def move(self): for snake_num in range(len(self.snake_list) - 1, 0, -1): new_x = self.snake_list[snake_num - 1].xcor() new_y = self.snake_list[snake_num - 1].ycor() self.snake_list[snake_num].goto(new_x, new_y) self.head.forward(MOVE_DISTANCE) def up(self): if self.head.heading() != DOWN: self.head.setheading(UP) def down(self): if self.head.heading() != UP: self.head.setheading(DOWN) def left(self): if self.head.heading() != RIGHT: self.head.setheading(LEFT) def right(self): if self.head.heading() != LEFT: self.head.setheading(RIGHT)
17006504ef5dd7a5558297e7e7f741f66f605653
daimictse/skill-exercises
/reservation.py
5,927
4.1875
4
""" Reservation finder Along with this file, you'll find two files named units.csv and reservations.csv with fields in the following format units.csv location_id, unit_size reservations.csv location_id, reservation_start_date, reservation_end_date You will write a simple application that manages a reservation system. It will have two commands, 'available' and 'reserve' with the following behaviors: available <date> <number of occupants> <length of stay> This will print all available units that match the criteria. Any unit with capacity equal or greater to the number of occupants will be printed out. Example: SeaBnb> available 10/10/2013 2 4 Unit 10 (Size 3) is available Unit 20 (Size 2) is available reserve <unit number> <start date> <length of stay> This creates a record in your reservations that indicates the unit has been reserved. It will print a message indicating its success. A reservation that ends on any given day may be rebooked for the same evening, ie: If a reservation ends on 10/10/2013, a different reservation may be made starting on 10/10/2013 as well. Example: SeaBnb> reserve 10 10/11/2013 3 Successfully reserved unit 10 for 3 nights Reserving a unit must make the unit available for later reservations. Here's a sample session: SeaBnb> available 10/10/2013 2 4 Unit 10 (Size 3) is available Unit 20 (Size 2) is available SeaBnb> reserve 10 10/11/2013 3 Successfully reserved unit 10 for 3 nights SeaBnb> available 10/10/2013 2 4 Unit 20 (Size 2) is available SeaBnb> reserve 10 10/11/2013 3 Unit 10 is unavailable during those dates SeaBnb> quit Notes: Start first by writing the functions to read in the csv file. These have been stubbed for you. Then write the availability function, then reservation. Test your program at each step (it may be beneficial to write tests in a separate file.) Use the 'reservations' variable as your database. Store all the reservations in there, including the ones from the new ones you will create. The datetime and timedelta classes will be immensely helpful here, as will the strptime function. """ import sys import datetime def parse_one_record(line): """Take a line from reservations.csv and return a dictionary representing that record. (hint: use the datetime type when parsing the start and end date columns)""" resDict = {} thisRes = line.split(",") unit_id = int(thisRes[0]) startDate = datetime.datetime.strptime(thisRes[1], "%m/%d/%Y") endDate = datetime.datetime.strptime(thisRes[2], "%m/%d/%Y") resDict[unit_id] = (startDate, endDate) return resDict def read_units(): """Read in the file units.csv and returns a list of all known units.""" list_of_units = [] for line in open("units.csv").readlines(): list_of_units.append(line.replace("\n", "").replace(" ","")) return list_of_units def read_existing_reservations(): """Reads in the file reservations.csv and returns a list of reservations.""" list_of_res = [] for line in open("reservation.csv").readlines(): list_of_res.append(line.replace("\n","").replace(" ","")) return list_of_res def available(units, reservations, start_date, occupants, stay_length): """Prints out what is available based on the start_date, occupants, and stay_length""" num_unit_avail = 0 for unit in units: # get unit id and unit size thisUnit = unit.split(",") unit_id = int(thisUnit[0]) unit_size = int(thisUnit[1]) # make sure unit size is big enough if unit_size >= int(occupants): # when size is good, look up reservations for this unit to make sure it's avail for res in reservations: resDict = parse_one_record(res) # returns (the first unavail date, the last unavail date) for this unit id res_info = resDict.get(unit_id, None) if res_info: startDate = datetime.datetime.strptime(start_date, "%m/%d/%Y") # unit is available on the start_date for stay_length days if res_info[0] <= startDate < res_info[1]: unit_id = 0 break if unit_id: num_unit_avail += 1 print "Unit %d (Size %d) is available"%(unit_id, unit_size) if not num_unit_avail: print "No unit is available" def reserve(units, reservations, unit_id, start_date, stay_length): for res in reservations: resDict = parse_one_record(res) res_info = resDict.get(int(unit_id), None) # go through all reservations for this unit_id if res_info: startDate = datetime.datetime.strptime(start_date, "%m/%d/%Y") # make sure startDate doesn't fall into any existing reservations if res_info[0] <= startDate < res_info[1]: print "Unit %s is unavailable during those dates"%unit_id return; # gather all existing reservations for this unit_id # fix this... if avail_list: print avail_list # check if unit is avail for stay_length days from existing reservations # reserve the unit and record in write to reservations.csv print "Successfully reserved unit %d for %d days"%(unit_id, stay_length) def main(): units = read_units() reservations = read_existing_reservations() while True: command = raw_input("SeaBnb> ") cmd = command.split() if cmd[0] == "available": # look up python variable arguments for explanation of the * available(units, reservations, *cmd[1:]) elif cmd[0] == "reserve": reserve(units, reservations, *cmd[1:]) elif cmd[0] == "quit": sys.exit(0) else: print "Unknown command" if __name__ == "__main__": main()
6a719ce777caa40e77569b84c5605e77429bb659
thinkerston/curso-em-video-python3
/mundo-03/exercicio-106.py
474
4.0625
4
'''Faça um mini-sistema que ultiliza interactive Help do python. o usuario vai digitaro comando e o manual vai aperecer. quando o usuário digitar a palavra "FIM", o programa se encerrará''' def ajudame(): funcao = str(input('Insira o nome da funcão: FIM PARA SAIR :')).lower() while True: if funcao == 'fim': return('SAI') print(help(funcao)) funcao = str(input('Insira o nome da funcão: FIM PARA SAIR: ')).upper() ajudame()
3892fa36d365f997f01b5cf34c9b6415ebedf6f0
felipmarqs/exerciciospythonbrasil
/exercicios/EstruturaSequencial/Metros_para_centímetros.py
162
4.25
4
#Faça um Programa que converta metros para centímetros m = float(input("Digite a medida em metros:")) c = m * 100 print(f"{m} metros são {c} centímetros.")
62fe4aaf167b46b1ac83568e09be032d23599a20
Mike-droid/estadistica_descriptiva
/media.py
222
3.640625
4
import random def calculate_mean(numbers): return sum(numbers) / len(numbers) random_numbers = [random.randint(1, 100) for _ in range(100)] print(f'La media de {random_numbers} es {calculate_mean(random_numbers)}')
77c7a0d1a236c1f275465cc21e6cbe3087f71939
LucasLeone/tp2-algoritmos
/cf/cf54.py
334
3.609375
4
''' Se dispone de cien pares ordenados de números y se quiere imprimir el cociente de cada uno. ''' for i in range(0, 100): print('---- Nuevo par ordenado ----') x = int(input('Ingrese el primer valor: ')) y = int(input('Ingrese el segundo valor: ')) print(f'El cociente entre estos 2 numeros es: {x / y}')
38d06cb7358fcac4a9d59f9b57c43825b9549015
DanielPahor/data-structures
/Stack.py
992
3.65625
4
import unittest import collections class Stack: def __init__(self): self.data = []; #O(1) def push(self, item): self.data.append(item) #O(1) def pop(self): if not self.data: return None else: return self.data.pop() #O(1) def peek(self): if not self.data: return None else: return self.data[-1] class Test(unittest.TestCase): def test_push(self): stack = Stack() stack.push('a') self.assertEqual(stack.data[0], 'a') stack.push('b') self.assertEqual(stack.data[1], 'b') def test_pop(self): stack = Stack() stack.push('a') element = stack.pop() self.assertTrue(element, 'a') self.assertIsNone(stack.pop()) def test_peek(self): stack = Stack() stack.push('a') self.assertEqual(stack.peek(), 'a') if __name__ == "__main__": unittest.main()
263fe657eb448df049642560368098ec9966f706
yordan-marinov/fundamentals_python
/regular_expression/softuni_bar_income.py
450
3.5625
4
import re regex = r"(^|(?<=%))([A-Z][a-z]+)(%)(<)([A-z][a-z]+)(>)(\|)(\d+)\7(\d+.\d+)((?=\$)|$)" total = 0 while True: data = input() if data == "end of shift": print(f"Total income: {total:.2f}") break matched = re.finditer(regex, data) for m in matched: result = float(m.group(8)) * float(m.group(9)) total += result print( f"{m.group(2)}: {m.group(5)} - {result}" )
9c06037e58e88be125ba73a406a8f61bd1f61366
cyruspythonprojects/Lab2_uppgifter
/uppg4.py
412
3.515625
4
# Skriv en funktion som returnerar alla heltal i en sträng som användaren matar in! Exempel på inmatning: ”hej32a1”.Exempel på vad funktionen skareturnera:[3,2,1]. def intFinder(s): lst = [] for c in s: try: if int(c): lst.append(c) except: continue return lst s = input("Skriv sträng: ") print(intFinder(s))
bff83c1f6acb27d164a002e79144339558ea8971
arungahlot/numerology
/main.py
457
3.84375
4
from numerology import PythagoreanNumerology def start_app(): """Interactive version of the package.""" print("Starting...\n") first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") birthdate = input("Enter your birthdate (yyyy-MM-dd, example 1994-11-30): ") my_pythagorean_numerology = PythagoreanNumerology(first_name, last_name, birthdate) if __name__ == "__main__": start_app()
5dd5cec67f0d827785489963736211f76bab4fd7
aklefebvere/Sprint-Challenge--Intro-Python
/src/cityreader/cityreader.py
4,886
4.28125
4
# Create a class to hold a city location. Call the class "City". It should have # fields for name, lat and lon (representing latitude and longitude). # We have a collection of US cities with population over 750,000 stored in the # file "cities.csv". (CSV stands for "comma-separated values".) # # In the body of the `cityreader` function, use Python's built-in "csv" module # to read this file so that each record is imported into a City instance. Then # return the list with all the City instances from the function. # Google "python 3 csv" for references and use your Google-fu for other examples. # # Store the instances in the "cities" list, below. # # Note that the first line of the CSV is header that describes the fields--this # should not be loaded into a City object. import csv # Create city class with name, lat, lon attributes class City: def __init__(self, name, lat, lon): self.name = name self.lat = lat self.lon = lon # Create cities list cities = [] def cityreader(cities=[]): # TODO Implement the functionality to read from the 'cities.csv' file # For each city record, create a new City instance and add it to the # `cities` list # open the csv file with open('src/cityreader/cities.csv') as csvfile: # Turn the csvfile into indiviudal lists split with ',' readcsv = csv.reader(csvfile, delimiter=',') # enumerate and iterate through the csvreader object # to take out the lists for i, row in enumerate(readcsv): # We don't want the first row since that contains # the headers of the csv file if i != 0: cities.append(City(row[0], float(row[3]), float(row[4]))) # if it is the header or i == 0, don't do anything else: pass # returns the list of cities return cities # Runs the function and creates the list of cities using the # city class cityreader(cities) # Print the list of cities (name, lat, lon), 1 record per line. for c in cities: print(c) # STRETCH GOAL! # # Allow the user to input two points, each specified by latitude and longitude. # These points form the corners of a lat/lon square. Pass these latitude and # longitude values as parameters to the `cityreader_stretch` function, along # with the `cities` list that holds all the City instances from the `cityreader` # function. This function should output all the cities that fall within the # coordinate square. # # Be aware that the user could specify either a lower-left/upper-right pair of # coordinates, or an upper-left/lower-right pair of coordinates. Hint: normalize # the input data so that it's always one or the other, then search for cities. # In the example below, inputting 32, -120 first and then 45, -100 should not # change the results of what the `cityreader_stretch` function returns. # # Example I/O: # # Enter lat1,lon1: 45,-100 # Enter lat2,lon2: 32,-120 # Albuquerque: (35.1055,-106.6476) # Riverside: (33.9382,-117.3949) # San Diego: (32.8312,-117.1225) # Los Angeles: (34.114,-118.4068) # Las Vegas: (36.2288,-115.2603) # Denver: (39.7621,-104.8759) # Phoenix: (33.5722,-112.0891) # Tucson: (32.1558,-110.8777) # Salt Lake City: (40.7774,-111.9301) # TODO Get latitude and longitude values from the user def cityreader_stretch(lat1, lon1, lat2, lon2, cities=[]): # within will hold the cities that fall within the specified region within = [] # TODO Ensure that the lat and lon valuse are all floats # Go through each city and check to see if it falls within # the specified coordinates. # Makes sure that lat1 will always be the lower number if lat1 < lat2: pass else: lat1, lat2 = lat2, lat1 # makes sure that lon1 will always be the lower number if lon1 < lon2: pass else: lon1, lon2 = lon2, lon1 # iterates through the cities list and checks if the lat on is within # the boundrys of a specific city. If it is, append it to the within # list for city in cities: if city.lat >= lat1 and city.lat <= lat2 and city.lon >= lon1 and city.lon <= lon2: within.append(city) # returns the within list return within # Uncomment everything below if you want to test the user input yourself # # asks for user input for lat1 and lon1 # latlon1 = input("Enter lat1,lon1: ") # latlon1 = latlon1.split(', ') # # asks for user input for lat2 and lon2 # latlon2 = input("Enter lat2,lon2: ") # latlon2 = latlon2.split(', ') # # runs the cityreader_stretch function and sets it to a variable that holds the list # within = cityreader_stretch(float(latlon1[0]), float(latlon1[1]), float(latlon2[0]), float(latlon2[1]), cities) # # print out the list of cities within the boundrys # for city in within: # print(f"{city.name}: {(city.lat, city.lon)}")
f67636e6231083a2ba38e466c79deab4f53e93de
dmeckley/FigureCanvas
/main.py
1,320
3.6875
4
from tkinter import * from figureCanvas import FigureCanvas def main(): # Creates a Tk Widget Object Instance as the main window of the application: window = Tk() window.title("Display Figures") '''Outline Objects''' # Line Outline Shape Object Creation: xOutline = FigureCanvas(window, "line", 100, 100) xOutline.grid(row = 1, column = 1) # Rectangle Outline Shape Object Creation: squareOutline = FigureCanvas(window, "rectangle", False, 100, 100) squareOutline.grid(row = 1, column = 2) # Oval Outline Shape Object Creation: circleOutline = FigureCanvas(window, "oval", False, 100, 100) circleOutline.grid(row = 1, column = 3) # Arc Outline Shape Object Creation: arcOutline = FigureCanvas(window, "arc", False, 100, 100) arcOutline.grid(row = 1, column = 4) '''Shaded Objects''' # Rectangle Shaded Shape Object Creation: squareShaded = FigureCanvas(window, "rectangle", True, 100, 100) squareShaded.grid(row = 2, column = 2) # Oval Shaded Shape Object Creation: circleShaded = FigureCanvas(window, "oval", True, 100, 100) circleShaded.grid(row = 2, column = 3) # Arc Shaded Shape Object Creation: arcShaded = FigureCanvas(window, "arc", True, 100, 100) arcShaded.grid(row = 2, column = 4) # Halts Excution of Program: window.mainloop() if __name__ == '__main__': main()
06497822c9674420ce2d8344c4dc6d1d8a004db7
GJAI-School/GJAI-Algorithm
/queue.py
924
3.546875
4
# import sys # input = sys.stdin.readline def process_queue(queue_list, f_idx, r_idx, command): cmd = command[0] if cmd == "push": queue_list[r_idx] = command[1] r_idx += 1 elif cmd == "pop": if f_idx == r_idx: print(-1) else: print(queue_list[f_idx]) f_idx += 1 elif cmd == "size": print(r_idx-f_idx) elif cmd == "empty": print(int(r_idx == f_idx)) elif cmd == "front": if f_idx == r_idx: print(-1) else: print(queue_list[f_idx]) elif cmd == "back": if f_idx == r_idx: print(-1) else: print(queue_list[r_idx-1]) return [f_idx, r_idx] n = int(input()) queue_list = [0 for _ in range(n)] f_idx = 0 r_idx = 0 for _ in range(n): command = input().split() f_idx, r_idx = process_queue(queue_list, f_idx, r_idx, command)
9a9fe3c8bffc2eca97fe693c746af3ff976441f4
chengbo/leetcode
/leetcode/binary_tree/maximum_depth.py
546
3.671875
4
def maximum_depth(root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 left_result = maximum_depth(root.left) right_result = maximum_depth(root.right) return max(left_result, right_result) + 1 def maximum_depth2(root, depth): """ :type root: TreeNode :rtype: int """ if root is None: return depth left_result = maximum_depth2(root.left, depth + 1) right_result = maximum_depth2(root.right, depth + 1) return max(left_result, right_result)
0ad7289d6aee3f084334e5252b7ba6f9df7d6415
pratikshah1701/hackerrank
/xml-1-find-the-score.py
419
3.65625
4
#!/usr/bin/env python3 import xml.etree.ElementTree as etree def main(): line_num = int(input()) xml = '' for i in range(line_num): xml += input() + '\n' tree = etree.ElementTree(etree.fromstring(xml)) score = len(tree.getroot().attrib) for element in tree.findall('.//*'): score += len(element.attrib) print(score) if __name__ == "__main__": main()
8fecea8a5edaf8197955a3e3ffdb507322316249
kalidindiravi1/sample-python-code
/pyglatin.py
329
3.984375
4
pyg = 'ay' original = raw_input('Enter a word:') if len(original) == 0: print "empty" elif len (original) > 0 and not original.isalpha(): print "not a string" else: word = original.lower() first = word[0] new_word = word+first+pyg new_word = new_word[1:len(new_word)] print new_word
fb598caac8ec1aea76022a3ebab5e3b032fc1829
alex-lenk/python_fast_start
/les02.py
701
4.09375
4
# coding : utf-8 answer = input("Кто сегодня хочет поработать? (Y/N)") if answer == 'Y' or answer == 'y': print ("Выберите цифру, которая подходит для работы сегодня") select = int(input("Изучать python: 1, изучать JAVA: 2 = ")) if select == 1: print ("Начинаем изучать питон") elif select == 2: print ("Изучаю ДЖАВА") else: print ("Вы не указали одну из двух цифр") elif answer == "N" or answer == 'n': print ('Тогда досвидания') else: print ('Вы дали непонятный ответ')
2b37a0897ec1da5b841578a19afd49532f6be25e
Qualia1789/Challenges
/HackerRank.py
1,027
3.734375
4
global_list = [] numbers = [] numbers2 = [] names = [] list = [] raw_input_string = '''5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39''' raw_input_list = raw_input_string.split('\n') def raw_input(): return raw_input_list.pop(0) for _ in range(int(raw_input())): name = raw_input() score = float(raw_input()) numbers.append(score) list = [name,score] global_list.append(list) print(numbers) #works up to here def takeSecond(score): return score[1] global_list.sort(key=takeSecond) #works up to here y = min(numbers) print(y) #works up to here i = 0 while i < len(global_list): x = global_list[i] print(x) if x[1] == y: global_list.remove(x) else: i = i + 1 print(global_list) for beta in global_list: numbers2.append(beta[1]) z = min(numbers2) def alphabetically(name): return name[0] global_list.sort(key=alphabetically) print(global_list) for alpha in global_list: if alpha[1] == z: print(alpha[0])
e002c532d571b89a9d70740f880918bc9f8c7851
thormeier-fhnw-repos/ip619bb-i4ds02-audio-text-alignment
/lib/src/align/utils/get_none_part.py
254
3.625
4
from typing import List def get_none_part(l: List) -> float: """ Calculates the amount of gaps relative to the sentence length :param l: Sentence or sentence part :return: Percentage of gaps """ return (l.count("-")) / len(l)
cac1eb499e415d46b391896be5fdbd53f2f97e08
mindovermiles262/codecademy-python
/03 PygLatin/02_ahoy_or_should_i_say_ahoyay.py
172
3.6875
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 08:43:27 2017 @author: mindovermiles262 Codecademy Python Please print the phrase "Pig Latin". """ print("Pig Latin")
2fe1294e339644b243fa12319d041238ee310341
hanbinq/own_stu
/Py/02_quick_sort.py
2,443
4.3125
4
""" 快速排序 1、从列表中挑出一个元素,作为基准值key 2、所有小于key的元素放左边,所有大于key的元素放右边 3、分别递归左侧列表,右侧列表 """ def quick_sort(lists, start, end): """快速排序""" # 递归过程中,发现start和end一致时,停止递归,直接返回列表(递归的退出条件) if start >= end: return lists # 设定起始元素为要寻找位置的基准元素 mid = lists[start] # low为序列左边的由左向右移动的游标 low = start # high为序列右边的由右向左移动的游标 high = end while low < high: # 如果low与high未重合,high指向的元素不比基准元素小,则high向左移动 while low < high and lists[high] >= mid: high -= 1 # 将high指向的元素放到low的位置上 lists[low] = lists[high] # 如果low与high未重合,low指向的元素比基准元素小,则low向右移动 while low < high and lists[low] < mid: low += 1 # 将low指向的元素放到high的位置上 lists[high] = lists[low] # 退出循环后,low与high重合,此时所指位置为基准元素的正确位置 # 将基准元素放到该位置 lists[low] = mid # 对基准元素左边的子序列进行快速排序 quick_sort(lists, start, low - 1) # 处理右侧元素 quick_sort(lists, low + 1, end) return lists alist = [54, 26, 93, 17, 77, 31, 44, 55, 20] quick_sort(alist, 0, len(alist)-1) print(alist) """ 快速排序,又称划分交换排序(partition-exchange sort), 通过一趟排序将要排序的 数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再 按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据 变成有序序列。 步骤为: 1. 从数列中挑出一个元素,称为"基准", 2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在 基准的后面(相同的数可以放在任一边)。在这个分区结束之后,该基准就处于数列的 中间位置。这个称为分区(partition)操作。 3. 递归的(recursive)把小于基准值元素的子数列和大于基准元素的子数列排序。 """
1130b669de80a4bd25ecf3e3e8f97c1dd4e961fa
ElonDormancy/solvepde
/fourier_transform.py
776
3.671875
4
import numpy as np import matplotlib.pyplot as pl #Consider function f(t)=1/(t^2+1) #We want to compute the Fourier transform g(w) #Discretize time t # t0=-100. dt=0.001 # t=np.arange(t0,-t0,dt) t0 = 0 t=np.arange(t0, 200, dt) #Define function f=np.cos(t*10) + np.cos(t*5) #Compute Fourier transform by numpy's FFT function g=np.fft.fft(f) #frequency normalization factor is 2*np.pi/dt w = np.fft.fftfreq(f.size)*2*np.pi/dt #In order to get a discretisation of the continuous Fourier transform #we need to multiply g by a phase factor g*=dt*np.exp(-complex(0,1)*w*t0)/(np.sqrt(2*np.pi)) #Plot Result pl.scatter(w,g,color="r") #For comparison we plot the analytical solution # pl.plot(w,np.exp(-np.abs(w))*np.sqrt(np.pi/2),color="g") pl.gca().set_xlim(-10,10) pl.show()
ce63fa4de0b4fa4cb4eb40e4de83880d5d2053fa
accolombini/python_completo
/lab91_lendo_arquivos_csv.py
4,448
4.375
4
""" Lendo arquivos CSV => Coma Separeted Values -> Valores Seprados por vírgula. Observações: 1- O primeiro ponto aqui é ter consciência de que podemos ter outros tipos de separadores que não apenas a vírgula e ainda estamos tratando de um arquivo CSV, o importante é que exista um padrão, não pode haver mistura de separadores. Os separadores mais comuns: - Separador por vírgulas -> 1, 2, 3, 4, 5 => "python", "ciência de dados", "ml" - Separador por ponto e virgulas -> 1; 2; 3; 4; 5 => "python"; "ciência de dados"; "ml" - Separador por espaço -> 1 2 3 4 5 => "python" "ciência de dados" "ml" 2- Você pode conseguir muitos dados para testes e simulações em: http://dados.gov.br/dataset 3- A linguagem Python possui duas formas diferentes para ler dados em arquivos CSV: - reader -> permite que iteremos sobre as linhas do arquivo CSV como se fossem listas - DictReader -> Permite que iteremos sobre as linhas do arquvio CSV como OrderedDicts # Iniciando seus trabalhos -> como arquivos não recomendado with open('lutadores.csv', 'r', encoding='utf8') as arquivo: # 'r' não é necessário já é defautl para Python dados = arquivo.read() print(f'Qual o tipo de dados? -> {type(dados)}') dados = dados.split(',') print(f'Imprimindo dados \n {dados}') arquivo.close() # Trabalhando com CSV -> usando reader from csv import reader with open('lutadores.csv', encoding='utf8') as arquivo: leitor_csv = reader(arquivo) # A grande sacada aqui é que reader() devolve cada linha numa lista facilitando # o processo de iteração e manipulação de seu arquivo. Ainda temos um problema, observe que o cabeçalho está # sendo impresso como um dado, mas podemos não querer isso. for linha in leitor_csv: # Cada linha é uma lista print(f'{linha[0]} nasceu no(a)s {linha[1]} e mede {linha[2]} centimetros') arquivo.close() print(f'\n') # Vamos refatorar nosso código para não trabalhar com o cabeçalho como um dado. Lembre-se da vantagem de # estar usando iterators, observe # Você pode confirmar o retorno de readerf() posicionando o mause sobre ele pressionando CTRL -> note que # o retorno é um iterator, logo, tudo o que apresndeu sobre iterators vale para este caso with open('lutadores.csv', encoding='utf8') as arquivo: leitor_csv = reader(arquivo) # A grande sacada aqui é que reader() devolve cada linha numa lista facilitando # o processo de iteração e manipulação de seu arquivo. Ainda temos um problema, observe que o cabeçalho está # sendo impresso como um dado, mas podemos não querer isso. next(leitor_csv) # Simples assim, pulamos para o próximo iterável, no caso a linha seguinte ao cabeçalho for linha in leitor_csv: # Cada linha é uma lista print(f'{linha[0]} nasceu no(a)s {linha[1]} e mede {linha[2]} centimetros') arquivo.close() # Trabalhando com DictReader from csv import DictReader with open('lutadores.csv', 'r', encoding='utf8') as arquivo: leitor_csv = DictReader(arquivo) for linha in leitor_csv: # Cada linha é um OrderedDict - Note que a chave é o cabeçalho, logo devem ser escritas exatamente # conforme especificado no cabeçalho do seu arquivo print(f"{linha['Nome']} nasceu no(a)(s) {linha['País']} e mede {linha['Altura (em cm)']}") arquivo.close() """ # Trabalhando com DictReader -> com outro separador, lembre esses métodos consideram a vírgula o separador default from csv import DictReader with open('lutadores.csv', 'r', encoding='utf8') as arquivo: leitor_csv = DictReader(arquivo, delimiter=',') # Observe o uso do delimiter =, aqui especifique o # delimitador de seu arquivo, no caso estamos usando a vírgula e isso é desnecessário, mas imagine # que o delimitador fosse '$', ficaria no seu código da seguinte forma => delimiter='$' for linha in leitor_csv: # Cada linha é um OrderedDict - Note que a chave é o cabeçalho, logo devem ser escritas exatamente # conforme especificado no cabeçalho do seu arquivo print(f"{linha['Nome']} nasceu no(a)(s) {linha['País']} e mede {linha['Altura (em cm)']}") arquivo.close()
0b7f65062a0c952842363c913efb45b53dbcaf6c
NathanaelV/CeV-Python
/Exercicios Mundo 3/ex094_unindo_dicionarios_e_listas.py
3,416
3.96875
4
# Class Challenge 19 # Read Name, gender and age of several people. # Guardando esse valor em um dicionário # Mostrar: # Número de pessoa cadastradas: len() # A média da idade do grupo # Uma lista com todas as mulheres # Uma lista com as pessoas com idade acima da média person = dict() people = [] while True: person['name'] = str(input('Name: ')).strip() person['gender'] = str(input('Gender [M/F]: ')).strip().upper()[0] while person['gender'] not in 'MF': print('ERROR! Please enter M or F: ') person['gender'] = str(input('Gender [M/F]: ')).strip().upper()[0] person['age'] = int(input('Age: ')) people.append(person.copy()) resp = str(input('Do you want to continue? [Y/N] ')) while resp not in 'NnYy': print('ERROR! Please enter Y or N.') resp = str(input('Do you want to continue? [Y/N] ')).strip()[0] if resp in 'Nn': break print('-=' * 25) person['total'] = 0 for a in people: person['total'] += a['age'] media = person['total'] / len(people) print(f'A) There are {len(people)} people registered') print(f'B) Media of the ages are: {media:.1f} years') print('C) Women in the list are: ', end='') for m in people: if m['gender'] == 'F': print(f'{m["name"]}', end=', ') print() print('D) People who are above average age:') for m in people: if m['age'] > media: print(' - ', end='') for k, v in m.items(): print(f'{k.capitalize()} = {v}', end='; ') print('') print('\n<< ENCERRADO >>') # Mostrando com , 'e' e ponto final: print('\nTeste:') old = 0 velho = list() # List to save all category names for p in people: # Count how many people are in this group if p['age'] > person['total'] / len(people): velho.append(p['name']) old += 1 print('Pessoas com idade acima da média: ', end='') for n, m in enumerate(velho): if n < old - 2: # and m['age'] > person['total'] / len(people): print(m, end=', ') elif n < old - 1: # and m['age'] > person["total"] / len(people): print(m, end=' and ') else: # m['age'] > person['total'] / len(people): print(f"{m}.") # Teacher Example: print('\nTeacher Example:') pessoa = dict() galera = list() soma = media = 0 while True: pessoa['nome'] = str(input('Nome: ')) while True: pessoa['sexo'] = str(input('Sexo: [M/F] ')).strip().upper()[0] if pessoa['sexo'] in 'MF': break print('ERRO! Por favor, digite apenas M ou F.') pessoa['idade'] = int(input('Idade: ')) soma += pessoa['idade'] galera.append(pessoa.copy()) pessoa.clear() while True: resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if resp in 'SN': break print('ERRO! Responda apenas S ou N') if resp == 'N': break print('-=' * 30) print(f'A) Ao todo temos {len(galera)} pessoas cadastradas.') media = soma / len(galera) print(f'B) A média de idade é de {media:.2f} anos') print('C) As mulheres cadastradas foram: ', end='') for p in galera: if p['sexo'] in 'Ff': print(f'{p["nome"]}', end=', ') print() print('D) Lista das pessoas que estão acima da média:') for p in galera: if p['idade'] >= media: print(' ', end='') for k, v in p.items(): print(f'{k} = {v};', end='') print() print(' << ENCERRADO >>')
b1f8a595797a24f4391f673300230f39fc813842
flobabs/Linear-Regression
/Linear regression.py
1,496
3.578125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import numpy as np # In[2]: Data = pd.read_csv('cost-revenue-dirty.csv') # In[3]: Data.describe() # In[4]: x = DataFrame(data, columns=['Production_budget_usd']) y = DataFrame(data, columns=['worldwide_gross_usd']) # In[ ]: regression = LinearRegression() regression.fit(x,y) # In[ ]: plt.figure(figsize=(20,16)) plt.scatter(x, y, alpha=0.5) plt.title('Film cost vs Global Revenue') plt.xlabel('production budget $') plt.ylabel('Worldwide Gross $') plt.ylim(0, 3000000000) plt.xlim(0, 450000000) plt.show() # Slope Coefficient # In[ ]: regression.coef_ # In[ ]: #Intercept regression.intercept_ # In[ ]: # In[ ]: plt.figure(figsize=(20,16)) plt.scatter(x, y, alpha=0.5) #calculating the predicted value plt.plot(x, regression.predict(x), color='green', linewidth=4) #plt.plot(y, regression.predict(y)) plt.title('Film cost vs Global Revenue') plt.xlabel('production budget $') plt.ylabel('Worldwide Gross $') plt.ylim(0, 3000000000) plt.xlim(0, 450000000) plt.show() # In[ ]: #Goodness of Fit (Finding R Squred) regression.score(x, y) # In[ ]: type(Data) # In[10]: a = 20 b = 20 # In[11]: a # In[12]: b # In[ ]: import collections # In[ ]: plt.pie(data.values(), labels=day.keys(),autopct='%1.1f%%') plt.axis('equal'); # In[ ]: # In[ ]:
fc94ccf4863669c344f1b3eb1239c212009fc13c
ascaniopy/python
/pythonexercicios/ex012.py
236
3.609375
4
print('=' * 100) preco = float(input('Qual é o preço do produto? ')) novo = preco - (preco * 5 / 100) print('O produto que custava R$ {:.2f}, na promoção com desconte de 5% vai custar R$ {:.2f}'.format(preco, novo)) print('=' * 100)
23b98747b79dbc09658a5caad8f46cfcbf8bdf7b
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_emilmgeorge_coinjam.py
1,055
3.578125
4
#!/bin/python2 import itertools def isPrime(n,skip=True): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return 2 if n < 9: return True if n%3 == 0: return 3 r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return f if n%(f+2) == 0: return f+2 if skip and f>100000: return -1 f +=6 return True def xmain(N,J,lst,skip=True): skipped=[] print "Case #1:" for x in lst: if J==0: break s='1'+''.join(x)+'1' divisors=[] for b in xrange(2,11): r=isPrime(int(s,b),skip) if(r==-1): skipped.append(s) break if(r==True): break else: divisors.append(str(r)) if len(divisors)==9: print s,' '.join(divisors) J=J-1 return skipped,J==0 raw_input() N,J=[int(x) for x in raw_input().split()] skipped,r=xmain(N,J,itertools.product(['0','1'], repeat=N-2)) if r!=1 and len(skipped)!=0: xmain(N,J,skipped,False)
138ab81e765175a98759e587ed4368d00dd09581
0x232/BOJ
/1929.py
288
3.671875
4
from math import sqrt def prime(n): if n == 1: return False else: for i in range(2, int(sqrt(n))+1): if n % i == 0: return False return True m, n = map(int, input().split()) for i in range(m, n+1): if prime(i): print(i)
791dc62f33a24fef19e22a7fe1fd7889d2765a0f
drwit/2015SummerPython
/7-22/function.py
350
3.796875
4
def add(a, b): y = a + b print '%d + %d = %d' % (a, b, y) def none(): print 'There is no arg in the function' def get_shit(): """You may get some shit""" str = 'shit' return str print 'Plz input two numbers:' a = int(raw_input('first one>')) b = int(raw_input('second one>')) add(a, b) none() print 'We are getting shit!>>>', get_shit()
af27f48da8ace55ab443766248e81c48ac1bccfc
ivnxyz/practicas-programacion-inviertete
/Frida/dado.py
113
3.5625
4
import random dado= input("presiona enter para tirar el dado") for numero in dado: print(random.randrange(1,7,1))
7d76637576161d210b785cfe09817e36e2beac37
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-FabianMontoya9975
/Taller3/Ejercicio06.py
226
3.5
4
""" Genere y presente el resultado en pantalla de la siguiente expresión: ____ V 81 + 9 ( ----------- == 9 ) and (10 > 1) 3 """ resultado = (((81**(1.0/2)+9)/3)==9) and (10>1) print(resultado)
ad6d04547dd5c97b1cc93cdafb1356e0ba34adc8
denze11/gb_osnovi_python_vebinar
/lesson_1/4.py
232
3.90625
4
number = int(input('Введите число: ')) item = number % 10 number //= 10 while number > 0: if number % 10 > item: item = number % 10 number //= 10 print(f'Самое большое число - {item}')
be54cbbf7ef9004c428769207bd1a936b7c5ee2f
GSilva-N/Cursoemvideo_Python
/Mundo 03/Aula 21/Ex102.py
402
3.84375
4
def fatorial(num, show=False): fat = 1 if show == True: for i in range(num, 0, -1): fat *= i print(i, end=' ') if i > 1: print('x', end=' ') else: print('=', end=' ') return fat else: for i in range(num, 0, -1): fat *= i return fat print(fatorial(9, show=True))
f9a841b92d4736a992b08fffafee5245b40a042d
SabithaSubair/pythonpgms
/flowcontrols/second largest no.py
347
4.1875
4
num1=int(input("number1")) num2=int(input("number2")) num3=int(input("number3")) if((num1>num2)^(num1>num3)): print(" 2nd greater number is:",num1) elif((num2>num1)^(num2>num3)): print("2nd greater number is:",num2) elif((num3>num2)^(num1<num3)): print(" 2nd greater number is:",num3) else: print("eqal numbers",num1)
cc0c7322ce17ab845f6b6eb23b8b549e2810d112
RF-Fahad-Islam/Python-Practice-Program
/jumble_funny_names.py
847
4.0625
4
''' Author : Fahad Practice Problem 9 Solution ''' import random def jumbleName(nameList): #* Jumbled the names lastnames = [] firstnames = [] jumbled = [] for name in nameList: name = name.split(" ") for i in range(1,len(name)): lastnames.append(name[1]) firstnames.append(name[0]) lastnames.reverse() for i,l in enumerate(lastnames): jumbled.append(f"{firstnames[i]} {lastnames[random.randint(0, len(lastnames)-1)]}") for name in jumbled: print(name) if __name__ == "__main__": #* Take the input from the user n = input("Enter the friends number : ") nameList = [] for i in range(int(n)): name = input(f"{i+1}. Enter the friend name : ") nameList.append(name) jumbleName(nameList)
fd645ecff92258000da58498e9f4288ab2c50143
oneandzeroteam/python
/rhino/1부터n까지합.py
196
3.765625
4
''' i = 0 sum = 0 n = int(input()) while i < n: i += 1 sum += i print(sum) ''' n = int(input()) total = 0 for x in range(1,n+1): total = total + x print(total)
b364bfa326f2d94207dbaff2d93bc72065ea3cdb
timmalstead-cfa/mssql_server_data
/data/parser_join_tables.py
1,233
3.546875
4
from typing import List from csv import reader final_csv: str = "" try: with open("./join/services_organizations.csv") as csv_data: csv_file: List = list(reader(csv_data, delimiter=",")) for index, page in enumerate(csv_file): if(index == 0): final_csv += f"{','.join(page)}\n" continue else: first_val, second_val = page[0], page[1] is_second_value: bool = bool(second_val) if(is_second_value): if(second_val.find(',') != -1): second_value_list: List = second_val.split(',') for value in second_value_list: line_to_insert: str = first_val + ',' + value.strip() final_csv += f"{line_to_insert}\n" else: final_csv += f"{','.join(page)}\n" else: final_csv += f"{','.join(page)}\n" with open('./join/services_organizations_processed.csv', 'w') as processed_csv: processed_csv.write(final_csv) except Exception as error: print(f"#{error.__class__} occured when trying to parse the csv.")
36a8cc1d565bd5fc18f49feebf892fa2364e24c8
Phantom1911/leetcode
/algoexpert/mergeSort.py
654
4.03125
4
def mergeSort(array): # Write your code here. if len(array) == 1: return array mid = len(array) // 2 leftHalf = array[:mid] rightHalf = array[mid:] return merge(mergeSort(leftHalf), mergeSort(rightHalf)) def merge(array1, array2): i, j = 0, 0 ans = [] while i < len(array1) and j < len(array2): if array1[i] <= array2[j]: ans.append(array1[i]) i += 1 else: ans.append(array2[j]) j += 1 while i < len(array1): ans.append(array1[i]) i += 1 while j < len(array2): ans.append(array2[j]) j += 1 return ans
682cf2b673796e09e0a31d2386005cbe04763b96
yaHaart/hometasks
/Module16/10_simmetrical_seq/main.py
902
3.515625
4
n = int(input('Кол-во чисел: ')) numbers = [] for _ in range(n): number = int(input('Число: ')) numbers.append(number) revers_numbers = numbers.copy() revers_numbers.reverse() flag = True for i in range(len(numbers)): length_revers = len(revers_numbers) counter = 0 for j in range(length_revers): if revers_numbers[-1 - j] != numbers[-1 - j]: flag = False break else: counter += 1 if counter == length_revers: flag = True if flag: print('ПОследовательность ', numbers) print('Нужно приписать чисел ', len(numbers) - counter) print('Сами числа', end=' ') for ind in range(len(numbers) - counter - 1, -1, -1): print(numbers[ind], end=' ') break del revers_numbers[-1] # зачёт! 🚀
4a4f5b35cc8f613ce39c9df5c17f6fa71e64d60c
sreyaandalkovil/CS421
/assignment15.py
2,270
3.53125
4
class moviecollection: def __innit__(self, list_of_movies): self.list_of_movies=list_of_movies def __repr__(self): return 'SILC(list_of_movies=%s)' % (self.list_of_movies) def __str__(self): return 'SILC(list_of_movies=%s)' % (self.list_of_movies) def count_songs(self): total = 0 for movie_songs in self.list_of_movies: count = len(cs_class.list_of_songs) total = total + count return total class movies: def __init__(self, list_of_songs): self.list_of_songs = list_of_songs def __repr__(self): return 'movies(list_of_songs=%s)' % (self.list_of_songs) def __str__(self): return 'movies(list_of_songs=%s)' % (self.list_of_songs) class song: def __init__(self, name, genre, singer): self.name = name self.genre = genre self.singer = singer def __repr__(self): return 'song(name=%s, genre=%s, singer=%s)' % (self.name, self.genre, self.singer) def __str__(self): return 'song(name=%s, genre=%s, singer=%s)' % (self.name, self.genre, self.singer) class people: def __init__(self, gender, age, name): self.gender = gender self.age = age self.name = name def __repr__(self): return 'people(gender=%s, age=%s, name=%s)' % (self.gender, self.age, self.name) def __str__(self): return 'people(gender=%s, age=%s, name=%s)' % (self.gender, self.age, self.name) song_1= song("let it go", "pop", "idina menzel") song_2 = song("do you want to build a snowman", "pop", "kristen bell") song_3= song( "mother knows bestr", "pop", "donna murphy") person_1= people("female", "unknown", "elsa") person_2= people("female", "18", "anna") person_3= people("female", "18", "repunzel") frozen_people = [person_1, person_2] frozen_movie = movies(frozen_people) tangled_people = [person_3] tangled_movie = movies(tangled_people) list_of_movies = [tangled_movie, frozen_movie] disneymovies = moviecollection(list_of_movies) total_count_of_songs = disneymovies.count_songs() print("All Movies --> ", disneymovies) print("Total Count of Songs ", total_count_of_songs)
56ca674a990ccc7ec73580e10d8ff8209ea540bd
alsgh4098/workspace_python
/venv/pkg/1__/test_8_26.py
335
3.625
4
#format함수를 이용한 입출력. age = 27 name = "진민호" print("이름은{0}, 나이는 {1}".format(name,age)) age = 44 print('I’m {0} years old.'.format(age)) print("*"*100) zzz = {"uid":"kim" , "upw":"111", "gen":"f"} print(zzz) print("*"*100) del zzz["uid"] print(zzz) print("*"*100) zzz.clear() print(zzz) # ^복습
29958f10a9f5e8c5e4f48a2bc922e85062b0a37f
xiangcao/Leetcode
/python_leetcode_2020/Python_Leetcode_2020/752_open_the_lock.py
2,643
3.640625
4
""" You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. """ """Hints: We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. """ class Solution: # BFS def openLock(self, deadends: List[str], target: str) -> int: def neighbors(node: str): for i in range(4): x = int(node[i]) for d in (-1, 1): y = (x + d) % 10 yield node[:i] + str(y) + node[i+1:] dead = set(deadends) queue = collections.deque([('0000', 0)]) seen = {'0000'} while queue: node, depth = queue.popleft() if node == target: return depth if node in dead: continue for nei in neighbors(node): if nei not in seen: seen.add(nei) queue.append((nei, depth+1)) return -1 # second round def openLock(self, deadends: List[str], target: str) -> int: start = "0000" queue = collections.deque([(start, 0)]) deadends = set(deadends) visited = {start} while queue: current, step = queue.popleft() if current == target: return step if current in deadends: continue for i in range(4): for d in (1, -1): newValue = str((int(current[i]) + d ) % 10) nextState = current[:i] + newValue + current[i+1:] if nextState in deadends or nextState in visited: continue visited.add(nextState) queue.append((nextState, step + 1))
4bd5c3cb848171b556d89f2605e82febe1de37a6
annaymj/LeetCode
/KthLargestElementInAStream.py
1,630
3.96875
4
# -*- coding: utf-8 -*- """ Created on Sun May 26 23:01:40 2019 @author: annayu 703. Kth Largest Element in a Stream Easy 299 132 Favorite Share Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream. Example: int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8 """ import bisect import heapq class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.nums = sorted(nums) def add(self, val: int) -> int: bisect.insort(self.nums, val) return self.nums[-1*self.k] class KthLargest2: def __init__(self, k: int, nums: List[int]): self.k = k nums.sort() self.heap = nums[-k:] self.nums = sorted(nums) heapq.heapify(self.heap) def add(self, val: int) -> int: if (len(self.heap) < self.k): heapq.heappush(self.heap,val) elif val >= self.heap[0]: heapq.heappop(self.heap) heapq.heappush(self.heap,val) return self.heap[0]
482638594d178078403b0b2bf266bf96bff05a54
VincentMatthys/OMEN
/buildings.py
1,212
3.578125
4
# -*- coding: utf-8 -*- import overpass def get_buildings(response): """ Returns the list of buildings of the overpass api response """ # List of buildings buildings = [] # For every element in the features of the reponse for element in response['features']: # when the feature is a building if 'building' in element['properties']: buildings.append(element) return buildings def get_positions(features): """ Given a list of features, return the list of positions """ # List of positions positions = [] # For every element in the features for element in features: # Append the list of coordinates positions.append(element['geometry']['coordinates']) return positions """ # Query by name response = api.Get('node["name"="Salt Lake City"]') print ([(feature['properties']['name'], feature['id']) for feature in response['features']]) """ if __name__ == '__main__': api = overpass.API() # Query by map map_query = overpass.MapQuery(50.746,7.154,50.748,7.157) # Get the response from the API response = api.Get(map_query) # Get every buildings from this reponse buildings = get_buildings(response) # Get the positions of every buildings pos = get_positions(buildings)
3095b2b7892f864a256ee9e1bc7ebee7a3bf87c3
ArmandoRuiz2019/Python
/POO/POO04/pruebas.py
841
3.90625
4
''' Created on Agosto, 2019 @author: Armando Ruiz Este ejemplo muestra como se usa el __str__ 1. Teníamos para mostrar los detalles del objeto el metodo "mostrarDetalles" 2. Si queremos imprimir un objeto, saca una referencia a la memoria 3. entonces definimos el metodo __string__ que regresa una cadena 4. y ya podemos imprimir un objeto 5. cambiamos mostrarDetalles en todas las clases por este nuevo ''' from cuenta import * from cliente import * class Pruebas: pass print ( "Desde las pruebas" ) cuenta1 = Cuenta( 300 ) print ( cuenta1 ) cuenta1.depositar( 400 ) print ( cuenta1 ) """ Imprimimos un objeto y nos mandará una referencia en la memoria si es que no tenemos reescrito el me´todo __str__ """ print ("Objeto cuenta::", cuenta1) cliente = Cliente( "Virginia", "direccion", 25, cuenta1) print ("Objeto cliente::", cliente )
456d40e841815bc55fff9a88f7ec803151a1a8d8
jackandrea54/C4T39-NDN
/Lesson9MiniHack/ex6.py
241
3.90625
4
numbs = ["2","5","92","84","-99"] choice = int(input("What number: ")) for i in range(0,len(numbs)): if choice == int(numbs[i]): print("Found,","Position:",i+1) break elif i == len(numbs)-1: print("Not found")
7a742a675954bb8abb5b17e4037809147bbc94d8
LukeMcCulloch/PyCFD
/src/Utilities.py
9,690
3.53125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun May 5 15:14:18 2019 @author: luke """ import numpy as np from math import pi # An alias for np.linal.norm, because typing that is ugly def norm(vec, *args, **kwargs): return np.linalg.norm(vec, *args, **kwargs) # A quicker cross method when calling on a single vector def cross(u, v): return np.array(( u[1]*v[2] - u[2]*v[1], u[2]*v[0] - u[0]*v[2], u[0]*v[1] - u[1]*v[0] )) def dot(u,v): return np.dot(u,v) ''' 2D vector utilities ''' ## A wrapper for the purposes of this class, to avoid interacting with numpy def Vector2D(x,y): return np.array([float(x),float(y)]) def printVec2(v): return "({:.5f}, {:.5f})".format(v[0], v[1]) # Normalizes a numpy vector # This methods modifies its argument in place, but also returns a reference to that # array for chaining. # Works on both single vectors and nx3 arrays of vectors (perfomed in-place). # If zeroError=False, then this function while silently return a same-sized 0 # for low-norm vectors. If zeroError=True it will throw an exception def normalize2D(vec, zeroError=False, return_mag=False): # Used for testing zeroError eps = 0.00000000001 # Use separate tests for 1D vs 2D arrays (TODO is there a nicer way to do this?) if(len(vec.shape) == 1): norm = np.linalg.norm(vec) if(norm < 0.0000001): if(zeroError): raise ArithmeticError("Cannot normalize function with norm near 0") else: vec[0] = 0 vec[1] = 0 return vec vec[0] /= norm vec[1] /= norm if return_mag: return vec, norm else: return vec elif(len(vec.shape) == 2): # Compute norms for each vector norms = np.sqrt( vec[:,0]**2 + vec[:,1]**2 + vec[:,2]**2 ) # Check for norm zero, if checking is enabled if(zeroError and np.any(norms < 0.00000000001)): raise ArithmeticError("Cannot normalize function with norm near 0") # Normalize in place # oldSettings = np.seterr(invalid='ignore') # Silence warnings since we check above if the user cares vec[:,0] /= norms vec[:,1] /= norms vec[:,2] /= norms # np.seterr(**oldSettings) else: raise ValueError("I don't know how to normalize a vector array with > 2 dimensions") if return_mag: return vec, norms else: return vec # Normalizes a numpy vector. # This method returns a new (normalized) vector # Works on both single vectors and nx3 arrays of vectors (perfomed in-place). # If zeroError=False, then this function while silently return a same-sized 0 # for low-norm vectors. If zeroError=True it will throw an exception def normalized2D(vec, zeroError=False, return_mag=False): # Used for testing zeroError eps = 0.00000000001 # Use separate tests for 1D vs 2D arrays (TODO is there a nicer way to do this?) if(len(vec.shape) == 1): norm = np.linalg.norm(vec) if(norm < 0.0000001): if(zeroError): raise ArithmeticError("Cannot normalize function with norm near 0") else: return np.zeros_like(vec) if return_mag: return vec / norm, norm else: return vec / norm elif(len(vec.shape) == 2): # Compute norms for each vector norms = np.sqrt( vec[:,0]**2 + vec[:,1]**2 ) # Check for norm zero, if checking is enabled if(zeroError and np.any(norms < 0.00000000001)): raise ArithmeticError("Cannot normalize function with norm near 0") else: norms += 1.e-8 # if np.any(norms[:,0] < 0.00000000001): # norms[:,0] += 1.e-8 # elif np.any(norms[:,1] < 0.00000000001): # norms[:,1] += 1.e-8 # elif np.any(norms[:,2] < 0.00000000001): # norms[:,2] += 1.e-8 # Normalize in place # oldSettings = np.seterr(invalid='ignore') # Silence warnings since we check above if the user cares vec = vec.copy() #if not np.any(norms >0.): #norms = sum(norms) #print 'norms = ',type(norms),norms vec[:,0] /= norms vec[:,1] /= norms # np.seterr(**oldSettings) else: raise ValueError("I don't know how to normalize a vector array with > 2 dimensions") if return_mag: return vec, norms else: return vec def triangle_area(node1,node2,node3): """ area of a 2D triangular cell which is assumed to be ordered counter clockwise. 1 2 o------------o \ . \ . \ . \ . o 3 Note: Area vector is computed as the cross product of edge vectors [32] and [31]. """ q1 = node1.vector q2 = node2.vector q3 = node3.vector x1,x2,x3 = q1[0],q2[0],q3[0] y1,y2,y3 = q1[1],q2[1],q3[1] # area = -0.5*( (x1-x3)*(y2-y3)-(y1-y3)*(x2-x3) ) #<- cross product return -0.5*( x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2) ) #re-arranged ''' 3D vector utilities ''' ## A wrapper for the purposes of this class, to avoid interacting with numpy def Vector3D(x,y,z): return np.array([float(x),float(y),float(z)]) def printVec3(v): return "({:.5f}, {:.5f}, {:.5f})".format(v[0], v[1], v[2]) # Normalizes a numpy vector # This methods modifies its argument in place, but also returns a reference to that # array for chaining. # Works on both single vectors and nx3 arrays of vectors (perfomed in-place). # If zeroError=False, then this function while silently return a same-sized 0 # for low-norm vectors. If zeroError=True it will throw an exception def normalize(vec, zeroError=False): # Used for testing zeroError eps = 0.00000000001 # Use separate tests for 1D vs 2D arrays (TODO is there a nicer way to do this?) if(len(vec.shape) == 1): norm = np.linalg.norm(vec) if(norm < 0.0000001): if(zeroError): raise ArithmeticError("Cannot normalize function with norm near 0") else: vec[0] = 0 vec[1] = 0 vec[2] = 0 return vec vec[0] /= norm vec[1] /= norm vec[2] /= norm return vec elif(len(vec.shape) == 2): # Compute norms for each vector norms = np.sqrt( vec[:,0]**2 + vec[:,1]**2 + vec[:,2]**2 ) # Check for norm zero, if checking is enabled if(zeroError and np.any(norms < 0.00000000001)): raise ArithmeticError("Cannot normalize function with norm near 0") # Normalize in place # oldSettings = np.seterr(invalid='ignore') # Silence warnings since we check above if the user cares vec[:,0] /= norms vec[:,1] /= norms vec[:,2] /= norms # np.seterr(**oldSettings) else: raise ValueError("I don't know how to normalize a vector array with > 2 dimensions") return vec # Normalizes a numpy vector. # This method returns a new (normalized) vector # Works on both single vectors and nx3 arrays of vectors (perfomed in-place). # If zeroError=False, then this function while silently return a same-sized 0 # for low-norm vectors. If zeroError=True it will throw an exception def normalized(vec, zeroError=False): # Used for testing zeroError eps = 0.00000000001 # Use separate tests for 1D vs 2D arrays (TODO is there a nicer way to do this?) if(len(vec.shape) == 1): norm = np.linalg.norm(vec) if(norm < 0.0000001): if(zeroError): raise ArithmeticError("Cannot normalize function with norm near 0") else: return np.zeros_like(vec) return vec / norm elif(len(vec.shape) == 2): # Compute norms for each vector norms = np.sqrt( vec[:,0]**2 + vec[:,1]**2 + vec[:,2]**2 ) # Check for norm zero, if checking is enabled if(zeroError and np.any(norms < 0.00000000001)): raise ArithmeticError("Cannot normalize function with norm near 0") else: norms += 1.e-8 # if np.any(norms[:,0] < 0.00000000001): # norms[:,0] += 1.e-8 # elif np.any(norms[:,1] < 0.00000000001): # norms[:,1] += 1.e-8 # elif np.any(norms[:,2] < 0.00000000001): # norms[:,2] += 1.e-8 # Normalize in place # oldSettings = np.seterr(invalid='ignore') # Silence warnings since we check above if the user cares vec = vec.copy() #if not np.any(norms >0.): #norms = sum(norms) #print 'norms = ',type(norms),norms vec[:,0] /= norms vec[:,1] /= norms vec[:,2] /= norms # np.seterr(**oldSettings) else: raise ValueError("I don't know how to normalize a vector array with > 2 dimensions") return vec #****************************************************************************** # Printing Utilities # def default_input( message, defaultVal ): """http://stackoverflow.com/ questions/5403138/how-to-set-a-default-string-for-raw-input """ if defaultVal: return raw_input( "%s [%s]:" % (message,defaultVal) ) or defaultVal else: return raw_input( "%s " % (message) )
6140ff8968cf8a88f4c8d016a29835e57b33dc66
SolidDarrama/Python
/Hands On Quiz/Hands on Quiz for Lists.py
1,522
4.21875
4
# Jose Guadarrama #10/22/2014 #create the list list = ['eggs', 'bacon', 'homefries', 'jelly', 'coffee'] #printed statement print('Your items:') #print list for item in list: print(item) #print Statement + # of items in list print('\nbreakfast has', len(list), 'items') #add two more items to the list list = list + ['orange juice', ' toast'] #print Statement + new # of items in list print('breakfast now has', len(list), 'items') #print statement print('I need some jelly for my toast') #remove the unwanted item from the list list.remove('homefries') #print Statement + final # of items in list print('breakfast now has', len(list), 'items') #print the items within the list print('\nThe complete contents are:', set(list),'\n') #open txt file BKi = open('Breakfastitems.txt', 'w') #write the list to the txt BKi.write(str(list)) #close txt BKi.close() #open txt BKi2 = open('Breakfastitems.txt', 'r') #read the txt lines =BKi2.readlines() #stripe each line from txt for i in range(len(lines)): lines[i] = lines[i].rstrip('\n') #close txt again BKi2.close() #------------------------------------------------- #create a two dimensional list def main(): #print statement print(' List1 List2') #Input the info in the list List1 = [['Batman', ' Robin'],['Bevis', ' Butthead'],['Shaggy',' Scooby'],['Chip',' Dale'],['Tom',' Jerry']] #print the list for Names in List1: print (Names) main()
e7be281863c45e24fbbb20520c8491eee75ec3b3
docjulz/averages
/simple-grade-average.py
1,598
4.1875
4
# This program gets five test scores from the student # then displays their average test score and grade def main(): # NEED TO ASK IN MAIN print("Enter your exam scores") test1 = float(input("Enter score 1: ")) test2 = float(input("Enter score 2: ")) test3 = float(input("Enter score 3: ")) test4 = float(input("Enter score 4: ")) test5 = float(input("Enter score 5: ")) # Calculate the Avereage average = calc_average(test1,test2,test3,test4,test5) # Calculate the grade grade1= determine_grade(test1) grade2= determine_grade(test2) grade3= determine_grade(test3) grade4= determine_grade(test4) grade5= determine_grade(test5) # Display results print("--------------------") print("You earned these grades on your exams") print("Score\t Grade") print("--------------------") print(test1,"\t",grade1) print(test2,"\t",grade2) print(test3,"\t",grade3) print(test4,"\t",grade4) print(test5,"\t",grade5) print("********************") print("Your average exam score is",format(average, '.1f'), "points") # Get the average def calc_average(test1,test2,test3,test4,test5): average = (test1+test2+test3+test4+test5)/5 return average # Determine final grade based on average def determine_grade(test): if test >=90: score='A' elif test >=80: score='B' elif test >=70: score='C' elif test >=60: score='D' else: score='F' return score main()
2ff13d1cd2670001094bf9c58da214cf6527148f
chunweiliu/leetcode
/problems/repeated-dna-sequences/repeated_dna_sequences.py
602
3.625
4
class Solution(object): def findRepeatedDnaSequences(self, s): """ :type s: str :rtype: List[str] Find these string * 10 chars * repeated """ STRING_LENGTH = 10 seen = set() repeated = set() for i in range(len(s) - STRING_LENGTH + 1): substring = s[i:i + STRING_LENGTH] if substring not in seen: seen.add(substring) else: repeated.add(substring) return list(repeated) s = "AAAAAAAAAAA" print Solution().findRepeatedDnaSequences(s)
6e0a49f8816f28724a33ffbeac800e9caa12233d
poojan124/Competitive
/black_jack/main_file.py
5,488
3.59375
4
from abc import ABCMeta, abstractmethod from enum import Enum from random import shuffle import sys class Suit(Enum): HEART = 0 DIAMOND = 1 CLUBS = 2 SPADE = 3 class Card(metaclass=ABCMeta): def __init__(self, value, suit): self.value = value self.suit = suit self.is_available = True @property @abstractmethod def value(self): pass @value.setter @abstractmethod def value(self, other): pass class BlackJackCard(Card): def __init__(self, value, suit): super(BlackJackCard, self).__init__(value, suit) def is_ace(self): return True if self._value == 1 else False def is_face_card(self): """Jack = 11, Queen = 12, King = 13""" return True if 10 < self._value <= 13 else False @property def value(self): if self.is_ace() == 1: return 1 elif self.is_face_card(): return 10 else: return self._value @value.setter def value(self, new_value): if 1 <= new_value <= 13: self._value = new_value else: raise ValueError('Invalid card value: {}'.format(new_value)) class Hand(object): def __init__(self, cards): self.cards = cards def add_card(self, card): self.cards.append(card) class BlackJackHand(Hand): BLACKJACK = 21 def __init__(self, cards): super(BlackJackHand, self).__init__(cards) def score(self): min_over = 100 max_under = -100 for score in self.possible_scores(): if self.BLACKJACK < score < min_over: min_over = score elif max_under < score <= self.BLACKJACK: max_under = score return max_under if max_under != -100 else min_over def possible_scores(self): """Return a list of possible scores, taking Aces into account.""" scores = [0] for card in self.cards: if card.value == 1: ace_score_1 = [score + 1 for score in scores] ace_score_11 = [score + 11 for score in scores] scores = ace_score_1 + ace_score_11 else: scores = [score + card.value for score in scores] return scores def is_burst(self): if self.score() > self.BLACKJACK: return True else: return False class Deck(object): def __init__(self, cards): self.cards = cards self.deal_index = 0 def remaining_cards(self): return len(self.cards) - self.deal_index def deal_card(self): try: card = self.cards[self.deal_index] card.is_available = False self.deal_index += 1 except IndexError: return None return card def shuffle(self): shuffle(self.cards) class Game(object): def __init__(self, cards): self.deck = Deck(cards) self.score_player = 0 self.dealer_hand = BlackJackHand([]) self.player_hand = BlackJackHand([]) def check(self): if self.player_hand.is_burst(): print("Player Lost!") while self.dealer_hand.score() < self.player_hand.score() : if not self.deck.remaining_cards(): print("Game ended due to lack of cards!") return card = self.deck.deal_card() self.dealer_hand.add_card(card) if self.dealer_hand.is_burst(): print("Player Won!") elif self.player_hand.score() == self.dealer_hand.score(): print("Tied") else: print("Player Lost!") def draw_initial(self): if self.deck.remaining_cards(): card = self.deck.deal_card() self.player_hand.add_card(card) print("Player got {} card".format(card.value)) else: return False if self.deck.remaining_cards(): card = self.deck.deal_card() print("Dealer got {} card".format(card.value)) self.dealer_hand.add_card(card) else: return False if self.deck.remaining_cards(): card = self.deck.deal_card() self.player_hand.add_card(card) print("Player got {} card".format(card.value)) else: return False if self.deck.remaining_cards(): card = self.deck.deal_card() self.dealer_hand.add_card(card) print("Dealer hidden card.") else: return False return True def play(self): self.deck.shuffle() while self.draw_initial(): while input("Hit? Y or N : ") == "Y": if not self.deck.remaining_cards(): print("Game ended due to lack of cards!") return card = self.deck.deal_card() self.player_hand.add_card(card) if self.player_hand.is_burst(): print("Player Burst! New hand.") break self.check() print("Game ended") if __name__ == "__main__": cards = [] for suit in Suit: for value in range(1,14): cards.append(BlackJackCard(value, suit.value)) print(len(cards)) game = Game(cards) game.play() # deck = Deck(cards) # print(deck.remaining_cards())
b05ea9b1800183cd6629f8d767ec990ff7facc3c
DiegoHeer/sec_web_scraping
/index.py
1,274
3.546875
4
import requests import urllib from bs4 import BeautifulSoup # Function that makes building url's easy def make_url(base_url, comp): url = base_url # add each component to the base url for r in comp: url = '{}/{}'.format(url, r) return url # Base url for the daily index files base_url = r'https://www.sec.gov/Archives/edgar/daily-index' components = ['886982', '000156459019011378', '0001564590-19-011378-index-headers.html'] # Create the daily index url for 2019 year_url = make_url(base_url, ['2019', 'index.json']) # Request the 2019 url content = requests.get(year_url) decoded_content = content.json() # Loop through the dictionary for item in decoded_content['directory']['item']: # get the name of the folder print('-'*100) print('Pulling url for quarter {}'.format(item['name'])) # Create the qtr url qtr_url = make_url(base_url, ['2019', item['name'], 'index.json']) print(qtr_url) # Request the url and decode it file_content = requests.get(qtr_url) decoded_content = file_content.json() print('-'*100) print('Pulling files') for file in decoded_content['directory']['item']: file_url = make_url(base_url, ['2019', item['name'], file['name']]) print(file_url)
1ad6b9dba65e1ed6b8c4f50cde56950109039294
youngkiu/keras-cats-dogs-tutorial
/dogs_vs_cats/plot_curve.py
2,280
3.671875
4
# https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-imbalanced-classification/ from matplotlib import pyplot # example of a roc curve for a predictive model from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression from sklearn.metrics import precision_recall_curve, roc_curve from sklearn.model_selection import train_test_split # generate 2 class dataset X, y = make_classification(n_samples=1000, n_classes=2, random_state=1) # split into train/test sets trainX, testX, trainy, testy = train_test_split(X, y, test_size=0.5, random_state=2) # fit a model model = LogisticRegression(solver='lbfgs') model.fit(trainX, trainy) # predict probabilities yhat = model.predict_proba(testX) # retrieve just the probabilities for the positive class pos_probs = yhat[:, 1] # plot no skill roc curve pyplot.plot([0, 1], [0, 1], linestyle='--', label='No Skill') # calculate roc curve for model fpr, tpr, _ = roc_curve(testy, pos_probs) # plot model roc curve pyplot.plot(fpr, tpr, marker='.', label='Logistic') # axis labels pyplot.xlabel('False Positive Rate') pyplot.ylabel('True Positive Rate') # show the legend pyplot.legend() # show the plot pyplot.show() # example of a precision-recall curve for a predictive model # generate 2 class dataset X, y = make_classification(n_samples=1000, n_classes=2, random_state=1) # split into train/test sets trainX, testX, trainy, testy = train_test_split(X, y, test_size=0.5, random_state=2) # fit a model model = LogisticRegression(solver='lbfgs') model.fit(trainX, trainy) # predict probabilities yhat = model.predict_proba(testX) # retrieve just the probabilities for the positive class pos_probs = yhat[:, 1] # calculate the no skill line as the proportion of the positive class no_skill = len(y[y == 1]) / len(y) # plot the no skill precision-recall curve pyplot.plot([0, 1], [no_skill, no_skill], linestyle='--', label='No Skill') # calculate model precision-recall curve precision, recall, _ = precision_recall_curve(testy, pos_probs) # plot the model precision-recall curve pyplot.plot(recall, precision, marker='.', label='Logistic') # axis labels pyplot.xlabel('Recall') pyplot.ylabel('Precision') # show the legend pyplot.legend() # show the plot pyplot.show()
a71c4c22fecefcec3cfae1e5f9bd552a83cc4edf
DucThanh1997/Data-Structures
/binary tree.py
2,045
4.21875
4
# 1 phần tử trong cây được gọi là node # 1 node chứa 3 thứ: data, left node, right node # nếu bé hơn thì là left node nếu lớn hơn là right node # cài đặt: class Node: def __init__(self, data): self.data = data self.right_node = None self.left_node = None def insert(self, data): if self.data: if data < self.data: if self.left_node is None: self.left_node = Node(data) else: self.left_node.insert(data) elif data > self.data: if self.right_node is None: self.right_node = Node(data) else: self.right_node.insert(data) else: self.data = data def print_tree(self): if self.left_node: self.left_node.print_tree() if self.right_node: self.right_node.print_tree() print(self.data) def height(self): if self.data is None: return 0 elif self.left_node is None and self.right_node is None: return 0 elif self.left_node is None: if self.right_node is not None: return 1 + self.right_node.height() elif self.right_node is None: if self.left_node is not None: return 1 + self.left_node.height() else: return 1 + max(self.left_node.height(), self.right_node.height()) def look(self, number): if self.data == number: print("Tồn tại số ", number) else: if self.left_node is not None: self.left_node.look(number) elif self.right_node is not None: self.right_node.look(number) if __name__ == "__main__": root = Node(12) root.insert(6) root.insert(14) root.insert(3) print("kết quả: ", root.height()) root.print_tree()
a63be4ac96dad2dc8ae7286c78174e110b0b1357
olacodes/algorithm
/python/testing.py
500
3.609375
4
def almostIncreasingSequence(sequence): sorted_sequence = sequence # sorted_sequence.sort() diff1 = sorted_sequence[1] - sorted_sequence[0] count = 0; for i in range(len(sorted_sequence)-1): diff = sorted_sequence[i + 1] <= sorted_sequence[i] if diff: count += 1 if count > 1: return False return True arr = [1,2,1,2] print(almostIncreasingSequence(arr)) a = [1,2,3,4] a.pop(2) print(a)
3773a12a30a27e85de2785845b16544e0c086576
lvhanh270597/Information-Retrieval
/source/processor/preprocessing/Tree.py
1,197
3.6875
4
from math import sqrt class Node: def __init__(self): self.info = None self.child = {} class Trie: def __init__(self): self.root = Node() def insertWord(self, word, info): p = self.root for c in word: if c not in p.child: p.child[c] = Node() p = p.child[c] p.info = info def searchWord(self, word): p = self.root for c in word: if c not in p.child: return None else: p = p.child[c] return p.info def buildTreeDepend(self, vector): size = 0 for word, val in vector: self.insertWord(word, val) size += val * val self.size = sqrt(size) def exist(self, word): return self.searchWord(word) != None def cosine(self, vector): sizeVector = 0 dot = 0 for word, val in vector: sizeVector += val * val valTree = self.searchWord(word) if valTree == None: continue dot += val * valTree sizeVector = sqrt(sizeVector) return dot / (sizeVector * self.size + 0.0000001)
9375d2922f06e50eaf5f626b6b212cd7ccf89ac4
mariurzua/nivelaci-n-mcoc
/27082019/000059.py
1,066
4.09375
4
# 11 minutos y 41 segundos # Se aprendio a multiplicar, sumar, y ordenar los numeros de una matriz. Tambien a trasponerla. import numpy as np #importacion libreria numpy from skimage import io #importacion io para leer la foto import matplotlib.pyplot as plt #importacion para que salga la imagen a_array = np.array([1,2,3,4,5]) #creacion matriz mediante transformacion de una lista b_array = np.array([6,7,8,9,10]) #creacion matriz mediante transformacion de una lista suma = (a_array + b_array) #suma de dos matrices print(suma) #impresion "suma" que es una matriz mult = (a_array * b_array) #mult de dos matrices print (mult) #impresion "mult" que es una matriz print a_array*10 #impresion matriz "a_array" mult por 10 plt.imshow(foto[:,:,0].T) #el .T intercambia filas y columnas, traspone x = np.array([2,1,4,3,5]) #creacion matriz con una lista desordenada np.sort(x) #ordena la matriz orden menor a mayor print x #impresion matriz "x"
f827e50ff838cffca57cd2491b03b61fd819686b
brianhang/tritonscheduler
/tritonscheduler/algorithm.py
11,990
3.640625
4
#!/usr/bin/env python import itertools from random import uniform from random import randint from classtime import ClassTime # Restrictions on class times. TIME_EARLIEST = ClassTime.fromString("MTuWThFS 12:00a-8:00a") TIME_LATEST = ClassTime.fromString("MTuWThFS 4:30p-11:50p") TIME_LUNCH = ClassTime.fromString("MTuWThFS 12:00p-1:00p") # Maximum time (in minutes) between any two classes. MAX_GAP = 60 * 3 class Algorithm(object): """ The Algorithm class is responsible for performing the genetic algorithm logic. This includes creating and handling populations. :ivar chromosomes: a set of potential lecture/section combinations :ivar schedule: the schedule data that is used as genetic information :ivar capacity: the maximum number of individuals in a population :ivar crossoverRate: the probability of crossover occuring :ivar mutateRate: the probability of an mutation occuring :ivar elitism: what percent of the fittest individuals is carried over :ivar population: the set of all individuals :ivar fitness: the set of all fitness variables for the population :ivar fitnessSum: the total fitness value of the population """ def __init__(self, schedule): """ Constructor for the Algorithm class. The constructor turns the Schedule output into chromosomes for individuals. :param self: the Algorithm object :param schedule: schedule data that will be used as genetic information """ self.chromosomes = {} self.schedule = schedule # Get all the possible alleles, which would be a specific lecture and # section(s) for a course. for code, courseList in schedule.items(): # Treat each course as a chromosome. self.chromosomes[code] = [] # Find all the genes for the "chromosome". for index in range(len(courseList)): course = courseList[index] indices = {} # Find set of all sections for the lecture. for meetingType, meeting in course.items(): if meetingType == "LE" or meetingType == "FI": continue indices[meetingType] = [i for i in range(len(meeting))] # Create a gene with one possibility for each section for the # lecture and add it to the chromosome. if len(indices) > 0: # Find the Cartesian Product of the different types of # sections to get all forms of the gene. product = [dict(zip(indices.keys(), x)) for x in itertools.product(*indices.values())] # Encode the lecture index into the gene. for gene in product: gene["LE"] = index self.chromosomes[code].append(gene) else: self.chromosomes[code].append({"LE": index}) # TODO: Refactor this. def getFitness(self, individual): """ Calculates the fitness of an individual by adding points for certain factors. This includes: having no conflicts. :param self: the Algorithm object :param individual: the individual to calculate the fitness for :returns: the fitness value of the individual """ # The fitness value for the given individual. fitness = 0 # Schedule data that was set in initiate(). schedule = self.schedule # Sum the fitness for each section. for course, meetings in individual.items(): index = meetings["LE"] meetingInfo = schedule[course][index] final = None if "FI" in meetingInfo: final = meetingInfo["FI"]["time"] for meetingType, meeting in meetings.items(): item = meetingInfo[meetingType] if meetingType != "LE": item = item[meeting] # Check for no conflicts. for course2, meetings2 in individual.items(): for meetingType2, meeting2 in meetings2.items(): index2 = meetings2["LE"] meetingInfo2 = schedule[course2][index2] item2 = meetingInfo2[meetingType2] if meetingType2 != "LE": item2 = item2[meeting2] # Check for no time conflicts. if not item["time"].conflictsWith(item2["time"]): fitness += 1 # Check for no finals conflicts. if final is not None and "FI" in meetingInfo2: final2 = meetingInfo2["FI"]["time"] if not final.conflictsWith(final2): fitness += 1 # Try to avoid multiple finals on one day. if not final.isOnDay(final2.days): fitness += 1 # Try to limit the number of classes per day. if not item["time"].isOnDay(item2["time"].days): fitness += 1 # Check for large gaps throughout the day. if (abs(item["time"].startTime - item2["time"].startTime) <= MAX_GAP): fitness += 1 # Check for too early class. if item["time"].isTimeAfter(TIME_EARLIEST): fitness += 1 # Check for too late class. if item["time"].isTimeBefore(TIME_LATEST): fitness += 1 # Check for lunch break. if not item["time"].conflictsWith(TIME_LUNCH): fitness += 1 if final is not None: # Check for finals being too early. if final.isTimeAfter(TIME_EARLIEST): fitness += 1 # Check for finals being too late. if final.isTimeBefore(TIME_LATEST): fitness += 1 return fitness def initiate(self, size, crossoverRate, mutateRate, elitism): """ Creates an initial, random population so the genetic algorithm has a base to start from. :param self: the Algorithm object :param size: the population size """ self.capacity = size self.crossoverRate = crossoverRate self.mutateRate = mutateRate self.elitism = elitism self.population = [] # Keep adding random individuals until the population is full. while len(self.population) < self.capacity: individual = {} for locus, genes in self.chromosomes.items(): index = randint(0, len(genes) - 1) individual[locus] = self.chromosomes[locus][index] self.population.append(individual) # Get fitness information for the current generation. self.calculateFitness() def calculateFitness(self): """ Sorts the current population by fitness (least to greatest) and then calculates the fitness for each individual and the sum of the fitness values for the population. :param self: the Algorithm object """ # Sort the population by fitness. self.population = sorted(self.population, key=lambda x: self.getFitness(x)) # Calculate the fitnesses of the population. self.fitness = [0] * len(self.population) self.fitnessSum = 0 for i in range(len(self.population)): self.fitness[i] = self.getFitness(self.population[i]) self.fitnessSum += self.fitness[i] # Get the total fitness for a fitness proportionate selection. self.fitnessSum = float(self.fitnessSum) def evolve(self): """ Picks which members of the population will not be discarded for the next generation by finding the fittest individuals. """ # The next generation population. nextGeneration = [] # Select parents using fitness proportionate selection. def select(): previousProb = 0.0 for i in range(len(self.population)): chance = previousProb + float(self.fitness[i]) / self.fitnessSum previousProb = chance if uniform(0.0, 1.0) <= chance: return self.population[i] # Keep the most fit individual for the next generation. for i in range(int(self.capacity * self.elitism)): nextGeneration.append(self.population[-(i + 1)]) # Fill the next generation with offspring of selected parents. while len(nextGeneration) < self.capacity: parent1 = select() parent2 = select() nextGeneration.append(self.crossover(parent1, parent2)) # Add some diversity to the next generation with random mutation. for individual in self.population: self.mutate(individual) # Make the next generation become the current generation. self.population = nextGeneration # Get fitness information for the current generation. self.calculateFitness() def crossover(self, parent1, parent2): """ After selection occurs, parents will be chosen from remaining population and children will be created by crossing the genes at certain points. """ # The new child individual. child = {} # Copy genes from either the first parent or second parent. # Shallow copy is used here since the values are just numbers. for chromosome in parent1: if uniform(0.0, 1.0) <= self.crossoverRate: child[chromosome] = parent2[chromosome].copy() else: child[chromosome] = parent1[chromosome].copy() return child def mutate(self, individual): """ Picks random individuals in the population and mutates their genes to provide some additional genetic diversity. """ # Pick random genes within the individual to mutate. for chromosome, gene in individual.items(): if uniform(0.0, 1.0) <= self.mutateRate: pool = self.chromosomes[chromosome] individual[chromosome] = pool[randint(0, len(pool) - 1)] def getHighestFitness(self): """ Returns the fitness value of the most fit individual in the population. """ if self.fitness: return self.fitness[len(self.fitness) - 1] return 0 def getTotalFitness(self): """ Returns the sum of all of the fitness values of individuals in the population. """ return self.fitnessSum or 0 def printFittest(self): fittest = self.population[len(self.population) - 1] # Print the times for each meeting in each course. for courseCode, info in fittest.items(): courseIndex = info["LE"] course = self.schedule[courseCode][courseIndex] print(courseCode + ":") for meetingType, index in info.items(): meeting = course[meetingType] time = "N/A" if meetingType != "LE": time = meeting[index]["time"] else: time = meeting["time"] print("\t" + meetingType + ": " + str(time)) if "FI" in course: print("\tFI: " + str(course["FI"]["time"]))
a7f22bb2b4427ef1c30b92eded5c99b509cb2726
ValenokKib/lessons_python_base
/Yakovenko_Valentin_dz_5/dz_5.1.py
148
3.9375
4
def odd(num): for num in range(1, num + 1, 2): yield num n = int(input('Введите число: ')) for i in odd(n): print(i)
ad0ec00200704e3121627d681369d4a3a604619a
Just-CJ/PAT
/PAT (Basic Level) Practise/1028. 人口普查/popularity.py
859
3.734375
4
__author__ = 'Just_CJ' import re import datetime if __name__ == '__main__': num = int(raw_input()) today = datetime.date(2014, 9, 6) min_p = ['', 200*266] max_p = ['', -1] eff_num = 0 for i in range(num): name, birth = re.split(r'\s+(?!$)', raw_input()) birth = birth.split('/') birth = datetime.date(int(birth[0]), int(birth[1]), int(birth[2])) if birth < datetime.date(1814, 9, 6) or birth > today: continue else: eff_num += 1 years = today - birth if years.days > max_p[1]: max_p[0] = name max_p[1] = years.days if years.days < min_p[1]: min_p[0] = name min_p[1] = years.days if eff_num: print eff_num, max_p[0], min_p[0] else: print eff_num
a355def05be55a805a617ac0e5ad9442ffb9ffb2
felcygrace/guvi_beginner-py
/sum_of_arithmetic.py
103
3.578125
4
n=int(input()) a=int(input()) d=int(input()) sum1=0 for i in range(a,n+1,d): sum1=i+sum1 print(sum1)
75738704a97581fb560291b1430057b5914861a2
gabriellaec/desoft-analise-exercicios
/backup/user_105/ch36_2019_09_04_18_57_06_740316.py
513
4.09375
4
numero = int(input('diga um numero')) divisor=2 if numero==2: print('primo') elif numero==1: print('nao é primo') elif numero==0: print('nao é primo') else: if numero%2==0: print('nao é primo') elif numero%2!=0: while((divisor+2)<numero): if numero%divisor==0: print('nao é primo') break divisor=divisor+1 else: print('primo')
084d28fe2f41314978fc795c90ca6c2c32aa3b06
ngintaka/CS-learning
/python/scripts/iterPower.py
219
3.53125
4
def iterPower(base, exp): ans = base if exp == 0: ans = 1 elif exp == 1: ans = base else: while exp > 1: ans = ans * base exp -= 1 return ans
d3ff5c5d855b26d04851a403b2b4b2b0eb21b862
ggabriel96/mapnames
/mapnames/string.py
12,334
3.765625
4
import operator as op from collections import Counter from collections import defaultdict as ddict import numpy as np def diff_view(str1, str2): """ Calculate the lengths of the longest common prefix and suffix between str1 and str2. Let str1 = axb of length m and str2 = ayb of length n, then this function finds and returns i and j such that: str1[0:i] = str2[0:i] = a and str1[m-j:] = str2[n-j:] = b. In the case that a or b does not exist (no common prefix or suffix), then i or j are 0. :param str1: the first string :param str2: the second string :return: common prefix and suffix lengths (i.e. i and j; see description) """ m, n = len(str1), len(str2) len_limit = min(m, n) prefix_len, suffix_len = 0, 0 while prefix_len < len_limit and str1[prefix_len] == str2[prefix_len]: prefix_len += 1 # was using negative indexing, # I just think this way is better understandable while suffix_len < len_limit \ and len_limit - suffix_len > prefix_len \ and str1[m - 1 - suffix_len] == str2[n - 1 - suffix_len]: suffix_len += 1 return prefix_len, suffix_len def trim_both_equal(str1, str2): """ Removes common prefix and suffix of both str1 and str2. :param str1: the first string :param str2: the second string :return: str1 and str2 with their common prefix and suffix removed """ begin, end = diff_view(str1, str2) if end == 0: return str1[begin:], str2[begin:] return str1[begin:-end], str2[begin:-end] def print_trace(str1, str2, trace): """ Prints the sequence of edit operations performed by wagner_fischer() to transform str1 into str2. Indicates deletion with '-', insertion with '+' and change with '.'. :param str1: a string :param str2: the string that str1 was compared to :param trace: the trace obtained from wf_trace() """ print(f'str1: {str1}') print(' ', end='') for op in trace[::-1]: if op == -1: print('-', end='') elif op == +1: print('+', end='') else: print(f'.', end='') print(f'\nstr2: {str2}') def wf_trace(D, str1, str2): """ Gets the list of operations performed by wagner_fischer(). :param D: the memo matrix D used in wagner_fischer() :param str1: a string :param str2: the string that str1 was compared to :return: a list of -1, 0, +1 indicating insert, change, delete (from end to beginning of a and str2) """ trace = [] i, j = len(str1), len(str2) while i > 0 and j > 0: if D[i][j] == D[i - 1][j] + 1: trace.append(-1) i -= 1 elif D[i][j] == D[i][j - 1] + 1: trace.append(+1) j -= 1 else: trace.append(0) i -= 1 j -= 1 return trace def wagner_fischer(str1, str2, trim=False, with_trace=False): """ Calculates the edit distance from str1 to str2. :param str1: a string :param str2: a string to compare str1 to :param trim: if should remove equal prefix and suffix between str1 and str2 :param with_trace: if should also return the sequence of performed operations :return: the edit distance and the sequence of performed operations if with_trace = True """ if trim: a, b = trim_both_equal(str1, str2) else: a, b = str1, str2 m, n = len(a), len(b) D = np.empty((m + 1, n + 1), dtype=np.int64) # Positions of D represent the edit distance from s1 to s2 where row # i and column j means the edit distance from s1[0..i] to s2[0..j]. So: # D[0][0] = 0 because there is no operation to do on empty strings # D[i][0] = D[i - 1][0] + 1 (cost of deletion) for i from # 1 to len(str1) 'cause the only thing to do is delete all # characters of str1 until ''. Same for D[0][j]. D[:, 0] = np.arange(m + 1) D[0, :] = np.arange(n + 1) for i in np.arange(1, m + 1): for j in np.arange(1, n + 1): # Change operation change_cost = D[i - 1][j - 1] + int(a[i - 1] != b[j - 1]) # Minimum of deletion and insertion operations # Deletion means cost of transforming str1[0..i-1] # to str2[0..j] and deleting str1[i] # Insertion means cost of transforming str1[0..i] # to str2[0..j-1] and inserting str2[j] delete_cost = D[i - 1][j] + 1 insert_cost = D[i][j - 1] + 1 d_or_i_cost = np.minimum(delete_cost, insert_cost) D[i][j] = np.minimum(change_cost, d_or_i_cost) # [-1][-1] is the last column of the last row, which holds the edit # distance of the whole str1 and str2 strings trace = None if with_trace: trace = wf_trace(D, a, b) return D[-1][-1], trace def edit_distance(str1, str2, trim=False, with_trace=False): dist, _ = wagner_fischer(str1, str2, trim, with_trace) return dist def qprofile(string, q): n = len(string) qgrams = [string[i:i + q] for i in range(n - q + 1)] return Counter(qgrams) def qdistance(str1, str2, q): profile1 = qprofile(str1, q) profile2 = qprofile(str2, q) profile1.subtract(profile2) return sum((abs(count) for count in profile1.values())) class QProfile(Counter): def __init__(self, param, q=2): """ If a QProfile is passed in through param, a new object is constructed that is a copy of it. In this case, the q parameter is ignored. :param param: string or QProfile :param q: q-value for this profile """ if isinstance(param, str): self.q = q n = len(param) qgrams = [param[i:i + q] for i in range(n - q + 1)] super().__init__(qgrams) elif isinstance(param, QProfile): self.q = param.q super().__init__(param) else: raise TypeError(f'object of type {type(param)} not supported') def __sub__(self, other): """ Returns a new QProfile that is the subtraction of self and other """ if not isinstance(other, QProfile): return NotImplemented result = QProfile(self) result.subtract(other) return result def distance_to(self, other): diff = self - other return sum((abs(count) for count in diff.values())) class QGramIndex: def __init__(self, strings, q=2): """ Builds the q-gram index. This index does not currently store the list of strings. :param strings: the list of strings to build the q-gram index on :param q: the q-value for the index """ self.q = q self.index = ddict(list) for i in range(len(strings)): iqp = QProfile(strings[i], q) for qgram, count in iqp.items(): self.index[qgram].append((count, i)) for v in self.index.values(): v.sort(reverse=True) def __call__(self, query, qgram_count_ratio=0.5, profile_ratio=0.75): """ Query the index. :param query: string or QProfile :param qgram_count_ratio: the minimum ratio of the count of a q-gram of a possible candidate compared to query. If the candidate count is less than the query count for the same q-gram, the candidate is disregarded. :param profile_ratio: the minimum ratio of match between the profile of a candidate and the query. A value of 1.0 means that candidates must have a profile that contains at least all q-grams that the query has. :return: a list of indices that index the list of strings originally passed to the constructor """ if isinstance(query, QProfile): if query.q != self.q: raise ValueError(f'query has different q-value:' f' {query.q} instead of {self.q}') query_profile = query else: query_profile = QProfile(query, self.q) all_candidates = [] for qgram, count in query_profile.items(): count_threshold = int(count * qgram_count_ratio) candidates = self.index.get(qgram) if candidates is not None: for candidate_count, candidate_idx in candidates: if candidate_count >= count_threshold: all_candidates.append(candidate_idx) else: break candidates_count = Counter(all_candidates) profile_threshold = max(1, int(len(query_profile) * profile_ratio)) indices = [candidate for candidate, count in candidates_count.items() if count >= profile_threshold] return indices class SuffixArray: def __init__(self, strings): """ Saves the strings and builds the Suffix Array. :param strings: list of strings to build the Suffix Array on """ self.strings = strings self.suffixes = None self.build() def build(self): """ Builds the Suffix Array based on saved strings """ self.suffixes = [(self.strings[i][j:], i, j) for i in range(len(self.strings)) for j in range(len(self.strings[i]))] self.suffixes.sort() def binary_search(self, string, lower=True): """ Searches for lower or upper bound for string on self.suffixes with a binary search. Method based on stringMatching function from Competitive Programming 3 book (page 259). :param string: string to search for :param lower: True to return the lower bound or False to return the upper bound :return: the lower or upper bound, according to lower """ if lower: cmp = op.ge else: cmp = op.gt strlen = len(string) lo, hi = 0, len(self.suffixes) - 1 while lo < hi: mid = int(lo + (hi - lo) / 2) suffix = self.suffixes[mid][0] # print(lo, mid, hi, suffix) if cmp(suffix[:strlen], string): hi = mid else: lo = mid + 1 # special case: if searching for upper bound and # last suffix is not equal to the query string, # then decrease upper bound (should we?) if not lower: if self.suffixes[hi][0][:strlen] != string: hi -= 1 return lo if lower else hi def suffix_bounds(self, string): """ Searches for both lower and upper bounds for string on self.suffixes. :param string: string to search for :return: tuple containing lower and upper bounds of self.suffixes """ lower_bound = self.binary_search(string) upper_bound = self.binary_search(string, lower=False) if lower_bound > upper_bound: lower_bound, upper_bound = upper_bound, lower_bound return lower_bound, upper_bound def indices_between_bounds(self, string): """ Given the lower and upper bounds on self.suffixes, returns a list of indices of self.strings which point to the strings that own the suffixes between the bounds. (What a good explanation, huh) :param string: string to search for :return: list of indices pointing to filtered strings of self.strings """ lower_bound, upper_bound = self.suffix_bounds(string) return [self.suffixes[i][1] for i in range(lower_bound, upper_bound + 1)] def __call__(self, string): return self.indices_between_bounds(string) class SimpleIndex(SuffixArray): def __init__(self, strings): super(SimpleIndex, self).__init__(strings) def build(self): """ Builds the Simple Index based on saved strings """ self.suffixes = [(self.strings[i], i) for i in range(len(self.strings))] self.suffixes.sort()
9dc9394bc7cc097a4ee298ea1383d6b4cfbe759b
ARN0LD-2019/Ejercicios_Python_2020
/unidad15/ejercicio3.py
275
3.6875
4
# FUNCIONES GENERADAS numero = [] for numero in [0, 1, 2, 3, 4, 5]: if numero % 2 == 0: print(numero) def pares(n): for numero in range(n + 1): if numero % 2 == 0: yield numero numero = [numero for numero in pares(10)] print(numero)
1022bd49507bcfbbfce65265115fdd2f1c217166
guzvladimir/epam_homeworks
/homework_11/task02/task02.py
1,692
4.375
4
""" You are given the following code: class Order: morning_discount = 0.25 def __init__(self, price): self.price = price def final_price(self): return self.price - self.price * self.morning_discount Make it possible to use different discount programs. Hint: use strategy behavioural OOP pattern. https://refactoring.guru/design-patterns/strategy Example of the result call: def morning_discount(order): ... def elder_discount(order): ... order_1 = Order(100, morning_discount) assert order_1.final_price() == 50 order_2 = Order(100, elder_discount) assert order_1.final_price() == 10 """ from __future__ import annotations from abc import ABC, abstractmethod class BaseStrategy(ABC): @abstractmethod def discount_price(self, order: Order) -> float: pass class NoDiscount(BaseStrategy): def discount_price(order: Order) -> float: return 0 class MorningDiscount(BaseStrategy): def discount_price(order: Order) -> float: return order.price * 0.5 class ElderDiscount(BaseStrategy): def discount_price(order: Order) -> float: return order.price * 0.9 class Order: def __init__(self, price: float, discount_strategy: BaseStrategy = NoDiscount): self.price = price self._discount_strategy = discount_strategy @property def discount_strategy(self) -> BaseStrategy: return self._discount_strategy @discount_strategy.setter def discount_strategy(self, discount_strategy: BaseStrategy): self._discount_strategy = discount_strategy def final_price(self) -> float: return self.price - self._discount_strategy.discount_price(self)
8028bf38ea033edaf31d753a7e2e319ce931701c
leexiaosi/learnPython
/python-visual-quickstart-guide-3/chapter-03/s-33.py
689
4.125
4
# -*- coding: utf-8 -*- import unittest class S33Test(unittest.TestCase): # 输入文件 def test_input(self): name = input('What is your name?') print('hello ' + name.capitalize() + '!') self.assertEqual(name, 'ldh') # 过滤空白 def test_strip(self): name = input('What is your name?').strip() print('hello ' + name.capitalize() + '!') self.assertEqual(name, 'ldh') # 数字 def test_number(self): value = input('Enter number:').strip() number = int(value) + 10 print('the value is ' + str(number)) self.assertEqual(number, 20) if __name__ == '__main__': unittest.main()
5e229dcbd2e292347706cfe106c7e5da95e715e7
FunsoAdetola/SCAMP-Assesment
/fibonacci.py
159
4.0625
4
fibonacci = int(input("How many Fibonacci numbers? ")) a = 0 b = 1 for i in range(fibonacci): print(a) first = a a = b b = first + a
93366aaa04027d1ede6de458123e4db79aab5e99
Vrushali-Kolhe/Assignments
/ass4/shapes.py
3,060
3.828125
4
from math import sqrt class Shape: #base class pass class Circle(Shape): #derived class def set_radius(self, radius): self.__radius = radius def get_radius(self): return self.__radius def area(self): return 3.14* self.get_radius() * self.get_radius() def perimeter(self): return 2*3.14* self.get_radius() class Triangle(Shape): __width = None __height = None def set_width(self, width): self.__width = width def set_height(self, height): self.__height = height def get_width(self): return self.__width def get_height(self): return self.__height def area(self): #polymorphism defined again return self.get_width() * self.get_height() / 2 class Right_angled_triangle(Triangle): def get_hypoteneous(self): a = self.get_height()* self.get_height() b= self.get_width()* self.get_width() return sqrt(a+b) class Equilateral_triangle(Triangle): def set_side(self, side): self.__side = side def get_side(self): return self.__side def perimeter(self): return (3 * self.get_side()) class Isosceles_triangle(Triangle): def set_equalside(self, side): self.__side = side def get_equalside(self): return self.__side def set_base(self, base): self.__base = base def get_base(self): return self.__base def perimeter(self): return (2*self.get_equalside())+self.get_base() class Quadrilater(Shape): __width = None __height = None def set_width(self, width): self.__width = width def set_height(self, height): self.__height = height def get_width(self): return self.__width def get_height(self): return self.__height def area(self): #area defined in parent class return self.get_width() * self.get_height() class Square(Quadrilater): def set_side(self, side): self.__side = side def get_side(self): return self.__side def area(self): #area defined in base class return self.get_side()*self.get_side() def perimeter(self): return 4* self.get_side() class Rectangle(Quadrilater): def perimeter(self): return 2 * (self.get_height() + self.get_width()) class Rhombus(Quadrilater): def set_side(self, side): self.__side = side def get_side(self): return self.__side def area(self): return self.get_side() * self.get_side() def perimeter(self): return 4 * self.get_side() class Parallelogram(Quadrilater): def set_side(self, side): self.__side = side def get_side(self): return self.__side def set_base(self, base): self.__base = base def get_base(self): return self.__base def perimeter(self): return 2 * (self.get_side() + self.get_base())
f4506a41f21652bd250f6896810cd6fbdec72bfb
Aasthaengg/IBMdataset
/Python_codes/p03042/s013075072.py
186
3.84375
4
s=int(input()) a=s//100 b=s%100 if a>0 and a<=12: if b>0 and b<=12: print("AMBIGUOUS") else: print("MMYY") else: if b>0 and b<=12: print("YYMM") else: print("NA")
feba84a102d87b02caaf4a54f255ceb9a96fd2c5
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 09 - Tuples, Lists and Dictionaries/069 Country Tuple select country.py
268
4.21875
4
#069 Country Tuple country_tuple = ("UK", "France", "Germany", "Holland", "Spain") print(country_tuple[0:5]) selection = input("Which country would you like: ") print("You have selected " + selection+ ". The index for this is " + str(country_tuple.index(selection)))