blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f84b1ee9b4b674ea912c1ea342869972b6b63838
chords-app/chords-app.github.io
/Python/שבוע 1/מעבדה שבוע 1/W1LAB1Q3.py
73
3.5625
4
#W1LAB1Q3 a = int(input('Enter two digit number ')) print(a%10,a,sep="")
2f5b8a2988be72d16004e30896cedcabfdeab0d3
the-polymath/Python-practicals
/Practical 4/prac_4_8.py
489
4.28125
4
# 4.8 Write a Python program to overload + operator. class add: def __init__(self, a): self.a = a def __add__(self, other): return self.a + other.a obj1 = add(int(input("Enter a number : "))) obj2 = add(int(input("Enter a number : "))) obj3 = obj1 + obj2 print("Adding numbers using operator overloading", obj3) print() o1 = add(input("Enter a string : ")) o2 = add(input("Enter a string : ")) o3 = o1 + o2 print("Adding Strings using operator overloading", o3)
599bf13e85e44ce0b5132c83cea6cf26cb6bf6ca
shubee17/HackerEarth
/Searching/monk_takes_a_walk.py
1,070
4.09375
4
""" Today, Monk went for a walk in a garden. There are many trees in the garden and each tree has an English alphabet on it. While Monk was walking, he noticed that all trees with vowels on it are not in good state. He decided to take care of them. So, he asked you to tell him the count of such trees in the garden. Note : The following letters are vowels: 'A', 'E', 'I', 'O', 'U' ,'a','e','i','o' and 'u'. Input: The first line consists of an integer T denoting the number of test cases. Each test case consists of only one string, each character of string denoting the alphabet (may be lowercase or uppercase) on a tree in the garden. Output: For each test case, print the count in a new line. Constraints: SAMPLE INPUT Sample Output: 2 2 nBBZLaosnm 1 JHkIsnZtTL Explanation In test case 1, a and o are the only vowels. So, count=2 """ N = raw_input() vowel = ['a','e','i','o','u'] cnt = 0 for i in range(int(N)): name = raw_input().lower() for j in range(len(name)): if name[j] in vowel: cnt += 1 print cnt cnt = 0
31cfeedc6d91a4ef7f064f4e99ad70eed9ebf97b
Zahidsqldba07/competitive-programming-1
/Codechef/DSA_Learning_Series/FCTRL.py
674
3.78125
4
from math import log T = int(input()) powers_of_5 = [1] for testcase in range(T): N = int(input()) k = int(log(N, 5)) zeros_count = 0 # so, there can be max k^th power of 5 in all the numbers up to N, i.e., in # the factorial of N for i in range(1, k + 1): if len(powers_of_5) > i: zeros_count += N // powers_of_5[i] else: init = powers_of_5[-1] old_length = len(powers_of_5) for power in range(old_length, i + 2): powers_of_5.append(powers_of_5[-1] * 5) # assert len(powers_of_5) >= i zeros_count += N // powers_of_5[i] print(zeros_count)
fd3f470851b944845335d1276d2888de5be8d6c8
hitochan777/kata
/leetcode/python/product-of-array-except-self.py
581
3.578125
4
from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: result = [1] * len(nums) multiplied = 1 for i in range(len(nums)-1): multiplied *= nums[i] result[i+1] *= multiplied multiplied = 1 for i in range(len(nums)-1, 0, -1): multiplied *= nums[i] result[i-1] *= multiplied print(result) return result if __name__ == "__main__": solver = Solution() assert solver.productExceptSelf([1,2,3,4]) == [24,12,8,6]
ec8086e41dd7981ccc6cafa0f9a5d0285d0b370d
da-ferreira/uri-online-judge
/uri/2584.py
308
3.703125
4
from math import tan, radians casos = int(input()) for i in range(casos): lado = int(input()) lado /= 2 altura_triangulo = lado / tan(radians(36)) area_triangulo = 1/2 * lado * altura_triangulo area_pentagono = area_triangulo * 10 print(f'{area_pentagono :.3f}')
e9851f630fded478877776e8ff270fb0ad397f02
inwk6312fall2018/programmingtask2-TawsifAhmad
/task1.py
793
3.90625
4
def crime_list(): # main function fin = open("Crime.csv","r") # reading data from csv file my_dic = dict() my_list = [] my_list2 = [] for line in fin: line=line.strip() line2 = line.split(',') my_list.append(line2[-1]) my_list2.append(line2[-2]) #appending data (only crime name data to list) for i in my_list: #loop list if i not in my_dic: #checking the required data in dictinary my_dic[i]=1 # if no exists it will append else: my_dic[i]+=1 # if exists it will add a count value print ("{:<8} {:<73}".format('Crime_type',' Crime_count')) for key, value in my_dic.items(): # printing tabular format v= value print("{:<8} {:<15}".format(key, v)) crime_list() # function called
d66df55d20e7ce1fc6094219dadafd4372302cab
Genora51/Bitwise
/blib/classbit.py
1,920
3.65625
4
class Bit(object): def __init__(self, binst): self.st = binst def __getitem__(self, index): if index >= len(self.st): return Bit('0') else: return Bit(self.st[-1 - index]) def __add__(self, bit): ast = self.st + bit.st return Bit(ast) def __iter__(self): return (self[n] for n in range(len(self.st))) def __len__(self): return len(self.st) def __or__(self, bit): newst = '' ln = max(len(self), len(bit)) for a in range(ln): newst = bin(int(self[a].st, 2) | int(bit[a].st, 2))[2:] + newst return Bit(newst) def __repr__(self): return ("Bit(%s)" % (repr(self.st))) def __and__(self, bit): newst = '' ln = max(len(self), len(bit)) for a in range(ln): newst = bin(int(self[a].st, 2) & int(bit[a].st, 2))[2:] + newst return Bit(newst) def __int__(self): return int(self.st, 2) def __xor__(self, bit): newst = '' ln = max(len(self), len(bit)) for a in range(ln): newst = bin(int(self[a].st, 2) ^ int(bit[a].st, 2))[2:] + newst return Bit(newst) def __rshift__(self, bit): newst = bin(int(self.st, 2) >> int(bit.st, 2))[2:] return Bit(newst) def __lshift__(self, bit): newst = bin(int(self.st, 2) << int(bit.st, 2))[2:] return Bit(newst) def __invert__(self): newst = '' ln = len(self) for a in range(ln): newst = ('1' if self[a].st == '0' else '0') + newst return Bit(newst) def hash(self): nst = self.st[1:] return Bit(nst) def mxl(self, other): if int(self) > int(other): return Bit(self.st) else: return Bit(other.st)
da414cc2f334962fe35018b8c581b70f43ed66f8
pdhummel/corridor
/Space.py
920
3.59375
4
class Space: def __init__(self): self.occupied_by_player = None self.top_has_wall = False self.bottom_has_wall = False self.left_has_wall = False self.right_has_wall = False self.x = -1 self.y = -1 def clone(self): s = Space() s.top_has_wall = self.top_has_wall s.bottom_has_wall = self.bottom_has_wall s.left_has_wall = self.left_has_wall s.right_has_wall = self.right_has_wall s.x = self.x s.y = self.y s.occupied_by_player = self.occupied_by_player return s def __str__(self): return str(self.x) + "," + str(self.y) + " " #+ \ # ": top=" + str(self.top_has_wall) + \ # ", bottom=" + str(self.bottom_has_wall) + \ # ", left=" + str(self.left_has_wall) + \ # ", right=" + str(self.right_has_wall) + " "
48eded567d82f199b1ca5510c99186c0e96fa476
chuusan/DSCI_522_GROUP_311
/src/data_download.py
1,858
4.09375
4
# author: Group 311 - Tao Huang, Xugang(Kirk) Zhong, Hanying Zhang # date: 2020-01-19 '''This script downloads data file from a url and writes it to local. This script takes a URL and a local file path as the arguments. The URL used for this file should be ended with '.csv', here is an example: "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv" Usage: src/data_download.py --url=<url> --filepath=<filepath> --filename=<filename> Options: --url=<url> URL from where to download the data. This link should be ended with '.csv', eg. "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv" --filepath=<filepath> Local file path to write the data file. The path should not contain any filename or a "/" at the end, eg. "data/raw" --filename=<filename> Local file name. This filename should not include any extension, here is an example: "red_wine" ''' import pandas as pd import requests import os from docopt import docopt opt = docopt(__doc__) def main(url, filepath, filename): try: request = requests.get(url, stream=True) request.status_code == 200 # successful request except Exception as ex: print("URL does not exist.") print(ex) filepath_long = filepath + "/" + filename + ".csv" assert url[-4:] == '.csv', "The URL must point to a csv file!" # check file path if not os.path.exists(filepath): os.makedirs(filepath) # download csv file from url try: data = pd.read_csv(url, sep=";") data.to_csv(filepath_long, index=False) except Exception as e: print("Unable to download. Please check your URL again to see whether it is pointing to a downloadable file.") print(e) if __name__ == "__main__": main(opt["--url"], opt["--filepath"], opt["--filename"])
f50f64565b816b0223de74b1be33c87d9d82cbbd
ActonLeBrein/data-structures
/LinkedList__Intersection_Union.py
2,228
3.828125
4
class Node: def __init__(self,data,next=None): self.val=data self.next=next def getData(self): return self.val def setData(self,data): self.val=val def getNextNode(self): return self.next class LinkedList: def __init__(self,head=None): self.head=head self.size=0 def getSize(self): return self.size def contains(self,data): if self.head==None: return False else: tmp_head=self.head while tmp_head is not None: if tmp_head.val==data or data==None: return True tmp_head=tmp_head.next return False def addNode(self,data): if not self.contains(data): newNode=Node(data,self.head) self.head=newNode self.size+=1 def printNode(self): curr = self.head while curr: print curr.val curr = curr.next class Solution: def Intersection(self,headA,headB): curA,curB,curC=headA.head,headB,LinkedList() while curA is not None: if curB.contains(curA.getData()): curC.addNode(curA.getData()) print 'Found a match' curA=curA.getNextNode() curC.printNode() def Union(self,headA,headB): curA,curB,curC=headA.head,headB.head,LinkedList() while curA is not None: curC.addNode(curA.getData()) curA=curA.getNextNode() while curB is not None: curC.addNode(curB.getData()) curB=curB.getNextNode() curC.printNode() link_A=LinkedList() link_A.addNode(2) link_A.addNode(5) link_A.addNode(10) link_A.addNode(4) link_A.addNode(10) print 'link_A ' link_A.printNode() link_B=LinkedList() link_B.addNode(5) link_B.addNode(1) link_B.addNode(10) link_B.addNode(105) link_B.addNode(2) print 'link_B ' link_B.printNode() sol=Solution() print 'link_C intrsection ' sol.Intersection(link_A,link_B) print 'link_C union ' sol.Union(link_A,link_B)
a1499442cb6f595070059551854c3cd653fc8245
altvec/MITx6.00.1x
/week2/paying_the_minimum.py
811
3.828125
4
# Test 1 balance = 4213 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 # Output should be: # Month: 1 # Minimum monthly payment: 168.52 # Remaining balance: 4111.89 # ... # Month: 12 # Minimum monthly payment: 129.0 # Remaining balance: 3147.67 # Total paid: 1775.55 # Remaining balance: 3147.67 monthlyInterestRate = annualInterestRate / 12.0 totalPaid = 0 for month in range(1, 13): print "Month:", month monthlyPayment = monthlyPaymentRate * balance unpaidBalance = balance - monthlyPayment balance = unpaidBalance + (monthlyInterestRate * unpaidBalance) print "Minimum monthly payment:", round(monthlyPayment, 2) print "Remaining balance:", round(balance, 2) totalPaid += monthlyPayment print "Total paid:", round(totalPaid, 2) print "Remaining balance:", round(balance, 2)
ca0319691a0ee146317fea935cea65c3e80d5a89
iMaureen/practice-deeplearning
/Part 1: Predicting House Prices/part1.py
3,960
3.765625
4
#!/usr/bin/env python # coding: utf-8 ''' Author: Maureen Rojsutivat Source: https://github.com/josephlee94/intuitive-deep-learning ''' # In[1]: import pandas as pd df = pd.read_csv('/Users/mrojsutivat/Documents/COD Advanced Python/practice-deeplearning-master/Part 1: Predicting House Prices/housepricedata.csv') print(df) # In[2]: dataset = df.values # In[3]: print(dataset) # In[4]: X = dataset[:,0:10] Y = dataset[:,10] # In[5]: from sklearn import preprocessing # In[6]: min_max_scaler = preprocessing.MinMaxScaler() X_scale = min_max_scaler.fit_transform(X) # In[7]: print(X_scale) # In[8]: from sklearn.model_selection import train_test_split # In[9]: X_train, X_val_and_test, Y_train, Y_val_and_test = train_test_split(X_scale, Y, test_size=0.3) # In[10]: X_val, X_test, Y_val, Y_test = train_test_split(X_val_and_test, Y_val_and_test, test_size=0.5) # In[11]: print(X_train.shape, X_val.shape, X_test.shape, Y_train.shape, Y_val.shape, Y_test.shape) # In[12]: from keras.models import Sequential from keras.layers import Dense model = Sequential([ Dense(32, activation='relu', input_shape=(10,)), Dense(32, activation='relu'), Dense(1, activation='sigmoid'), ]) # In[13]: model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy']) # In[14]: hist = model.fit(X_train, Y_train, batch_size=32, epochs=100, validation_data=(X_val, Y_val)) # In[15]: model.evaluate(X_test, Y_test)[1] # In[16]: import matplotlib.pyplot as plt # In[17]: plt.plot(hist.history['loss']) plt.plot(hist.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper right') plt.show() # In[20]: plt.plot(hist.history['accuracy']) plt.plot(hist.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='lower right') plt.show() # In[21]: model_2 = Sequential([ Dense(1000, activation='relu', input_shape=(10,)), Dense(1000, activation='relu'), Dense(1000, activation='relu'), Dense(1000, activation='relu'), Dense(1, activation='sigmoid'), ]) model_2.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) hist_2 = model_2.fit(X_train, Y_train, batch_size=32, epochs=100, validation_data=(X_val, Y_val)) # In[22]: plt.plot(hist_2.history['loss']) plt.plot(hist_2.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper right') plt.show() # In[24]: plt.plot(hist_2.history['accuracy']) plt.plot(hist_2.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='lower right') plt.show() # In[25]: from keras.layers import Dropout from keras import regularizers # In[26]: model_3 = Sequential([ Dense(1000, activation='relu', kernel_regularizer=regularizers.l2(0.01), input_shape=(10,)), Dropout(0.3), Dense(1000, activation='relu', kernel_regularizer=regularizers.l2(0.01)), Dropout(0.3), Dense(1000, activation='relu', kernel_regularizer=regularizers.l2(0.01)), Dropout(0.3), Dense(1000, activation='relu', kernel_regularizer=regularizers.l2(0.01)), Dropout(0.3), Dense(1, activation='sigmoid', kernel_regularizer=regularizers.l2(0.01)), ]) # In[27]: model_3.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) hist_3 = model_3.fit(X_train, Y_train, batch_size=32, epochs=100, validation_data=(X_val, Y_val)) # In[29]: plt.plot(hist_3.history['accuracy']) plt.plot(hist_3.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='lower right') plt.show() # In[ ]:
d2fc00abc1e76994cb92974b4d7cd17a56644fbb
miriam1506/PEP21G02
/modul4/app2.py
1,387
3.671875
4
multi_dimensional_list = [[1, [2, [3]]], [4, [5, [6]]], [7, [8, [9]]]] #met1 fin_list=[] for i in multi_dimensional_list: list2=i fin_list.append(list2.pop(0)) for j in list2: list3=j fin_list.append(list3.pop(0)) for k in list3: list4=k fin_list.append(list4.pop(0)) print(fin_list) #met2 # result = [1, 2, 3, 4, 5, 6, 7, 8, 9] def flatten_list(data:list): fin_list = [] for i in data: if type(i) == int: fin_list.append(i) continue print(i) for j in i: if type(j) == int: fin_list.append(j) continue print(j) for m in j: if type(m) == int: fin_list.append(m) continue print(m) for n in m: if type(n) == int: fin_list.append(n) continue print(n) return fin_list result = flatten_list(multi_dimensional_list) print(result) #recursivitate def flatten_list(data :list): fin_list = [] for i in data: if type(i) == int: fin_list.append(i) continue print(i) fin_list.extend(flatten_list(i)) return fin_list result=flatten_list(multi_dimensional_list) print(result)
b51b9f47b8f4d10bfee6015909cfd4726878fec6
ErenBtrk/Python-Fundamentals
/Python Object-Oriented Programming/6-QuizApplication.py
2,275
3.78125
4
# Question Class class Question: def __init__(self,text,choices,answer): self.text = text self.choices = choices self.answer = answer def checkAnswer(self,answer): return self.answer == answer q1 = Question("Which is the best programming language?",["C#","Python","Javascript","C++"],"python") q2 = Question("Which is the main programming language of Unreal Engine?",["C#","Python","Javascript","C++"],"c++") q3 = Question("Which is the central city of Turkey?",["Istanbul","Izmir","Ankara","Corum"],"ankara") q4 = Question("Which one of the basketball players has more scoring leader award?",["Kevin Durant","Michael Jordan","Lebron James","Kobe Bryant"],"michaeljordan") q5 = Question("Who is the owner of space-X?",["Einstein","Jeff Bezos","Bill Gates","Elon Musk"],"elonmusk") # Quiz Class class Quiz: def __init__(self,questions): self.questions = questions self.score = 0 self.questionIndex = 0 def getQuestion(self): return self.questions[self.questionIndex] def displayQuestion(self): question = self.getQuestion() print(f"Question {self.questionIndex + 1} : {question.text}") for q in question.choices: print("-" + q) answer = input("Your Answer : ").lower().replace(" ","") self.guess(answer) self.loadQuestion() def guess(self,answer): question = self.getQuestion() if question.checkAnswer(answer): self.score += 1 print("YOUR ANSWER IS RIGHT! :)") else: print("YOUR ANSWER IS WRONG :(") self.questionIndex += 1 def loadQuestion(self): if len(self.questions) == self.questionIndex: self.showScore() else: self.displayProgress() self.displayQuestion() def showScore(self): print(f"Your score is : {self.score}") def displayProgress(self): totalQuestion = len(self.questions) questionNumber = self.questionIndex + 1 if questionNumber > totalQuestion: print("Quiz is ended.") else: print(f"Question {questionNumber} of {totalQuestion}".center(100,"*")) question_list = [q1,q2,q3,q4,q5] quiz = Quiz(question_list) quiz.loadQuestion()
3ff2bd19b1bfdf023fe9f1f30ac5550309df0e40
amora2860/learning_python
/strings_and_lists.py
1,859
4.1875
4
# Name: # Section: # strings_and_lists.py # ********** Exercise 2.7 ********** def sum_all(number_list): # number_list is a list of numbers total = 0 for num in number_list: total += num return total # Test cases print("sum_all of [4, 3, 6] is:", sum_all([4, 3, 6])) print("sum_all of [1, 2, 3, 4] is:", sum_all([1, 2, 3, 4])) def cumulative_sum(number_list): # number_list is a list of numbers cumul_total = [] flag = True # Ensures that the first value is entered unchanged into the list. for i in number_list: if flag == True: # dont add 4 to its self print(i) cumul_total.append(i) flag = False #makes sure we do not enter this again n = i else: n += i # add the previous number in the list to the next number print(n) cumul_total.append(n) n = i return cumul_total print("The cumulative sum of [4, 3, 6] is:", cumulative_sum([4, 3, 6])) # ********** Exercise 2.8 ********** def report_card(): #ask for class name and the gpa #ask if there are more classes to enter and to enter y or n # list one has names of the classes class_list[] # list two has the GPA's gpa_list[] #take the total of the GPA list and divide by the total number of items in either list len(gpa_list) # # Test Cases ## In comments, show the output of one run of your function. # ********** Exercise 2.9 ********** # Write any helper functions you need here. #VOWELS = ['a', 'e', 'i', 'o', 'u'] #def pig_latin(word): # word is a string to convert to pig-latin ##### YOUR CODE HERE ##### #return "Not Implemented Yet" # Test Cases ##### YOUR CODE HERE ##### # ********** Exercise 2.10 ********** # Test Cases ##### YOUR CODE HERE ##### # ********** Exercise OPT.1 ********** # If you do any work for this problem, submit it here
e9c636963bcce1d2d483e63e32ed44dd2cd2ed91
zaghir/python
/python-opencv/image_contours.py
2,840
3.765625
4
""" Created on Thu Dec 10 22:51:52 2020 @author: yzaghir https://docs.opencv.org/master/d4/d13/tutorial_py_filtering.html Image Contours Find and draw contours En traitement d'image et en vision par ordinateur, on appelle détection de contours les procédés permettant de repérer les points d'une image matricielle qui correspondent à un changement brutal de l'intensité lumineuse. Ces changements de propriétés de l'image numérique indiquent en général des éléments importants de structure dans l'objet représenté. Ces éléments incluent des discontinuités dans la profondeur, dans l'orientation d'une surface, dans les propriétés d'un matériau et dans l'éclairage d'une scène. La détection des contours dans une image réduit de manière significative la quantité de données en conservant des informations qu'on peut juger plus pertinentes. Il existe un grand nombre de méthodes de détection des contours de l'image mais la plupart d'entre elles peuvent être regroupées en deux catégories. La première recherche les extremums de la dérivée première, en général les maximums locaux de l'intensité du gradient. La seconde recherche les annulations de la dérivée seconde, en général les annulations du laplacien ou d'une expression différentielle non linéaire. Contours is crurve joining all the continuous points along the boundary of the image FindContour() function of Opencv helps in extracting the contours from the image Steps Involved : -1 read the image from computer and make a copy of the image to display later -2 Pre-rpocess the image to pass into findContours() function -3 Pass pre-processed image , Contour retrieval mode and Contour approximation method into the findContours() Will return back Detected contours and hierarchy (containing information about the image topology) """ # import cv library import cv2 as cv #read the image from computer img = cv.imread('images/plaque-voiture.jpg') img_original = img.copy() #apply preprocessing, conver to gery, blur and threshold img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) img = cv.GaussianBlur(img, (15, 15), 0) img = cv.Canny(img, 30, 170) thresh, thresh_img = cv.threshold(img, 127, 255, 0) #pass pre-processed image, Contour retrieval mode and Contour approximation #Will return back Detected contours and hierarchy (containing information about the image topology) contours, hierarchy = cv.findContours(thresh_img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) #pass image, contours, contourIdx (-1 means all), color, thickness #contours will be drawn on the image passed cv.drawContours(img_original, contours, -1, (0,255,0), 3) cv.imshow("Preprocessed Image", thresh_img) cv.imshow("Contours Drawn on Original", img_original) print('No of objects detected is {}'.format(len(contours)))
bcd3885085f5b0bbdd866ca7c674b0cc32b740a1
ArmstrongSubero/Python-Programs
/Python and Arduino/06_Graph.py
481
3.546875
4
import numpy as np import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] z = [2, 0, -2, -4, -6] plt.plot(x, y, 'bo') # blue dots plt.plot(x, y, 'r-', label = "y = 2x") # red line plt.plot(x, z, 'g--', label = "y = -x + 4") # green dotted line plt.plot(x, z, 'g^') # green triangles plt.axis([0, 6, -8, 12]) #scale plt.title("My line graph") plt.xlabel("My X axis") plt.ylabel("Y = 2 * X") plt.grid(True) plt.legend() # plot legend plt.show()
e21d3b27ad5666c1791165c5e44bedadb39915b5
ioahKwon/PythonforEngineering
/2015312904_Week 12.py
2,554
3.671875
4
''' Date : 2019. 11. 24. Subject : Processing Data 2 Student ID : 2015312904 Name : 권준우 (Kwon Joon Woo) ''' # assignment_01 a=(input("Enter the first set in CSV format: ")) b=(input("Enter the second set in CSV format: ")) a=set(a.split(",")) b=set(b.split(",")) print('First set:', a) print('Second set:', b) print('Intersection:', a.intersection(b)) # assignment_02 def countAllLetters(a): a = a.lower() counts ={} for num in a: if num.isalpha(): if num in counts: counts[num] += 1 else: counts[num] = 1 return counts a = input('Enter the string: ') print(countAllLetters(a)) # assignment_03 f_s=int(input("Enter the start index of the first interval: ")) f_e=int(input("Enter the end index of the first interval: ")) s_s=int(input("Enter the start index of the second interval: ")) s_e=int(input("Enter the end index of the second interval: ")) print("First Interval:",[f_s,f_e]) print("Second Interval:",[s_s,s_e]) set1=set(range(f_s,f_e+1)) set2=set(range(s_s,s_e+1)) i=set1.intersection(set2) u=set1.union(set2) y=list(i) t=list(u) answer=round(len(y)/len(t),5) print("Intersection of Union(IoU):",answer) # assignment_04 import string import random num_of_ids=int(input("Enter the number of IDs: ")) alphabet_digit_list = string.ascii_letters + string.digits ids = list() def genrateRandomList(maxLimit): rList =[] for i in range(0,11): rList.append(random.randint(0,maxLimit-1)) return rList while len(ids) < num_of_ids: id = "" randomList=genrateRandomList(len(alphabet_digit_list)) for b in randomList: id += alphabet_digit_list[b] if id not in ids: ids.append(id) for id in ids: print(id) # assignment_05 import random a = int(input("Enter the number of times of tossing a coin: ")) b = int(input("Enter the number of consecutive outcomes to find: ")) result = "" for i in range(a): if random.randint(0,1) == 0: result += "H" else: result += "T" print("Outcomes:", result) heads = 0 tails = 0 while len(result) >= b: if result[:b] == "T"*b or result[:b] == "H"*b: if result[:b] == "T" * b: tails += 1 else: heads += 1 result = result[b:] else: result = result[1:] print("The number of", b, "consecutive heads:", heads) print("The number of", b, "consecutive tails:", tails)
e592f6ceb4a664cc48311bf0891fc16be4b85528
DeshawnN/python-progs
/word_counter.py
1,123
4.125
4
#This Program can count the number of words in a string or a .txt file. word_count = 0 def main(): global word_count word_count = 0 print 'Please enter a String or filename' print 'If the file isn\'t in the same directory as the program, be sure to enter the full path! (e.g. C:/xxxx.txt, or E:/xxxxxxx/xxxx.txt' string = raw_input() if string[-4:] == '.txt': read_file(string) else: for word in string.split(): if word.isalpha() == True: word_count += 1 else: pass print 'There are ' + str(word_count) + ' words in that string.' reset() def read_file(file): global word_count word_count = 0 f = open(file, 'r') for line in f: print line f.close() f = open(file, 'r') for word in f.read().split(): word_count += 1 print 'There are ' + str(word_count) + ' words in that file.' f.close() reset() def reset(): print 'Would you like to count another string? (Press y or n)' user_input = raw_input() if user_input == 'y': main() elif user_input == 'n': print 'Thank you for trying my program, Goodbye!' quit() else: print 'Invalid input!' reset() main()
d0cfb30b0fec64cd0eb6467004b9dc1093378e83
demosdemon/rando
/rando/__init__.py
1,591
4.03125
4
#!/usr/bin/env python import random class Rando(object): def __init__(self, weights, rng=random.random): """Initialize the Rando class. :param weights: A sequence of (Item, Weight) tuples. Items of equal weight are selected in ascending order. :type weights: Sequence[Tuple[Any, Union[int, float]]] :param rng: A callable that takes zero arguments and returns a float between 0 (inclusive) and 1 (exclusive). The default uses the Python Standard Library generator. If the generator needs a seed, it should be set prior to invoking this object. :type rng: Callable[[], float] """ self.rng = rng # convert the sequence into a list # in case a generator or other singlely enumerable item is provided weights = list(weights) total_weight = sum(float(w) for (_, w) in weights) self.weights = [ (item, float(weight) / total_weight) for (item, weight) in weights ] def __repr__(self): rng = self.rng if self.rng is random.random: rng = "random.random" else: rng = repr(rng) return "Rando({!r}, {})".format(self.weights, rng) def __iter__(self): return self def __next__(self): rng = self.rng() for item, weight in self.weights: rng -= weight if rng < 0: return item raise RuntimeError("rng value greater than the sum of all weights") # py2 compatibility next = __next__
b211e2ed368bd51aaa0ea2f42cf159b42bbe07a2
roxanavasile/Python
/lesson12/problem1.py
297
3.515625
4
import random list1=[] for count in range(10): numbers=random.randint(1,4) list1.append(numbers) print(list1) print('\n') list2=[] list2=[]+list1 print(list2) print('\n') list3=[] for item in list1: list3.append(item) print(list3) print('\n') list4=[] list4=list1[:] print(list4)
e5b9ea6522a7a7479d861bc73f23510a4363b128
ParthShinde2004/PythonChallenges
/AS259_BinomialTheormCal.py
352
3.78125
4
import math print("(a+bX)^c") a = int(input('a =')) b = int(input('b =')) c = int(input('c =')) x = 2 expansion = str(a**c) + ' + ' + str(b*c) + 'x' while x < (c+1): nCr = (math.factorial(c)) / ((math.factorial(x)) * (math.factorial(c-x))) expansion = expansion + ' + ' + str((c**x) * int(nCr)) + 'x^' + str(x) x = x + 1 print(expansion)
574a72fdd754a2ef96da9c12594d23c0f217a26f
Esk3tit/cs362-extra-credit
/test_two_sum_pytest.py
445
3.578125
4
import two_sum # Just make test functions directly with simple assert statements def test1(): assert two_sum.two_sum([2, 7, 11, 15], 9) == [2, 7] assert two_sum.two_sum([3, 3], 6) == [3, 3] # Invalid input tests (but this time we check such that the invalid inputs actually meet conditions) # and therefore pass the tests def test2(): assert two_sum.two_sum([], 0) is None assert two_sum.two_sum(["3", "3"], 6) != ["3", "3"]
dfe395808ebaf13842bb377f9bf191c42a103a26
Laura-Puckett/INF502
/assignment3.py
10,276
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ## part 1 def inputValues(): walletList = [] for i in range(5): value = float(input('Enter the amount of money: ')) walletList.append(value) return walletList def printSummary(walletList): maxValue = max(walletList) minValue = min(walletList) sumValues = sum(walletList) totalDimes = sumValues*10 print("The fattest wallet has $"+str(maxValue)+" in it.") print("The skinniest wallet has $"+str(minValue)+" in it.") print("All together, these wallets have $"+str(sumValues)+" in them.") print("All together, the total value of these wallets is worth $"+ str(totalDimes) +" dimes") walletList = inputValues() printSummary(walletList) ## Part 2 elements = {"H":{"row":1,"column":1,"atomic number":1,"name":"Hydrogen"}, "He":{"row":1,"column":18,"atomic number":2,"name":"Helium"}, "Li":{"row":2,"column":1,"atomic number":3,"name":"Lithium"}, "Be":{"row":2,"column":2,"atomic number":4,"name":"Beryllium"}, "B":{"row":2,"column":13,"atomic number":5,"name":"Boron"}, "C":{"row":2,"column":14,"atomic number":6,"name":"Carbon"}, "N":{"row":2,"column":15,"atomic number":7,"name":"Nitrogen"}, "O":{"row":2,"column":16,"atomic number":8,"name":"Oxygen"}, "F":{"row":2,"column":17,"atomic number":9,"name":"Fluorine"}, "Ne":{"row":2,"column":18,"atomic number":10,"name":"Neon"}, "Na":{"row":3,"column":1,"atomic number":11,"name":"Sodium"}, "Mg":{"row":3,"column":2,"atomic number":12,"name":"Magnesium"}, "Al":{"row":3,"column":13,"atomic number":13,"name":"Aluminum"}, "Si":{"row":3,"column":14,"atomic number":14,"name":"Silicon"}, "P":{"row":3,"column":15,"atomic number":15,"name":"Phosphorus"}, "S":{"row":3,"column":16,"atomic number":16,"name":"Sulfur"}, "Cl":{"row":3,"column":17,"atomic number":17,"name":"Chlorine"}, "Ar":{"row":3,"column":18,"atomic number":18,"name":"Argon"}, "K":{"row":4,"column":1,"atomic number":19,"name":"Potassium"}, "Ca":{"row":4,"column":2,"atomic number":20,"name":"Calcium"}, "Sc":{"row":4,"column":3,"atomic number":21,"name":"Scandium"}, "Ti":{"row":4,"column":4,"atomic number":22,"name":"Titanium"}, "V":{"row":4,"column":5,"atomic number":23,"name":"Vanadium"}, "Cr":{"row":4,"column":6,"atomic number":24,"name":"Chromium"}, "Mn":{"row":4,"column":7,"atomic number":25,"name":"Manganese"}, "Fe":{"row":4,"column":8,"atomic number":26,"name":"Iron"}, "Co":{"row":4,"column":9,"atomic number":27,"name":"Cobalt"}, "Ni":{"row":4,"column":10,"atomic number":28,"name":"Nickel"}, "Cu":{"row":4,"column":11,"atomic number":29,"name":"Copper"}, "Zn":{"row":4,"column":12,"atomic number":30,"name":"Zinc"}, "Ga":{"row":4,"column":13,"atomic number":31,"name":"Gallium"}, "Ge":{"row":4,"column":14,"atomic number":32,"name":"Germanium"}, "As":{"row":4,"column":15,"atomic number":33,"name":"Arsenic"}, "Se":{"row":4,"column":16,"atomic number":34,"name":"Selenium"}, "Br":{"row":4,"column":17,"atomic number":35,"name":"Bromine"}, "Kr":{"row":4,"column":18,"atomic number":36,"name":"Krypton"}, "Rb":{"row":5,"column":1,"atomic number":37,"name":"Rubidium"}, "Sr":{"row":5,"column":2,"atomic number":38,"name":"Strontium"}, "Y":{"row":5,"column":3,"atomic number":39,"name":"Yttrium"}, "Zr":{"row":5,"column":4,"atomic number":40,"name":"Zirconium"}, "Nb":{"row":5,"column":5,"atomic number":41,"name":"Niobium"}, "Mo":{"row":5,"column":6,"atomic number":42,"name":"Molybdenum"}, "Tc":{"row":5,"column":7,"atomic number":43,"name":"Technetium"}, "Ru":{"row":5,"column":8,"atomic number":44,"name":"Ruthenium"}, "Rh":{"row":5,"column":9,"atomic number":45,"name":"Rhodium"}, "Pd":{"row":5,"column":10,"atomic number":46,"name":"Palladium"}, "Ag":{"row":5,"column":11,"atomic number":47,"name":"Silver"}, "Cd":{"row":5,"column":12,"atomic number":48,"name":"Cadmium"}, "In":{"row":5,"column":13,"atomic number":49,"name":"Indium"}, "Sn":{"row":5,"column":14,"atomic number":50,"name":"Tin"}, "Sb":{"row":5,"column":15,"atomic number":51,"name":"Antimony"}, "Te":{"row":5,"column":16,"atomic number":52,"name":"Tellurium"}, "I":{"row":5,"column":17,"atomic number":53,"name":"Iodine"}, "Xe":{"row":5,"column":18,"atomic number":54,"name":"Xenon"}, "Cs":{"row":6,"column":1,"atomic number":55,"name":"Cesium"}, "Ba":{"row":6,"column":2,"atomic number":56,"name":"Barium"}, "La":{"row":8,"column":3,"atomic number":57,"name":"Lanthanum"}, "Ce":{"row":8,"column":4,"atomic number":58,"name":"Cerium"}, "Pr":{"row":8,"column":5,"atomic number":59,"name":"Praseodymium"}, "Nd":{"row":8,"column":6,"atomic number":60,"name":"Neodymium"}, "Pm":{"row":8,"column":7,"atomic number":61,"name":"Promethium"}, "Sm":{"row":8,"column":8,"atomic number":62,"name":"Samarium"}, "Eu":{"row":8,"column":9,"atomic number":63,"name":"Europium"}, "Gd":{"row":8,"column":10,"atomic number":64,"name":"Gadolinium"}, "Tb":{"row":8,"column":11,"atomic number":65,"name":"Terbium"}, "Dy":{"row":8,"column":12,"atomic number":66,"name":"Dysprosium"}, "Ho":{"row":8,"column":13,"atomic number":67,"name":"Holmium"}, "Er":{"row":8,"column":14,"atomic number":68,"name":"Erbium"}, "Tm":{"row":8,"column":15,"atomic number":69,"name":"Thulium"}, "Yb":{"row":8,"column":16,"atomic number":70,"name":"Ytterbium"}, "Lu":{"row":8,"column":17,"atomic number":71,"name":"Lutetium"}, "Hf":{"row":6,"column":4,"atomic number":72,"name":"Hafnium"}, "Ta":{"row":6,"column":5,"atomic number":73,"name":"Tantalum"}, "W":{"row":6,"column":6,"atomic number":74,"name":"Wolfram"}, "Re":{"row":6,"column":7,"atomic number":75,"name":"Rhenium"}, "Os":{"row":6,"column":8,"atomic number":76,"name":"Osmium"}, "Ir":{"row":6,"column":9,"atomic number":77,"name":"Iridium"}, "Pt":{"row":6,"column":10,"atomic number":78,"name":"Platinum"}, "Au":{"row":6,"column":11,"atomic number":79,"name":"Gold"}, "Hg":{"row":6,"column":12,"atomic number":80,"name":"Mercury"}, "Tl":{"row":6,"column":13,"atomic number":81,"name":"Thallium"}, "Pb":{"row":6,"column":14,"atomic number":82,"name":"Lead"}, "Bi":{"row":6,"column":15,"atomic number":83,"name":"Bismuth"}, "Po":{"row":6,"column":16,"atomic number":84,"name":"Polonium"}, "At":{"row":6,"column":17,"atomic number":85,"name":"Astatine"}, "Rn":{"row":6,"column":18,"atomic number":86,"name":"Radon"}, "Fr":{"row":7,"column":1,"atomic number":87,"name":"Francium"}, "Ra":{"row":7,"column":2,"atomic number":88,"name":"Radium"}, "Ac":{"row":9,"column":3,"atomic number":89,"name":"Actinium"}, "Th":{"row":9,"column":4,"atomic number":90,"name":"Thorium"}, "Pa":{"row":9,"column":5,"atomic number":91,"name":"Protactinium"}, "U":{"row":9,"column":6,"atomic number":92,"name":"Uranium"}, "Np":{"row":9,"column":7,"atomic number":93,"name":"Neptunium"}, "Pu":{"row":9,"column":8,"atomic number":94,"name":"Plutonium"}, "Am":{"row":9,"column":9,"atomic number":95,"name":"Americium"}, "Cm":{"row":9,"column":10,"atomic number":96,"name":"Curium"}, "Bk":{"row":9,"column":11,"atomic number":97,"name":"Berkelium"}, "Cf":{"row":9,"column":12,"atomic number":98,"name":"Californium"}, "Es":{"row":9,"column":13,"atomic number":99,"name":"Einsteinium"}, "Fm":{"row":9,"column":14,"atomic number":100,"name":"Fermium"}, "Md":{"row":9,"column":15,"atomic number":101,"name":"Mendelevium"}, "No":{"row":9,"column":16,"atomic number":102,"name":"Nobelium"}, "Lr":{"row":9,"column":17,"atomic number":103,"name":"Lawrencium"}, "Rf":{"row":7,"column":4,"atomic number":104,"name":"Rutherfordium"}, "Db":{"row":7,"column":5,"atomic number":105,"name":"Dubnium"}, "Sg":{"row":7,"column":6,"atomic number":106,"name":"Seaborgium"}, "Bh":{"row":7,"column":7,"atomic number":107,"name":"Bohrium"}, "Hs":{"row":7,"column":8,"atomic number":108,"name":"Hassium"}, "Mt":{"row":7,"column":9,"atomic number":109,"name":"Meitnerium"}, "Ds""":{"row":7,"column":10,"atomic number":110,"name":"Darmstadtium"}, "Rg""":{"row":7,"column":11,"atomic number":111,"name":"Roentgenium"}, "Cn""":{"row":7,"column":12,"atomic number":112,"name":"Copernicium"}, "Uut""":{"row":7,"column":13,"atomic number":113,"name":"Ununtrium"}, "Uuq""":{"row":7,"column":14,"atomic number":114,"name":"Ununquadium"}, "Uup""":{"row":7,"column":15,"atomic number":115,"name":"Ununpentium"}, "Uuh""":{"row":7,"column":16,"atomic number":116,"name":"Ununhexium"}, "Uus""":{"row":7,"column":17,"atomic number":117,"name":"Ununseptium"}, "Uuo""":{"row":7,"column":18,"atomic number":118,"name":"Ununoctium"}} toContinue = True while toContinue == True: option = input('\n\nTo see all the information for an element, enter 1. \n' 'To see one property for every element in the table, enter 2 \n' 'To enter a new element, enter 3. \n' 'to change the attribues of an element, enter 4. \n' 'to exit the program, enter 5. \n') if option == "1": element = input("Type the element's symbol: ") info = elements[element] print("\n\nName: " + str(info["name"])) print("Atomic number: " + str(info["atomic number"])) print("Row: " + str(info["row"])) print("Column: " + str(info["column"])) elif option == "2": attribute = input('Input the property that you want to see the value for: '+ '\n[name]'+ '\n[atomic number]'+ '\n[row]'+ '\n[column]') for element in elements: print("The " + str(attribute) + " of " + str(element) + " is " + str(elements[element][attribute])) elif option == "3": newSymbol = input("Type the new element's symbol name: ") newName = input("Type the new element's name: ") newNumber = input("Type the new element's atomic number: ") newRow = input("Type the new element's row number: ") newColumn = input("Type the new element's column number: ") elements[newSymbol] = {"name": newName, "atomic number": newNumber, "row": newRow, "column": newColumn} elif option == "4": symbol = input('Enter the symbol of the element to change: ') attribute = input('Enter the name of the attribute to change: ') value = input('Enter the new value for ' + attribute + ": ") elements[symbol][attribute] = value elif option == "5": toContinue = False
ab4e10ca1bb7076a0b8c869d75a3588eba21c517
vmakksimov/PythonFundamentals
/ListAdvanced/6. Group of 10&#39;s.py
448
3.5
4
list_of_numbers = [int(el) for el in input().split(', ')] max_number = max(list_of_numbers) group = 10 while len(list_of_numbers) > 0: nums_group = [] for num in list_of_numbers: if num in range(group - 10, group + 1): nums_group.append(num) for number in nums_group: if number in list_of_numbers: list_of_numbers.remove(number) print(f'Group of {group}\'s: {nums_group}') group += 10
baf779e891335af4d699675d66020e1ae05d1c44
bransfieldjack/Practical_Python
/test_boggle.py
4,944
3.8125
4
import unittest #Imports unittest framework import boggle #imports from boggle.py from string import ascii_uppercase #Imports the ascii characters a-z class TestBoggle(unittest.TestCase): #Creates the TestBoggle class, test suite for Boggle. """ Our test suite for boggle solver """ def test_can_create_an_empty_grid(self): #Method to create an empty grid, self parameter. """ Test to see if we can create an empty grid """ grid = boggle.make_grid(0, 0) #Variable grid, calls the make.grid method in the boggle.py self.assertEqual(len(grid), 0) #Assertion test to test the length of the grid. def test_grid_coordinates(self): #Method to test different coordinates on the grid. """ Test to ensure that all of the coordinates inside of the grid can be accessed. """ grid = boggle.make_grid(2, 2) #Another local grid variable, calls make_grid from boggle.py self.assertIn((0, 0), grid) #Assertion tests to test grid positions. self.assertIn((0, 1), grid) self.assertIn((1, 0), grid) self.assertIn((1, 1), grid) self.assertNotIn((2, 2), grid) #Assertion test to test that some coordinates are NOT in the grid. def test_grid_is_filled_with_letters(self): #Function to confirm that the frid is filled with letters. """ Ensure that each of the coordinates on the grid contains letters. """ grid = boggle.make_grid(2, 3) #Local grid variable, calls make_grid from boggle.py. Passes arguments (2, 3) for letter in grid.values(): #For loop to check for and return letters in the grid. self.assertIn(letter, ascii_uppercase) #Seertion test to confirm that letter is an Ascii character. def test_neighbours_of_a_position(self): """ Ensure that a position has 8 neighbours """ coords = (1, 2) #Variable coords set to (1, 2) neighbours = boggle.neighbours_of_a_position(coords) #Neighbours variable calls function from boggle.py self.assertIn((0, 1), neighbours) #Tests positions on the grid self.assertIn((0, 2), neighbours) self.assertIn((0, 3), neighbours) self.assertIn((1, 1), neighbours) self.assertIn((1, 3), neighbours) self.assertIn((2, 1), neighbours) self.assertIn((2, 2), neighbours) self.assertIn((2, 3), neighbours) def test_all_grid_neighbours(self): """ Ensure that all of the grid positions have neighbours """ grid = boggle.make_grid(2, 2) #Grid variable, makes a 2 x 2 grid (Neighbours of any position are the other two positions in the grid) neighbours = boggle.all_grid_neighbours(grid) #Creates a dictionary self.assertEqual(len(neighbours), len(grid)) #Asserts the correct length of the neighbours dictionary. for pos in grid: #For loop iterates through the grid. others = list(grid) #Creates a list which is the full grid minus the position in question. others.remove(pos) #Removes the position in question from the others list. self.assertListEqual(sorted(neighbours[pos]), sorted(others)) #Asserts that the positions are the neighbours of the position being checked. def converting_a_path_to_a_word(self): #Converts a path to a word. """ Ensure that paths can be converted to words. """ grid = boggle.make_grid(2, 2) #Make a grid 2x2 oneLetterWord = boggle.path_to_word(grid, [(0, 0)]) twoLetterWord = boggle.path_to_word(grid, [(0, 0), (1, 1)]) self.assertEqual(oneLetterWord, grid[(0, 0)]) self.assertEqual(twoLetterWord, grid[(0, 0)] + grid[(1, 1)]) def test_search_grid_for_words(self): """ Ensure that certain patterns can be found in a path_to_word """ grid = {(0, 0): 'A', (0, 1): 'B', (1, 0): 'C', (1, 1): 'D'} twoLetterWord = 'AB' threeLetterWord = 'ABC' notThereWord = 'EEE' full_words = [twoLetterWord, threeLetterWord, notThereWord] stems = ['A', 'AB', 'E', 'EE'] dictionary = stems, full_words foundWords = boggle.search(grid, dictionary) self.assertTrue(twoLetterWord in foundWords) self.assertTrue(threeLetterWord in foundWords) self.assertTrue(notThereWord not in foundWords) def test_load_dictionary(self): """ Test that the 'get_dictionary' function returns a dictionary that has a length greater than 0 """ dictionary = boggle.get_dictionary('words.txt') self.assertGreater(len(dictionary), 0)
8b6c8b1d8844af376ca34e3b487510faa56a1dfd
Segmev/AdventOfCode2020
/day3/main.py
896
3.5
4
class Map: def __init__(self, path) -> None: self.content = [] self.rowsCount = 0 f = open(path, 'r') for l in f: self.rowsCount += 1 self.content.append(l[:-1]) def rowsCount(self): return self.rowsCount def rowsLen(self): return len(self.content[0]) def countTrees(self, stepsX, stepsY): trees = 0 x, y = 0, 0 while y < self.rowsCount: if self.content[y][x % self.rowsLen()] == '#': trees += 1 x += stepsX y += stepsY return trees def main(): map = Map("inputs.txt") stepsList = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] res = 1 print(map.countTrees(stepsList[1][0], stepsList[1][1])) for steps in stepsList: res *= map.countTrees(steps[0], steps[1]) print(res) main()
d037a38487a9196066d09ccc8448f9480014c55a
mohamedmohsen20/python
/sec4-DataTypesVariables/HomeWork/easyChallange/Specialconcatenation.py
310
4.15625
4
''' Write a program that read 3 strings. -For simplicity let’s say input is 3 letters A, B and C The output is A’B”C repeated 10 times -A’B”CA’B”CA’B”CA’B”CA’B”CA’B”CA’B”CA’B”CA’B”CA’B”C ''' a,b,c=input("Enter 3 strings: ").split() s=a+"'"+b+"\""+c print(s*10)
0c180ecf1a0d156c2d5822598bc6d091bf7c78f8
sunilhector/Design-2
/implementQueueUsingStack.py
1,104
4.1875
4
class MyQueue(object): def __init__(self): self.queueinstack=[] self.queueoutstack=[] """ Initialize your data structure here. """ def push(self, x): while(self.queueinstack): top =self.queueinstack.pop() self.queueoutstack.append(top) self.queueinstack.append(x) while self.queueoutstack: top =self.queueoutstack.pop() self.queueinstack.append(top) """ Push element x to the back of queue. :type x: int :rtype: None """ def pop(self): return self.queueinstack.pop() """ Removes the element from in front of queue and returns that element. :rtype: int """ def peek(self): self.queueinstack[-1] """ Get the front element. :rtype: int """ def empty(self): return len(self.queueinstack)>0 if __name__ == '__main__': ls=[23,89,90,99] stack = MyQueue() for element in ls: stack.push(element) print(stack.pop())
78f23a3fc24f2167cf657f4457ffc8c95b337623
Plasmoxy/MaturitaInformatika2019
/python/gui/nahodne_stvorce.py
449
3.515625
4
from tkinter import * from random import randint WIDTH = 500 HEIGHT = 500 root = Tk() c = Canvas(root, width=WIDTH, height=HEIGHT) for i in range(1, 11): a = randint(30, 100) x = randint(0, WIDTH-a) # neklipuj mimo obrazovky y = randint(0, HEIGHT-a) # neklipuj mimo obrazovky c.create_rectangle(x, y, x+a, y+a) c.create_text(x + a//2, y + a//2, fill="darkblue", font="Times 10 italic bold", text=f"{i}") c.pack() mainloop()
45f53b173fa2871e7f4594d897ee367ec67ad5b3
jirayasama89/Universidade
/Métodos numéricos/Trabalho 1/questao9.py
558
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 20 12:45:52 2016 @author: Caio Cid Santiago """ def f(x): return ((x)**3)- 7*((x)**2)+ 8*(x) - 0.35 def deriv(f,x,delta): return (f(x + delta*x) - f(x)) / delta*x def ModifiedSecant(f,x,delta,tol): i = 1 xns = x - (f(x)/deriv(f,x,delta)) while abs(f(xns))>tol : xns = xns - (f(xns)/deriv(f,xns,delta)) i = i + 1 return xns,i raiz,iterações = ModifiedSecant(f,0.05,0.000001,0.00000001) print("Raiz da função: ",raiz) print("Iterações: ",iterações)
6efbb7e046632b3ec3193e0455b373188c623d2f
swigder/pos_tagger
/pos_tagger/hidden_markov_model.py
5,357
3.765625
4
from utilities.utilities import binary_search class HiddenMarkovModel: """ Implementation of a Hidden Markov Model given counts of hidden states and observations as seen in training data """ START = "<START>" def __init__(self, hidden_bigram_frequencies, observation_frequencies, state_counts, observations, unseen_observation_handler): """ :param hidden_bigram_frequencies: map of maps, where outside map is prior state, inside map is current state, and value is bigram count of prior state, current state :param observation_frequencies: map of maps, where outside map is state, inside map is observations, and value is count of the given observation in the given state :param state_counts: map of states to the number of times that state occurs (for converting counts to probabilities) :param unseen_observation_handler handler that will give probabilities for observations that were unseen in the training data """ self.hidden_bigram_frequencies = hidden_bigram_frequencies self.observation_frequencies = observation_frequencies self.state_counts = state_counts self.states = [state for state in state_counts.keys() if state != self.START] self.observations = sorted(observations) self.unseen_observation_handler = unseen_observation_handler def decode(self, observations): """ Decodes a given observation into the most likely sequence of hidden states, using Viterbi :param observations: list of observations :return: most probable list of hidden states """ matrix = [{}] for state in self.states: probability_state_given_previous = self.get_bigram_probability(self.START, state) probability_word_given_state = self.get_observed_probability(state, observations[0]) probability = probability_state_given_previous * probability_word_given_state backpointer = None if probability > 0: matrix[0][state] = (probability, backpointer) for i, observation in enumerate(observations[1:], 1): matrix.append({}) for state in self.states: probability_observation_given_state = self.get_observed_probability(state, observation) if probability_observation_given_state == 0: continue best_probability, best_backpointer = 0, None for previous_state, previous_value in matrix[i-1].items(): probability_previous, _ = previous_value probability_current_given_previous = self.get_bigram_probability(previous_state, state) current_probability = probability_previous * probability_current_given_previous if current_probability > best_probability: best_probability, best_backpointer = current_probability, previous_state probability = best_probability * probability_observation_given_state if probability > 0: matrix[i][state] = (probability, best_backpointer) # reconstruct the best path best_probability = 0 backpointer = None for state, value in matrix[-1].items(): probability, _ = value if probability > best_probability: best_probability = probability backpointer = state if best_probability == 0: print("No possible result found for observations", observations) return ['<UNK>'] * len(observations) states = [] for i in range(len(observations), 0, -1): states.append(backpointer) _, backpointer = matrix[i-1][backpointer] states.reverse() return states def get_bigram_probability(self, prior, state): """ Gets the probability of a state given a prior state :param state: the current state :param prior: the previous state :return: probability of current state given prior state, defined as as count(prior, current) / count(prior) """ priors = self.hidden_bigram_frequencies[prior] return priors[state] / self.state_counts[prior] if state in priors else 0 def get_observed_probability(self, state, observation): """ Gets the probability of an observation given a state. This is not a true probability, as observations that are not part of the list of observations will be given a weight as specified by the unseen_observation_handler :param state: the current state of the model :param observation: the observation :return: probability of the observation given the state, defined as count(observation, state) / count(state), or value provided by the unseen_observation_handler if the observation does not exist in the list of possible observations """ if binary_search(self.observations, observation) == -1: return self.unseen_observation_handler.get_probability(state, observation) observations = self.observation_frequencies[state] return observations[observation] / self.state_counts[state] if observation in observations else 0
6c908f73930344a8a3fd56578beb89a427b75a0f
bishajitchakraborty/Python_Basic
/String.py
224
4
4
print("Enter your input:") string=str(input()) print(string) print(string[0]) print(string[3]) print(string[:4]) print(string[1:4]) print(string) print(string[-3:]) print(string[-4:-1]) print(string[::-1])#reverse order
4cba62d7ab54a80e6c1ada200107eddda0460eba
dfeusse/codeWarsPython
/08_august/26_palindromeChecker.py
928
3.953125
4
''' According to wiki palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers. Famous examples include "A man, a plan, a canal, Panama!", "Amor, Roma", "race car" and "No 'x' in Nixon". All requirements from definition should be fulfilled. In case of null input (None for Python) return false. ''' import string def palindrome(s): return "".join(l for l in s if l not in string.punctuation).lower().replace(" ", "") == "".join(l for l in s if l not in string.punctuation).lower().replace(" ", "")[::-1] if s != None else False print palindrome("A man, a plan, a canal, Panama!") ''' def is_palindrome(s): if s is not None: wor=[wo.lower() for wo in s if wo.isalnum()] if wor==wor[::-1]:return True return False else: return False '''
7464c2f4354d1c83e602e7c77bb16e2b259a5623
XinZhaoFu/leetcode_moyu
/771宝石与石头.py
827
3.921875
4
"""  给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。 J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。 示例 1: 输入: J = "aA", S = "aAAbbbb" 输出: 3 """ class Solution(object): def numJewelsInStones(self, jewels, stones): """ :type jewels: str :type stones: str :rtype: int """ res = 0 stones_dict = {} for ch in stones: stones_dict[ch] = stones_dict.get(ch, 0) + 1 for ch in jewels: if ch in stones_dict: res += stones_dict[ch] return res
72fabb55566007b51f47d8efb4f2360b98803e1a
GalyaBorislavova/SoftUni_Python_Fundamentals_January_2021
/5_List Advanced/Exercises and More Exercises/07. Decipher This.py
554
3.75
4
words = input().split(" ") decipher = "" for word in range(len(words)): current = words[word] new_word = [] nums_in_word = "" for letters in range(len(words[word])): if current[letters].isnumeric(): nums_in_word += current[letters] else: new_word.append(current[letters]) new_word.insert(0, chr(int(nums_in_word))) new_word[1], new_word[-1] = new_word[-1], new_word[1] for l in new_word: decipher += l if not word == len(words) - 1: decipher += " " print(decipher)
bacf84bd3a1bd104ca13a8a3c41b0bb9dd295dcb
cIvanrc/problems
/ruby_and_python/8_math/random_serie.py
237
4.03125
4
# write a python program to generate a series of unique random numbers import random n = int(input("Say a number: ")) choices = list(range(n)) a = random.shuffle(choices) print(choices.pop()) while choices: print(choices.pop())
7460da6a85c46b93c0381d547ac9d8772a6b0591
Egor-05/Yandex2
/3/2dop.py
3,413
3.5625
4
from itertools import product class Bell: def __init__(self, *args, **kwargs): self.args_positional = [] for arg in args: self.args_positional.append(arg) self.args_named = {arg: kwargs[arg] for arg in sorted(kwargs)} def print_info(self): result = '' for i in self.args_named: result += f'{i}: {self.args_named[i]}, ' if result != '' and len(self.args_positional): result = result[:-2] + '; ' elif not len(self.args_positional): result = result[:-2] for i in self.args_positional: result += f'{i}, ' if len(self.args_positional): result = result[:-2] print(result.strip() if result != '' else '-') class BigBell(Bell): a = 0 def sound(self): if not self.a: print('ding') self.a = 1 else: print('dong') self.a = 0 def name(self): return 'BigBell' class LittleBell(Bell): def sound(self): print("ding") def name(self): return 'LittleBell' class BellTower: def __init__(self, *args): self.bells = [] for i in args: if type(i) not in [tuple, list]: i = [i] for j in i: self.bells.append(j) def append(self, bell): self.bells.append(bell) def sound(self): for bell in self.bells: bell.sound() print('...') def print_info(self): for i in range(len(self.bells)): print(f'{i + 1} {self.bells[i].name()}') self.bells[i].print_info() print() class SizedBellTower(BellTower): def __init__(self, *args, size=10): super().__init__(args) self.size = size if len(self.bells) > size: self.bells = self.bells[len(self.bells) - size:] def append(self, bell): if len(self.bells) < self.size: self.bells.append(bell) else: self.bells = self.bells[1:] self.bells.append(bell) class TypedBellTower(BellTower): def __init__(self, *args, bell_type=LittleBell): super().__init__(args) self.b_t = 'LittleBell' if bell_type == LittleBell else 'BigBell' self.cleaner() def cleaner(self): a = self.bells.copy() self.bells.clear() for i in a: if i.name() == self.b_t: self.bells.append(i) def append(self, bell): if bell.name() == self.b_t: self.bells.append(bell) bells = [BigBell(), BigBell("медный"), BigBell(цвет="серебристый"), BigBell("звонкий", диаметр="5 см"), BigBell("ля"), LittleBell("звонкий"), LittleBell(нота="до"), LittleBell(), LittleBell("тихий", "мелодичный", вес="100 грамм", нота="ре"), LittleBell()] bt_default = SizedBellTower(*bells) bt_1 = SizedBellTower(*bells, size=1) bt_2 = SizedBellTower(*bells, size=2) bt_10 = SizedBellTower(*bells, size=10) bt_11 = SizedBellTower(*bells, size=11) bt_20 = SizedBellTower(*bells, size=20) bts = [bt_default, bt_1, bt_2, bt_10, bt_11, bt_20] bb = BigBell("самый звонкий") lb = LittleBell("самый маленький") for bt in bts: bt.append(bb) bt.append(lb) for bt in bts: bt.print_info()
ff84cc66b24e7d0a60d97339dc43a8d6754220c8
twok020101/Password_Manager
/Main.py
7,278
3.734375
4
import finder import adder import updater import deleter import displayer import getpass import sys import key_manager import os from easygui import passwordbox def password_validator(password): _PASSWORDMAIN = "Password" #change root password if password == _PASSWORDMAIN: return "Access granted" return "Dennied!!" if __name__ == '__main__': ft=int(input("Is this your first time using program?\n" "1. Yes \n" "2. No \n")) if ft==1: key_manager.genwrite_key() while True: root_pass = passwordbox("Enter root password: ") # root_pass="Sonubitu@24" check = password_validator(root_pass) if check == "Access granted": print(check) path=input("Enter path of key file: ") if os.path.exists(path): while True: x = int(input("Enter the choice: \n" "1. Check for password \n" "2. Add a new password \n" "3. Update password \n" "4. Delete password\n" "5. Display all passwords \n" "6. Exit\n")) if x == 1: while True: choice = int(input("1. Find using username \n" "2. Find using website \n" "3. Go back previous menu \n" "4. Exit\n")) if choice == 1: flag = False username = input("Please enter username of the site you want to access: ") finder.finder_username(username,path) break elif choice == 2: flag = False website = input("Enter name of the website: ") finder.finder_website(website,path) break elif choice == 3: break elif choice == 4: sys.exit() else: print("Invalid input!!") elif x == 2: while True: choice = int(input("1. Confirm adding new password \n" "2. Return back to previous menu\n" "3. Exit\n")) if choice == 1: adder.add_new(path) break elif choice == 2: break elif choice == 3: sys.exit() else: print("Invalid input!!") elif x == 3: while True: choice = int(input("1. Update using username: \n" "2. Update using website name: \n" "3. Return to previous menu \n" "4. Exit\n")) if choice == 1: username = input("Enter username: ") status = updater.password_update_username(username,path) if status == "Done": print(f"Password updated for {username}") break else: print(status) break elif choice == 2: website = input("Enter website: ") status = updater.password_update_name(website,path) if status == "Done": print(f"Password updated for {website}") break else: print(status) break elif choice == 3: break elif choice == 4: sys.exit() else: print("Invalid input!!") elif x == 4: while True: choice = int(input("1. Delete using username: \n" "2. Delete using website \n" "3. Return to previous menu \n" "4. Exit\n")) if choice == 1: flag = False username = input("Enter username: ") status = deleter.delete_username(username,path) if status == "Done": print(f"Password deleted for {username}") break else: print(status) break elif choice == 2: website = input("Enter website name: ") status = deleter.delete_website(website,path) if status == "Done": print(f"Password deleted for {website}") break else: print(status) break elif x == 5: displayer.display(path) elif x == 6: print("Thank you!\n" "Developed by twok020101!") sys.exit() else: print("Invalid input!!") else: print("No key file found access denied!") else: print(check) x = int(input("Do you want to enter password again? \n" "1. Yes \n" "2. No\n")) flag = True while flag: if x == 1: flag = False continue elif x == 2: flag = False break else: print("Invalid input!")
54222ed90f522b4538ef709c4d7ade0a1d2af8bb
ShashankPatil20/Crash_Course_Python
/Week_2/Conditions_Quiz.py
2,025
4.21875
4
"""Question 2 Complete the script by filling in the missing parts. The function receives a name, then returns a greeting based on whether or not that name is "Taylor". """ def greeting(name): if name == "Taylor": return "Welcome back Taylor!" else: return "Hello there, " + name print(greeting("Taylor")) print(greeting("John")) """ 3.Question 3 What’s the output of this code if number equals 10? """ def equal(number): if number > 11: print(0) elif number != 10: print(1) elif number >= 20 or number < 12: print(2) else: print(3) equal(10) """ Is "A dog" smaller or larger than "A mouse"? Is 9999+8888 smaller or larger than 100*100? Replace the plus sign in the following code to let Python check it for you and then answer. """ print("A dog" > "A mouse") print(9999+8888 > 100*100) # Result False True """ If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size? """ def calculate_storage(filesize): block_size = 4096 # Use floor division to calculate how many blocks are fully occupied full_blocks = filesize // block_size # Use the modulo operator to check whether there's any remainder partial_block_remainder = block_size % filesize # Depending on whether there's a remainder or not, return # the total number of bytes required to allocate enough blocks # to store your data. if partial_block_remainder > 0: return 8192 else: return 4096 # pass return full_blocks print(calculate_storage(1)) # Should be 4096 print(calculate_storage(4096)) # Should be 4096 print(calculate_storage(4097)) # Should be 8192 print(calculate_storage(6000)) # Should be 8192
ef97d9c62ca29aa6f9da671b1e825ac0682459c6
allensallinger/compsci
/reverse_string.py
497
4.25
4
# reverse_string.py # given a string return the string with the words reversed def main(): print("main") a = 1 s0 = "The cat ate the mouse" print("Input::: " + s0) ts0 = "ehT tac eta eht esuom" assert( ts0 == reverse_string(s0)) def reverse_string(s): alpha = "abcdefghijklmnopqrstuvwxyz"; reversed_s = s[::-1] split_reversed_s = " ".join(reversed_s.split(" ")[::-1]) print("Reversed::: " + split_reversed_s) return split_reversed_s if __name__ == "__main__": main()
728ee7df6d99cf76a87eaf551836a02cf786705e
andjelao/Zbirka1
/str3_zad1.py
241
3.625
4
# stampa da li je uneseni broj djeljiv sa 3 n = int(input("Unesite zeljeni broj: ")) def djeljiv_sa_3(n): if n % 3 == 0: print("Broj je djeljiv sa 3. ") else: print("Broj nije djeljiv sa 3. ") djeljiv_sa_3(n)
3a55a9f7fb3b5d0778081db8ebebc704af24d9f1
daniel-reich/ubiquitous-fiesta
/HpJCBwggQMDLWTHsM_10.py
142
3.6875
4
def average_word_length(txt): lengths = [len(word.rstrip(',.!?')) for word in txt.split()] return round(sum(lengths) / len(lengths), 2)
f3a1737de20e6ab7ecbb95120fbcca9a0cf24d9b
PrateekKumarSingh/Data-Structures-and-Algorithms
/data structures/linked list/doubly-linked-lists.py
2,778
4.0625
4
class Node(object): def __init__(self, data, next = None, prev = None): self.data = data self.next = next self.prev = prev def getNode(self): return "{} -> {}".format(self.data, self.next) class DoublyLinkedList(object): def __init__(self): self.head = None def printLinkedList(self): temp = self.head print('Doubly Linked List : Head <-> ',end='') pr = None while temp: print(f'{temp.data} <-> ', sep=' ',end='') pr = temp temp = temp.next print('None') print('Reversed Doubly Linked List : None <-> ',end='') temp = pr while temp: print(f'{temp.data} <-> ', sep=' ',end='') temp = temp.prev print('Head\n') def insertAtStart(self,data): if self.head == None: newNode = Node(data) self.head = newNode else: newNode = Node(data) self.head.prev = newNode newNode.next = self.head self.head = newNode def insertBetween(self,prevNode,data): if prevNode.next != None: newNode = Node(data) newNode.next = prevNode.next prevNode.next.prev = newNode newNode.prev = prevNode prevNode.next = newNode def insertAtEnd(self, data): newNode = Node(data) temp = self.head while temp.next != None: temp = temp.next temp.next = newNode newNode.prev = temp # # delete on basis of data def delete(self, item): if self.head == item: self.head = None else: temp = self.head while temp.next != None: if temp.next.data == item: prev = temp next = temp.next.next temp.next.next.prev = prev prev.next = next print('deleted: ',item) temp = temp.next # search on basis of data def search(self,item): temp = self.head while temp.next != None: if temp.data == item: print(f'Found: {item}') break temp = temp.next ll = DoublyLinkedList() myNode0 = Node(1) myNode1 = Node(3) myNode2 = Node(4) ll.head = myNode0 ll.head.prev = None ll.printLinkedList() ll.head.next = myNode1 ll.head.next.prev = myNode0 ll.printLinkedList() ll.head.next.next = myNode2 ll.head.next.next.prev = myNode1 ll.printLinkedList() ll.insertAtEnd(5) ll.insertAtEnd(6) ll.printLinkedList() ll.insertBetween(myNode0,2) ll.printLinkedList() ll.search(5) ll.delete(5) ll.printLinkedList() # ll.delete(7) # ll.printLinkedList()
6710867e20705f0b7eef83713f6bbd7c2692847a
LDZ-RGZN/b1804
/1804/二/day7/私有.py
800
3.90625
4
class People: def __init__(self,name,salary): self.__name = name #私有化属性,只能自己访问 self.salary = salary def get_name(self): return self.__name def set_name(self,n): #?set 更改 self.__name = n return self.__name def get_salary(self): #获得 return self.salary def __send_msg(self): return '验证码发送成功' #这里的私有化只有自己才可以访问 def get_msg(self,p): '''从这里调用可以查看验证码''' if p == 123 : print (self.__send_msg()) else : print ('验证码错误') xh = People('小花',8000) print (xh.get_name()) xh.set_name('小王') print (xh.get_name()) print (xh.get_salary()) print (xh.get_msg(111))
394416fde3f67b032794986ee3cfb40fa9afd653
RizkyKhapidsyah/PackingNilaiKeDalamList__PY
/Program.py
120
3.609375
4
a = 10 b = 20 c = 30 d = [None] * 3 d[0] = a d[1] = b d[2] = c print(f'a = {a}, b = {b}, c = {c}') print(f'd = {d}')
77e4538179d2bbf2c0d1b422f0407fb1496bad74
jre233kei/procon-atcoder
/ABC120/D.py
952
3.5
4
n, m = map(int, input().split()) cons = [] for i in range(m): a, b = map(int, input().split()) cons.append([a, b]) cons.append([b, a]) cons = cons[::-1] def is_connected(a, b, closed): if [a, b] in cons: return 1 if [b, a] in cons: return 1 open = [] for c in cons: if c in closed: continue if c[0] == a or c[1] == a: open.append(c) for o in open: if o[0] == a: return is_connected(o[1], b, closed + open) if o[1] == a: return is_connected(o[0], b, closed + open) return 0 def check_connection(): res = 0 for i in range(1,n+1): for j in range(i+1, n+1): ic = is_connected(i, j, []) print('{0} {1} {2}'.format(i, j, ic)) res += ic return res for i in range(m): cons.pop() cons.pop() print(cons) print(n * (n - 1) // 2 - check_connection())
e689e3248f425e4373bdb9d82dd6780ab0b3d491
AlbertoMorillo/TecnicaDeProgramacion
/MateriaHome.py
2,268
3.5625
4
from conexionMateria import MateriaDAO import funcionesMateria def MateriaHome(): continuar = True while(continuar): opcionCorrecta = False while(not opcionCorrecta): print("##### Menu principal ####") print("1 ##### Listar materias ####") print("2 ##### Registrar materias ####") print("3 ##### Actualizar materias ####") print("4 ##### Eliminar materias ####") print("5 ##### Salir ####") print("#######################") opcion = int(input("Selecciona una opcion: ")) if opcion < 1 or opcion > 5: print("Opcion incorrecta, ingrese nuevamente.") elif opcion == 5: continuar = False break else: opcionCorrecta = True ejecutarOpcion(opcion) def ejecutarOpcion(opcion): dao = MateriaDAO() if opcion == 1: try: materia = dao.listarMaterias() if len(materia) > 0: funcionesMateria.listarMaterias(materia) else: print("No se encuentran cursos") except: print("Ocurrio un error.") elif opcion == 2: materia = funcionesMateria.pedirDatosRegistro() try: dao.registrarMateria(materia) except: print("Ocurrio un error.") elif opcion == 3: materia = dao.listarMaterias() if len(materia) > 0: curso = funcionesMateria.pedirDatosActualizacion(materia) if curso: dao.actualizarMateria(curso) else: print("Codigo de materia no encontrado.") elif opcion == 4: try: materia = dao.listarMaterias() if len(materia) > 0: codigoEleminar = funcionesMateria.pedirDatosEliminacion(materia) if not(codigoEleminar == ""): dao.eliminarMateria(codigoEleminar) else: print("Codigo de materia no encontrado.") else: print("No se encontro materia.") except: print("Ocurrio un error.") else: print("Opcion no valida.")
62dd6dfe195c916f54a33d8e266a4b6464a80750
MarcusPlieninger/codility
/ch1_BinaryGap.py
559
3.515625
4
def solution(N): # set up variables to store max_gap = 0 current_gap = 0 # skip trailing zeros until hit 1 while N > 0 and N%2 == 0: N //=2 # gap tracker: count, compare while N > 0: if N%2 == 0: current_gap +=1 elif current_gap > max_gap: max_gap = current_gap current_gap = 0 elif current_gap < max_gap: current_gap = 0 elif current_gap == max_gap: current_gap = 0 N //=2 # here's the result! return max_gap
097c073e349213c8d3eeba8ca33e670365f98933
dianatibre/University
/Year1Sem1/FundamentalsOfProgramming/Battleship/board2.py
694
3.65625
4
from texttable import Texttable class Board: def __init__(self): self._data = [0] * 36 def set_square(self, row, col, value): self._data[row * 6 + col] = value def draw(self): board = Texttable() for i in range(7): row = [] for j in range(7): if i == 0 and j == 0: row.append(0) elif i == 0: row.append(j) elif j == 0: row.append(i) else: row.append(self._data[6 * (i - 1) + j - 1]) board.add_row(row) print(board.draw()) board = Board() board.draw()
a20d67a2c316a9ac7c0da4a542bc69cc9d7b0c39
Kcheung42/Leet_Code
/Design/0535_encode_and_decode_tiny_url.py
2,188
3.71875
4
# **************************************************************************** # # # # ::: :::::::: # # 535_Encode_and Decode_TinyURL.py :+: :+: :+: # # +:+ +:+ +:+ # # By: kcheung <kcheung@42.fr> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2018/01/12 16:21:38 by kcheung #+# #+# # # Updated: 2018/01/12 16:39:40 by kcheung ### ########.fr # # # # **************************************************************************** # ''' Time: O(1) Space: O(n) TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL ''' import random class Codec: def __init__(self): self.tiny_urls = {} def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ num_form = random.randint(1, 1E10) while num_form in self.tiny_urls: num_form = random.randint(1,1E10) self.tiny_urls[num_form] = longUrl return ('http://tinyurl.com/' + str(num_form)) def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ num_form = int(shortUrl[19:]) return self.tiny_urls[num_form] # Your Codec object will be instantiated and called as such: url = 'https://leetcode.com/problems/design-tinyurl' codec = Codec() print(codec.decode(codec.encode(url)))
af1721853d3df24ee2ce2a970db547ce81903ad4
bmadren/MadrenMATH361B
/IntroToProgramming/PartialProd_Madren.py
783
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 4 22:08:34 2019 @author: benma """ #%% import numpy as np N = 50 x = np.zeros([N]) term = 1 for nn in range(2, N): term *= (nn**3 - 1)/(nn**3 + 1) x[nn] = term print("The first 15 terms are ", x[:15], " and the last 15 terms are ", x[-15:]) #%% import numpy as np from math import exp N = 50 x = np.zeros([N]) term = 1 for nn in range(1, N): term *= (exp(nn/100))/(nn**10) x[nn] = term print("The first 15 terms are ", x[:15], " and the last 15 terms are ", x[-15:]) #%% import numpy as np from math import exp N = 50 x = np.zeros([N]) term = 1 for nn in range(1, N): term *= (exp(nn/10))/(nn**100) x[nn] = term print("The first 15 terms are ", x[:15], " and the last 15 terms are ", x[-15:])
f5d7fb51d6c48345c2a72dc41b287160cad3db75
xpessoles/Informatique
/Exercices/01_python_bases/PYB-523/PYB-523-cor.py
1,904
3.859375
4
def reste_a_payer(p,t,m,d): """p = montant du pret en euros t = taux mensuel m = mensualites d = duree en annees Calcule le montant restant a payer a l'echeance du pret""" dette = p for mois in range(d*12): # Inv : dette est dû au début du mois dette = dette*(1+t)-m return dette def somme_totale_payee(p,t,m,d): """p = montant du pret t = taux m = mensualites d = duree en annees Calcule le montant total paye""" return reste_a_payer(p,t,m,d) + 12*d*m def cout_total(p,t,m,d): """p = montant du pret t = taux m = mensualites d = duree en annees Calcule le cout total du credit""" return somme_totale_payee(p,t,m,d) - p def duree_mensualite(p,t,m): """Durée du prêt p = montant prêté t = taux mensuel m = mensualité""" emprunt = p d = 0 while (1+t)*emprunt >= m: print(emprunt) # Inv : emprunt est dû au début du mois d d = d+1 emprunt = (1+t)*emprunt-m return d import matplotlib.pyplot as plt def tracer_mensualite(p,t,m): """Trace p = montant prêté t = taux mensuel m = mensualité""" emprunt = p d = 0 mois=[]#numero de mensualite capital_rd=[]#capital restant du interets=[] while (1+t)*emprunt >= m: # Inv : emprunt est dû au début du mois d d = d+1 emprunt = (1+t)*emprunt-m mois.append(d) capital_rd.append(emprunt) interets.append(t*emprunt) plt.clf() plt.plot(mois,capital_rd) plt.xlabel('Mensualité') plt.ylabel('capital restant dû') plt.grid() plt.savefig('capital_restant_du.png') plt.clf() plt.plot(mois,interets,'b') plt.xlabel('Mensualité') plt.ylabel('Intérêts') plt.grid() plt.savefig('interets.png')
f3b7ac3a60eebfe13172f554c1a653d11dd188bd
yushu-liu/30daysofCode
/binaryday10.py
339
3.640625
4
def day10(num): empty = [] arr = [] while num > 0: c = chr(ord('0') + int(num & 1)) num >>= 1 arr.append(c) print arr count = 0 while (count < len(arr)): if arr[count] == 1 and arr[count + 1] != 0: empty.append(arr[count]) count = count + 1 return len(empty)
735dfccba77ea551f191d4fd0ecdfe9ff80ce23a
Raindeca/Python-Trial-Error
/LinierProgramming/calculation.py
1,401
3.578125
4
from pulp import * from problem import Problem class Calculation: def __init__(self, tujuan, kendala): self.tujuan = tujuan self.kendala = kendala def calculation(self): # Mengerjakan Formulasi LP dengan 2 variabel prob = LpProblem("Maximize Case", LpMaximize) x = LpVariable("X", lowBound=0, cat='integer') # Membuat Variabel X (produk 1), di mana X >= 0 y = LpVariable("y", lowBound=0, cat='integer') # Membuat Variabel y (produk 2), di mana y >= 0 #membuat fungsi tujuan prob += self.tujuan[0]*x + self.tujuan[1]*y #Membuat fungsi kendala print(self.kendala) for problem in range(len(self.kendala)): # element = self.kendala[problem] # f_tuple = self.kendala[problem][0] prob += self.kendala[problem][0]*x + self.kendala[problem][1]*y <= self.kendala[problem][2] #Menanpikan Permasalahan LP # print(int(prob)) masih error # Menunjukan Status Optimum status = prob.solve() # menyelesaikannya dengan solver default (bawaan library puPL) print(LpStatus[status]) # Mencetak status dari solusi yang diselesaikan # Menampilkan solusi dari permasalahan LP print(value(x), value(y), value(prob.objective))
4351d27fb5eed7b4818b5797570be9dc79647425
lseguin42/Mower
/main.py
1,059
3.625
4
#!/usr/bin/env python from Map import Map from Mower import Mower ### MAIN ### from sys import stdin, exit mapSize = stdin.readline().strip().split(' '); if len(mapSize) != 2: raise Exception('map size definition error'); map = Map(int(mapSize[0]), int(mapSize[1])); mowers = []; line = stdin.readline(); while line: mowerDef = line.strip().split(' '); if len(mowerDef) != 3: raise Exception('mower def error'); mower = Mower(int(mowerDef[0]), int(mowerDef[1]), mowerDef[2][0]); if not map.onMap(mower): raise Exception('mower not in the map'); actions = list(stdin.readline().strip()); for action in actions: if (action == 'G'): mower.left(); elif (action == 'D'): mower.right(); elif (action == 'A'): mower.walk(); if not map.onMap(mower): mower.back(); else: raise Exception('mower bad action'); print mower.x, mower.y, mower.getDirectionLetter(); line = stdin.readline(); ### END MAIN ###
7c2c62dc832c62ae5294072ba32f72b2979a4ad2
topmillerm2/bootcamp_projects_and_assignments
/Python_stack/python_fundamentals_oop/animal.py
1,081
3.921875
4
class Animal(object): def __init__(self, name): self.name = name self.health= 100 def walk(self): self.health-=1 return self def run(self): self.health -= 5 return self def display_health(self): print "Health:{}".format(self.health) return self class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) self.health = 150 def pet(self): self.health+=5 # print "Health:{}".format(self.health) return self class Dragon(Animal): def __init__(self, name): super(Dragon, self).__init__(name) self.health = 170 def fly(self): self.health-=10 return self def display_health(self): print "Health:{}. I am a Dragon".format(self.health) cat = Animal("cat") cat.walk().walk().walk().run().run().display_health() animal1 = Dog("Leo") animal1.walk().walk().walk().run().run().display_health() animal2 = Dragon("Garfield") animal2.walk().walk().walk().run().run().display_health()
1e6db308a52e917738c897b7457e9ce535834852
DanilKlukanov/Dynamic-programming-languages
/Functions/PAROL'.py
816
4.125
4
stroke = input() ######OK if len(stroke) < 6: print('Недопустимый пароль') ###### elif stroke.isalpha() == True and stroke.islower() == True or stroke.isupper() == True and stroke.isalpha() == True : print('Ненадежный пароль') elif stroke.isdigit() == True: print('Ненадежный пароль') elif stroke.isalpha() == True and stroke.islower() == False and stroke.isupper() == False : print('Слабый пароль') elif stroke.isalnum() == True and stroke.islower() == True or stroke.isupper() == True and stroke.isalnum() == True : print('Слабый пароль') elif stroke.isalnum() == True and stroke.islower() == False or stroke.isupper() == False and stroke.isalnum() == True: print('Надежный пароль')
417b90b7425f551e480d6123d29eb14f19f55cb0
LucasMoretti8/PythonExercicios
/ex071.py
359
3.8125
4
valor = int(input('Insira o valor a ser sacado: R$')) a = 0 b = 0 c = 0 d = 0 while valor >= 50: valor -= 50 a += 1 while valor >= 20: valor -= 20 b += 1 while valor >= 10: valor -= 10 c += 1 while valor > 0: valor -= 1 d += 1 print('Notas de R$50: {}\nNotas de R$20: {}\nNotas de R$10: {}\nNotas de R$1: {}\n'.format(a,b,c,d))
0bd4327595c00ded7c2c73e63a779b1fd10b01f9
kruart/coding_challenges
/hackerRank/data_structures/SparseArrays/sparse-arrays.py
733
3.578125
4
# https://www.hackerrank.com/challenges/sparse-arrays/problem def matchingStrings(strings, queries): d = {q: 0 for q in queries} # dict for s in strings: if s in queries: d[s] += 1 return [d[q] for q in queries] if __name__ == '__main__': arr1 = matchingStrings(["aba", "baba", "aba", "xzxb"], ["aba", "xzxb", "ab"]) # 2 1 0 arr2 = matchingStrings(["def", "de", "fgh"], ["de", "lmn", "fgh"]) # 1 0 1 arr3 = matchingStrings(["abcde", "sdaklfj", "asdjf", "na", "basdn", "sdaklfj", "asdjf", "na", "asdjf", "na", "basdn", "sdaklfj", "asdjf"], ["abcde", "sdaklfj", "asdjf", "na", "basdn", "abcde"]) # 1 3 4 3 2 1 print(arr1) print(arr2) print(arr3)
ac3ba5e826ca064b397651cfb6be0a3ec48b7887
mikeodf/Python_Graphics_Animation
/ch7_prog1_mybridge_stick_man_walking_1.py
12,134
4
4
""" Program name:muybridge stick_man_walking_1.py Objective: Demontrate animation code for stick man trajectories to produce motion animation. Keywords: canvas, stick man, walking, animation ============================================================================79 Comments: Use the time trajectories of joint positions captured from photographic images to create animated walking movement.. Tested on: Python 2.6, Python 2.7.3, Python 3.2.3 Author: Mike Ohlson de Fine """ from Tkinter import * import time root = Tk() root.title("stick Man Walking.") cw = 1800 # canvas width ch = 550 # canvas height chart_1 = Canvas(root, width=cw, height=ch, background="white") chart_1.grid(row=0, column=0) cycle_period =200 # time between new positions of the ball (milliseconds). def animdelay(): chart_1.update() # This refreshes the drawing on the canvas. chart_1.after(cycle_period) # This makes execution pause for 100 milliseconds. chart_1.delete('line_1') # This erases everything on the canvas. #======================================================================= # Stick-man walker joint time-trajectories. #======================================================================= head = [ 203.6,86.9 , 268,80.6 , 319.1,85.5 , 373,82 , 420,84.1 , 466.3,79.9 , 518.7,82.7 , 581.5,80.6 , 634.7,84.8 , 686.2,80.6 , 734.3,82.7 , 778.7,80.6 ] neck = [ 206.4,108.6 , 267.3,104.4 , 321.2,106.5 , 373.7,106.5 , 432.1,101.6 , 482.7,96.7 , 520.7,103.7 , 580.1,104.4 , 637.6,105.8 , 688.6,106.5 , 746.2,100.9 , 794.5,96.7 ] #............................................................................. shoulder_a = [ 215.5,120.5 , 272.2,118.4 , 335.2,121.9 , 402.4,121.2 , 463.7,106.5 , 503.1,103 , 518.4,114.2 , 574,121.2 , 632.1,123.3 , 673.6,120.5 , 723.4,114.9 , 773,107.9 ] elbow_a = [ 247.7,165.3 , 269.4,200.3 , 284.8,196.1 , 304.4,170.2 , 335.9,143.6 , 375.1,138.7 , 478.4,182.1 , 601.6,196.1 , 699.3,198.9 , 780.4,168.1 , 845.5,129.6 , 882.4,114.9 ] wrist_a = [ 291.1,158.3, 332.4,240.9 , 307.2,268.9 ,297.4,245.1 ,314.9,210.8 , 360.4,199.6 , 501.2,243 ,660.1,254.2 ,766.9,215 ,826.7,138.7 ,847.9,86.2 , 854.4,75.7 ] hand_a = [ 292.5,147.1 , 350.6,240.9 , 320.5,281.5 , 304.4,258.4 , 319.1,230.4 , 365.3,217.1 , 514.2,254.9 , 673.4,260.5 , 781.1,211.5 , 833.8,127.5 , 841.6,72.9 , 838.5,71.5 ] #............................................................................. shoulder_b = [ 205,119.1 , 261,120.5 , 316.3,124 , 360.4,122.6 , 409.4,114.9 , 453.1,107.9 , 528.8,115.6 , 584.7,121.2 , 650.6,122.6 , 716.5,119.8 , 777.8,106.5 , 817,103.7 ] elbow_b = [ 165.1,185.6 , 289.7,195.4 , 384.2,200.3 , 466.3,168.8 , 531.1,130.3 , 570,114.2 , 562.8,161.8 , 582.6,201 , 601.1,196.1 , 619.2,167.4 , 649.4,143.6 , 688,140.1 ] wrist_b = [ 186.8,246.5 , 347.1,253.5 , 450.2,216.4 , 512.1,140.1 , 534.3,87.6 , 541.1,74.3 , 605.4,154.8 , 646,241.6 , 622.3,268.2 , 611.4,243 , 629.6,208.7 , 673,201 ] hand_b = [ 200.8,259.1 , 361.1,260.5 , 465.2,212.9 , 519.6,128.9 , 527.6,73.6 , 525,70.1 , 607.4,142.9 , 663.2,240.9 , 635.6,280.8 , 620,257.7 , 634.2,229.7 , 678.2,218.5 ] #............................................................................. hips = [ 256.8,255.6 , 318.4,251.4 , 354.8,261.9 , 412.9,262.6 , 461.5,264.7 , 512.4,255.6 , 571.8,250 , 631.6,250 , 671.6,263.3 , 725.7,259.8 , 777.5,264 , 825.9,256.3 ] knee_a = [ 213.4,383 , 334.5,378.8 , 436.9,364.1 , 512.7,343.1 , 573.7,339.6 , 616.6,345.9 , 656.9,347.3 , 687.4,361.3 , 709,375.3 , 716.8,375.3 , 733.5,367.6 , 770.7,366.2 ] heel_a = [ 83.9,427.1 , 207.8,434.1 , 334.5,462.8 , 481.6,479.6 , 597.9,471.2 , 624.4,483.1 , 623.8,485.2 , 624.9,483.8 , 625.2,480.3 , 624.9,477.5 , 628.4,471.2 , 643.4,436.9] foot_a = [ 97.2,468.4 , 227.4,462.8 , 372.3,481.7 , 519.6,478.2 , 635.6,464.9 , 665.2,474.7 , 667.6,484.5 , 666.7,486.6 , 668.1,484.5 , 668.1,482.4 , 669.3,479.6 , 670.7,476.8 ] toe_a = [ 120.3,481 , 251.2,476.8 , 395.4,485.2 , 544.1,466.3 , 647.7,451.6 , 679.7,460.7 , 686.9,483.1 , 686.9,485.2 , 686.6,488 , 688.6,487.3 , 688.6,485.9 , 688.8,483.8 ] #............................................................................. knee_b = [ 342.2,351.5 , 374.4,360.6 , 394,376 , 403.1,376 , 420,366.9 , 457.4,365.5 , 528.5,378.8 , 647.7,380.2 , 752.5,364.1 , 826.8,341.7 , 889,339.6 , 929.6,346.6 ] heel_b = [ 309.3,489.4 , 309.3,488 , 309.3,485.9 , 309.3,483.8 , 313.5,471.2 , 330.3,436.2 , 398.2,423.6 , 521.3,434.8 , 649.3,462.1 , 795,477.5 , 912.1,471.2 , 938,485.2 ] toe_b = [ 374.4,482.4 , 374.4,484.5 , 374.4,485.9 , 373,486.6 , 373,484.5 , 373.7,483.1 , 434.2,476.8 , 564,476.8 , 710.9,483.8 , 859,464.9 , 961.6,450.9 , 993.5,461.4 ] foot_b = [ 354.1,490.1, 354.1,488.7 , 353.4,488 , 353.4,486.6 ,354.1,485.9 , 357.6,475.4 ,412.2,464.2 ,539.7,464.2 ,687.6,481 , 832,477.5 , 950.1,464.9 , 980,476.8 ] #================================================================================================= def scale_shape(shape, x_amp, y_amp, x_offset, y_offset): """ Amplify/attenuate and position a shape. First add the offset and then amplify the result. """ x_list =[] y_list =[] new_shape = [] # Split the list into separate x and y lists. for i in range(len(shape)/2): x_list.append(shape[2*i]) y_list.append(shape[2*i + 1]) # Scale and position the x-coordinates of the shape to a width of 1.0 and # Re-interleave the x and y components. for j in range(len(x_list)): x_list[j] = ( x_list[j] * x_amp )+ x_offset new_shape.append( x_list[j] ) y_list[j] = ( y_list[j] * y_amp ) + y_offset new_shape.append( y_list[j] ) return new_shape def next_step(shape, x_offset): """ Re-position all limbs for next step. """ x_list =[] y_list =[] new_shape = [] # Split the list into separate x and y lists. for i in range(len(shape)/2): x_list.append(shape[2*i]) y_list.append(shape[2*i + 1]) # Scale and position the x-coordinates of the shape to a width of 1.0 and # re-interleave the x and y components. for j in range(len(x_list)): x_list[j] = x_list[j] + x_offset new_shape.append( x_list[j] ) #y_list[j] = ( y_list[j] * y_amp ) + y_offset new_shape.append( y_list[j] ) return new_shape def draw_walker(indx): """ Draw entire body as a stick man. """ chart_1.create_oval(head[indx]-20, head[indx+1]-20, head[indx]+20, head[indx+1]+20,fill= "brown", width = 2, tag = 'line_1') chart_1.create_oval(hips[indx]-12, hips[indx+1]-12,hips[indx]+12, hips[indx+1]+12, fill= "magenta", width = 1, tag = 'line_1') chart_1.create_line( shoulder_a[indx], shoulder_a[indx+1], shoulder_b[indx], shoulder_b[indx+1], fill= "magenta", width = 4, tag = 'line_1') chart_1.create_line(hips[indx], hips[indx+1], shoulder_a[indx], shoulder_a[indx+1], fill= "magenta", width = 4, tag = 'line_1') chart_1.create_line(hips[indx], hips[indx+1], shoulder_b[indx], shoulder_b[indx+1], fill= "magenta", width = 4, tag = 'line_1') chart_1.create_line(hips[indx], hips[indx+1], knee_a[indx], knee_a[indx+1], fill= "blue", width = 5, tag = 'line_1') chart_1.create_line(hips[indx], hips[indx+1], knee_b[indx], knee_b[indx+1], fill= "green", width = 5, tag = 'line_1') chart_1.create_line(knee_a[indx], knee_a[indx+1], heel_a[indx], heel_a[indx+1], fill= "blue", width = 2, tag = 'line_1') chart_1.create_line(knee_b[indx], knee_b[indx+1], heel_b[indx], heel_b[indx+1], fill= "green", width = 2, tag = 'line_1') chart_1.create_line(foot_a[indx], foot_a[indx+1], heel_a[indx], heel_a[indx+1], fill= "blue", width = 2, tag = 'line_1') chart_1.create_line(foot_b[indx], foot_b[indx+1], heel_b[indx], heel_b[indx+1], fill= "green", width = 2, tag = 'line_1') chart_1.create_oval( toe_a[indx]-6, toe_a[indx+1]-6, toe_a[indx]+6, toe_a[indx+1]+10,fill= "blue", width = 2, tag = 'line_1') chart_1.create_oval( toe_b[indx]-6, toe_b[indx+1]-6, toe_b[indx]+6, toe_b[indx+1]+10,fill= "green", width = 2, tag = 'line_1') chart_1.create_line(elbow_a[indx], elbow_a[indx+1], shoulder_a[indx], shoulder_a[indx+1], fill= "blue", width = 5, tag = 'line_1') chart_1.create_line(elbow_b[indx], elbow_b[indx+1], shoulder_b[indx], shoulder_b[indx+1], fill= "green", width = 5, tag = 'line_1') chart_1.create_line(elbow_a[indx], elbow_a[indx+1], wrist_a[indx], wrist_a[indx+1], fill= "blue", width = 2, tag = 'line_1') chart_1.create_line(elbow_b[indx], elbow_b[indx+1], wrist_b[indx], wrist_b[indx+1], fill= "green", width = 2, tag = 'line_1') chart_1.create_oval( wrist_a[indx]-10, wrist_a[indx+1]-10, wrist_a[indx]+10, wrist_a[indx+1]+10,fill= "blue", width = 2, tag = 'line_1') chart_1.create_oval( wrist_b[indx]-10, wrist_b[indx+1]-10, wrist_b[indx]+10, wrist_b[indx+1]+10,fill= "green", width = 2, tag = 'line_1') def place_shape(shape, x_pos, y_pos): """ Position a shape at a position given by coordinates x_pos, y_pos. """ x_list =[] y_list =[] new_shape = [] # Split the list into separate x and y lists. for i in range(len(shape)/2): x_list.append(shape[2*i]) y_list.append(shape[2*i + 1]) # Scale and position the x and y coordinates of the shape to new positions and # re-interleave the x and y components. for j in range(len(x_list)): x_list[j] = x_list[j] + x_pos new_shape.append( x_list[j] ) y_list[j] = y_list[j] + y_pos new_shape.append( y_list[j] ) return new_shape def advance_step(x_offset): """ Prior to each step the trajectory ofr eack joint must be advanced by one stride. """ global hips, head, shoulder_a, shoulder_b, knee_a, knee_b, heel_a, heel_b, foot_a, foot_b, toe_a, toe_b,\ elbow_a, elbow_b, wrist_a, wrist_b, hand_a, hand_b hips = next_step(hips, x_offset) head = next_step(head, x_offset) shoulder_a = next_step(shoulder_a, x_offset) shoulder_b = next_step(shoulder_b, x_offset) knee_a = next_step(knee_a, x_offset) knee_b = next_step(knee_b, x_offset) heel_a = next_step(heel_a, x_offset) heel_b = next_step(heel_b, x_offset) foot_a = next_step(foot_a, x_offset) foot_b = next_step(foot_b, x_offset) toe_a = next_step(toe_a, x_offset) toe_b = next_step(toe_b, x_offset) elbow_a = next_step(elbow_a, x_offset) elbow_b = next_step(elbow_b, x_offset) wrist_a = next_step(wrist_a, x_offset) wrist_b = next_step(wrist_b, x_offset) hand_a = next_step(hand_a, x_offset) hand_b = next_step(hand_b, x_offset) #====================================================================== max_hips = len(hips) -2 stride_len = max_hips - hips[0] stride_len = hips[22] - hips[0] x_offset = 0.0 y_offset = 0.0 x_amp = 1.0 y_amp = 1.0 # Scale and position all limbs. hips = scale_shape(hips, x_amp, y_amp, x_offset, y_offset) head = scale_shape(head, x_amp, y_amp, x_offset, y_offset) shoulder_a = scale_shape(shoulder_a, x_amp, y_amp, x_offset, y_offset) shoulder_b = scale_shape(shoulder_b, x_amp, y_amp, x_offset, y_offset) knee_a = scale_shape(knee_a, x_amp, y_amp, x_offset, y_offset) heel_a = scale_shape(heel_a, x_amp, y_amp, x_offset, y_offset) elbow_a = scale_shape(elbow_a, x_amp, y_amp, x_offset, y_offset) wrist_a = scale_shape(wrist_a, x_amp, y_amp, x_offset, y_offset) knee_b = scale_shape(knee_b, x_amp, y_amp, x_offset, y_offset) heel_b = scale_shape(heel_b, x_amp, y_amp, x_offset, y_offset) elbow_b = scale_shape(elbow_b, x_amp, y_amp, x_offset, y_offset) wrist_b = scale_shape(wrist_b, x_amp, y_amp, x_offset, y_offset) # Complete the first step. for i in range(len(hips)/2): draw_walker(2*i) animdelay() x_offset += stride_len*x_amp advance_step(x_offset) # Complete the second step. for i in range(len(hips)/2): draw_walker(2*i) animdelay() advance_step(x_offset) # Complete the third step. for i in range(len(hips)/2): draw_walker(2*i) animdelay() root.mainloop()
bce0a007afb0200203d528b9471ceb9a764c447b
jovenan/Exercicios-python
/Menu_opcoes.py
682
3.875
4
from time import sleep print('Calculadora com menu.') num1 = int(input('Digite um numero: ')) num2 = int(input('Digite um numero: ')) op = "" while op is not 4: op = int(input('Digite uma das opções:\n[ 1 ] somar\n[ 2 ] multiplicar\n[ 3 ] maior\n[ 4 ] sair do programa\n')) if op == 1: result = num1 + num2 if op == 2: result = num1 * num2 if op == 3: if num1 > num2: result = num1 else: result = num2 if op < 4: print('A sua solicitação resultou em: {}'.format(result)) sleep(3) if op > 4: print('Digite um valor valido!') sleep(3) print('Você saiu do programa.')
913f5f1d69c83a48096ed2c72049f420db8587ec
klbinns/project-euler-solutions
/Solutions/Problem15.py
526
3.640625
4
''' Problem 15: Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? ''' # cache previously traversed paths cache = {} def num_of_routes(x, y): if x == 0 or y == 0: return 1 if (x, y) in cache: return cache[(x, y)] cache[(x, y)] = num_of_routes(x-1, y) + num_of_routes(x, y-1) return cache[(x, y)] print(num_of_routes(20, 20)) # 137846528820
4978c87aaabe781c04091934688f14707137dd15
antoniopaolillo/antoniopaolillo.github.io
/trybe-exercises/block36/36.4/script_request.py
1,358
3.515625
4
import requests # # Requisição do tipo GET # response = requests.get("https://www.betrybe.com/") # print(response.status_code) # código de status # print(response.headers["Content-Type"]) # conteúdo no formato html # # Conteúdo recebido da requisição # print(response.text) # # Bytes recebidos como resposta # print(response.content) # # Requisição do tipo post # response = requests.post("http://httpbin.org/post", data="some content") # print(response.text) # # Requisição enviando cabeçalho (header) # response = requests.get("http://httpbin.org/get", headers={"Accept": "application/json"}) # print(response.text) # # Requisição a recurso binário # response = requests.get("http://httpbin.org/image/png") # print(response.content) # # Recurso JSON # response = requests.get("http://httpbin.org/get") # # Equivalente ao json.loads(response.content) # print(response.json()) # # Podemos também pedir que a resposta lance uma exceção caso o status não seja OK # response = requests.get("http://httpbin.org/status/404") # response.raise_for_status() import time # Coloca uma pausa de 6 segundos a cada requisição # Obs: este site de exemplo tem um rate limit de 10 requisições por minuto for _ in range(15): response = requests.get("https://www.cloudflare.com/rate-limit-test/") print(response) time.sleep(6)
fbb15dcfc07e556ab3d024e9226a130494452de5
mnoiseless/tasks
/Fib.py
369
3.828125
4
def fib1(n): # через цикл fib1 = [0, 1] for i in range(2,n+1): fib1.append(fib1[i-1]+fib1[i-2]) return fib1[n] n = int(input('Введите n ')) print(fib1(n)) def fib2(n): # рекурсивно if n < 2: return n else: return fib2(n-1)+fib2(n-2) n = int(input('Введите n ')) print(fib2(n))
10ab9c250d7703399a1d2721d745c06b26f96c1c
JADSON-ANDRE/Python
/Exercícios/conversorSeg.py
329
3.59375
4
segundos = input("Entre com o valor em segundos: ") s = int(segundos) dia = s // 86400 restoSegundos = s % 86400 horas = restoSegundos // 3600 restoSegundos = s % 3600 minutos = restoSegundos // 60 restoFinal = restoSegundos % 60 print("", dia, "dias,", horas, "horas,", minutos, "minutos e", restoFinal, "segundos.")
da2c95cb95a2b6ccbaf0cbc4c9c178fea0570e22
Gor02/Python-HW
/Python HW 3/Python HW3.py
4,066
3.984375
4
# Problem 1 # Construct a Dictionary cities_AM that corresponds to largest 5 Armenian cities their population, say, for Yerevan, # the population is 1077.6 (in thousands). # cities_AM = {"Yerevan": 1077.6, # "Vagharshapat": 46.4, # "Kapan": 42.5, # "Vanadzor": 79.3, # "Gyumri": 114.5 # } # Print the names of cities # for i in cities_AM: # print(i) # Print the sum of population in largest 5 Armenian cities # s = 0 # for i in cities_AM.values(): # s += i # print(s) # Get the name of the second largest (by population) city in Armenia (not by a hand, of course ☺) # l = [] # for i in cities_AM.values(): # l.append(i) # for j in range(len(l)): # for k in range(len(l)): # if l[j] > l[k]: # l[j], l[k] = l[k], l[j] # for i in cities_AM: # if cities_AM[i] == l[1]: # print(i) # Add the 6th city with its population to the dictionary # cities_AM["Hrazdan"] = 40.4 # Find information about the surface areas of cities, and update dictionary to include tuples (population, area) for # each city. # area = [223, 40, 36, 32, 54, 152] # key = [i for i in cities_AM.keys()] # cities_AM.update({key[i]: (cities_AM[key[i]], area[i]) for i in range(len(cities_AM))}) #Construct a similar dictionary cities_GE for Germany 2 largest cities, and create a new Dictionary, # with keys "Armenia", "Germany", and values as the constructed dictionaries # cities_GE = {"Berlin": 3.275, # "Hamburg": 1.686 # } # countries = {"Armenia": cities_AM, # "Germany": cities_GE # } # Problem 2 # Consider the list x = [1, -2, 3, 9, 0, 1, 3, 2, -2, -4, 1, -3] . Construct two lists, x_neg and x_pos containng, # correspondingly, all negative and all positive elements of x in the same order. # Construct also lists ind_neg and ind_pos which will contain the indices of all negative and positive elements of x, # respectively. # x = [1, -2, 3, 9, 0, 1, 3, 2, -2, -4, 1, -3] # x_neg = [i for i in x if i < 0] # x_pos = [i for i in x if i > 0] # ind_neg = [i for i in x if x[i] < 0] # ind_pos = [i for i in x if x[i] > 0] # Find the sum 1+3+5+...+101 # sum_ = 0 # for i in range(1, 102, 2): # sum_ += i # Calculate the sum 1+1/2+3+1/4+5+1/6+...+99+1/100 # sum_ = 0 # for i in range(101): # if not i % 2: # sum_ += i # else: # sum_ += 1 / i # Calculate the semifactorial 20!! # factorial = 1 # for i in range(2, 21, 2): # factorial *= i # Calculate the sum # def f(x): # fact = 1 # for i in range(1, x): # fact *= i # return fact # sum_ = 0 # for i in range(20): # sum_ += (-1) ** i / f(i) # Calculate the sum # s_n = 0 # n = 0 # while True: # for i in range(n + 1): # s_n += i / 2 ** i # if abs(s_n - 2) <= 0.001: # print(n) # break # n += 1 # s_n = 0 # Given a list of real numbers, find the maximum element of that list, without using any built-in Python max function # l = [1, 2, 3, 4, 5, 6] # max_element = l[0] # for i in l: # if i > max_element: # max_element = i # Given a list of arbitrary reals, write a sorting algorithm to sort the list in the increasing order, # without using the Python built-in sorting algorithms. You can implement quicksort, # bubble sort or any other well-known algorithm, or just write a simple (maybe non-effective) algorithm. # for j in range(len(l)): # for k in range(len(l)): # if l[j] > l[k]: # l[j], l[k] = l[k], l[j] # Define the following function in Python # def f(x): # if x < 0: # return -1 # elif x <= 0 and x <= 5: # return 4 # else: # return 9 # Define the following function in Python # def g(x): # if x < 0 and x > 10: # return 1 # else: # return 0 # Write a function of natural variable 𝑛 that will return the 𝑛 -the Fibonacci number # def fibo(x): # a = 0 # b = 1 # while a <= x: # print(a) # c = a + b # a = b # b = c
8e525c2fe50607fbc5ca7cc70c26b5b9cfd0a2bc
AnPanian/Python
/turtle-practice.py
398
3.546875
4
import turtle shelly = turtle.Turtle() shelly.shape('turtle') for i in range (4): shelly.forward(100) shelly.left(90) print (i) shelly.begin_fill() shelly.color('red') for i in range (4): shelly.forward(100) shelly.left(90) print (i) shelly.end_fill() shelly.reset() for i in range (50): for n in range (4): shelly.forward(100) shelly.left(90) shelly.right(35) print (i)
f6234b9f57277ffd4c8689697c408c9796232bbe
asthakur1805/Arithmetic-Formatter
/arithmetic_arranger.py
3,271
3.640625
4
def arithmetic_arranger(problems,*args): # Error handling for more than five problems if len(problems) > 5: return 'Error: Too many problems.' operand1_list = list() operator_list = list() operand2_list = list() max_width_list = list() if len(args) == 1: result_list = list() # Traversing through the problems for problem in problems: problem_list = problem.split(); operator = problem_list[1] # Error handling for operation other than addition and subtraction if operator not in ['+','-']: return "Error: Operator must be '+' or '-'." # Exception handling for traceback if the operands are not digits try: operand1 = int(problem_list[0]) operand2 = int(problem_list[2]) except: return "Error: Numbers must only contain digits." # Error handling for width more than four digits if operand1 > 9999 or operand2 > 9999: return 'Error: Numbers cannot be more than four digits.' operand1_list.append(operand1) operator_list.append(operator) operand2_list.append(operand2) operand1_width = get_width(operand1) operand2_width = get_width(operand2) if operand1_width >= operand2_width: max_width_list.append(operand1_width) else: max_width_list.append(operand2_width) # Result to be calculated only if optional boolean parameter True passed if len(args) == 1: if(operator=='+'): result_list.append(operand1+operand2) else: result_list.append(operand1-operand2) arranged_problems = '' # Generation of operand1 format string for index in range(0,len(problems)-1): width = max_width_list[index]+2 arranged_problems+=f'{operand1_list[index]:>{width}} ' width = max_width_list[len(problems)-1]+2 arranged_problems+=f'{operand1_list[len(problems)-1]:>{width}}\n' # Generation of operand2 format string for index in range(0,len(problems)-1): width = max_width_list[index]+1 arranged_problems+=f'{operator_list[index]}{operand2_list[index]:>{width}} ' width = max_width_list[len(problems)-1]+1 arranged_problems+=f'{operator_list[len(problems)-1]}{operand2_list[len(problems)-1]:>{width}}\n' # Generation of dashed line string for index in range(0,len(problems)-1): width = max_width_list[index]+2 arranged_problems+=f'{"-"*width} ' width = max_width_list[len(problems)-1]+2 # Generation of result format string only if optional boolean parameter True is passed if len(args) == 1: arranged_problems+=f'{"-"*width}\n' for index in range(0,len(problems)-1): width = max_width_list[index]+2 arranged_problems+=f'{result_list[index]:>{width}} ' width = max_width_list[len(problems)-1]+2 arranged_problems+=f'{result_list[len(problems)-1]:>{width}}' else: arranged_problems+=f'{"-"*width}' return arranged_problems def get_width(num): count = 0 while num != 0: num //= 10 count = count + 1 return count
ec4ce996cee759b2571a710fe31727a1da50dcf0
hcxie20/Algorithm
/086_Partition_list.py
795
3.84375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def partition(self, head: ListNode, x: int) -> ListNode: if not head: return head dumb_small = ListNode(None) dumb_big = ListNode(None) small = dumb_small big = dumb_big cur = head while cur != None: next = cur.next cur.next = None if cur.val < x: dumb_small.next = cur dumb_small = dumb_small.next else: dumb_big.next = cur dumb_big = dumb_big.next cur = next dumb_small.next = big.next return small.next
2920bd5590bb10477b677cbbbdccc3e7eeb9b32f
DylanTrull/cs362HW4
/Average List/AverageTest.py
402
3.5625
4
import unittest import Average list = [1,2,3,4,5,6,7,8,9,10, 11] ## should average of 6 class TestAverage(unittest.TestCase): def test_average(self): self.assertEqual(Average.Average(list), 5) def test_listNotEmpty(self): self.assertIsNotNone(Average.Average(list)) def test_listNotEqual(self): self.assertNotEqual(Average.Average(list), 0) if __name__ == '__main__': unittest.main()
252a572acf745ebbafa716cf844742eb345a8a31
hasbycs/Loker-App
/loker.py
1,025
3.890625
4
def testing(loker): floor = 1 nine = True three = False seven = False two = False array = [] if loker.isdigit(): for i in range(1,int(loker)+1): array.append(i) if int(loker) == i: return 'loker ' + str(loker) + ' terdapat di lantai ' + str(floor) elif nine and len(array)==9: floor+=1 nine = False three = True array = [] elif three and len(array)==3: floor+=1 three = False seven = True array = [] elif seven and len(array)==7: floor+=1 seven = False two = True array = [] elif two and len(array)==2: floor+=1 two = False nine = True array = [] return 'loker tidak ditemukan' else: return 'masukkan nomor loker' flag=False while(not flag): print('masukkan nomor loker : ') x = input() print(testing(x))
4319ad0e8904113b3b8f5e22af225e91484738fa
alexnad/Programing-101-week0
/solutions/matrix_bombing_plan.py
1,046
3.578125
4
def valid_index(matrix, index, bomb_place): valid_row_index = index[0] >= 0 and index[0] < len(matrix) valid_column_index = index[1] >= 0 and index[1] < len(matrix[0]) return valid_column_index and valid_row_index and index != bomb_place def detonate(element, amount): if element <= amount: return 0 return element - amount def plant_bomb(matrix, index): matrix = [[y for y in x] for x in matrix] bomb_damage = matrix[index[0]][index[1]] for i in range(index[0] - 1, index[0] + 2): for j in range(index[1] - 1, index[1] + 2): if valid_index(matrix, (i, j), index): matrix[i][j] = detonate(matrix[i][j], bomb_damage) return matrix def matrix_sum(matrix): sum_rows = 0 for row in matrix: sum_rows += sum(row) return sum_rows def matrix_bombing_plan(m): bombed_matrix = {} for i in range(len(m)): for j in range(len(m)): bombed_matrix[(i, j)] = matrix_sum(plant_bomb(m, (i, j))) return bombed_matrix
dda8b2524c9c90f9099ce36093abf343bc355260
Geeky-har/Python-Files
/dunder_meth.py
2,049
4.3125
4
# -------------------------dunder methods and operator overloading------------------------ # class Employee: # def __init__(self, name, salary, designation): # self.name = name # self.salary = salary # self.designation = designation # # def __repr__(self): # this executes when the whole obj is printed # return f"(repr)The name of the employee is {self.name}, salary is {self.salary} and he is a {self.designation}" # # def __str__(self): # does the same but get more preference # return f"(str)The name of the employee is {self.name}, salary is {self.salary} and he is a {self.designation}" # # # if __name__ == '__main__': # emp1 = Employee("Harsh", 400, "Dev") # emp2 = Employee("Aditya", 200, "Manager") # # print(emp2) # this will print str # print(repr(emp1)) # this will print repr class Complex: # created a class for performing operations on complex no. def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def print_num(self): return f'The result is {self.num1} and {self.num2}' def __add__(self, other): # + operator overloaded result = Complex(self.num1 + other.num1, self.num2 + other.num2) return result def __sub__(self, other): # - operator overloaded result1 = Complex(self.num1 - other.num1, self.num2 - other.num2) return result1 def __mul__(self, other): # * operator overloaded result2 = Complex(self.num1 * other.num1, self.num2 * other.num2) return result2 def __truediv__(self, other): # / operator overloaded result3 = Complex(self.num1 / other.num1, self.num2 / other.num2) return result3 if __name__ == '__main__': obj1 = Complex(2, 3) obj2 = Complex(6, 2) sum1 = obj1 + obj2 sub1 = obj1 - obj2 mul1 = obj1 * obj2 div1 = obj1 / obj2 print(sum1.print_num()) print(sub1.print_num()) print(mul1.print_num()) print(div1.print_num())
33adc5cb23d07492ee2e2663b33e79d131ecc247
Raushan-Raj2552/URI-solution
/1035.py
194
3.640625
4
a,b,c,d=(input().split()) A=int(a) B=int(b) C=int(c) D=int(d) if D>A and B>C and C+D>A+B and C>0 and D>0 and A%2==0: print('Valores aceitos') else: print('Valores nao aceitos')
836bd4dc3c87a270cbe044ab44f2c61c28ce98bf
ricardoquijas290582/PythonCourse
/tarea/longest_word.py
143
3.921875
4
words = [ "jjdjddjjdjd", "jdjd", "kdsjsf" ] print(words) longest = max(words, key=len) print("La palabra mas larga es:",longest)
7bbc29b4920ac8b27091fbb8b0f30413a6e76413
andreanndrade10/python-algorithms
/python_exercises/array_pair_sum.py
486
4.0625
4
''' Given an integer array, output all the unique pairs that sum up to a specific value 'k' Example: pair_sum([1,3,2,2],4) would return 2 pairs: (1,3) and (2,2) ''' def pair_sum(vector, k): sum = 0 for i in vector: temp_vector = vector a = temp_vector.pop(i) for j in temp_vector: if a or j > k: pass else: sum = a + j if sum == k: print(a,j) pair_sum([1,3,2,2],4)
c903b58d0189c90590ca198e3e88a28f35a5f20f
fouad89/algorithms_python
/08-number_line_jumps.py
967
4.09375
4
# ---------------------------------------------------------------- # You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). # The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. # The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump. # You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO. # ---------------------------------------------------------------- def kangaroo(x1, v1, x2, v2): if (x1 < x2 and v1 < v2) or (x1 < x2 and v1 == v2): return "NO" if (x1 - x2) % (v2 - v1) == 0: return "YES" else: return "NO" if __name__ == '__main__': test = [0, 3, 4, 2] test2 = [0, 2, 5, 3] print(kangaroo(*test)) print(kangaroo(*test2))
073fcb36ea9d6731e1b3ea48e982900c781069a6
Tiberius24/Python_Training
/3Nplus1 Lab.py
1,197
3.65625
4
import turtle def moveTurtle(k, m): k.lt(90) k.fd(m) k.rt(90) k.fd(5) x = k.xcor() y = k.ycor()+2 if m > 100: k.pu() k.goto(x,y) k.write(m, align="center", font=("Arial", 10)) y = k.ycor() - 2 k.goto(x,y) k.pd() k.fd(5) k.rt(90) k.fd(m) k.lt(90) k.fd(5) def seq3np1(n,k): """ Print the 3n+1 sequence from n, terminating when it reaches 1.""" count = 0 while n != 1: if n % 2 == 0: # n is even n = n // 2 else: # n is odd n = n * 3 + 1 count = count +1 moveTurtle(k,count) return count def main(): wn = turtle.Screen() wn.bgcolor("light green") wn.reset() wn.setworldcoordinates(0, 0, 750, 200) koda = turtle.Turtle() koda.color("saddle brown") koda.speed(20) maxSoFar = 0 for start in range(1,50): result = seq3np1(start, koda) if maxSoFar < result: maxSoFar = result if start == 49: print(maxSoFar) wn.exitonclick() if __name__ == '__main__': main()
1dfc0d20c7252ef8c683fce6a1ced0faa6aa138e
xioperez01/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
299
4.25
4
#!/usr/bin/python3 """ Module 4-append_write.py """ def append_write(filename="", text=""): """ Appends a string at the end of a text file and Returns the number of characters added """ with open(filename, mode="a") as f: chars_added = f.write(text) return chars_added
3b3d25ef55d1664a3edddb74898d648e04c248fc
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/steve-long/lesson01-enviro/activities-exercises/task-2-puzzles/list1.py
6,538
4.09375
4
# Python210 | Fall 2020 # ---------------------------------------------------------------------------------------- # Lesson01 # Task 2: Puzzles (http://codingbat.com/python) (list1.py) # Steve Long 2020-09-15 # python /Users/steve/Documents/Project/python/uw_class/python210/lessons/lesson01-enviro/list1.py # first_last6: # ------------ # Given an array of ints, return True if 6 appears as either the first or last element in # the array. The array will be length 1 or more. # first_last6([1, 2, 6]) → True # first_last6([6, 1, 2, 3]) → True # first_last6([13, 6, 1, 2, 3]) → False def first_last6(nums): return ((len(nums) > 0) and ((nums[0] == 6) or (nums[len(nums) - 1] == 6))) print("\nfirst_last6:\n") for iArray in [[1,2,6], [6,1,2,3], [13,6,1,2,3], [], [6,0], [0,6], [11], [6]]: print("first_last6({}) = {}".format(iArray, first_last6(iArray))) # common_end: # ----------- # Given 2 arrays of ints, a and b, return True if they have the same first element or they # have the same last element. Both arrays will be length 1 or more. # common_end([1, 2, 3], [7, 3]) → True # common_end([1, 2, 3], [7, 3, 2]) → False # common_end([1, 2, 3], [1, 3]) → True def common_end(a, b): result = False if ((len(a) * len(b)) > 0): result = ((a[0] == b[0]) or (a[len(a) - 1] == b[len(b) - 1])) return result print("\ncommon_end:\n") for iArray in [[[1,2,3],[7,3]], [[1,2,3],[7,3,2]], [[1,2,3],[1,3]], [[1],[1]], \ [[3,2,4,1],[1,4,2,3]], [[1],[0]], [[],[13]] ]: a = iArray[0] b = iArray[1] print("common_end({}, {}) = {}".format(a, b, common_end(a, b))) # reverse3: # --------- # Given an array of ints length 3, return a new array with the elements in reverse order, # so {1, 2, 3} becomes {3, 2, 1}. # reverse3([1, 2, 3]) → [3, 2, 1] # reverse3([5, 11, 9]) → [9, 11, 5] # reverse3([7, 0, 0]) → [0, 0, 7] def reverse3(nums): return [n for n in reversed(nums)] print("\nreverse3:\n") for iArray in [[1, 2, 3], [5, 11, 9], [7, 0, 0], [11, 17], [19], []]: print("reverse3({}) = {}".format(iArray, reverse3(iArray))) # middle_way: # ----------- # Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their # middle elements. # middle_way([1, 2, 3], [4, 5, 6]) → [2, 5] # middle_way([7, 7, 7], [3, 8, 0]) → [7, 8] # middle_way([5, 2, 9], [1, 4, 5]) → [2, 4] def middle_way(a, b): return [a[1],b[1]] print("\nmiddle_way:\n") for iArray in [[[1, 2, 3], [4, 5, 6]], [[7, 7, 7], [3, 8, 0]], [[5, 2, 9], [1, 4, 5]], \ [[98, 97, 96], [1, 4, 9]]]: a = iArray[0] b = iArray[1] print("middle_way({}, {}) = {}".format(a, b, middle_way(a, b))) # same_first_last: # ---------------- # Given an array of ints, return True if the array is length 1 or more, and the first # element and the last element are equal. # same_first_last([1, 2, 3]) → False # same_first_last([1, 2, 3, 1]) → True # same_first_last([1, 2, 1]) → True def same_first_last(nums): return ((len(nums) > 0) and ((nums[0] == nums[len(nums) - 1]))) print("\nsame_first_last:\n") for iArray in [[1, 2, 3], [1, 2, 3, 1], [1, 2, 1], [4, 2], [4, 4], [7], []]: print("same_first_last({}) = {}".format(iArray, same_first_last(iArray))) # sum3: # ----- # Given an array of ints length 3, return the sum of all the elements. # sum3([1, 2, 3]) → 6 # sum3([5, 11, 2]) → 18 # sum3([7, 0, 0]) → 7 def sum3(nums): sum = 0 for n in nums: sum += n return sum print("\nsum3:\n") for iArray in [[1, 2, 3], [5, 11, 2], [7, 0, 0], [4, 2], [7], []]: print("sum3({}) = {}".format(iArray, sum3(iArray))) # max_end3: # --------- # Given an array of ints length 3, figure out which is larger, the first or last element # in the array, and set all the other elements to be that value. Return the changed array. # max_end3([1, 2, 3]) → [3, 3, 3] # max_end3([11, 5, 9]) → [11, 11, 11] # max_end3([2, 11, 3]) → [3, 3, 3] def max_end3(nums): newNums = [] if (len(nums) > 0): maxEnd = max(nums[0],nums[(len(nums) - 1)]) newNums = [maxEnd]*(len(nums)) return newNums print("\nmax_end3:\n") for iArray in [[1, 2, 3], [11, 5, 9], [2, 11, 3], [1, 4, 9], [2, 32, 14], [2, 3], [7], []]: print("max_end3({}) = {}".format(iArray, max_end3(iArray))) # make_ends: # ---------- # Given an array of ints, return a new array length 2 containing the first and last # elements from the original array. The original array will be length 1 or more. # make_ends([1, 2, 3]) → [1, 3] # make_ends([1, 2, 3, 4]) → [1, 4] # make_ends([7, 4, 6, 2]) → [7, 2] def make_ends(nums): result = [] if (len(nums) > 0): result = [nums[0], nums[len(nums) - 1]] return result print("\nmake_ends:\n") for iArray in [[1, 2, 3], [1, 2, 3, 4], [7, 4, 6, 2], [1, 4], [2], []]: print("make_ends({}) = {}".format(iArray, make_ends(iArray))) # make_pi: # -------- # Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}. # make_pi() → [3, 1, 4] def make_pi(): return [3, 1, 4] print("\nmake_pi:\n") print("make_pi() = {}".format(make_pi())) # rotate_left3: # ------------- # Given an array of ints length 3, return an array with the elements "rotated left" so {1, # 2, 3} yields {2, 3, 1}. # rotate_left3([1, 2, 3]) → [2, 3, 1] # rotate_left3([5, 11, 9]) → [11, 9, 5] # rotate_left3([7, 0, 0]) → [0, 0, 7] def rotate_left3(nums): rotated = [] if (len(nums) > 0): rotated = nums[1:] rotated.append(nums[0]) return rotated print("\nrotate_left3:\n") for iArray in [[1, 2, 3], [5, 11, 9], [7, 0, 0], [1, 4], [2], []]: print("rotate_left3({}) = {}".format(iArray, rotate_left3(iArray))) # sum2: # ----- # Given an array of ints, return the sum of the first 2 elements in the array. If the # array length is less than 2, just sum up the elements that exist, returning 0 if the # array is length 0. # sum2([1, 2, 3]) → 3 # sum2([1, 1]) → 2 # sum2([1, 1, 1, 1]) → 2 def sum2(nums): sum = 0 for i in range(0,min(2,len(nums))): sum += nums[i] return sum print("\nsum2:\n") for iArray in [[1, 2, 3], [1, 1], [1, 1, 1, 1], [17], [-47, 81], []]: print("sum2({}) = {}".format(iArray, sum2(iArray))) # has23: # ------ # Given an int array length 2, return True if it contains a 2 or a 3. # has23([2, 5]) → True # has23([4, 3]) → True # has23([4, 5]) → False def has23(nums): result = False for n in nums: if ((n == 2) or (n == 3)): result = True return result print("\nhas23:\n") for iArray in [[2, 5], [4, 3], [4, 5], [-2, -3], [2], [17], []]: print("has23({}) = {}".format(iArray, has23(iArray)))
17aea703f0b7dbe59cbe0041a50ce39541afb30d
bregneM/PR
/22.10.2.py
252
4.0625
4
#Программа вычисляет произведение 2 целых чисел. #числа-целые. запрещается использовать * b=int(input()) a=int(input()) i=0 k=0 while(i<b): k+=a i+=1 print(k)
8a7ccfcf83e99150151fa6f92aeb43acda1d7b9f
Geeky-har/Python-Files
/Practice_Set/palindromifyList.py
700
3.859375
4
def isPal(a): return str(a) == str(a)[::-1] if __name__ == "__main__": size = int(input("Enter the size of the initial list: ")) lst = [] print(f"Enter {size} elements in the list:") for i in range(size): item = int(input()) lst.append(item) print("The next Palindromes of the elements in the list are: ") finalList = [] for e in lst: if e <= 10: continue else: if isPal(e): finalList.append(e) else: temp = e + 1 while not isPal(temp): temp += 1 finalList.append(temp) print(finalList)
41d83739d4eb898d1a27ea8d93101b19fbbab1b5
Diogogrosario/FEUP-FPRO
/RE08/manipulator.py
672
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 22 09:05:09 2018 @author: diogo """ def manipulator(l,cmds): final = "" for i in cmds: com = i.split() if com[0] == "insert": l.insert(int(com[1]),int(com[2])) elif com[0] == "print": final += str(l) + " " elif com[0] == "remove": l.remove(int(com[1])) elif com[0] == "append": l.append(int(com[1])) elif com[0] == "sort": l.sort() elif com[0] == "pop": l.pop(-1) elif com[0] == "reverse": l = l[::-1] final = final [:-1] return final
46d20cef9f9b3ca372a145527e05f12fe7b4af59
sandeepkumar8713/pythonapps
/04_tree/19_top_view_of_binary_tree.py
2,054
4.40625
4
# https://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/ # Question : Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. # Given a binary tree, print the top view of it. The output nodes can be printed in any order. # # 1 # / \ # 2 3 # \ # 4 # \ # 5 # \ # 6 # Top view of the above binary tree is : 2 1 3 6 # # Question Type : Generic # Used : Do level order traversal of tree while maintaining Horizontal Distance HD of each node. # Push root element in queue, set its root.HD = 0. Maintain myMap dict, to store visited HD. # Loop until queue is empty # a) Pop top node from queue and if node.hd is not in myMap then insert HD and # node.data in myMap # b) If node.left is present set temp.left.hd = hd - 1 and push it in queue # c) If node.right is present set temp.right.hd = hd + 1 push it in queue # After the loop, sort the map based on keys and print its value # Complexity : O(n) import sys class Node: def __init__(self, data): self.data = data self.hd = sys.maxsize self.left = None self.right = None def topView(root): if root is None: return hd = 0 myMap = dict() queue = [] root.hd = hd queue.append(root) while len(queue) > 0: temp = queue.pop(0) hd = temp.hd if hd not in myMap.keys(): # print temp.data, myMap[hd] = temp.data if temp.left: temp.left.hd = hd - 1 queue.append(temp.left) if temp.right: temp.right.hd = hd + 1 queue.append(temp.right) for key in sorted(myMap): print(myMap[key], end=" ") if __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(4) root.left.right.right = Node(5) root.left.right.right.right = Node(6) topView(root)
10e843699a8ff74f24d5c1f73f1670b6fc150dbb
margaritagirl/LinearRegression
/linear regression.py
2,510
4.3125
4
#!/usr/bin/env python # coding: utf-8 # # Simple linear Regression # A simple linear regression asuumes a linear relationship between an input variable X and an output variable Y # The value of Y is depended on the value of X, Hence # Y is the dependent variable # X is the independent variable # Mathematically 'linear relationship' can be reresented by 'linear equation' such as # # Y=mX+b # # Formula to find m and b (using least square method) # # $m = \frac {N Σ(xy) − Σx Σy}{NΣ(x^{2}) − (Σx)^{2}}$ # # $b = \frac{(Σy − m Σx)}{N}$ # # # If you are curious about the derivation of these formulas,I recommend reading https://nptel.ac.in/content/storage2/courses/122104019/numerical-analysis/Rathish-kumar/least-square/r1.htm # # The basic idea is when we have scatterred data, we try to find a curve that best fits the data, by figuring out the best fit line. Now which line would be the best fit? The line which lies as close to the scattered data points in the most optimum way. # # In[2]: import pandas as pd import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[10]: df=pd.read_csv('weather.csv') # In[11]: df=df[['MinTemp','MaxTemp']] # In[12]: df.head() # Now that we have our dataset, We will now predict the maximum temperature given the minimum temperature. # Lets start by splitting the features and target variable # In[16]: x=df.iloc[:,0].values.reshape(-1,1) y=df.iloc[:,1].values.reshape(-1,1) # In[18]: plt.scatter(x,y) plt.xlabel("minimum temperature") plt.ylabel("maximum teperature") plt.show() # In[19]: #splitting the data to test and train from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test =train_test_split(x,y,test_size=0.30,random_state=0) # In[20]: #create the model then train the model and then predict from sklearn.linear_model import LinearRegression linearregression =LinearRegression() linearregression.fit(x_train,y_train) y_predict=linearregression.predict(x_test) # In[21]: y_predict # In[24]: from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_predict)) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict))) # rmsd=4.183076841116088 # which means that our model is not very accurate but still it would be able to make approximate predictions. # In[ ]:
d8d8c2c570137c84d2678d13d0eeab5a43ae922d
saifazmi/learn
/languages/python/sentdex/intermediate/4_listCompAndGenExp.py
840
4.5
4
# List comprehension and generator expressions ''' ' One of the most common generator is range() ' This doesn't generate a list of the given size but rather creates a ' stream of that size without commiting it to memory. But this makes it ' slower compared to list comprehension ''' ''' ' List comprehension on the other hand stores the list to the memory, but ' is faster than a generator ''' ## List comprehension, notice the [] xyz = [i for i in range(5)] print(xyz) # The code above produces the same output as the following code xyz = [] for i in range(5): xyz.append(i) print(xyz[:3]) ## Generator expression, notice the () xyz = (i for i in range(5)) print(xyz) # <generator object <genexpr> at 0x7f4d55fe4d58> # print(list(xyz)[:3]) # converting to a list # the object can be used for iteration for i in xyz: print(i)
ab0a9bc482e0034a83e008318732b818c757aa0b
smreferee/Lame-Game
/Lab2_Richard_Nolan.py
823
4.34375
4
################################################ #This is Lab 2 for COSC 1336 by Richard Nolan # #The program will display program information, # #ask and display the user name, display a menu,# #and finally confirm the menu choice. # ################################################ #Introduction to the program print('Hi! Welcome to the Lame Game!') print("This is the introduction, where you'll be asked your name.") print('Finally, you will select a menu option, and that choice will be confirmed.') #Username query name = input('What is your name? ') print (name) #Game Menu print("GAME MENU") choice = int(input('1.Make Change\ 2.High Card\ 3.Quit\ Choice:')) #Menu Choice Response print(name,', you chose menu option ',choice,".", sep='');
ded8382743996a354640e96e2ac71c7eef878e09
XHaotaX/homework
/psevdoPython.py
7,422
3.5
4
from collections import deque ##27.02.2020 09:55 как же сдесь мало кометраиев ## нужно больше крови class Player: card=[] state=0 bet=0 wallet=1500##кошелек id def main(): gg=[[2, 12], [1, 5], [3, 12], [4, 12], [1, 12], [2, 8], [1, 2], [4, 5], [2, 9], [2, 7], [2, 4]] around=0 bank=0 bb=2 ## or ## bakr=bb+mbb curCost=0 endRoundId=int((len(gg)-5)/2) Pls=deque() for i in range(int((len(gg)-5)/2)):##тут ## pl=Player()##типо заполняю ## pl.card.append(gg[5+2*i:5+2*(i+1)])##даю карты каждому игроку ## pl.id=i ## Pls.append(pl) Pls.append(Player()) Pls[i].card=gg[5+2*i:5+2*(i+1)] ## Pls.##даю карты каждому игроку Pls[i].id=i Pls[i].state=9 for pl in Pls: print(pl.card) print(pl.id) end=0 table=[] ##теперь есть масив обьектов представляюших каждого игрока Pls curCost=2 Pls[0].bet=1 Pls[0].wallet=Pls[0].wallet-Pls[0].bet bank=bank+Pls[0].bet Pls.rotate(-1) Pls[0].bet=2 Pls[0].wallet=Pls[0].wallet-Pls[0].bet bank=bank+Pls[0].bet endRoundId=Pls[0].id print("start") while True: Pls.rotate(-1) print("id-",Pls[0].id) if endRoundId==Pls[0].id:##тут типо оканчание круга торговли, around=around+1 if around==1: print(gg[:3]) table=gg[:3] if around==2: print(gg[:4]) table=gg[:4] if around==3: print(gg[:5]) table=gg[:5] if around==4: return bank,Pls##конец торговли # 0- 0 карт на столе ## 1- 3 карты на столе ## 2- 4 карты на столе ## 3- 5 карт на столе ## переход на следуюшую улицу или вообше выход и там покмане придумал ## а там просто сравнение карта тоесть алогритм делает точто уже умеет ## смотреть затем чтоб непроверял игроков не принемашив участиев розыгрыше, и ли по иным причинам ##не имеющий прав участвовать в розыгреше for pl in Pls: if pl.state==0: end=end+1 if (end+1)==int((len(gg)-5)/2): return bank,Pls end=0 ## навыводить всю информацию каждому игроку о текушем столе if not (Pls[0].state==0 or Pls[0].state==4): print(table) print("id \t state \t bet \t wallet") for pl in Pls: print(pl.id,"\t",pl.state,"\t",pl.bet,"$\t",pl.wallet) if Pls[0].state==0 or Pls[0].state==4: continue else: move=0 print(Pls[0].card) if curCost==Pls[0].bet: print(" fall \t check(ch) \t raise") while (True): move=input() if not (move=="f" or move=="ch" or move=="r"): print("incorrect") else: break if move=="f": ##fall Pls[0].state=0 continue if move=="ch": Pls[0].state=1 continue if move=="r":##rais фунциюю all in можно сделать также while True: state=3 bet=input("You is push r.\nBB bet pls:")##ток добавь к параметрам класса парметр текушихших вишек if "all"==bet: print("all") Pls[0].state=4 bet=100 break if str.isdigit(bet): bet=int(bet) break else: print("non number") bank=bank+bet curCost=curCost+bet Pls[0].wallet=Pls[0].wallet-(curCost-Pls[0].bet) Pls[0].bet=Pls[0].bet+bet##сделано одельно, чтоб в случии, ошибки были видны @) endRoundId=Pls[0].id continue else: print(" fall \t call \t raise") while (True): move=input() if not (move=="f" or move=="c" or move=="r"): print("incorrect") else: break if move=="f": ##fall Pls[0].state=0 continue if move=="c": bank=bank+(curCost-Pls[0].bet)##call Pls[0].wallet=Pls[0].wallet-(curCost-Pls[0].bet) Pls[0].bet=curCost Pls[0].state=2 ##2 or 1 thinking about it continue if move=="r":##rais фунциюю all in можно сделать также while True: state=3 bank=bank+(curCost-Pls[0].bet)##call ## Pls[0].bet=curCost bet=input()##ток добавь к параметрам класса парметр текушихших вишек if "all"==bet: print("all") Pls[0].state=4 bet=Pls[0].wallet break if str.isdigit(bet): bet=int(bet) break else: print("non number") bank=bank+bet ## if bet+Pls[0].bet>curCost:##нужно дорроотать , это в тех случая когда нехватает денег ## curCost=bet+Pls[0].bet ## else: curCost=curCost+bet Pls[0].wallet=Pls[0].wallet-(curCost-Pls[0].bet) ## Pls[0].bet=curCost Pls[0].bet=curCost##сделано одельно, чтоб в случии, ошибки были видны @) endRoundId=Pls[0].id continue for pl in Pls: if not pl.state==0: print(pl.id,"\t",pl.state,"\t",pl.bet,"$\t",pl.wallet) k,t=main() print("{",k) print("id \t state \t bet \t wallet") for pl in t: print(pl.id,"\t",pl.state,"\t",pl.bet,"$\t",pl.wallet)
63a729ac31967f983d8ba9c7d99bea830d64caf3
simofleanta/Coding_Mini_Projects
/mini coding projects/sample_countries.py
1,580
3.984375
4
import pandas as pd import pandas as DataFrame import seaborn as sns import matplotlib.pyplot as plt """Analyze and visualize population in coauntries. Data is a fake sample data from google data on a certain country and population slicing data on a certain country and population slicing extract population column and do the mean of it. print population on a certain country+slice it and perform mean charts""" country=pd.read_csv('countries.csv') print(country.head(10)) print(country.columns) # Romania=country[country.country=='Romania'] print(Romania) Ro=Romania.population.iloc[0:12] print(Ro) Roy=Romania.year.iloc[0:12] print(Roy) country.columns=['country','year','population'] # p=country.population p_mean=p.mean print(p_mean) country['Mean_population']=p.mean print(country.columns) # Romania=country[country.country=='Romania'] R0=Romania.population.iloc[:5] print(Ro.head(3)) r=Romania.population r_mean=r.mean print(r_mean) #------------------------------------------------------------------------ """Perform charts on the data""" print(country.head(0)) print(country.columns) p=country.population p_mean=p.mean print(p_mean) vis1 = sns.distplot(country["population"]) vis2= sns.lmplot(data=country, x='year', y='population', fit_reg=False) vis1 = sns.distplot(country["population"]) vis3= sns.lmplot(data=country, x='country', y='population', fit_reg=False) vis4= sns.boxplot(data=country, x="year", y="population") sns.pairplot(country) plt.show()
d48def05b15c78ba9d1a687f0f50daf274b96510
nuxeo-cps/products--CPSBlog
/skins/cpsblog/getBlogEntryDaySeparators.py
909
3.546875
4
##parameters=items # $Id$ """Returns day_separators list containing ids of blog entry proxies which marks first objects in group of objects posted in the same year-month-day. Lets say we have items sorted on creation date in reverse order and containing: [test5, test4, test3, test2, test1] test5, test4 are posted on January 4 test3, test2, test1 are posted on January 3 then our day_separators will look like: [test5, test3] day_separators makes sense when 'items' are sorted on creation date and is used for visually groupping blog entries by day.""" day_separators = [] if len(items) > 0: day_separators.append(items[0].getId()) def get_date(proxy): return proxy.effective().strftime('%Y-%m-%d') for i in range(1, len(items)): proxy = items[i] prev_proxy = items[i-1] if get_date(proxy) != get_date(prev_proxy): day_separators.append(proxy.getId()) return day_separators
3f9a979525fce9b4679ea64e6f06e1404736375e
Soloman-IT/Project
/ships.py
630
3.578125
4
list_ship = [] class Ship(): def __init__(self, length,name): self.length = length self.name = name sh_1_1 = Ship(1,"sh_1_1") list_ship.append(sh_1_1) sh_1_2 = Ship(1,"sh_1_2") list_ship.append(sh_1_2) sh_1_3 = Ship(1,"sh_1_3") list_ship.append(sh_1_3) sh_1_4 = Ship(1,"sh_1_4") list_ship.append(sh_1_4) sh_2_1 = Ship(2,"sh_2_1") list_ship.append(sh_2_1) sh_2_2 = Ship(2,"sh_2_2") list_ship.append(sh_2_2) sh_2_3 = Ship(2,"sh_2_3") list_ship.append(sh_2_3) sh_3_1 = Ship(3,"sh_3_1") list_ship.append(sh_3_1) sh_3_2 = Ship(3,"sh_3_2") list_ship.append(sh_3_2) sh_4_1 = Ship(4,"sh_4_1") list_ship.append(sh_4_1)
f08c0e824cd2c2d109bc58ec9b22ba692a386275
keeganosler/Random-Number-Generator-Library
/Python/linear_congruence.py
369
3.75
4
# this program generates random numbers using the linear congruence method def linear_congruence(seed, mod, mult, inc, num): random_nums = [] random_nums.append(seed) for i in range(0,num): print(i) q = (mult*seed) + inc seed = q % mod random_nums.append(seed) return random_nums print(linear_congruence(4, 9, 5, 6, 8))
5836e7a7364c05cb904ceb076134479f1927965d
robertdave/code
/integral_riemann.py
554
3.625
4
# Soma de Rieman import math from calcula_polinomios import leitura_px,fx #import calcula_polinomios as pol def soma_rieman(): print('Polinomios - Soma de Rieman') grau = int(input('Grau do px: ')) px = leitura_px(grau) print(px) a = float(input('a=')) b = float(input('b=')) n = float(input('n=')) i = 0 ax = (b-a)/n soma=0.0 print(ax) # calcula a soma de rieman while i<n: x= a+(ax*i) soma = soma + fx(px,grau,x)*ax i=i+1 print(soma)
33a51f75a03ca6c6ab217f0bcd6de7340c09347d
Eroica-cpp/LeetCode
/018-4Sum/solution01.py
3,418
3.625
4
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: Jun 19, 2015 # Question: 018-4Sum # Link: https://leetcode.com/problems/4sum/ # ============================================================================== # Given an array S of n integers, are there elements a, b, c, and d in S such # that a + b + c + d = target? Find all unique quadruplets in the array which # gives the sum of target. # # Note: # Elements in a quadruplet (a,b,c,d) must be in non-descending order. # (ie, a <= b <= c <= d) # # The solution set must not contain duplicate quadruplets. # For example, given array S = {1 0 -1 0 -2 2}, and target = 0. # # A solution set is: # (-1, 0, 0, 1) # (-2, -1, 1, 2) # (-2, 0, 0, 2) # ============================================================================== # Method: Use "twoSum" method; enumerate the sum of any two numbers and store # them into a hash table, so four sum problem becomes a two sum problem # Time Complexity: O(n^2) # Space Complexity: O(n^2) # ============================================================================== class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer[][]} def fourSum(self, nums, target): size = len(nums) nums.sort() twoSumDic = {} fourSumDic = {} counter = {} for i in xrange(size): counter[nums[i]] = counter.get(nums[i])+1 if counter.get(nums[i]) else 1 for j in xrange(i+1,size): if not twoSumDic.get(nums[i]+nums[j]): twoSumDic[nums[i]+nums[j]] = [[nums[i],nums[j]]] else: twoSumDic[nums[i]+nums[j]].append([nums[i],nums[j]]) keys = [] for key,val in twoSumDic.items(): times = 2 if len(val) >= 2 else 1 keys += [key] * times pairs = self.twoSum(keys, target) for pair in pairs: for i in twoSumDic[pair[0]]: for j in twoSumDic[pair[1]]: new = tuple(sorted(i+j)) flag = True for k in new: if new.count(k) > counter.get(k): flag = False break if flag and not fourSumDic.get(new): fourSumDic[new] = 1 return fourSumDic.keys() def twoSum(self, nums, target): size = len(nums) nums.sort() i, j = 0, size-1 res = [] while i < j: if nums[i]+nums[j] == target: res.append([nums[i], nums[j]]) i += 1 j -= 1 elif nums[i]+nums[j] > target: j -= 1 elif nums[i]+nums[j] < target: i += 1 return res if __name__ == '__main__': nums, target = [1,0,-1,0,-2,2], 0 nums, target = [-471,-434,-418,-395,-360,-357,-351,-342,-317,-315,-313,-273,-272,-249,-240,-216,-215,-214,-209,-198,-179,-164,-161,-141,-139,-131,-103,-97,-81,-64,-55,-29,11,40,40,45,64,87,95,101,115,121,149,185,230,230,232,251,266,274,277,287,300,325,334,335,340,383,389,426,426,427,457,471,494], 2705 nums, target = [1,1,1,1], 4 nums, target = [1,4,-3,0,0,0,5,0], 0 print Solution().fourSum(nums, target)
b05bed5540d0eb2cd6a32b8dd46c111a2a0815f6
maq-622674/python
/最近项目要做的功能/判断两个列表的内容是否相等.py
567
3.953125
4
''' 列表长度相等的时候 ''' data=['a','b','c'] data1=['a','b','c'] if(data==data1): print("data和data1两个列表内容相等") data2=['a','b','c'] data3=['a','b','d'] if(data2==data3): print("data2和data3两个列表内容相等") else: for i,j in zip(data,data1): print("data2的数据:",i) print("data3的数据:",j) # data2=['a','b','c'] # data3=['a','b'] # if(data==data1): # print("data2和data3两个列表内容相等") # else: # print("data2和data3两个列表内容相等") # for i,j
d61c04814a92920e4f851ddba30dc35898827b14
zaoyuaner/Learning-materials
/python1812/python_1/7_字符串_编解码/代码/09_替换replace.py
615
4.25
4
# 替换 # .replace(old,new,maxCount) 使用new替换old,可以指定替换次数 str1 = "this is a test test test" print(str1.replace("test","school")) # 不带次数则替换所有 print(str1.replace("test","exam",2)) # .maketrans() translate 翻译. 可以使用映射表进行简单加密 # str.maketrans() # 创建一个翻译表,字符映射表 table = str.maketrans("hlo","abc") # hlo翻译成了ASCII码,对应123 print(table) # {104: 49, 108: 50, 111: 51} 输出为字典 # .translate() 翻译 str2 = "hello" str3 = str2.translate(table) # 使用table映射表翻译str2 print(str3)
1422716fbf03c44ef6ff84a50b12827f6eb3d66d
bineeshpc/problemsolving
/unixtools/sort.py
745
3.578125
4
#! /usr/bin/env python import sys import six import argparse def parse_cmdline(): parser = argparse.ArgumentParser( description='Unix like sort tool, does not use disk space') parser.add_argument('--filename', type=str, help='name of the file', default=sys.stdin ) args = parser.parse_args() return args def sort_(filename): f = filename if filename is sys.stdin else open(filename) content = [line.strip() for line in f] if f is not sys.stdin: f.close() content.sort() for line in content: six.print_(line) if __name__ == '__main__': args = parse_cmdline() sort_(args.filename)
2d9aa5c0cd1042985f68bcb1b78403d1b74aa67f
tsu-nera/AOJ
/Volume100/10011.py
146
3.671875
4
n = int(input()) array = list(input().split()) array.reverse() for i in range(n - 1): print(array[i] + " ", end = "") print (array[n - 1])