blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
59a2f82317bc85485726d4afd49de00fa0990e27
Prashanth073-cloud/Python-files
/countingSort.py
1,461
3.890625
4
def main(): unsortedList = [10,1,5,12,1,18,0,6] countingSort(unsortedList) def countingSort(unsortedList): countList = [] #initializing list with zeroes. count list size is maximum of the unsortlist for items in range(max(unsortedList)+1): countList.append(0) #print(countList) #counting occurences of list for item in range(len(unsortedList)): itemValue = unsortedList[item] itemCount = 0 for j in range(len(unsortedList)): if(itemValue==unsortedList[j]): itemCount+=1 countList[itemValue]=itemCount #print(countList) #adding values side by side for item in range(len(countList)): if(item>0): countList[item]=countList[item]+countList[item-1] #print(countList) sortedList = [] for i in range(max(unsortedList)+1): sortedList.append(0) #checking unsorted list items value position in the countlist for items in range(len(unsortedList)): itemValue = unsortedList[items] #print("unsorted list value ",itemValue) position = countList[itemValue] #print("count list posiiton",position) sortedList[position-1]=itemValue countList[itemValue]=countList[itemValue]-1 #print("countList after deduction",countList) print(sortedList) main()
726acb608f63cc2fb97970b0e35a84bced82f8fc
SSyeon/Programming-Python-
/1학기/multi.py
306
3.78125
4
def multi_num(multi, start, end): result = [] for n in range(start, end): if n % multi == 0: result.append(n) return result multi2 = multi_num(17, 1, 200) print("multi_num(17, 1, 200) :", multi2) print() multi3 = multi_num(3, 1, 100) print("multi_num(3, 1, 100) :", multi3)
6d7750da09f5c3e96951cfb161e5f79ab7ff76a2
SenFuerte/dt211-3-cloud
/Euler/Sol_nr6.py
682
3.859375
4
squRes = 0 sumOfSquares = 0 def squareOfTheSum(nr): # define a method to calculate the square of the sum global squRes # squRes have to be global for use in this method. for i in range(1, nr+1): squRes = squRes + i # add all numbers to squRes return (squRes * squRes) # square the added numbers def sumOfTheSquares(num): #define a method to calculate the sum of the square global sumOfSquares # like squRes for x in range(1, num+1): sumOfSquares = sumOfSquares + (x * x) # first square the number and then add it to sumOfSquares return sumOfSquares squareOfSum = squareOfTheSum(100) sumOfSqua = sumOfTheSquares(100) print(squareOfSum - sumOfSqua)
c1245c0f79bf441021263672fce7a69bfd7171ed
mvoecks/CSCI5448
/OO Project 2/Source Code/Canine.py
1,888
4.21875
4
import abc from Animal import Animal from roamBehaviorAbstract import hunt ''' We will define the behavior of all Canines to hunt when they roaming, therefore we will create the roamBehaviorAbstract hunt class to use to set out roam behavior. ''' huntBehavior = hunt() ''' Here we create our Canine abstract class. This is an extension of the animals class and defines the roam behavior and eating behavior of all canines and the sleep behavior for each Canine. ''' class Canine(Animal): __metaclass__ = abc.ABCMeta ''' Initializing a Canine object and set its name, type, and behavior in the superclass Animal ''' def __init__(self, name, type): super().__init__(name, type) super().setRoamBehavior(huntBehavior) ''' All Canines eat and sleep the same, so initialize these functions here ''' def eat(self): print(super().getType() + "-" + super().getName() +": Bark Bark this is some good food.") def sleep(self): print(super().getType() + "-" + super().getName() +": Growl, time to sleep, Zzzzz.....") ''' Create a class for the dogs, which are an extension of Canines. In this class we initialize a dog by giving it a name. The only function defines how dogs will make noise. ''' class Dog(Canine): def __init__(self, name): super().__init__(name, 'Dog') def makeNoise(self): print(super().getType() + "-" + super().getName() +": Woof Woof, I'm a dog.") ''' Create a class for the wolfs, which are an extension of Canines. In this class we initialize a wolfs by giving it a name. The only function defines how wolfs will make noise. ''' class Wolf(Canine): def __init__(self, name): super().__init__(name, 'Wolf') def makeNoise(self): print(super().getType() + "-" + super().getName() +": Grrrrr, watch out I'm a wolf.")
4de5f9ed9e924063809a1a95bea978d7ba4a462a
Aasthaengg/IBMdataset
/Python_codes/p03130/s065579795.py
526
3.546875
4
import collections as cl # 全街のつながりは保証されていて、橋は3本固定なので、枝分かれしてなければたどり着けるはず def main() : bridges = [] for i in range(3) : in_list = [int(i) for i in input().split()] bridges.extend(in_list) c = cl.Counter(bridges) com = c.most_common() if (com[0][1] == 2 and com[1][1] == 2 and com[2][1] == 1 and com[3][1] == 1) : print("YES") else : print("NO") main()
a4a19cbabab3921402b36ec5b9c338cf50dcd5cb
otisscott/1114-Stuff
/Homework 2/oms275_hw2_q7.py
446
3.953125
4
# Otis Scott # CS - UY 1114 # 19 Sept 2018 # Homework 2 def bmi(w, h): bmi = w / h ** 2 return bmi weight = int(input("Please enter weight in kilograms: ")) height = float(input("Please enter height in meters: ")) print("BMI is: " + str(bmi(weight, height))) pweight = int(input("Please enter weight in pounds: ")) * 0.453592 iheight = int(input("Please enter height in inches: ")) * 0.0254 print("BMI is: " + str(bmi(pweight, iheight)))
3620cab4d9984262e313548b3d29a68704a1145c
parzivale/woolsey-exercises
/exercises/exercise_1.py
630
3.953125
4
name = "A new student" description = "A program that takes in a students name, age and nationality and outputs it to a text file and the console" class student: def __init__(self, name, age, nationality): self.name = name self.age = age self.nationality = nationality self.content = [self.name, self.age, self.nationality] def run_exercise(): new_student = student(input("Name\n"),input("Age\n"),input("Nationality\n")) for item in new_student.content: print(item) file = open("file.txt", "a") for item in new_student.content: file.write(item) file.write("\n") file.write("\n") file.close()
ea9738de509dc760765702e7b666d88b86611356
OmarSalah95/Sorting
/src/recursive_sorting/recursive_sorting.py
4,503
4.0625
4
<<<<<<< HEAD # Helper function below to merge 2 sorted arrays def merge( arrA, arrB ): merged_arr = [] i_of_a, i_of_b = 0, 0 # We initiate a loop to continue to iterate until 1 of the 2 arrays we recieved as inputs has been completed. We will then tack # Whatever is left of the remaining array to the end of our Merged array, as it already sorted at this point. while i_of_a < len(arrA) and i_of_b < len(arrB): # Next we will need to compare the individual values within each of our 2 input arrays, compare, and append the lesser value # TO the end of the sorted Return array. if arrA[i_of_a] < arrB[i_of_b]: merged_arr.append(arrA[i_of_a]) i_of_a+=1 else: merged_arr.append(arrB[i_of_b]) i_of_b+=1 # Tack on the last remnant of which ever array be it A or B to the end of our newly sorted list if i_of_a == len(arrA): merged_arr.extend(arrB[i_of_b:]) else: merged_arr.extend(arrA[i_of_a:]) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # First we will acount for the Base/edge case of to handle the last case of recurssion recieving a bad input or one of an array with a # singular value stored within it. if len(arr) <= 1: return arr # Here we take our input array and split it in to 2 segments, one from the start to the middle, the other from the middle to the end # using a call stack(allowing the machine to keep tracking of the ever changing data using recursion) initialized by recursively calling # Our function. L, R = merge_sort(arr[ : len(arr) // 2]), merge_sort(arr[ len(arr) // 2 : ]) # Now that both our left and our right arrays are both sorted, we can sort both the left and right arrays into eachother now. return merge(L,R) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): l, r, i_of_l, i_of_r = arr[start:mid], arr[mid:end], 0, 0 for k in range(start, end): if i_of_r >=len(r) or (i_of_l < len(l) and l[i_of_l] < r[i_of_r]): arr[k] = l[i_of_l] i_of_l += 1 else: arr[k] = r[i_of_r] i_of_r += 1 return arr def merge_sort_in_place(arr, l, r): if r - l > 1: mid = int((l+r)/2) merge_sort_in_place(arr, l, mid) merge_sort_in_place(arr, mid, r) merge_in_place(arr, l, mid, r) return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr ======= # TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): merged_arr = [] i_of_a, i_of_b = 0, 0 # TO-DO while i_of_a < len(arrA) and i_of_b < len(arrB): if arrA[i_of_a] < arrB[i_of_b]: merged_arr.append(arrA[i_of_a]) i_of_a+=1 else: merged_arr.append(arrB[i_of_b]) i_of_b+=1 if i_of_a == len(arrA): merged_arr.extend(arrB[i_of_b:]) else: merged_arr.extend(arrA[i_of_a:]) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO if len(arr) <= 1: return arr if len(arr) == 2: merge([arr[0]],[arr[1]]) L, R = merge_sort(arr[ : len(arr) // 2]), merge_sort(arr[ len(arr) // 2 : ]) return merge(L,R) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO L, R, i_of_L, i_of_R = arr[start:mid] ,arr[mid:end], 0, 0 for k in range(start,end): if i_of_R >= len(R) or (i_of_L < len(L) and L[i_of_L] < R[i_of_R]): arr[k] = L[i_of_L] i_of_L += 1 else: arr[k] = R[i_of_R] i_of_R += 1 return arr def merge_sort_in_place(arr, l, r): # TO-DO if r - l > 1: mid = int((l+r)/2) merge_sort_in_place(arr,l,mid) merge_sort_in_place(arr,mid,r) merge_in_place(arr,l,mid,r) return arr A = [20, 30, 21, 15, 42, 45, 31, 0, 9] merge_sort_in_place(A,0,len(A)) print(A) # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr >>>>>>> 9b4a9be2f977aea7442456b7adb34c8d9b387a9d
5daf0b07f4e19f2ab73b4d08f1d858ab62941642
Said-Akbar/exercises
/Python_by_Zelle/chapter_4_ex/ex7.py
1,365
3.921875
4
# ex 7 Circle Intersection. Created by SaidakbarP 12/24/2019 from graphics import * def main(): #r = int(input("Enter Radius of the circle: ")) win = GraphWin("Circle Intersection", 640, 640) win.setCoords(-10, -10, 10, 10) # entry box for radius radius_entry = Entry(Point(-3, 9), 10) radius_entry.setText("7.0") radius_entry.draw(win) Text(Point(-7, 9), "Enter radius (x<10): ").draw(win) # entry box for y-intercept y_int = Entry(Point(-3, 8), 10) y_int.setText("-3.0") y_int.draw(win) Text(Point(-7, 8), "Enter y-intercept (y<10) : ").draw(win) Rectangle(Point(-1, 7.7), Point(2, 8.8)).draw(win) button = Text(Point(0.5, 8.2), "Calculate!") button.draw(win) # get values win.getMouse() r = float(radius_entry.getText()) y = float(y_int.getText()) # draw circle circle = Circle(Point(0,0), r) circle.draw(win) # draw line y_ints = Line(Point(-10,y), Point(10,y)) y_ints.draw(win) # Intersections x-values x1 = -round((r**2-y**2)**(1/2)) x2 = round((r**2-y**2)**(1/2)) # draw intersections Text(Point(x1+0.5,y-0.5), "x1: {}".format(x1)).draw(win) win.plot(x1, y, "red") Text(Point(x2+0.5,y-0.5), "x2: {}".format(x2)).draw(win) win.plot(x2, y, "red") button.setText("Quit!") win.getMouse() win.close() main()
5f6709d502b7d3b195173b50a265d4422af81298
adsl305480885/leetcode-zhou
/653.两数之和-iv-输入-bst.py
1,825
3.65625
4
''' Author: Zhou Hao Date: 2021-04-09 20:30:42 LastEditors: Zhou Hao LastEditTime: 2021-04-09 20:57:34 Description: file content E-mail: 2294776770@qq.com ''' # # @lc app=leetcode.cn id=653 lang=python3 # # [653] 两数之和 IV - 输入 BST # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: '''BFS''' # def findTarget(self, root: TreeNode, k: int) -> bool: # if not root:return False # if not root.left and not root.right:return False # cur,res = [root],[] # while cur: # next_lay = [] # for node in cur: # res.append(node.val) # if node.left: # next_lay.append(node.left) # if node.right: # next_lay.append(node.right) # cur = next_lay # for r in res: # if k-r in res: # if k-r == r and res.count(r) >1: # return True # elif k-r!=r: # return True # return False '''DFS''' def findTarget(self, root: TreeNode, k: int) -> bool: if not root:return False if not root.left and not root.right:return False res = [] def dfs(root): if not root:return dfs(root.left) res.append(root.val) dfs(root.right) dfs(root) #double pointers i,j = 0,len(res)-1 while i <j: if res[i] + res[j] == k: return True elif res[i] + res[j] > k: j-=1 else : i+=1 return False # @lc code=end
3f78445c7a568a58370a6060417a3004b3287868
visha-v/Trying_Python
/miles_into_km.py
147
4.15625
4
miles = input('Enter Miles: ') miles = int(miles) km = (miles * 1.60934) print("{} miles equals {} kilometers".format(miles, float(km)))
d4d246fc4604c443e3ed4653f6dd441fa04953b0
FiodorGrecu/Exercises
/data_structures/binary_trees/2_search_node/solution/model_solution/solution.py
575
3.8125
4
# Write solutions here class Node: def __init__(self, key, left=None, right=None): self.left = left self.right = right self.key = key def search(root, key): if not root: return False if key == root.key: return True elif key < root.key: return search(root.left, key) else: return search(root.right, key) items = Node(6) items.left = Node(4) items.right = Node(9) items.left.left = Node(3) items.left.right = Node(5) items.right.left = Node(7) items.right.right = Node(11) print(search(items,11))
8ddba3a17040540648341b4e83822ced1b26855e
xiao-a-jian/python-study
/month01/day15/exercise01.py
381
3.703125
4
""" 定义函数,获取成绩.如果输入有误,重新输入,直到输入正确。 """ def get_score(): while True: try: # score = float(input("请输入你的成绩")) # return score return float(input("请输入你的成绩")) except: print("输入错误重新输入") print("成绩是:", get_score())
8f90ddbf11dbeb10e49983bb1cde07e28d671afa
nyck33/coding_practice
/Python/leetcode/dpv_longest_palindromic_subseq.py
1,207
3.8125
4
def longest(the_str): ''' :param the_str: :return: length of longest palindromic subseq and the subseq from s(i..j) ''' length = len(the_str) T = [[0 for x in range(length)] for y in range(length)] #subseq of 1 is a palindrome for i in range(length): T[i][i] = 1 # shift window from size 2 to len of string strings = [] for w in range(1, length): for i in range(length-w): j = i + w if the_str[i] == the_str[j]: T[i][j] = T[i+1][j-1] + 2 strings.append(the_str[i:j+1]) else: T[i][j] = max(T[i+1][j], T[i][j-1]) # find the longest string longest = longest_str(strings) return T[0][length-1], longest def longest_str(strings): longest = strings[0] len_longest = len(longest) for i in range(len(strings)): if len(strings[i]) > len_longest: longest = strings[i] return longest if __name__=="__main__": the_str = 'abcbaf' length, chars = longest(the_str) print(f'len: {length}, chars: {chars}') the_str = 'abb' length, chars = longest(the_str) print(f'len: {length}, chars: {chars}')
cbb1cdb15048c604a6b019a895534f72c1f84404
viegasviegasviegas/alegriaDaRapaziada
/GnomeSort.py
275
3.53125
4
def gnome(lista): pivot = 0 lista_length = len(lista) while pivot < lista_length - 1: if lista[pivot] > lista[pivot + 1]: lista[pivot + 1], lista[pivot] = lista[pivot], lista[pivot + 1] if pivot > 0: pivot -= 2 pivot += 1 return lista
4cda8e27092ad617bba45961d635cdcb46e74421
shuddha7435/Python_Data_Structures-Algorithms
/Queue.py
1,142
4.15625
4
class Queue: def __init__(self,size): self.items = [0] * size self.max_size = size self.head, self.tail, self.size = 0, 0, 0 def enqueue(self,item): if self.is_full(): print("Queue is full!") return print("Inserting", item) self.items[self.tail] = item self.tail = (self.tail + 1) % self.max_size self.size += 1 def dequeue(self): item = self.items[self.head] self.head = (self.head) + 1 % self.max_size self.size -= 1 return item def is_empty(self): if self.size == 0: return True return False def is_full(self): if self.size == self.max_size: return True return False if __name__ == "__main__": q = Queue(3) q.enqueue("Shuddha") q.enqueue("Rudro") q.enqueue("Ratna") q.enqueue("Rupam") while not q.is_empty(): person = q.dequeue() print(person) q.enqueue("Rupam") print(q.items) print("head:", q.head) print("tail:", q.tail)
ed8e99d90faaf4b797915eaa6f1cfaae049c18a5
heejongahn/algospot
/BEGINNER/endians.py
2,052
3.65625
4
##### Problem # The two island nations Lilliput and Blefuscu are severe rivals. They dislike # each other a lot, and the most important reason was that they break open boiled # eggs in different ways. # People from Lilliput are called little-endians, since they open eggs at the # small end. People from Blefuscu are called big-endians, since they open eggs at # the big end. # This argument was not only about their breakfasts but about their computers, # too. Lilliput and Blefuscu's computers differed in the way they store integers; # they stored the bytes in different orders. Computers from # Lilliput(*little-endians*) ordered it from the LSB(least significant byte) to # the MSB(most significant byte), and computers from Blefuscu was exactly the # opposite. # For example, a 32-bit unsigned integer 305,419,896 (0x12345678) would be saved # in two different ways: # 00010010 00110100 01010110 01111000 (in an Blefuscu computer) # 01111000 01010110 00110100 00010010 (in an Lilliput computer) # Therefore, if there was any need to exchange information between # Blefuscu and Lilliput computers, some kind of conversion process was # inevitable. Since nobody liked converting the data by himself before # sending, recipients always had to do the conversion process. # Given some 32-bit unsigned integers retrieved in a wrong endian, # write a program to do a conversion to find the correct value. ##### Input # The first line of the input file will contain the number of test cases, C (1 ≤ # C ≤ 10, 000). Each test case contains a single 32-bit unsigned integer, which # is the data without endian conversion. ##### Output # For each test case, print out the converted number. cases = int(input()) numbers = [] for case in range(cases): numbers.append(int(input())) for number in numbers: hex = '{:x}'.format(number).zfill(8) hexList = [] hexList.append(hex[6:]) hexList.append(hex[4:6]) hexList.append(hex[2:4]) hexList.append(hex[0:2]) ansString = ''.join(hexList) print(int(ansString, 16))
0527958448ad9fb3fc5a3a400358f2c9a7f5e3a5
swissfiscal/offer
/leetcode_7整数反转.py
774
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2019/3/12 @author: luomashuzi desc: 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 ''' class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x==0: return 0 str_x = str(x) x = '' if str_x[0] == '-': x += '-' x += str_x[len(str_x)-1::-1].lstrip("0").rstrip("-") x = int(x) if -2**31<x<2**31-1: return x return 0 if __name__ == '__main__': a=Solution() print(a.reverse(-123))
7c61bd421a08cf59210cb2857f4b813dbd2eed02
dongpingbio/ModelNeuro
/stim.py
4,601
3.671875
4
class Stim: """ A class for adding current injections into model neurons or networks. Takes in a maximum time (T), sampling rate (Fs), and steady-state current (I0) as initial parameters. Note that these parameters are relative to miliseconds, not seconds. Thus, for a 10 kHz sampling rate, one would use Fs = 100 Once initialized, it is easy to add varying currents at different times using "Stim.add_current()", which takes in a start time (t_on), end time (t_off), start value (I_start), and optionally an ending value (I_end) plus the number of steps to get there (I_step). To visualize the stimulus protocol, you can use "Stim.plot_protocol()", which plots all traces in the current protocol on top of one another in a new figure. By default, the current values are in Picoamps (pA). Thus, no need to input small values (1e-12). This class assumes numpy, scipy, and matplotlib are all installed on your machine and available in your python path! Writen by Jordan Sorokin, 8/4/2016 """ # imports import numpy as np import matplotlib.pyplot as plt global np global plt def __init__(self, T, Fs, I0): """ Initialize the current protocol with a max time and sampling rate. Additionally, set the number of trials = 1, which will change if we include stepped currents in the protocol to match the # of steps. """ global np self.Tmax = float(T) self.Fs = float(Fs) self.timevec = np.arange(0,self.Tmax,1/self.Fs) # time vector, discretized by 1/Fs steps self.I0 = float(I0) # converted to pico amps self.ntrials = 1 # now initialize the stimulus parameters that will be updated with "addcurrent()" self.ton = [] self.toff = [] self.Istart = [] self.Iend = [] self.nstep = [] self.Istep = [] self.I = dict() # will be updated with added currents def add_current(self, t_on, t_off, I_start, I_end=0, nstep=1): """ Add a current protocol with starting time t_on, ending time t_off, picoamp value I_start, ending value I_end, and number of steps to reach I_end by num_step """ global np self.ton.append(t_on) self.toff.append(t_off) self.Istart.append(I_start) self.Iend.append(I_end) self.nstep.append(nstep) self.ntrials = max(self.nstep) # update the current number of trials # cmake a series of currents for the number of steps. If nstep =1, the list will hold a single value self.Istep.append(list(np.linspace(I_start,I_end,nstep))); # append a list of current steps # update the running current protocol separately for this added current index = len(self.I) current = np.zeros( (len(self.timevec),nstep) ) + self.I0 # T x nstep matrix of zeros + constant current I0, to be updated in the loop # loop through the number of steps of this added current, and update each current trace for i in xrange(self.nstep[-1]): val = self.Istep[-1][i] # pull out the i-th current step and update the i-th current trace pulsetime = (self.timevec >= t_on) & (self.timevec <= t_off) # get logical array indicating where the current step occurs current[pulsetime,i] = self.Istep[-1][i] # populate the i-th current pulse with the value of the i-th current step self.I['I'+str(index+1)] = current # add this current step(s) to the dictionary of individual currents self.Itot = sum(self.I.values()) # now sum (i.e. broadcasting) all of the individual currents in "self.I" into a total current protocol "self.Itot" def remove_current(self,index): ''' remove specific current from the total protocol using the "index" of that current ''' k = self.I.keys() k.sort() # sort the I1 --> IN by name self.I.pop(k[index],0) self.ton.pop(index) self.toff.pop(index) self.Istart.pop(index) self.Iend.pop(index) self.nstep.pop(index) self.Istep.pop(index) # now re-calculate Itot and ntrials if len(self.nstep) > 0: self.ntrials = max(self.nstep) self.Itot = sum(self.I.values()) def plot_protocol(self): """ plot the current stim protocol in a new figure """ global plt # initialize matrix of I0 for storing currents plt.figure() plt.plot(self.timevec,self.Itot,'k') plt.show()
8629ac500602b9df014cf5f9e66de96e82469dae
Runweiw/Stats607
/Assignment_1/test_assignment1_RunweiWang.py
1,404
3.96875
4
#1.1 import assignment1_Data as a1Data #import module as 'a1Data' crime = a1Data.get_US_crime() #assign it to a local name 'crime' with() means return to a list, #without() means return to a function print(crime,'\n') #1.2 import assignment1_RunweiWang as a2Data #import module as 'a2Data' print('Do the lists inside the crimes list have the same number of elements?', a2Data.equal_length(crime),'\n') #1.3 print(a2Data.get_states(crime),'\n') #1.4 print('Does the total number of violent crimes is equal to the ‘Violent crime total’ column?', a2Data.equal_vc(crime),'\n') print('Does the total number of property crimes is equal to the ‘Property crime total’ column?', a2Data.equal_pc(crime),'\n') #1.5 print('Does US total values correspond to the sum of reported values for all states?', a2Data.equal_total(crime),'\n') #1.6 print(a2Data.get_crime_rate(crime), '\n') crimeRate=a2Data.get_crime_rate(crime) #1.7 crimeRatesOriginal = a1Data.get_US_crime_rates() a2Data.equal_rates(crimeRate,crimeRatesOriginal,3) #1.8 print('The top 5 states with the highest violent crime rate are', a2Data.top5_violent_states(crimeRate), '\n') #1.9 crimeRate=a2Data.get_crime_rate(crime) print(a2Data.top_crime_states(crimeRate,8,6), '\n') #1.10 crimeRate=a2Data.get_crime_rate(crime) print(a2Data.crime_stats(crimeRate,7))
48fb16159bc9b5ddbe86709ef960e6baaf146c30
Jon-Ting/UH-DA-with-PY-summer-2019
/part03-e03_most_frequent_first/ans.py
417
3.546875
4
#!/usr/bin/env python3 import numpy as np def most_frequent_first(a, c): b = a[:,c] # get column c _,s,t = np.unique(b, return_inverse=True, return_counts=True) idx = np.argsort(t[s]) return a[idx][::-1] def main(): np.random.seed(0) a = np.random.randint(0,10, (10,10)) print("a:\n", a) print("result:\n", most_frequent_first(a, -1)) if __name__ == "__main__": main()
87cfcb03bb2a62d4d28a1f0b8760d7eca9b65168
pujanm/competitive_programing
/Mock1-DJ-2019/editor.py
198
3.75
4
import math operations = int(input()) num1 = math.ceil((operations - 2) / 2) num2 = abs((operations - 2) - num1) if num1 > num2: print(num1 + num2 * num1) else: print(num2 + num1 * num2)
00376b59dc26a85b18667a4bff3b32239cc93d53
tomglinnan/EC400
/Penalties.py
2,895
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ PENALTY SHOOTOUT EXTENSION """ """ In the in-person class, we talked about an extension to the penalty shootout question How penalties work: each team takes 5. If one team has scored strictly more than the other, that team wins. If it's a draw, then we have sudden death - teams take one penalty each. If both score or both miss, they go on. Otherwise the team that scores wins and the other loses. The original question was about sudden death only but what about the whole match? If team 1 has probability of scoring p and team 2 has probability q, what's the probability team 1 win? We didn't do it fully because the addition required is annoying, but fortunately we can get Python to count for us In the case considered in class, [Brazil] p = 0.8 [Italy] q = 0.75 [Standard Fooball / Soccer Rules] n = 5 To try out, write prob(p,q,n) in the console with the assosciated p,q,n you're interested in You need scipy installed on your computer (eg if you have anaconda you'll be fine) * Result afer 5 rounds: * Probability Brazil win without sudden death is 42.2% Probability Italy win without sudden death is 27.9% Probability of going to sudden death is 29.8% Note that the probability of Brazil winning conditional on going to sudden death was 4/7 = 57.1% Intuitively: in sudden death there's no prospect of a draw. But it's actually relatively easier for the weaker team to win in sudden death than in the 5 shootouts at the start. Total probability of Brazil winning = 0.422 + (0.298*0.571) = 59.2%, so Italy probability 40.8% Does the conclusions work for general p,q,n? Try yourself if you're interested! """ from scipy.special import comb def prob_draw(p,q,n): Team_1_pdf = [comb(n,x)*(p**x)*((1-p)**(n-x)) for x in range(n+1)] Team_2_pdf = [comb(n,x)*(q**x)*((1-q)**(n-x)) for x in range(n+1)] prob = 0 for i in range(n+1): prob = prob + Team_1_pdf[i]*Team_2_pdf[i] print('Probability of a draw after', n, 'rounds is', round(prob,4)*100, '%') def prob_win(p,q,n): Team_1_pdf = [comb(n,x)*(p**x)*((1-p)**(n-x)) for x in range(n+1)] Team_2_pdf = [comb(n,x)*(q**x)*((1-q)**(n-x)) for x in range(n+1)] prob = 0 for i in range(n+1): for j in range(i): prob = prob + Team_1_pdf[i]*Team_2_pdf[j] print('Probability of a team 1 winning after', n, 'rounds is', round(prob,4)*100, '%') def prob(p,q,n=5): prob_win(p,q,n) prob_draw(p,q,n) Team_1_pdf = [comb(n,x)*(p**x)*((1-p)**(n-x)) for x in range(n+1)] Team_2_pdf = [comb(n,x)*(q**x)*((1-q)**(n-x)) for x in range(n+1)] prob = 0 for i in range(n+1): for j in range(i): prob = prob + Team_1_pdf[j]*Team_2_pdf[i] print('Probability of a team 2 winning after', n, 'rounds is', round(prob,4)*100, '%')
50dcbd1a0b793e0ef9a91dda6ef34d6746ace2ba
sigma7i/PythonLessons
/Lesson04/easy.py
1,998
3.765625
4
# Все задачи текущего блока решите с помощью генераторов списков! # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список, элементы которого будут # квадратами элементов исходного списка # [1, 2, 4, 0] --> [1, 4, 16, 0] original_list = [1, 2, 4, 0] pow_list = [i*i for i in original_list] print(pow_list) # Задание-2: # Даны два списка фруктов. # Получить список фруктов, присутствующих в обоих исходных списках. fruit1 = ['Apple', 'Orange', 'grape', 'Banana', 'blackberry', 'Kiwi', 'waterMelon'] fruit2 = ['Apple', 'Orange', 'Grape', 'Banana', 'Orange', 'Strawberry','Cherry', 'Melon'] def tolower(*args): try: return [i.lower() for i in args] except AttributeError: print('В качестве аргумента была передана НЕ последовательность элементов') union_list = [i for i in tolower(*fruit1) if i in tolower(*fruit2)] print(union_list) # Задание-3: # Дан список, заполненный произвольными числами. # Получить список из элементов исходного, удовлетворяющих следующим условиям: # + Элемент кратен 3 # + Элемент положительный # + Элемент не кратен 4 import random rand_list = [random.randint(-5, 100) for _ in range(20)] # def is_satisfies(el): # if el % 3 == 0 and el > 0 and el % 4 != 0: # return True # return False # чтобы не нагромождать генератор is_satisfies = lambda el: el % 3 == 0 and el > 0 and el % 4 != 0 satisf_elements = [el for el in rand_list if is_satisfies(el)] print(satisf_elements)
317a67648c49c473f9521b0a22eddfafd1ea0169
ThyEvilOne/LSC-python-class-Noah-David
/DavidBChap10/10.3.2.py
755
4.15625
4
user_input = '' while user_input != 'q': try: weight = int(input('Enter weight (in pounds): ')) if weight < 0: raise ValueError('Invalid weight.') height = int(input('Enter height (in inches): ')) if height < 0: raise ValueError('Invalid height.') bmi = (float(weight) / float(height * height)) * 703 print('BMI:', bmi) print('(CDC: 18.6-24.9 normal)\n') # Source www.cdc.gov except ValueError as excpt: print(excpt) print('Could not calculate health info.\n') except ZeroDivisionError as excpt: print(excpt) print('Could not calculate health info. \n') user_input = input("Enter any key ('q' to quit): ")
fea59d34bbd6651097865c7ae1dc84e24f3b2a07
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/2139.py
1,170
3.5625
4
import sys def main(): f = None output = None case = 1 if len(sys.argv) > 1 : f = open(sys.argv[1]) output = open(sys.argv[1][:-2] + 'out', 'w') else: print("PROBLEM") return tests = int(f.readline().strip()) case = 1 cost = 0 goal = 0 farm = 0 for t in range(tests): output.write("Case #" + str(case) + ": ") line = f.readline() data = line.strip().split() cost = float(data[0]) farm = float(data[1]) goal = float(data[2]) seconds_to_win = min_time(cost, farm, goal) output.write("{:.7f}\n".format(seconds_to_win)) case += 1 f.close() output.close() def min_time(cost, farm, goal): time = 0 farms = 0 def time_to_win(num_farms): return goal / (2 + farm * num_farms) def time_to_buy(num_farms): return cost / (2 + farm * num_farms) while True: if time_to_win(farms) <= time_to_win(farms+1) + time_to_buy(farms): return time + time_to_win(farms) else: time += time_to_buy(farms) farms += 1 if len(sys.argv) > 1: main()
13613c93925cc5c581ede043f507b636517f5e56
eyal-shagrir/Graph-Cluster-Covers
/utilities/util.py
8,501
3.703125
4
import networkx as nx import numpy as np import matplotlib.pyplot as plt GRAPH_GENERATION_TRIES = 1000000 PROBABILITY_STEP = 0.01 def draw_graph(g): nx.draw(g, with_labels=True) plt.show() plt.close() def generate_graph(n, p=0.5): """ :param n: number of nodes :param p: probability for choosing edge :return: random Erdős–Rényi graph with n nodes, and edges chosen in probability of 0.5 for more details: https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model """ seed = np.random.randint(1, 100) return nx.fast_gnp_random_graph(n, p, seed) def generate_connected_graph(n, p=0.5): """ generates a connected graph with n nodes in probability p if it doesn't succeed in 1000000 tries, it raises p by 0.01 :param n: number of nodes in graph :param p: probability for edge existence :return: a connected graph g """ if n <= 1: return generate_graph(n) for _ in range(GRAPH_GENERATION_TRIES): g = generate_graph(n, p) if nx.is_connected(g): return g p += PROBABILITY_STEP def weight_graph_edges(g, max_weight=100): """ assigns each edge in g a weight between 0 and max_weight :param g: graph :param max_weight: upper limit to edges weights :return: None """ for u, v in g.edges(): g[u][v]['weight'] = np.random.randint(0, max_weight + 1) def generate_weighted_connected_graph(n, p=0.5, max_weight=100): """ generates a weighted connected graph with n nodes in probability p if it doesn't succeed in 1000000 tries, it raises p by 0.01 :param n: number of nodes in graph :param p: probability for edge existence :param max_weight: upper limit to edges weights :return: a wighted connected graph g """ g = generate_connected_graph(n, p=p) weight_graph_edges(g, max_weight) return g def generate_random_cluster(g, min_cluster_size=0, max_cluster_size=0): """ a very simple function that generates a random cluster. every iteration it chooses a random node from the cluster, and then randomly one of its neighbours to join to the cluster. :param g: graph :param min_cluster_size: minimum nodes in a cluster :param max_cluster_size: maximum nodes in a cluster :return: a cluster, i.e. a clique of nodes in g, in random size between min_cluster_size and max_cluster_size """ n = nx.number_of_nodes(g) cluster = set() if n == 0 or min_cluster_size > max_cluster_size: return frozenset(cluster) if not min_cluster_size: min_cluster_size = 1 if not max_cluster_size: max_cluster_size = n cluster_size = np.random.randint(min_cluster_size, max_cluster_size + 1) u = np.random.choice(list(g.nodes())) cluster.add(u) while len(cluster) < cluster_size: u = np.random.choice(list(cluster)) v = np.random.choice(list(g.neighbors(u))) cluster.add(v) return frozenset(cluster) def generate_cover(g, cover_size, min_cluster_size=0, max_cluster_size=0): """ generates a requested clusters cover that covers all nodes in g. each iteration it adds a cluster to the cover, until there is full nodes coverage. that means that the cover size might be larger than cover_size. :param g: graph :param cover_size: size of requested cover :param min_cluster_size: minimum nodes in a cluster :param max_cluster_size: maximum nodes in a cluster :return: a cover with at least cover_size clusters. e.g. a set of tuples, each tuple represents a cluster of nodes """ nodes = set(g.nodes()) n = nx.number_of_nodes(g) clusters = set() if min_cluster_size and max_cluster_size: # too many restrictions may cause infinite loop trying to find impossible number of clusters in certain size cover_size = 1 min_cluster_size = min_cluster_size if min_cluster_size != 0 else 1 max_cluster_size = max_cluster_size if max_cluster_size != 0 else n i = 0 while i < cover_size or nodes != frozenset.union(*list(clusters)): fs = generate_random_cluster(g, min_cluster_size, max_cluster_size) if fs not in clusters: clusters.add(fs) i += 1 return clusters def cluster_induced_graph(g, cluster): """ :param g: graph :param cluster: a cluster in graph g :return: the induced graph by the nodes and edges of cluster in g """ return nx.subgraph(g, list(cluster)) def calculate_node_radius(g, v): """ calculates the node radius of v in graph g by the formula: Rad(v, g) = max(dist(v, w) | for every w in g) i.e. the maximum weight path in g from node v to some other node :param g: graph :param v: node v in g :return: radius of v in g """ easiest_paths_weights = nx.single_source_dijkstra_path_length(g, v) return max(easiest_paths_weights.values()) def calculate_graph_radius(g): """ calculates the radius of graph g by the formula: Rad(g) = min(Rad(v, g) | for every v in g) i.e. the minimum of all nodes radii in g This parameter is used as an indicator of the "cluster size", by approximating the weight of the paths between the nodes in the cluster. :param g: graph :return: radius of g """ nodes_radii = {} for v in g.nodes(): nodes_radii[v] = calculate_node_radius(g, v) return min(nodes_radii.values()) def calculate_collection_radius(g, collection): """ calculates the radius of collection in graph g by the formula: Rad(g) = max(Rad(g(cluster)) | for every cluster in g), when g(s) in the induced graph by cluster in g i.e. the maximum of all clusters radii in collection This parameter is used as an indicator of the "collection size", by approximating the "cluster size" of each cluster. More generally the "collection size" is one of the two main criterias for evaluating the quality of a graph's cluster coverage. It represents the amount of "internal communication" in each cluster. Intuitively, the bigger the size of a cluster, the harder it is to communicate inside it. While technically, the bigger the size of a cluster, the heavier the paths between the nodes in it. :param g: graph :param collection: a collection of clusters in g (usually the collection sent is a node coverage of g) :return: radius of collection """ clusters_radii = {} for cluster in collection: induced_graph = cluster_induced_graph(g, cluster) induced_graph_radius = calculate_graph_radius(induced_graph) clusters_radii[cluster] = induced_graph_radius return max(clusters_radii.values()) def calculate_node_degree_in_collection(collection, v): """ calculates the degree of node v in collection by the formula: deg(v, collection) = the number of clusters in collection, v belongs to :param collection: collection of clusters :param v: node :return: degree of v in collection """ counter = 0 for cluster in collection: if v in cluster: counter += 1 return counter def calculate_collection_degree(collection): """ calculates the degree of collection by the formula: deg(collection) = max(deg(v, collection) for each v appears in collection) This parameter is used as an indicator of the collection sparsity, by approximating how many clusters share the same nodes. More generally, the collection sparsity is one of the two main criterias for evaluating the quality of a graph's cluster coverage. It represents the amount of "external communication" between each cluster. Intuitively, the more sparse the collection is, the harder it is to communicate between its clusters. While technically, the more sparse the collection is, the smaller the amount of nodes they share. :param collection: collection of clusters :return: degree of collection """ nodes_abundances = {} for v in frozenset.union(*list(collection)): nodes_abundances[v] = calculate_node_degree_in_collection(collection, v) return max(nodes_abundances.values()) def get_collection_data(g, collection): collection_radius = calculate_collection_radius(g, collection) collection_degree = calculate_collection_degree(collection) return collection_radius, collection_degree
9a41edd8472ab06c2bfbad83d1285cd3598fd1f0
yeodongbin/PythonLecture
/03.Algorithm/Sort/selection_sort2.py
831
3.625
4
import unittest def selectionSort(input): for i in range(len(input) - 1): # assume the min is the first element idx_min = i j = i + 1 # test against elements after i to find the smallest while j < len(input): if(input[j] < input[idx_min]): # found new minimum; remember its index idx_min = j j = j + 1 if idx_min is not i: # swap input[idx_min], input[i] = input[i], input[idx_min] return input class unit_test(unittest.TestCase): def test(self): self.assertEqual([1, 2, 3, 4, 5, 6], selectionSort([4, 6, 1, 3, 5, 2])) self.assertEqual([1, 2, 3, 4, 5, 6], selectionSort([6, 4, 3, 1, 2, 5])) self.assertEqual([1, 2, 3, 4, 5, 6], selectionSort([6, 5, 4, 3, 2, 1]))
da702e3d62e07ea1804cc43b2fce36f2b27a30e9
quincysoul/python-ds-binarytree
/solutions/k_largest_elements_BST_eop14_3.py
813
4
4
import binarytree from collections import deque, namedtuple """ Problem: For 1 Binary Search Tree, return the k largest elements For simplifying tests, accept params as follows: tree_root: binarytree.Node k: int Return: val of k largest elements in array. __5 / \ 3 7 / \ \ 1 4 10 / \ 0 11 ------------- ------------- Time Complexity: O(N) Space Complexity: O(N) ------------- """ class Solution: def __init__(self): self.first_occurrence = None def k_largest_elements(self, tree_root, k): print(tree_root) def reverse_in_order(self, tree_root, k): root = tree_root tourist = root guide = root # while(tourist is not None): # while(guide is not None): # print(res)
ec02a8db5649b9da64db012e369b826f44ccd13e
Gendo90/HackerRank
/Tech Screenings/Verizon/Verizon Media Software Engineer.py
1,843
3.6875
4
# First technical screening question for Verizon Media Software Engineer def minOperations(comp_nodes, comp_from, comp_to): # Write your code here comp_groups = {} #could make a map of values back to keys, to see which key it is under... #useful later... together = zip(comp_from, comp_to) if(len(comp_from)+1<comp_nodes): return -1 for link in together: if(link[0] in comp_groups): comp_groups[link[0]].add(link[1]) elif(link[1] in comp_groups): comp_groups[link[1]].add(link[0]) elif(link[1] in comp_groups.values()): for key in comp_groups.keys(): if(link[1] in comp_groups[key] and link[0] not in comp_groups[key]): comp_groups[key].add(link[0]) break elif(link[0] in comp_groups.values()): for key in comp_groups.keys(): if(link[0] in comp_groups[key] and link[1] not in comp_groups[key]): comp_groups[key].add(link[1]) break else: comp_groups[link[0]] = set() comp_groups[link[0]].add(link[1]) #need to include the computers not connected to anything #currently off by a factor of comp_nodes-len(comp_seen) where #comp_seen is given as a map of the computer values encountered in together return len(comp_groups)-1 # Second technical screening question for Verizon Media Software Engineer def compressWord(word, K): # Write your code here ind = 0 while(ind<len(word)-(K-1)): if(word[ind:ind+K]==word[ind]*K): word = word[:ind] + word[ind+K:] if(ind-K>=0): ind = ind-K else: ind = 0 else: ind+=1 return word print(compressWord("aabbcccb", 3))
05969df2502bf52f7e5318c80bfc62966c14d331
alejandroorca/alejandroorca.github.io
/ejercicios_pc/09.py
1,113
3.84375
4
def asterisco(x): # Esta funcion imprime tan solo * multiplicado por X ( donde X será la longitud mas larga de caracteres ) a = "*" * x return a def lista(x): # Esta funcion me va a dar la longitud mas larga de caracteres y le sumo 4 ( para el * inicial y final mas espacios ) c = 0 #contador for i in range(len(x)): for j in range(len(x[i])): if c < len(x[i]): c = len(x[i]) c = c + 4 return c def prin(x): # Este es el cuerpo del programa. LLama a las otras funciones e imprime en pantalla d = lista(x) #Recojo el tamaño mas largo de caracteres de los arrays ejemplo ray1[] print(asterisco(d)) for i in range(len(x)): if len(x[i]) + 4 < d: e = d - len(x[i]) print("*", x[i], (" " * (e - 5)) ,"*") else: print("*", x[i], "*") print(asterisco(d)) return " " ray1 = ["Me", "gusta", "la", "pizza", "margherita"] ray2 = ["Holaaaaaa", "me", "llamo", "Ralph"] ray3 = ["Uso muchas funciones", "así mola", "muchooo mas"] print(prin(ray1)) print(prin(ray2)) print(prin(ray3))
27b061b08861fc11da06a18cce84fe2afff63476
testautomation8/Learn_Python
/CSV_Reader/CSVReader.py
290
3.796875
4
# Script to read data from CSV file import csv with open("D:\Learning\Python\PycharmProjects\CSV_Reader\example.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: print(row) print(row[0]) print(row[1]) print(row[2])
b0da78c93d739505bd08811ec89fe7f3e25c986e
julianespinel/training
/hackerrank/climbing_the_leaderboard.py
2,751
4.15625
4
''' https://www.hackerrank.com/challenges/climbing-the-leaderboard # Climbing the leaderboard The function that solves the problem is: ```python get_positions_per_score(ranks, scores) ``` The solution uses `deque` instead of lists. Why? To have O(1) in appends and pops from either side of the deque. See: https://docs.python.org/3/library/collections.html#collections.deque The complexity of this solution is: - Time: O(ranks) + O(scores) = O(max(ranks,scores)) - Space: O(ranks) + O(scores) = O(max(ranks,scores)) ''' import sys from collections import deque def read_values() -> list[int]: sys.stdin.readline() # skip ranks_str = sys.stdin.readline() strings = ranks_str.split(' ') return list(map(int, strings)) def remove_duplicates(ranks: list[int]) -> list[int]: ''' Given a list sorted in descending order (ranks), remove the duplicates of the list. Time complexity: O(n) Why? See: https://stackoverflow.com/a/7961390/2420718 ''' return list(dict.fromkeys(ranks)) def get_positions_per_score(ranks: list[int], scores: list[int]) -> deque[int]: ''' Return the position of each score in the ranks list using a zero-based index. ranks: list sorted in **descending** order scores: list sorted in **descending** order Time complexity: O(scores) + O(ranks) ''' positions = deque() # why a deque? to make all appends O(1) ranks_index = 0 # O(1) scores_index = 0 # O(1) scores_size = len(scores) # O(1) ranks_size = len(ranks) # O(1) # O(scores) + O(ranks) while (scores_index < scores_size) and (ranks_index < ranks_size): score = scores[scores_index] # O(1) rank = ranks[ranks_index] # O(1) if score >= rank: # O(1) positions.append(ranks_index) # O(1) scores_index += 1 # O(1) else: ranks_index += 1 # O(1) # add missing scores while scores_index < scores_size: # O(scores) in the worst case positions.append(ranks_index) # O(1) scores_index += 1 # O(1) positions.reverse() # O(scores) return positions def print_positions(positions: deque[int]) -> None: ''' Print the given positions. Add +1 to each element because the response must be one-based index instead of zero-based index. ''' for position in positions: print(position + 1) if __name__ == '__main__': ranks_input = read_values() scores = read_values() ranks = remove_duplicates(ranks_input) # O(ranks) scores.reverse() # O(scores) positions = get_positions_per_score(ranks, scores) # O(ranks) + O(scores) # O(scores), because len(positions) == len(scores) print_positions(positions)
3ca2464197e5ea01e66fe1f8ce0836c2ac8150a8
yanghaotai/leecode
/十大排序算法/10、基数排序.py
1,178
3.75
4
''' 10、基数排序 基数排序是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。由于整数也可以表达字符串(比如名字或日期)和特定格式的浮点数,所以基数排序也不是只能使用于整数。 基数排序 vs 计数排序 vs 桶排序 基数排序有两种方法: 这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异: 基数排序:根据键值的每位数字来分配桶; 计数排序:每个桶只存储单一键值; 桶排序:每个桶存储一定范围的数值; ''' def radix_sort(array): max_num = max(array) place = 1 while max_num >= 10 ** place: place += 1 for i in range(place): buckets = [[] for _ in range(10)] for num in array: radix = int(num / (10 ** i) % 10) buckets[radix].append(num) j = 0 for k in range(10): for num in buckets[k]: array[j] = num j += 1 return array arr = [2,1,32,41,42,33,4545,0,343,434,34232,44,3434,43,543,48,5] print(radix_sort(arr))
4aef7b821c1f046aa867b660358536607f1400ff
rbiswasfc/algorithms
/recursion/recursion_part1.py
3,978
3.84375
4
from typing import List class ReverseStringRecursion: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ if len(s) <= 1: return s def helper(p1, p2, s): if p2 < p1: return s[p1], s[p2] = s[p2], s[p1] helper(p1 + 1, p2 - 1, s) helper(0, len(s) - 1, s) class ReverseStringIteration: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ if len(s) <= 1: return s p1, p2 = 0, len(s) - 1 while p2 > p1: s[p1], s[p2] = s[p2], s[p1] p1 += 1 p2 -= 1 # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class SwapNodePairLL: def swapPairs(self, head: ListNode) -> ListNode: if not head: return if not head.next: return head n0 = head n1 = head.next n2 = head.next.next new_head = n1 new_head.next = n0 new_head.next.next = self.swapPairs(n2) return new_head # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class BSTTarget: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return def helper(node): if not node: return if node.val == val: # print('found') return node # print('not found') if node.val > val: left_ans = helper(node.left) if left_ans: return left_ans else: right_ans = helper(node.right) if right_ans: return right_ans return helper(root) class PascalTriangleII: def getRow(self, rowIndex: int) -> List[int]: memory = dict() def helper(i, j): key = "{}_{}".format(i, j) if key in memory: return memory[key] if i == 0: return 1 if (j == i) or (j == 0): return 1 else: ans = helper(i - 1, j - 1) + helper(i - 1, j) memory[key] = ans return ans to_return = [0] * (rowIndex + 1) for j in range(rowIndex + 1): to_return[j] = helper(rowIndex, j) return to_return class PoW: def myPow(self, x: float, n: int) -> float: def helper(x, a): if a == 0: return 1 elif a % 2 == 0: return helper(x * x, int(a / 2)) else: return x * helper(x, a - 1) if n == 0: return 1 elif n > 0: return helper(x, n) else: r = helper(x, -n) return 1.0 / r class Merge: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: def helper(head1, head2, curr): if (not head1) and (not head2): return if not head1: curr.next = head2 return helper(head1, head2.next, curr.next) # process remaining head2 if not head2: curr.next = head1 return helper(head1.next, head2, curr.next) # process remaining head1 if head1.val > head2.val: curr.next = head2 return helper(head1, head2.next, curr.next) else: curr.next = head1 return helper(head1.next, head2, curr.next) start = ListNode(0) helper(l1, l2, start) return start.next
da3b80465afdbedba8738a65079b5194b40275c9
nanli-7/algorithms
/150-evaluate-reverse-polish-notation.py
1,663
4.03125
4
""" 150. Evaluate Reverse Polish Notation - Medium #stack Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. Example 1: Input: ["2", "1", "+", "3", "*"] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: ["4", "13", "5", "/", "+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 """ import operator class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack = [] operators = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv } for token in tokens: if token not in operators: stack.append(int(token)) else: y, x = stack.pop(), stack.pop() stack.append(int(operators[token](x * 1.0, y))) return stack.pop() if __name__ == "__main__": tokens = [ "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" ] res = Solution().evalRPN(tokens) print(res)
94aaec9936fe17ebab1c6cbc5640fcc8ec0cab8f
feer921/PythonStudy
/04-数据类型的转换.py
665
4
4
# 进制转换,将 int类型以不同的进制表现出来 # 类型转换 将一个类型的数据转换为其他类型的数据 int==>str str==>int bool==> int int==>float age = input("请输入您的年龄:") print(type(age)) # <class 'str'> # print(age+1) # 会报错误,因为 接收到的用户输入,都是 [str]字符串类型;在python里,如果字符串和数字做 加法去处,会直接报错 # 应该 把字符串类型的变量 age 转换成为数字类型的 age # 使用 [int]内置函数可以将其他类型的数据转换成整数 age = int(age) print(type(age)) # <class 'int'> print(age + 1) # 这样就不会报错了
d98730e97b8373c1fb0e0bcbc8a54a282e373e38
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4148/codes/1637_1055.py
378
3.59375
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. from math import* g = 9.8 v0 = float(input("v0: ")) a = float(input("angulo: ")) d = float(input("distancia: ")) r = (v0) **2 * sin(2*(radians(a)))/g F = abs(r-d) if F < 0.1: print("sim") else: print("nao")
a68522813edc142fd7df3bb65f113c3b60f5af8f
NitinBnittu/Launchpad-Assignments
/problem3.py
131
3.53125
4
l=[1, 2, 3, 2, 0, 65, 21, 4, 2, 10] a=2 out=[] for i in range(0,len(l)): if l[i] == a: out.append(i) print(out)
41ba438e60e3857854451abcdb3319e2faa2065b
arifkhan1990/Competitive-Programming
/Data Structure/Linked list/Singly Linked List/practice/Leetcode/Intersection_of_Two_Linked_Lists _Solution.py
1,248
3.78125
4
# Name : Arif Khan # Judge: Leetcode # University: Primeasia University # problem: Intersection of Two Linked Lists # Difficulty: Medium # Problem Link: https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1215/ # class Solution: # Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 # Output: Reference of the node with value = 8 # Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). # From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; # There are 3 nodes before the intersected node in B. def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: curr1, curr2 = headA, headB while curr1 != curr2: if curr1 is None: curr1 = headB else: curr1 = curr1.next if curr2 is None: curr2 = headA else: curr2 = curr2.next return curr1
e8d144ecd4c3ce763c95470a94203b8a8343dd15
adamchung40/CSE-1321
/Labs/Lab4/WeeklyPay/WeeklyPay/WeeklyPay.py
285
3.796875
4
#Class: CSE 1321L #Section: 16 #Term: Spring 2019 #Instructor: Kristin Hegna #Name: Adam Chung #Lab#: 2 hours = int(input("How many hour did you work? ")) std_hours = 40 if hours > 40: overtime = (hours - 40)*15 + (std_hours*10) print(overtime) else: print(hours*10)
3242e005f7db7f56a6f772c740949b1f7aa6b7bc
ThiagoScodeler/Curso-Python-Inatel
/exercicios_python/exec26/exec26.py
439
3.671875
4
def calc_vet(): vet_numbers = list() for n in range(4): vet_numbers.append(int(input("Forneça um número: "))) vet_par = list((n for n in vet_numbers if n % 2 == 0)) vet_impar = list((n for n in vet_numbers if n % 2 != 0)) print("Lista original: ") print(vet_numbers) print("Lista par: ") print(vet_par) print("Lista ímpar: ") print(vet_impar) if __name__ == '__main__': calc_vet()
acaf8269ce9d390b3c017b1dde3c39ab99e7a4c9
mary-tano/python-programming
/python_for_kids/book/Projects/kehrwert.py
228
3.765625
4
# Обратное число try : print("Введи число: ") Number = float(input()) if Number != 0 : print(1/Number); else : print("Нет результата"); except : print("Нет числа!")
c982ab2e90c34f5369c1ea59c4a5867dd7433c7c
Jacolla/learning
/python/python.py
11,720
3.921875
4
# _______________________________________________ #Todo en phyton es un objeto #Las variables son marcadas por el contenido, no el contenedor. # msg = ("toma yaah") # print(msg) # _______________________________________________ # numero1=10 # numero2=20 # if numero1>numero2: # print("El numero uno mola mas") # # and numero2 == numero1 : # print("Pueh ya veh") # # else: # print("Pues no tanto") # # # _______________________________________________ # def mensajito(): # Defines # print("Mensaje 1") # | # print("Mensaje 2") # | --> Cuerpo de la definicion # print("Mensaje 3") # | # # mensajito() # | # mensajito() # || # mensajito() # |||--> Llamas a la definicion # mensajito() # || # mensajito() # | # _______________________________________________ # def suma(num1, num2): # # resultado=num1 + num2 # # return resultado # # almacena_resultado=suma(4,2) # # print(almacena_resultado) # _______________________________________________ # --Listas-- # Lista0=["Marta", True, 30, "False?"] # Lista0.append("Sandra") # Lista0.insert(1,"Jesusito") # Lista0.extend(["Antonio","Alia", "Pepote"]) # Lista0.remove("Antonio") # Lista0.pop() # Lista1=["Marta",25, True,] # Lista2=["Charlene", "Janet"] # Lista3= Lista0 + Lista1 + Lista2 # print(Lista3*2) # _______________________________________________ # -- Tuplas -- # Es como una lista, pero no es modificable, es decir, se pueden coger fracciones de la tupla, pero # no puedes quitar/añadir componentes de la tupla, util cuando se quiere mirar la tupla o comprobar si hay algo en la tupla. # Ocupan menos espacio, son mas rapidas de ejecutar, formatean strings(?) # tuplaPrueba=("Marta", 30, "Alia", 25, "Gisele", 23 ) # listaDos=list(tuplaPrueba) # print(listaDos[4]) # con los [], le decimos cual queremos seleccionar ( empezando por 0) # _______________________________________________ # -- Diccionario -- # pruebaDicc = {"Espania": "Mallorca", "England":"Manchester", "Russia": "Moscow", 2:"Puto amo"} # pruebaDicc["Latvia"] = "Riga" # # print (pruebaDicc["Latvia"]) # # Se le puede reasignar solo con meterlo en la "lista" # pruebaDicc ["Polonia"] = "Varsovia" # print (pruebaDicc["Polonia"]) # # del pruebaDicc["England"] # Con el Del se elimina de la tupla # # print (pruebaDicc ["Espania"]) # print (pruebaDicc [2]) # # print(pruebaDicc) # print(pruebaDicc.keys()) # Seleccionas la "resQuest" # print(pruebaDicc.values()) # selecciona la "respuesta" # print(len(pruebaDicc)) # _______________________________________________ # -- Condicionales -- # print("Probando el python") # # nota_Alumno=int(input("Cual crees que tienes? ")) # # def evaluacion(nota): # # valoracion="-.-" # # if nota<5: # print("Este es el if, condicion que abre canal de flujo, up") # # elif nota>6: # print("este es el elif, acompaña al if, middle") # # else: # print("esto es el else, tiene que ir al final de todo, down") # # return valoracion # # print(evaluacion(nota_Alumno)) # # print("Finish") #---------------- # print("Verificacion de acceso") # # cilindrada=int(input("Selecciona una cilindrada... : ")) # # # if cilindrada <= 250: # print("Empieza a no estar mal") # # elif cilindrada <= 650: # print("Eso empiezan a ser palabras mayores") # # elif cilindrada >= 650: # print("Uff... eso ya empieza a dar miedo de verdad") # # else: # print("Ni idea") # # print("Finish") #---------------- # edad=int(input("Que edad tienes? : ")) # if edad < 18: # print("Tira pa tu casa") # # elif edad < 100: # print("Puedes entrar") # # else: # print("Stás to flipao") # --/ version corta \-- # edad=int(input("Que edad tienes? : ")) # # if 18<edad<100: # concatenación de operadores # print("Puedes pasar, pero no te lo bebas todo, borrachin") # # else: # print("No puedes pasar, ffffflipao!") #---------------- # salario_Presidente = int(input("Introduce salario presidente: ")) # print("Salario presidente: " + str(salario_Presidente)) # # salario_director = int(input("Introduce salario director: ")) # print("Salario director: " + str(salario_director)) # # salario_Jefe_area = int(input("Introduce salario Jefe area: ")) # print("Salario Jefe area: " + str(salario_Jefe_area)) # # salario_administrativo = int(input("Introduce salario administrativo: ")) # print("Salario administrativo: " + str(salario_administrativo)) # # if salario_Presidente>salario_director>salario_Jefe_area>salario_administrativo: # print("Todo va bien") # else: # print("No va tan bien") # # # #---------------- #<-- Operadores and,or & in --> # print("Requisitos Becas") # # distancia_escuela=int(input("Distancia colegio: ")) # print( distancia_escuela) # # numero_hermanos=int(input("Cuantos hermanos tienes? ")) # print(numero_hermanos) # # salario_familiar=int(input("Cual es el salario anual bruto? ")) # print(salario_familiar) # # if distancia_escuela>= 30 and numero_hermanos>= 2 or salario_familiar<= 10000: # print("Merece beca") # else: # print("No cumple los requisitos") #---------------- # print("Asignaturas optativas") # print("Asignaturas optativas: Informatica grafica - Prueba de software - Desarrollo web") # opcion=input("Escribe la optativa deseada: ") # asignatura=opcion.lower() # # asignatura=opcion.upper() # El .upper/.lower, cambia el str recibido a mayusculas/minusculas # # # # if asignatura in ("informatica grafica","prueba de software", "desarrollo web"): # print("Asignatura elegida: " + asignatura) # else: # print("No has entendido nada...") # resQuest = print("Que moto vas a querer?") # # motos={1:"CB650R",2:"STREET TRIPLE",3:"GSX750",4:"AFRICA TWIN",} # #eleccion=motos.lower() # # print("1- Honda CBR 650 R") # print("2- Triumph street triple") # print("3- Suzuki GSX750") # print("4- Honda Africa Twin, CRF1000L") # # select=int(input("Numero de la afortunada? ")) # # # if select in (1,2,3,4): # print("La escogida es " + motos[select] + "... buen bicho") # # else: # print(resQuest) # # seguro = input("Estas seguro? ") # _______________________________________________ # <-- Bucles --> # for i in ["solo","cuenta","valor",]: # print("bucle(?)") # # for i in ["bucle(?)","bucle(?)2","bucle(?)3",]: # print(i) # i=1 # # # # while i < 5: # # print("Esta es la cuenta: "+str(i)) # i = i + 1 # for i in [1,2,3]: # print("estudia ", end="") # email=False # miEmail=input("Cual es tu email? ") # # for i in miEmail: # if (i == "J" ): # miEmail=True # # if miEmail== True: # print("Email correcto") # else: # print("Email NO correcto") # _______________________________________________ # for i in range(2,10,2): # print("valor de la variable {i}") # # i=1 # # while i<=10: # print("ejecucion: "+ str(i)) # i=i+1 # print("Finish") # seguro = input("Estas seguro? ") # while seguro != "enga": # print("venga que sii, se puede!") # seguro = input("¿Estas seguro, seguro? ") # print("Finish") # |/////////////////////////////////////////| # |/////// ///////| # |// seguro = input("Estas seguro? ") /| # |// while seguro != "si": /| # |// print("uf no se yo eh...") /| # |// seguro = input("Estas seguro? ")/| # |// print("Finish") /| # |/////// ///////| # |/////////////////////////////////////////| # for i in ["bucle(?)","bucle(?)2","bucle(?)3",]: # print(i) # i=1 # _______________________________________________ # import math # # print("Vamos a contar...") # numero=int(input("Dime un numero chavá: ")) # # intentos=0 # while numero != 5: # print("No puedo encontrar ese... dame otro") # # if intentos == 10: # print("Ya van muchas veces y... esto no... no va") # break # # numero = int(input("Dame un numero tio... ")) # if numero != 5: # intentos=intentos +1 # # if intentos <2: # solucion=math.sqrt(numero) # print("pues no va el chaval y acierta... : " + str(numero)) # _______________________________________________ # email=input("Introduce email: ") # # for i in email: # if i !="@": # arroba=True # # else: arroba=False # print(arroba) # # # _______________________________________________ # <-- Generadores --> # def generadorPrimero(limite): # num=1 # # while num<limite: # yield num*2 # # num=num+1 # # devuelvePares=generadorPrimero(10) # # for i in devuelvePares: # print(i) # # # ___________________ # def generadorSegundo(limite): # num=1 # while num<limite: # yield num*2 # num=num*2 # # devuelvePares=generadorSegundo(10) # # print("texto vacio simple sencillo sin ná") # print(next(devuelvePares)) # # print("texto vacio simple sencillo sin ná") # print(next(devuelvePares)) # # print("texto vacio simple sencillo sin ná") # print(next(devuelvePares)) # ___________________ # import time # import progressbar # for i in progressbar.progressbar(range(25)): # time.sleep(0.05) # print("Motos a tener en cuenta: ") # def devuelveMotos(*motos"): # for elemento in motos: # # for subElemento in elemento: # # yield from elemento # yield elemento # # motosDevueltas=devuelveMotos("Honda", "Gilera", "GasGas", "Triumph") # # print(next(motosDevueltas)) # print(next(motosDevueltas)) # print(next(motosDevueltas)) # print(next(motosDevueltas)) # _______________________________________________ # <-- Excepciones --> # ____________________________________________________________________________________ # """ <--- Jugueteo ---> """ # base = int(input("base:")) # altura = int(input("altura:")) # base_x_altura = base * altura / 2 # print("El area es: " + str(base_x_altura)) # ____________________________ # pi = (355/113) # radio = input("Cual es el radio? ") # resultado = pi * int(radio) * 2 # print(resultado) # <----------> # import math # pi = math.pi # print (pi) # ____________________________ # v0 # sabores = ["Chocochoco ", "Vanella ", "Mint "] # for s1 in sabores: # for s2 in sabores: # print("Helado de " + s1 + "con " + s2) # <----------> # v1 # sabores = ["Chocolata ", "Vainilla ", "Almendra "] # for s1 in range(len(sabores)): # for s2 in range(s1+1, len(sabores)): # print("Heladito de", str(sabores[s1]) + "con " + str(sabores[s2]) ) # ____________________________ # for d in range (1,31): # print("----") # print("dia", d) # if d % 7 == 1 or d % 7 == 0: # print("Descansito gueno") # continue # print("Levantarse a desayunar") # print("A tudial hueputa") # ____________________________ # # <-- BarraProgreso --> # import time # import progressbar # # for i in progressbar.progressbar(range(50)): # time.sleep(0.1) # # lista = range(10, 40, 5) # for i in lista: # print(i)
4152580f0efc0ed49f8e825f25334d8f2ea3347a
kyledugan/linear-algebra
/week3/symmetrize_upper.py
353
3.875
4
import numpy as np # makes the bottom half symmetrical to the top half def symmetrize_upper(A): # check that A is n x n matrix if len(A.shape) != 2 or A.shape[0] != A.shape[1]: return "FAILED" for i in range(1, A.shape[0]): A[i,:i] = A[:i,i] return A A = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(symmetrize_upper(A))
6e6cc4c176dbb9c28f52ca678d86336b20191573
TheRealTimCameron/cp1404Practicals
/prac_04/list_exercises.py
810
3.921875
4
# No.1 Numbers stuff numbers = [] for number in range(5): given_number = int(input("Number: ")) numbers.append(given_number) print("The first number is {}".format(numbers[0])) print("The last number is {}".format(numbers[-1])) print("The smallest number is {}".format(min(numbers))) print("The largest number is {}".format(max(numbers))) print("The average of the numbers is {}".format(sum(numbers) / len(numbers))) # No.2 Woefully inadequate security checker usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob'] given_username = input("Username: ") if given_username in usernames: print("Access granted") else: print("Access denied")
e7450a2ef9ed2c606d66a536c18e46f23be43f0f
rafaelperazzo/programacao-web
/moodledata/vpl_data/111/usersdata/235/63812/submittedfiles/av2_p3_m2.py
720
3.59375
4
# -*- coding: utf-8 -*- import numpy as np m=int(input('digite o numero de linhas e colunas sendo l=c:')) a=np.zeros((m,m)) for i in range(0,a.shape(0),1): for j in range(0,shape(1),1): a[i,j]=int(input('digite os valores para a matriz:')) def quasemagica1(a): lista1=[] for i in range(0,a.shape[0],1): soma=0 for j in range(0,a.shape[1],1): soma=soma+a[i,j] lista1.append(soma) return(lista1) def quasemagica2(a): lista2=[] for j in range(0,a.shape[1],1): soma=0 for i in range(0,a.shape[0],1): soma=soma+a[i,j] lista2.append(soma) return(lista2) a=quasemagica1 b=quasemagica2
a97b45518f8246a8f5ae3a6326beda932b7c53d0
pksaelee/GirlsWhoCode
/codeEncryption.py
1,327
4.09375
4
#GLOBAL VARIABLES codeList =[] realList = [] #FUNCTIONS def createCodeWords(): codingWords = True while codingWords: print("Would you like to add a word to your code words? (y/n)") ans = input().lower() if ans == "y": print("What is the real word?") real = input().lower() realList.append(real) print("What is the code word?") code = input().lower() codeList.append(code) elif ans == "n": print("Your code words have been saved.") codingWords = False else: print("Security breached! Shutting down.") exit() def encryptMessage(): print() print("__________________________________________________________________") print() print("What is the message you would like to encrypt?") message = input().lower() messageList = message.split() codedMessage = "" for words in messageList: for realWord in realList: if (words == realList): #print("Encrypted Text:") codedMessage = codedMessage + "" + codeList[0] else: codedMessage = codedMessage + "" + words #RUNNING CODE createCodeWords() encryptMessage()
4b38aa5ebff9dabc644b0bb1f6638e826727be04
katherinemurphy/ComputerElective
/Practice3.py
364
3.671875
4
name = raw_input("what is your name?") last = raw_input("what is your last name?") year = input("what is your birth year?") band = raw_input("what is your favorite band?") movie= raw_input("what is your favorite movie?") friend = raw_input("who is your best friend?") age = 2015 - year print "you are ", age , "years old" print "in 10 years you will be", age + 10
61e1e11f6d9a66c804f5bb6f3e8a0f4d7a88a8da
CCC53/Python
/Curso Python/1/entradas_de_usuario.py
569
3.828125
4
#En este programa se hara un ejemplo muy simple con el uso de entradas print("\tSaludos") nombre= input("Escriba su nombre: ") print("El nombre que has digitado es: ",nombre) #Por defecto python convierte las variables en tipo string y para convertirlo a entero o flotante se hace esto: edad= input("Ahora escriba su edad: ") #Primero se almacena en una variable e inmediatamente se convierte a entero o flotante pero #se necesita otra variable donde se pueda almacenar el entero o flotante edadnum= int(edad) print("El triple de su edad es: %d"%(edadnum*3))
6ebadb51969d9bcbfe4c6380c922595f9f75e522
jofre44/EIP
/scripts/functions.py
1,158
4.3125
4
print("Actividad 3. Programacion Avanzada en Python") print("Alumno: Jose Sepulveda \n") print("Ejercicio 1: Crear función para sumar o restar valores") def suma_resta(num_1, num_2): try: num_1 = float(num_1) num_2 = float(num_2) except: print("Error!! Datos introducidos no son números") return() print(f"Suma de los números: {num_1+num_2}\n") print(f"Resta de los números: {num_1-num_2}\n") # Pedir número por pantalla numero_1 = input("Introducir numero 1:\n") numero_2 = input("Introducir numero 2:\n") suma_resta(numero_1, numero_2) print("\nEjercicio 2: Función recursiva suma de numero") def suma_recursiva(numero=10, num_sum=0): if numero == 0: print(f"Suma de funcion recursiva: {num_sum}") else: num_sum = num_sum + numero numero -= 1 suma_recursiva(numero, num_sum) #Solicitar numero inicial por pantalla numero_inicial = input("Introducir numero entero:\n") try: numero_inicial = int(numero_inicial) suma_recursiva(numero_inicial) except: print("El numero introducido es incorrecto. Se calcula suma del 0 al 10") suma_recursiva()
3f4cae0f9cb71c79b0889f55f14d0700ec587be7
guolas/acm_icpc_team
/acm_icpc_team.py
931
3.859375
4
#!/bin/python3 def get_knowledge_of_the_pair(person_1, person_2): knowledge = 0 for ii in range(len(person_1)): knowledge += person_1[ii] | person_2[ii] return knowledge N,M = [int(x) for x in input().strip().split(" ")] persons = [] for ii in range(N): topic_t = [int(x) for x in list(input().strip())] persons.append(topic_t) """ To keep track of the maximum knowledge that can be stacked up """ max_knowledge = 0 """ To keep track of how many pairs share that "knowledgability" """ num_pairs = 0 for ii in range(N): person_1 = persons[ii] for jj in range(ii, N): person_2 = persons[jj] next_knowledge = get_knowledge_of_the_pair(person_1, person_2) if next_knowledge > max_knowledge: max_knowledge = next_knowledge num_pairs = 1 elif next_knowledge == max_knowledge: num_pairs += 1 print(max_knowledge) print(num_pairs)
9b352ff17f306aca7828afb4d1e8f683c76abd82
soulorman/Python
/practice/practice_4/kmp1.py
896
3.546875
4
# KMP算法 # 首先计算next数组,即我们需要怎么去移位 # 接着我们就是用暴力解法求解即可 # next是用递归来实现的 # 这里是用回溯进行计算的 def calNext(str2): i=0 next=[-1] j=-1 while(i<len(str2)-1): if(j==-1 or str2[i]==str2[j]):#首次分析可忽略 i+=1 j+=1 next.append(j) else: j=next[j]#会重新进入上面那个循环 return next print(calNext('abcabx'))#-1,0,0,0,1,2 def KMP(s1,s2,pos=0):#从那个位置开始比较 next=calNext(s2) i=pos j=0 while(i<len(s1) and j<len(s2)): if(j==-1 or s1[i]==s2[j]): i+=1 j+=1 else: j=next[j] if(j>=len(s2)): return i -len(s2)#说明匹配到最后了 else: return 0 s1 = "acabaabaabcacaabc" s2 = "abaabcac" print(KMP(s1,s2))
a3618cd48ad08024b48f9304ece96c74b1039815
kevin-kretz/Park-University
/CS 152 - Introduction to Python Programming/Unit 6/Assignment 2/programming_assignment_2.py
2,855
4.34375
4
""" Unit 6 - Programming Assignment (2) By Kevin Kretz | 20 July 2019 Using the data provided from the file "health-no-head.csv", print the values of the appropriate states according the filters provided by the user. Also print the states with the lowest and highest number of effected people. """ def main(): #get filter information filter_state = input("Enter state (Empty means all): ") filter_disease = input("Enter disease (Empty means all): ") filter_year = input("Enter year (Empty means all): ") #declare variables for future use lowest = [] highest = [] total = 0 #print header print("{:21} {:12} {:12} {:4}\n".format('State', 'Disease', 'Number', 'Year')) #open file file = open("health-no-head.csv", "r") # Process each line of the file for aline in file: values = aline.rstrip('\n').split(',') #rename values for easier readability state = values[2] disease = values[0] number = int(values[3]) year = values[5] #declare variables for filtering state_matches = False disease_matches = False year_matches = False line_matches = False #filter information #if state filter is empty or current state matches state in filter if (filter_state == "" or filter_state.lower() == state.lower()): state_matches = True #if disease filter is empty or current disease matches disease in filter if (filter_disease == "" or filter_disease.lower() == disease.lower()): disease_matches = True #if year filter is empty or current year matches year in filter if (filter_year == "" or filter_year.lower() == year.lower()): year_matches = True #if state, disease and year all match the filter infomation, set line matches to true if state_matches & disease_matches & year_matches: line_matches = True #if current line matches filter information provided by user if line_matches: #print line print ("{:21} {:12} {:6,} {:>9}".format(state, disease, number, year)) #add number to total total += number #if number is the new lowest number, change lowest if len(lowest) == 0 or number < lowest[1]: lowest = [state, number] #if number is the new highest, change highest if len(highest) == 0 or number > highest[1]: highest = [state, number] # Close file file.close() #print total print("{:21} {:12} {:6,}".format('', 'Total', total)) #if there was at least one found in the filter, print highest and lowest states. if len(lowest) != 0: print("\nLowest") print("{:21} {:12} {:6,}".format(lowest[0], '', lowest[1])) if len(highest) != 0: print("\nHighest") print("{:21} {:12} {:6,}".format(highest[0], '', highest[1])) main()
f059dcd41e634569dc9d1af36a06f3889d7ab695
tarnfeld/pi-tools
/gpio/memory.py
1,769
3.71875
4
#!/usr/bin/python import time from RPi import GPIO # Define the connection pins PIN_LED = 12 PIN_BUTTON = 8 def setup(): """Setup the GPIO library / pins""" # Setup the connections GPIO.setup(PIN_LED, GPIO.OUT) GPIO.setup(PIN_BUTTON, GPIO.IN) # Reset the output LED to off GPIO.output(PIN_LED, False) def main(): """Main function""" setup() blink(repeat=5, sleep=0.1) while not GPIO.input(PIN_BUTTON): pass GPIO.output(PIN_LED, True) time.sleep(2) GPIO.output(PIN_LED, False) flashes = record(duration=10, feedback=True) time.sleep(1) play(flashes) def record(duration=5, feedback=False): """Record a dictionary for the number of seconds passed in as the `duration` argument that keeps a key:value of the start:end time each time PIN_BUTTON was pressed""" input_data = [] recorded_seconds = 0 start_time = None end_time = None while recorded_seconds != duration: t = time.time() if end_time == t: continue if GPIO.input(PIN_BUTTON): if start_time == None: start_time = t end_time = t else: if start_time and end_time: print "ended session save the data" start_time = None end_time = None recorded_seconds += 1 def play(flashes): pass def blink(repeat=3, sleep=0.5): """Blink the LED the number of tmes passed in as the `repeat` argument""" GPIO.output(PIN_LED, False) i = 0 while i < repeat: GPIO.output(PIN_LED, True) time.sleep(sleep) GPIO.output(PIN_LED, False) time.sleep(sleep) i += 1 if __name__ == "__main__": main()
0247996f0f850290dd4e403e3f054688a9efc27f
CrislyGonzalez/Python-basic
/Metología de programación para niñas/modulo2/Ejercicio2OperadoresLogicos.py
597
3.734375
4
#Operacion de Suma def suma(): numeroUno= 2 numeroDos= 2 resultadoSuma= numeroUno + numeroDos #Operacion de Resta def resta(): numeroUno= 5 numeroDos= 1 resultadoResta= numeroUno - numeroDos #Operacion de Multiplicación def multiplicacion(): numeroUno= 2 numeroDos= 4 resultadoMultiplicacion= numeroUno * numeroDos #Operacion de División def division(): numeroUno= 8 numeroDos= 4 resultadoDivision= numeroUno / numeroDos #Operacion raiz cuadrada def raizCuadrada(): numero = 2 raizCuadrada= numero**2 print(raizCuadrada)
b6e76e0c84de165e87cc222d8080e8d7dac43622
RMeiselman/CS112-Spring2012
/hw12/points.py
1,785
4.5625
5
# Point Object # ===================================== # Create a Point point class. Point objects, when created, look like this: # >>> pt = Point(3,4) # >>> print pt.x # 3 # >>> print pt.y # 4 # # In addition points have the following methods: # distance(self, other): # calculates the distance between this point and another # # move(self, x, y): # sets the points location to x,y # # translate(self, x, y): # offsets the point by x and y # # When all done, points should work like this: # # >>> a = Point(0,0) # >>> b = Point(0,0) # >>> b.move(2, 2) # >>> print b.x, b.y # 2 2 # >>> b.translate(1,2) # >>> print b.x, b.y # 3 4 # >>> print a.distance(b) # 5 #!/usr/bin/env python import math class Point(object): #Initializes code def __init__(self, x, y): self.x = x self.y = y #Allows you to calculate the distance between two points def distance(self, other): distance = math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2) return distance #Sets the point's location to x,y def move(self, x, y): self.x = self.x = x self.y = self.y = y #Offsets the point by x and y def translate(self, x, y): self.x = self.x + x self.y = self.y + y #Defines the two points, and prints them a = Point(1,1) b = Point(2,1) print a.x, a.y print b.x, b.y #Prints the distance between the two points - a & b print a.distance(b) #Moves points a & b to the specified points, and prints the new location of the points. a.move(2,2) b.move(1,1) print a.x, a.y print b.x, b.y #Offsets the points by x and y, and prints the new location of the points. a.translate(6,6) b.translate(5,5) print a.x, a.y print b.x, b.y
89431c7f0e900c44d9cdd9aa8cd40b7fa28ca2d6
Wu-zpeng/PythonLearn
/day13/02 生成器函数.py
1,642
3.71875
4
# def func(): # print(111) # yield 222 # ret = func() # print(ret) #打印的是生成器地址 # gener = ret.__next__() # print(gener) #通过 __next__来取值,和迭代器一样 # def fun(): # print(111) # yield 222 # print(333) # yield 444 # # gen = fun() # ret = gen.__next__() # print(ret) # ret = gen.__next__() # print(ret) #普通函数,一次性打印全部 # def cloth(): # lst = [] # for i in range(0,100): # lst.append("衣服"+str(i)) # return lst # cl = cloth() # print(cl) #生成器函数需要的时候再取,省内存 # __next__ 让生成器执行到下一个yield # def cloth2(): # for i in range(0,100): # yield "衣服"+str(i) # cl = cloth2() # ret = cl.__next__() # print(ret) # ret = cl.__next__() # print(ret) # send方法 # def eat(): # print('我吃什么?') # a = yield '馒头' # print('a='+a) # b = yield '饺子' # print('b='+ b) # c = yield '韭菜盒子' # print('c='+ c) # yield 'GAME OVER' # gen = eat() #获取生成器 # ret1 = gen.__next__() #第一个元素 # print(ret1) # ret2 = gen.send('胡辣汤') # print(ret2) # ret3 = gen.send('狗粮') # print(ret3) # ret4 = gen.send('猫粮') # print(ret4) #send() 和 __next__区别 #1.send和__next__都是让生成器向下走一次 #2.send可以给上一个yield的位置传递值,不能给最后一个yield发送值,在第一次执行生成器代码时不能用send() #生成器可以使用for循环获取内部元素 def func(): print(111) yield 222 print(333) yield 444 gen = func() for el in gen: print(el)
263ddebaf1b4b3a34eb11bb2eba0fccd281ced24
CodeSoju/UdacityDS_Algo
/Problems/nth_row_pascal.py
582
3.78125
4
def nth_row_pascal(n): if n == 0: return [1] current_row = [1] for i in range(1, n +1): prev_row = current_row current_row = [1] print("Value of i: ", i) for j in range(1, i): print(prev_row[j], prev_row[j-1]) next_number = prev_row[j] + prev_row[j-1] print("Value of next num: ", next_number) current_row.append(next_number) print("value of j:", j) print(current_row) current_row.append(1) return current_row print(nth_row_pascal(4))
138328b1c16d641532cd295fec1ea4187c1a182d
satyam-seth-learnings/ds_algo_learning
/Applied Course/4.Problem Solving/3.Problems on Linked List/14.Reverse K alternative nodes in a linked list.py
3,324
3.890625
4
import sys class node: def __init__(self, info): self.info = info self.next = None self.random=None class LinkedList: def __init__(self): self.head = None def display(self): temp = self.head while (temp): print("{} ->".format(temp.info)), temp = temp.next print("NULL") def count(self): count=0 temp=self.head while(temp): count+=1 temp=temp.next return count def serach(self,value): temp=self.head pos=1 while(temp): if(temp.info==value): print("The value found at",pos) temp=temp.next pos+=1 print("Value not found in the linked list") def insert_at_beg(self,data): self.temp = node(data) if self.head is None: self.head = self.temp return self.temp.next = self.head self.head= self.temp def insert_at_end(self,data): self.temp = node(data) if self.head is None: self.head = self.temp return self.p = self.head while self.p.next is not None: self.p=self.p.next self.p.next = self.temp; def insert_after_given_node(self,data,item): self.p=self.head while self.p is not None: if(self.p.info==item): self.temp=node(data) self.temp.next=self.p.next self.p.next=self.temp return self.p=self.p.next print("Item not found") def insert_at_pos(self,data,pos): self.temp=node(data) if pos==1: self.temp.next = self.head self.head= self.temp return self.p=self.head while pos>2 and self.p is not None: self.p=self.p.next pos-=1 if self.p is None: print("Position exceeded the length of the list") else: self.temp.next=self.p.next self.p.next=self.temp def delete(self,data): if self.head is None: print("List is empty") return if self.head.info==data: self.temp=self.head self.head=self.head.next return self.p=None self.curr=self.head while self.curr is not None: if self.curr.info==data: self.temp=self.p.next self.p.next=self.temp.next return self.p=self.curr self.curr=self.curr.next def kthAlternate(head,k): prev=None curr=head Next=None count=0 while curr is not None and count<k: Next=curr.next curr.next=prev prev=curr curr=Next count+=1 if head is not None: head.next=curr count=0 while count<k-1 and curr is not None: curr=curr.next count+=1 if curr is not None: curr.next=kthAlternate(curr.next,k) return prev if __name__=='__main__': llist=LinkedList() print("Enter number of elements") n=int(input()) for i in range(n): llist.insert_at_end(int(input())) llist.head=kthAlternate(llist.head,3) llist.display()
8d39c25ffc14a29d451e95177dcfa14e25cd045b
cameronww7/Python-Workspace
/Python-Bootcomp-Zero_To_Hero/Sec-3-Py-Object-and-Data-Basics/11-Py-Numbers.py
302
3.921875
4
from __future__ import print_function """ Prompt 11 Numbers : """ print("11 Numbers") print(2 + 1) print(2 - 1) print(7/4) print(7%4) # Two the Power of 3 print(2**3) temp = 2 + 2 temp = 2 + temp print(temp) # https://docs.python.org/2/tutorial/floatingpoint.html print(0.1 + 0.2 - 0.3)
912c09b33930e10847afb142969ac139e0db6272
joshp8a/python
/3.1 and 3.2.py
359
3.765625
4
hrs = raw_input('Hours? ') pay = raw_input('Rate? ') try: iHrs = int(hrs) except: print 'ERROR, please enter a numeric input' sys.exit() try: fPay = float(pay) except: print 'ERROR, please enter a numeric input' sys.exit() if iHrs > 40: print 'Pay is', ((iHrs-40)*fPay*1.5)+(fPay*40) else: print 'Pay is', iHrs*fPay
422795a87bd9fb0767ac30ccc79eb592defee9ec
ESMCI/cime
/CIME/ParamGen/paramgen_utils.py
5,693
4.03125
4
"""Auxiliary functions to be used in ParamGen and derived classes""" import re def is_number(var): """ Returns True if the passed var (of type string) is a number. Returns False if var is not a string or if it is not a number. This function is an alternative to isnumeric(), which can't handle scientific notation. Parameters ---------- var: str variable to check whether number or not Returns ------- True or False Example ------- >>> "1e-6".isnumeric() False >>> is_number("1e-6") and is_number(1) and is_number(3.14) True >>> is_number([1,2]) or is_number("hello") False """ try: float(var) except ValueError: return False except TypeError: return False return True def is_logical_expr(expr): """ Returns True if a string is a logical expression. Please note that fortran array syntax allows for the use of parantheses and colons in namelist variable names, which "eval" counts as a syntax error. Parameters ---------- expr: str expression to check whether logical or not Returns ------- True or False Example ------- >>> is_logical_expr("0 > 1000") True >>> is_logical_expr("3+4") False """ assert isinstance( expr, str ), "Expression passed to is_logical_expr function must be a string." # special case: if expr.strip() == "else": return True try: return isinstance(eval(expr), bool) except (NameError, SyntaxError): return False def is_formula(expr): """ Returns True if expr is a ParamGen formula to evaluate. This is determined by checking whether expr is a string with a length of 1 or greater and if the first character of expr is '='. Parameters ---------- expr: str expression to check whether formula or not Returns ------- True or False Example ------- >>> is_formula("3*5") False >>> is_formula("= 3*5") True """ return isinstance(expr, str) and len(expr) > 0 and expr.strip()[0] == "=" def has_unexpanded_var(expr): """ Checks if a given expression has an expandable variable, e.g., $OCN_GRID, that's not expanded yet. Parameters ---------- expr: str expression to check Returns ------- True or False Example ------- >>> has_unexpanded_var("${OCN_GRID} == tx0.66v1") True """ return isinstance(expr, str) and bool(re.search(r"(\$\w+|\${\w+\})", expr)) def get_expandable_vars(expr): """ Returns the set of expandable vars from an expression. Parameters ---------- expr: str expression to look for Returns ------- a set of strings containing the expandable var names. Example ------- >>> get_expandable_vars("var1 $var2") {'var2'} >>> get_expandable_vars("var3 ${var4}") {'var4'} """ expandable_vars = re.findall(r"(\$\w+|\${\w+\})", expr) expandable_vars_stripped = set() for var in expandable_vars: var_stripped = var.strip().replace("$", "").replace("{", "").replace("}", "") expandable_vars_stripped.add(var_stripped) return expandable_vars_stripped def _check_comparison_types(formula): """ A check to detect the comparison of different data types. This function replaces equality comparisons with order comparisons to check whether any variables of different types are compared. From Python 3.6 documentation: A default order comparison (<, >, <=, and >=) is not provided; an attempt raises TypeError. A motivation for this default behavior is the lack of a similar invariant as for equality. Parameters ---------- formula: str formula to check if it includes comparisons of different data types Returns ------- True (or raises TypeError) Example ------- >>> _check_comparison_types("3.1 > 3") True >>> _check_comparison_types("'3.1' == 3.1") Traceback (most recent call last): ... TypeError: The following formula may be comparing different types of variables: '3.1' == 3.1 """ guard_test = formula.replace("==", ">").replace("!=", ">").replace("<>", ">") try: eval(guard_test) except TypeError as type_error: raise TypeError( "The following formula may be comparing different types of variables: {}".format( formula ) ) from type_error return True def eval_formula(formula): """ This function evaluates a given formula and returns the result. It also carries out several sanity checks before evaluation. Parameters ---------- formula: str formula to evaluate Returns ------- eval(formula) Example ------- >>> eval_formula("3*5") 15 >>> eval_formula("'tx0.66v1' != 'gx1v6'") True >>> eval_formula('$OCN_GRID != "gx1v6"') Traceback (most recent call last): ... AssertionError """ # make sure no expandable var exists in the formula. (They must already # be expanded before this function is called.) assert not has_unexpanded_var(formula) # Check whether any different data types are being compared _check_comparison_types(formula) # now try to evaluate the formula: try: result = eval(formula) except (TypeError, NameError, SyntaxError) as error: raise RuntimeError("Cannot evaluate formula: " + formula) from error return result if __name__ == "__main__": import doctest doctest.testmod()
7fe4463f98056eb4f73b11eaf9a5d033d436561e
ki4070ma/python-playground
/raise_from/raise_from.py
607
3.6875
4
# https://docs.python.org/ja/3.8/library/exceptions.html # https://docs.python.org/ja/3/reference/simple_stmts.html#the-raise-statement def raise_exc(): try: print(1 / 0) except Exception as exc: raise exc def raise_from_exc(): try: print(1 / 0) except Exception as exc: raise RuntimeError("Something bad happened") from exc def raise_from_None(): try: print(1 / 0) except Exception: raise RuntimeError("Something bad happened") from None if __name__ == '__main__': raise_exc() # raise_from_exc() # raise_from_None()
c1958a0ada14b0df5ec5f64041af225c8a701e41
Anomium/Quinto-Semestre
/Python/Ejercicios Python - Taller 2/Ejercicio 5.py
163
4
4
def orden(num): #y = sorted(num) num.sort() return num x=[] for i in range(3): x.append(input("Digite 3 valores enteros: ")) print(orden(x))
6a4b7ab86a02567a9ac093de1b0757db2d0d1822
ShivamRohilllaa/python-basics
/5) Dictionary.py
646
3.96875
4
# Make a dictionary of four words :- '''print("Enter Your Word") dict = {"Dog": "Kutta", "House": "Ghar", "Water": "Paani", "Rat": "Chuha"} dictinpt = input() print(dict.get(dictinpt))''' d2 = {"Harry": "Potter", "Aliza": "Beth", "Shivam": {"Burger": "Junk Food", "Chowmein": "Junk Food", "Pizza": "Baked"}} # Delete Function it is case sensitive del d2["Harry"] # Update Function means add a new key in the list d2.update({"Winters": "Summer"}) print(d2) # get functions means it gets the value of the given key print(d2.get("Winters")) # Print all the key in the list print(d2.keys()) # Print all the value of the keys print(d2.values())
08d20bd4d836d6228ad0e06650ae31acba78af6d
AugustineAykara/Competitive-Coding
/Coding Interview Problems/Sample03/solution.py
224
3.75
4
def fib(n): if(n in memo): return(memo[n]) if(n == 1 or n == 0): return memo[n] memo[n] = fib(n-1) + fib(n-2) return memo[n] n = int(input()) memo = {0:0, 1:1} print(fib(n-1))
7e72aea5b3530b61e32951f6c81a3a8eaf65e6f1
swissvoc/-Getting-Started-with-Object-Oriented-Programming-in-Python-3
/Section 1/object.py
319
3.671875
4
class Car: def start(self): print("Car started") def reverse(self): print("Car taking reverse") def speed(self): print("top speed = 200") def main(): volvo=Car() volvo.start() volvo.reverse() volvo.speed() if __name__ == "__main__": main()
5b60734a6562ec687683c56aa254e61566a5c0b8
tzxyz/leetcode
/problems/0747-largest-number-at-least-twice-of-others.py
1,721
3.75
4
from typing import List class Solution: """ 在一个给定的数组nums中,总是存在一个最大元素 。 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。 如果是,则返回最大元素的索引,否则返回-1。 示例 1: 输入: nums = [3, 6, 1, 0] 输出: 1 解释: 6是最大的整数, 对于数组中的其他整数, 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.   示例 2: 输入: nums = [1, 2, 3, 4] 输出: -1 解释: 4没有超过3的两倍大, 所以我们返回 -1.   提示: nums 的长度范围在[1, 50]. 每个 nums[i] 的整数范围在 [0, 99]. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ def dominantIndex(self, nums: List[int]) -> int: """ 先找到最大值,在遍历数组,如果存在一个数,满足 2n > max_n 则返回 -1, 否则返回 max_n 的索引。复杂度 O(n) :param nums: :return: """ max_n, idx = nums[0], 0 for i, n in enumerate(nums): if n > max_n: max_n = n idx = i for n in nums: if n != max_n and 2 * n > max_n: return -1 return idx if __name__ == '__main__': tests = [ ([3, 6, 1, 0], 1), ([1, 2, 3, 4], -1), ([1, 1, 0], 0), ] for nums, idx in tests: assert Solution().dominantIndex(nums) == idx
55a4c2c91b3177724c321a86599cf99d4b3a09b6
lyds214/DSA-Implementation
/Stacks and Queues/Stack Implementation (Array).py
681
4.125
4
class Stack(): def __init__(self): self.array = [] self.length = 0 # Returns the value of the last element def peek(self): return self.array[self.length - 1] # Adds the element at the end of the array def push(self, value): self.array.append(value) self.length += 1 # Removes the element at the end of the array def pop(self): del self.array[self.length - 1] self.length -= 1 # Returns the object's data instances def __str__(self): return str(self.__dict__) x = Stack() x.push(1) x.push(2) x.push(3) x.push(4) print(x) print(x.peek()) x.pop() x.pop() print(x)
06b20212dafd15eb923c8bfce7d035e45e92c1ae
ShangruZhong/leetcode
/Tree/99.py
1,255
3.640625
4
""" 99. Recover Binary Search Tree inOrder to find the first and second wrong node, and swap their val @date: 2017/05/07 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def __init__(self): self.first = None self.seconde = None self.prev = TreeNode(-1<<31+1) def recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ self.inOrder(root) self.first.val, self.second.val = self.second.val, self.first.val def inOrder(self, root): if not root: return self.inOrder(root.left) if not self.first and self.prev.val >= root.val: # not satisfy order, should be prev.val < root.val in BST self.first = self.prev if self.first != None and self.prev.val >= root.val: # find the second node that not satisfy order self.second = root self.prev = root self.inOrder(root.right)
f0f4049c7f561e8244292afe08556da4141ab0b5
davidhuangdw/leetcode
/python/410_SplitArrayLargestSum.py
1,955
3.5
4
from unittest import TestCase # https://leetcode.com/problems/split-array-largest-sum/ import itertools class SplitArrayLargestSum(TestCase): def splitArray(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ n = len(nums) sums = [0] for v in nums: sums.append(sums[-1]+v) dp = list(sums) for r in range(2, m+1): k = n-1 for i in range(n, r-1, -1): def cal(j): return max(dp[j], sums[i]-sums[j]) while k >= r and cal(k-1) <= cal(k): k -= 1 dp[i] = cal(k) return dp[n] # # O(n*logV) BS # def splitArray(self, nums, m): # l, r, n = max(nums), sum(nums), len(nums) # while l <= r: # md = (l+r) >> 1 # k, pre = 1, 0 # for v in nums: # pre += v # if pre <= md: continue # k += 1 # if k > m: break # pre = v # if k <= m: # r = md-1 # else: # l = md+1 # return l # # # O(n*m)t, O(n)s dp: d(i,m) = min{max(s[j+1, i], d(j,m-1)) | j<i }, the selected k is non-decrease to i # def splitArray(self, nums, m): # k, n = 0, len(nums) # sums = list(itertools.accumulate(nums)) # dp = list(sums) # # def cal(i, k): # return max(sums[i] - sums[k], dp[k]) if k >= 0 else sums[i] # for r in range(2, m+1): # k = n-1 # for i in range(n-1, -1, -1): # while k and (k >= i or cal(i, k-1) <= cal(i, k)): # bug: <= not <, otherwise k won't across == # k -= 1 # dp[i] = cal(i, k) # return dp[n-1] def test1(self): self.assertEqual(18, self.splitArray([7,2,5,10,8], 2))
8821a3454fbf7a16b1da7e3d37297907ea804250
Benji-Saltz/Early-Python-Projects
/Gr.11 Computer Science/Gr.11 Computer Science Lists.py
1,188
3.953125
4
''' By: Benji Saltz Date:11/9/2016 Description: Three programs, one which finds highest mark and average, another than sees how many a's are in a sentence and one which find 3 younest and oldest out of 50 people ''' import random marks=[] #stores inputed marks for i in range(5): #only allows 5 marks.append(int(input("enter a mark: ")))#allows you to enter mark print("Your hightest mark is: ",max(marks))#prints highest mark entered print("Your average mark is: ",round(sum(marks)/len(marks)))#prints lowest mark entered def count(letter):#stores how many a's have been entered return list(letter).count("a")#counts how many a's have been entered print("you have",count(input("Enter a sentence: ").lower()),"a('s) in your sentence") age=[]#allows 50 ages to be stored for i in range(50): age.append(random.randint(1,100))#will randomize 50 ages from 1 to 100 age.sort()# allows ages to be sorted from lowest to highest print("The three youngest out of 50 are ages: ",age[0],",",age[1],",&",age[2],"and the oldest out of 50 are ages: ",age[47],",",age[48],",&",age[49])#takes stored numbers from list which were sorted from lowest to highest and displays the 3 lowest and highest
a66726c3464c27dc092269f78902c60006f4964e
rebornbd/ALGORITHM-DATASTRUCTURE
/ds/queue/python/03-queue-reverse.py
478
3.84375
4
from queue import Queue import copy def reverseQueue(queue: Queue): if queue.empty(): return item = queue.get() reverseQueue(queue) queue.put(item) def displayQueue(queue: Queue): while(not queue.empty()): print(queue.get()) q = Queue() tem = Queue() q.put(10) q.put(20) q.put(30) q.put(40) reverseQueue(q) tem.queue = copy.deepcopy(q.queue) displayQueue(tem) reverseQueue(q) tem.queue = copy.deepcopy(q.queue) displayQueue(tem)
03129093614a40692aac03e2fd9e964257c1d72b
m8k7j/interview
/by_myself/reverse_string.py
557
3.890625
4
#!/usr/bin/env python # coding=utf-8 """ input_s = "terry ding is a good boy" output_s = "yob doog a si gnid yrret" """ def reverse_string(input_s): li_s = list(input_s) #字符串转列表 reverse_li = [] reverse = "" for i in range(len(li_s)): #当用pop的时候会影响到原列表, #因此不能用 for i in li_s, 而是用长度 reverse_li.append(li_s.pop()) for j in reverse_li: reverse += j #列表转字符串 return reverse if __name__ == '__main__': input_s = "terry ding is a good boy" print reverse_string(input_s)
26c622b918315d210b7806bc7cd70a1f74e1fb94
AstroYoung617/PythonStudy
/python_day1/testhello.py
247
3.84375
4
username = input() list1=input() print(list1) if username == "杨宇航": print("welcome") print("帅哥") if username == "李阳": print("welcome") print("猪头") else: print("not welcome") print(False)
81d54cf76b754e9ede21c901a1768e2a1d196f9c
nathanbarnesduncan/442-HW-1
/update_locations_modified.py
1,839
3.859375
4
#!/usr/bin/env python3 """ This program generates N random coordinates in space (3D), and N random velocity vectors. It then iterates M times to update the locations based on the velocity. Finally, it outputs the sum of all coordinates as a checksum of the computation. Coordinates start in the range [-1000:1000] per dimension. Velocities are chosen from the range [-1:1] per dimension. """ import random, sys, timeit, time, statistics ############### # Create a list of 'size' floating point numbers in the range [-bound, bound] def generate_random_list(size, bound): return [random.uniform(-bound, bound) for i in range(size)] ############### # Update location by velocity, one time-step def update_coords(x, y, z, vx, vy, vz): for i in range(size): x[i] = x[i] + vx[i] y[i] = y[i] + vy[i] z[i] = z[i] + vz[i] ############ Main: N = 2 ** 8 M = 2 ** 16 for i in range (0, 17): rstart = time.clock() rend = 0.0 numberoftrials = 0 outputlist = [] outputvalue = 0.0 size = N iters = M while (46. > rend): size = N iters = M random.seed(size) x = generate_random_list(size, 1000.) y = generate_random_list(size, 1000.) z = generate_random_list(size, 1000.) vx = generate_random_list(size, 1.) vy = generate_random_list(size, 1.) vz = generate_random_list(size, 1.) t = timeit.timeit(stmt = "update_coords(x, y, z, vx, vy, vz)", setup = "from __main__ import update_coords, x, y, z, vx, vy, vz", number = iters) chksum = sum(x) + sum(y) + sum(z) rend = time.clock() - rstart numberoftrials += 1 outputlist.append((1000000 * t / (size * iters))) outputvalue = statistics.median(outputlist) print(N) print(M) print(numberoftrials) print(outputvalue) N = N * 2 M = int(M / 2) exit(0)
ef83a7ee58c3e714e65264e1a4b62040e6fa84da
ChinaChenp/Knowledge
/learncode/python/json/dump.py
298
3.65625
4
import json filename = 'numbers.json' numbers = ['1', '2', '3', '4', '5'] with open(filename, 'w') as file_object: json.dump(numbers, file_object) with open(filename) as file_object: numbers2 = json.load(file_object) print(numbers2) for number in numbers2: print(number)
1c7fa902b0fa28ced07384b2a85cef537fc1dc98
viblo/pymunk
/pymunk/shape_filter.py
4,464
3.75
4
from typing import NamedTuple class ShapeFilter(NamedTuple): """ Pymunk has two primary means of ignoring collisions: groups and category masks. Groups are used to ignore collisions between parts on a complex object. A ragdoll is a good example. When jointing an arm onto the torso, you'll want them to allow them to overlap. Groups allow you to do exactly that. Shapes that have the same group don't generate collisions. So by placing all of the shapes in a ragdoll in the same group, you'll prevent it from colliding against other parts of itself. Category masks allow you to mark which categories an object belongs to and which categories it collides with. For example, a game has four collision categories: player (0), enemy (1), player bullet (2), and enemy bullet (3). Neither players nor enemies should not collide with their own bullets, and bullets should not collide with other bullets. However, players collide with enemy bullets, and enemies collide with player bullets. ============= =============== ==================== Object Object Category Category Mask ============= =============== ==================== Player 0b00001 (1) 0b11000 (4, 5) Enemy 0b00010 (2) 0b01110 (2, 3, 4) Player Bullet 0b00100 (3) 0b10001 (1, 5) Enemy Bullet 0b01000 (4) 0b10010 (2, 5) Walls 0b10000 (5) 0b01111 (1, 2, 3, 4) ============= =============== ==================== Note that in the table the categories and masks are written as binary values to clearly show the logic. To save space only 5 digits are used. The default type of categories and mask in ShapeFilter is an unsigned int, with a resolution of 32 bits. That means that the you have 32 bits to use, in binary notation that is `0b00000000000000000000000000000000` to `0b11111111111111111111111111111111` which can be written in hex as `0x00000000` to `0xFFFFFFFF`. Everything in this example collides with walls. Additionally, the enemies collide with each other. By default, objects exist in every category and collide with every category. Objects can fall into multiple categories. For instance, you might have a category for a red team, and have a red player bullet. In the above example, each object only has one category. The default type of categories and mask in ShapeFilter is unsigned int which has a resolution of 32 bits on most systems. There is one last way of filtering collisions using collision handlers. See the section on callbacks for more information. Collision handlers can be more flexible, but can be slower. Fast collision filtering rejects collisions before running the expensive collision detection code, so using groups or category masks is preferred. Example of how category and mask can be used to filter out player from enemy object: >>> import pymunk >>> s = pymunk.Space() >>> player_b = pymunk.Body(1,1) >>> player_c = pymunk.Circle(player_b, 10) >>> s.add(player_b, player_c) >>> player_c.filter = pymunk.ShapeFilter(categories=0b1) >>> hit = s.point_query_nearest((0,0), 0, pymunk.ShapeFilter()) >>> hit != None True >>> filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS() ^ 0b1) >>> hit = s.point_query_nearest((0,0), 0, filter) >>> hit == None True >>> enemy_b = pymunk.Body(1,1) >>> enemy_c = pymunk.Circle(enemy_b, 10) >>> s.add(enemy_b, enemy_c) >>> hit = s.point_query_nearest((0,0), 0, filter) >>> hit != None True """ group: int = 0 """Two objects with the same non-zero group value do not collide. This is generally used to group objects in a composite object together to disable self collisions. """ categories: int = 0xFFFFFFFF """A bitmask of user definable categories that this object belongs to. The category/mask combinations of both objects in a collision must agree for a collision to occur. """ mask: int = 0xFFFFFFFF """A bitmask of user definable category types that this object object collides with. The category/mask combinations of both objects in a collision must agree for a collision to occur. """ @staticmethod def ALL_MASKS() -> int: return 0xFFFFFFFF @staticmethod def ALL_CATEGORIES() -> int: return 0xFFFFFFFF
63048c65dae2fd68de8ced6939c5035e345be69a
zlatnizmaj/Advanced_Algorithm
/Bai tap Python_KHMT/BST.py
1,487
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri May 25 09:21:16 2018 @author: Administrator """ class Node: def __init__(self, val): self.val = val self.left = None self.right = None class BST: def __init__(self): self.root = None def isEmpty(self): return self.root == None def add(self, val): p = Node(val) tmp=self.root pre = None while (tmp is not None): pre = tmp if(val<=tmp.val): tmp=tmp.left else: tmp=tmp.right if (self.root is None): self.root = p else: if (val > pre.val): pre.right = p else: pre.left = p def preorder(self, t): if(t is not None): print(" ", t.val) self.preorder(t.left) self.preorder(t.right) def postorder(self, t): if(t is not None): print(" ", t.val) self.postorder(t.left) self.postorder(t.right) # tinh chieu cao cua Cay def CalHeight(self, p): if(p is None): return 0 a=self.CalHeight(p.left) b=self.CalHeight(p.right) if(a>b): return a+1 else: return b+1 a=[4,5,7,9,1,2] bst=BST() for i in range(len(a)): bst.add(a[i]) bst.preorder(bst.root) print("Chieu cao cua cay BST: ",bst.CalHeight(bst.root)) #bst.postorder(bst.root)
2345a7d9220d890cb4def299da95b4f6df0abbc2
sohamglobal/core-python
/20-sortlast.py
294
3.65625
4
# generate sorted list of last names in title case def getlastnames(nm): lnm=[] for n in nm: lnm.append(n.split(" ")[1].title()) lnm.sort() return(lnm) nm=["ethan hunt","mohd salah","edan hazard","david luiz","amir khan"] l=getlastnames(nm) print(l) # content of sohamglobal.com
bc97a69be14d09333d61674f469d5fd904892d16
roboGOD/Python-Programs
/sumOfLogs.py
105
3.5
4
import math a = int(raw_input()) summ = 0 for i in range(1,a+1): summ += math.log(i, a) print summ
30173464f4a01a4657e789af79bd9043f0d1204c
pranav1214/Python-practice
/lec10/dp3.py
368
3.53125
4
# wapp to insert rows into student table from sqlite3 import * con = None try: con = connect("test.db") print("Connected") cur = con.cursor() sql = "insert into student values(10, 'Amit')" cur.execute(sql) con.commit() print("Record Saved") except Exception as e: print("Insertion issue", e) finally: if con is not None: con.close() print("Disconnected")
fa5307df33cb36294872b3ac1a90be64d716161f
Bolvis/Pix-Challange-2020-eliminacje
/18.py
109
3.5625
4
for row in input: row = row.split("\t") if int(row[1]) % 2 == 0 and row[2].find("a") != -1: print(row[0])
f3a06cb1599db5e5cfac071d734ac5af7e2115c3
ankita2308/gittest
/factorialnumber.py
146
3.765625
4
def fact(n): if n==1: return 1 else: return n*fact(n-1) print(fact(5)) n=6 f=1 for a in range(1,n+1): f=f*a print(f)
0d680402858c6a0388f1985fb78be61c520a2496
yousstone/python3_learning_note
/do_map.py
103
3.546875
4
#!/usr/bin/python3 #coding=utf8 def f(x): return x * x print(list(map(f,[x for x in range(1,11)])))
7480c6a69f4cf35cbd353e73241d8e22394eb664
tolekes/new_repo
/Exhaustive enumeration.py
655
3.9375
4
possible_result = [111,222,333,444,555,666,777,888,999] #lookup table for the results for initial_number in range(100,999): #the range is between 100 and 999 because the numbers being added are 3 figured total_sum_of_numbers = 3*initial_number # i multiplied by 3 because the three no added are thesame if total_sum_of_numbers in possible_result and str(initial_number%10) in str(total_sum_of_numbers): #the line above provides 2 conditions # in the 2nd condition, %10 returns the last digit and searched for it in the numbers added. print(initial_number) print(total_sum_of_numbers)
3185b83e288b3a33a06db7bf716df0e5c39259a1
AntonFromEarth/from_lessons
/lesson22/les22.py
2,003
4.125
4
def linear_shift(array: list, shift: int) -> list: ''' array = [1, 2, 3, 4] shift = 1 => [0, 1, 2, 3] array = [1, 2, 3, 4] shift = 2 => [0, 0, 1, 2] array = [1, 2, 3, 4] shift = 3 => [0, 0, 0, 1] ''' temp = array[:-shift] temp1 = [0 for i in range(shift)] temp1.extend(temp) return temp1 def circular_shift(array: list, shift: int) -> list: ''' array = [1, 2, 3, 4] shift = 1 => [4, 1, 2, 3] array = [1, 2, 3, 4] shift = 2 => [3, 4, 1, 2] array = [1, 2, 3, 4] shift = 3 => [2, 3, 4, 1] ''' temp = [] for i in range(len(array)): temp.append(array[i-shift]) return temp def nested_parentheses(incoming: str) -> bool: ''' Функція отримує рядок, який складається тільки зі знаків "(" або ")" Рядок вважається таким, що містить коректно вкладені скобки, якщо для кожної скобки "(" існує відповідна ")". Функція повертає булевську змінну, яка показує, чи містить вхідний рядок тільки правильно вкладені скобки - True, чи ні - False incoming = "((())(())())" => True incoming = "" => True incoming = "(((())))" => True incoming = "())" => False incoming = "(()()(())" => False ''' if incoming == "": return True elif incoming[0] == "(" and incoming[len(incoming)-1] == ")": if incoming.count("(") == incoming.count(")"): return True else: return False if __name__ == '__main__': array = [1, 2, 3, 4]; shift = 2 print(linear_shift(array, shift)) print(circular_shift(array, shift)) #incoming = "((())(())())" incoming = "" #incoming = "(((())))" #incoming = "())" #incoming = "(()()(())" #incoming = ")()(" print(nested_parentheses(incoming))
50115ab355ba19d34d5547868db3821fb4064bd7
CelsoAntunesNogueira/Phyton3
/ex066 - Só vai parar quando digitar 999.py
224
3.765625
4
n = 0 s = 0 cont = 0 while True: n = int(input("Digite um número ,se quiser parar digite 999: ")) if n == 999: break cont += 1 s += n print(f"Foram mostrados {cont } números e a soma deles é {s}")
1f7af09fe9c4b54ad03d8e6ef159f4740e3b04dd
go0space/Hello-Python
/5.py
1,921
3.984375
4
# 조건문 : if # if문은 한 라인에 모두 쓸 수 있으므로 문법상 조건식 뒤에 :(콜론) 사용 x = 9 if x < 10: print(x) print("한 자리수") if x < 100: print(x) # 한 라인에 표현 # if문 조건식이 참이 아닐 경우, elif문 사용, 모든 if문이 거짓일 때, else문 블럭 실행 x = 20 if x < 10: print("한 자리수") elif x < 100: print("두 자리수") else: print("세 자리 이상") # if문 안에서 수행하지 않고 그냥 Skip하기 위해서 pass 사용 n = 17 if n < 10: pass else: print(n) # 반복문 # 반복되는 루프를 만들기 위해 while 또는 for 사용 # while문 # while 키워드 다음의 조건식이 참일 경우 실행 i = 1 while i <= 10: print(i) i += 1 # for문 # 컬렉션으로부터 하나씩 요소(element)를 가져와, 루프 내의 문장들을 실행 (foreach 와 비슷) # "for 요소 변수 in 컬렉션" 형식에서 in 뒤에 놓게 됨 sum = 0 for i in range(11): # python 내장 함수 range(n)는 0 ~ n-1까지의 숫자를 갖는 리스트를 리턴. 따라서 0 ~ 10 sum += i print(sum) list = ["This", "is", "a", "book"] # 문자열 요소를 갖는 리스트로 부터 각 문자열들을 순차적으로 출력 for s in list: print(s) # break / continue # break 루프 빠져나오기 # continue 루프 블럭의 나머지 문장들을 실행하지 않고 다음 루프로 직접 돌아가기 i = 0 sum = 0 while True: i += 1 if i == 5: continue if i > 10: break sum += i print(sum) # range # ex) # range(3) mean: stop return: 0, 1, 2 >> 0 ~ 2 # range(3,6) mean: stop, stop return: 3, 4, 5 >> 3 ~ 5 # range(2,11,2) mean: stop, stop, stop return: 2, 4, 6, 8, 10 numbers = range(2, 11, 3) # (2, 11, n) 2 ~ 10 중 2 + n 출력 for x in numbers: print(x) # 출력: 2, 5, 8 for i in range(10): print("Hello")
811f47ff793439a1eb3a8247ad9649f0846561dd
7ss8n/ProgrammingBasics2-Python
/lab07-cachingWebpage-scalingZipedImage/task4/cursor.py
887
3.84375
4
class Cursor: """Represents cursor""" def __init__(self, document): """Initializes variables""" self.document = document self.position = 0 def forward(self): """Move position forward""" self.position += 1 def back(self): """Move position back""" self.position -= 1 def home(self): """Move cursor to the beginning of the line (limitations described in document_test.py)""" while self.document.characters[self.position-1] != '\n': self.position -= 1 if self.position == 0: break def end(self): """Move cursor to the end of the line (limitations described in document_test.py)""" while self.position < len(self.document.characters) and self.document.characters[self.position] != '\n': self.position += 1
f3b7863d5695e387ef70ff73696b52d0568dd075
zed1025/coding
/coding-old/Codechef/Uncle_Johny.py
2,919
3.90625
4
t = int(input()) for i in range(t): n = int(input()) #N denoting the number of songs in Vlad's playlist. numbers = list(map(int, input().split())) #N space-separated integers A1, A2, ..., AN denoting the lenghts of Vlad's songs k = int(input()) #K - the position of "Uncle Johny" in the initial playlist. #store the value of 'Uncle Jhonny' in a variable u_jhonny = numbers[k-1] numbers.sort() new_index = numbers.index(u_jhonny) print(new_index+1) # Problem: Uncle Jhonny # URL: https://www.codechef.com/problems/JOHNY # Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants! # Vlad built up his own playlist. The playlist consists of N songs, each has a unique positive integer length. Vlad likes all the songs from his playlist, but there is a song, which he likes more than the others. It's named "Uncle Johny". # After creation of the playlist, Vlad decided to sort the songs in increasing order of their lengths. For example, if the lengths of the songs in playlist was {1, 3, 5, 2, 4} after sorting it becomes {1, 2, 3, 4, 5}. Before the sorting, "Uncle Johny" was on K-th position (1-indexing is assumed for the playlist) in the playlist. # Vlad needs your help! He gives you all the information of his playlist. Your task is to find the position of "Uncle Johny" in the sorted playlist. # # Input # The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. # The first line of each test case contains one integer N denoting the number of songs in Vlad's playlist. The second line contains N space-separated integers A1, A2, ..., AN denoting the lenghts of Vlad's songs. The third line contains the only integer K - the position of "Uncle Johny" in the initial playlist. # # Output # For each test case, output a single line containing the position of "Uncle Johny" in the sorted playlist. # # Constraints # 1 ≤ T ≤ 1000 # 1 ≤ K ≤ N ≤ 100 # 1 ≤ Ai ≤ 10^9 # # Example # Input: # 3 # 4 # 1 3 4 2 # 2 # 5 # 1 2 3 9 4 # 5 # 5 # 1 2 3 9 4 # 1 # # Output: # 3 # 4 # 1 # # Explanation # In the example test there are T=3 test cases. # Test case 1 # In the first test case N equals to 4, K equals to 2, A equals to {1, 3, 4, 2}. The answer is 3, because {1, 3, 4, 2} -> {1, 2, 3, 4}. A2 now is on the 3-rd position. # Test case 2 # In the second test case N equals to 5, K equals to 5, A equals to {1, 2, 3, 9, 4}. The answer is 4, because {1, 2, 3, 9, 4} -> {1, 2, 3, 4, 9}. A5 now is on the 4-th position. # Test case 3 # In the third test case N equals to 5, K equals to 1, A equals to {1, 2, 3, 9, 4}. The answer is 1, because {1, 2, 3, 9, 4} -> {1, 2, 3, 4, 9}. A1 stays on the 1-th position. # # Note # "Uncle Johny" is a real song performed by The Killers.
162d9cc2c67af4634237b830454f44cee32b8875
Kalson/Python-Treehouse
/pick_a_number_game.py
909
4
4
import random guess_nums = [] allowed_guesses = 5 run = True while run and len(guess_nums) < allowed_guesses: random_num = random.randint(1, 10) new_number = int(input("Guess a number from 1 to 10: ")) print("The random number is {}, your number is {}".format(random_num, new_number)) if new_number < 1 or new_number > 10: guess_nums.append(new_number) print("Wrong guess, that guess isn't between 1 and 10") run = False if len(guess_nums) == 5: run = False print("Game Over! You have no more chances!") elif random_num == new_number and new_number < 10: print("Great guess, CONGRATULATIONS! You Won!") print("It took you {} tries!".format(len(guess_nums))) run = False else: guess_nums.append(new_number) print("Wrong guess, but you got {} chances left".format(allowed_guesses - len(guess_nums)))
667e5a67923fe53f24be040c46cc2004fed2fd44
Grissie/Python
/1-Sintaxis/08-diccionarios.py
1,068
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 13 18:59:48 2020 @author: Gris """ #Creacion de un diccionario vacio x={} x['1']="Uno" x['2']="Dos" x['3']="Tres" x['4']="Cuatro" x['5']="Cinco" print(x) #Diccionario usa clave:valor v={'red':'rojo','green':'verde','blue':'azul'} print(v) #Las claves y valores pueden ser de diferente tipo y={'1':'Uno','flotante':2.34,'complejo':3-4j,'lista':[-5,2,0],'tupla':(1,2,5,6)} print(y) #Modificacion a un diccionario print("Diccionario original: \n",x) x['White']='Blanco' x['Cero']=0 print("Diccionario modificado: \n",x) #Obtener claves o valores del diccionario claves=x.keys() print("Calves del diccionario x: \n",claves) valores=x.values() print("Valores del diccionario x: \n",valores) #Obtener pares clave-valor como una lista de tuplas print(x.items()) #Eliminar un elemento de la lista print(x) #Se elimina el par clave-valor de la clave '4' del(x['4']) print(x) #Iterar sobre un diccionario for i in x: print(i) for i in x: print(x[i]) for clave,valor in x.items(): print(clave,valor)
6e51c817c46503ec2e5058e37b7ce1ea38265bf6
chenyan198804/myscript
/MyPython/MyPro06/oldboy02.py
508
3.8125
4
''' Created on 2016年10月18日 @author: y35chen ''' name = input("please input your name:") age = input("please input your age:") job = input("please input your job:") salary = input("please input your salary:") print(type(name),type(age),type(job),type(salary)) print( ''' Pernal information of %s: Name:%s Age:%s Job:%s Salary:%s -------------------------------------- '''%(name,name,age,job,salary) )
4e6d75cfe2363aaaf7459a8d55abe2857ec463d6
willpiam/oldPythonCode
/7CharecterRandomInt.py
257
3.65625
4
import random #random is a set of instructions for coming up with a number. newNum = random.randint(0000001,1000000)#the value of newNum is decided by #choising a random number between 0000001 to 1000000 print newNum #displays the value of newNum
b98c0666f79411abb69a7af4cb2bd30bfcc2e244
kubos777/cursoSemestralPython
/CodigosClase/Funciones/ejercicio1.py
775
3.921875
4
# -*- coding: utf-8 -*- def datos(): datos=[] nombre=str(input("Ingresa tu nombre: ")) datos.append(nombre) apMat=str(input("Ingresa tu apellido paterno: ")) datos.append(apMat) apPat=str(input("Ingresa tu apellido materno: ")) datos.append(apPat) direc=str(input("Ingresa tu dirección: ")) datos.append(direc) numTel=int(input("Ingresa tu número de teléfono: ")) datos.append(numTel) numCel=int(input("Ingresa tu número de celular: ")) datos.append(numCel) numCta=int(input("Ingresa tu número de cuenta: ")) datos.append(numCta) return datos datos_recibidos=datos() print(datos_recibidos) def formato(lista): print("Datos sin formato: ",lista) print("Datos con formato: ") for i in lista: print(lista.index(i),i) formato(datos_recibidos)
8df47310fe3d517afeea62aa99e732e023495431
munyoudoum/python-bootcamp-2020-01
/pav.munyoudoum19/week02/sc05_sudoku.py
1,000
3.65625
4
def sudoku(x): for ls in x: check = [] if len(ls) != 9: return "Invalid" else: for num in ls: if num < 1 or num > 9: return "Invalid" else: check.append(num) if sorted(check) != list(range(1, 10)): return "Unfinished" for col in range(9): checkv = [] for row in range(9): checkv.append(x[row][col]) if sorted(checkv) != list(range(1, 10)): return "Unfinished" sr = 0 er = 3 sc = 0 ec = 3 for _ in range(9): if sc == 9: sr += 3 er += 3 sc = 0 ec = 3 checkx = [] for row in range(sr, er): for col in range(sc, ec): checkx.append(x[row][col]) sc += 3 ec += 3 if sorted(checkx) != list(range(1, 10)): return "Unfinished" return "Finished"
60e01ca6e310db41b6c5597383d8d4a34f7fef8f
Piotr-Iwanicki/MilestoneProject_MoviesStorage
/movie_storage_app.py
4,762
3.921875
4
from movies_storage import m_storage def search_submenu(): print("_"*48, "\n") print("MOVIE`S SEARCHING - SUBMENU :") print(''' 1 - search by movie title 2 - search by director 3 - search by year of premiere 0 - back to main menu ''') def submenu_search_title(): title = input("Enter movie title: \n") print(f"\n*Searching movie by title: {title}") print("_" * 48) print("Found:\n") count = 1 for i in (m_storage.search_movie_name(title)): print(f"{count}. {i}") count += 1 input("\nPress [Enter] to continue.\n") def submenu_search_director(): director = input("Enter movie director: \n") print(f"\n*Searching movie by director: {director}") print("_" * 48) print("Found:\n") count = 1 for i in (m_storage.search_movie_director(director)): print(f"{count}. {i}") count += 1 input("\nPress [Enter] to continue.\n") def submenu_search_year(): year = input("Enter movie premiere year: \n") print(f"\n*Searching movie by director: {year}") print("_" * 48) print("Found:\n") count = 1 for i in (m_storage.search_movie_year(year)): print(f"{count}. {i}") count += 1 input("\nPress [Enter] to continue.\n") def add_submenu(): print("_"*48, "\n") print("ADDING MOVIE - SUBMENU :") print(''' 1 - add new movie to library 0 - back to main menu ''') def add_movie_storage(): user_new_title = input("Enter title: ") user_new_director = input("Enter director: ") user_new_year = input("Enter movie premiere year: ") user_new_location = input("Enter movie location: ") print("\nData you`ve entered: ") print(f""" Title: {user_new_title} Director: {user_new_director} Year: {user_new_year} Location: {user_new_location} """) global add_title, add_director, add_year, add_location add_title = user_new_title add_director = user_new_director add_year = user_new_year add_location = user_new_location """ def add_to_storage_data(): add_title = user_new_title add_director = user_new_director add_year = user_new_year add_location = user_new_location return add_title, add_director, add_year, add_location """ def show_all_movies(): count = 1 print("\nShowing all movies in storage:") print("_"*48) for movie in m_storage.movie_storage: print(f"{count} - {m_storage.search_movie_engine(movie)}") count += 1 while True: print("\nPiwan`s movies storage application - Gdynia 2020") print("_" * 48, "\n") print(""" MAIN MENU :\n 1 - search a movie 2 - add movie to storage 3 - view all movies in storage 0 - quit """) user_menu_select = (input("\nEnter your number according to the menu: \n")) if user_menu_select == "1": while True: search_submenu() print("_"*48) user_submenu_choice = (input("\nEnter your number according to the submenu: \n")) if user_submenu_choice == "1": submenu_search_title() elif user_submenu_choice == "2": submenu_search_director() elif user_submenu_choice == "3": submenu_search_year() elif user_submenu_choice == "0": break else: print("\nPlease select number only from menu: 1,2,3 or 0 !") elif user_menu_select == "2": while True: add_submenu() print("_"*48) user_submenu_choice = (input("\nEnter your number according to the submenu: \n")) if user_submenu_choice == "1": add_movie_storage() add_acceptation = input("\nEnter '1' to add new movie to storage or '0' to cancel operation: \n") if add_acceptation == '1': print(add_title, add_director, add_year, add_location) m_storage.add_movie_engine(add_title, add_director, add_year, add_location) print("\nThe new movie has been successfully added to the library.") input("Press [Enter] to continue.\n") elif add_acceptation == "0": continue elif user_submenu_choice == "0": break else: print("\nPlease select number only from menu: 1 or 0 !") elif user_menu_select == "3": show_all_movies() print("_"*46) input("\nPress [Enter] to continue.\n") elif user_menu_select == "0": print("\nEnding program.") break else: print("\nPlease select number only from menu: 1,2,3 or 0 !")
1b4d3b3198da8b095e17417844f84e747d0db0c9
quantumjim/jupyter-engine
/engine.py
1,453
3.546875
4
from ipywidgets import widgets from IPython.display import display def run_game(game): ''' Runs the given game. This game engine supports turn based play. In each turn, the player chooses first chooses an option for an input named `a`, and then chooses an option for `b` and one for `c`. The image and the possible options for each input can be altered based on the inputs given. ''' input_a = widgets.ToggleButtons(options=game.options_a) input_b = widgets.ToggleButtons(options=['']) input_c = widgets.ToggleButtons(options=['']) boxes = widgets.VBox([input_a,input_b,input_c]) display(boxes) def given_a(obs_a): if input_a.value not in ['',input_a.options[0]] and (input_a.value in input_a.options): game.given_a(input_a.value) input_b.options = game.options_b def given_b(obs_b): if input_b.value not in ['',input_b.options[0]] and (input_b.value in input_b.options): game.given_b(input_b.value) input_c.options = game.options_c def given_c(obs_c): if (input_c.value not in ['',input_c.options[0]]) and (input_c.value in input_c.options): game.given_c(input_c.value) input_a.options = game.options_a input_b.options = [''] input_c.options = [''] input_a.observe(given_a) input_b.observe(given_b) input_c.observe(given_c)