blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ca82fd8d846dcc3e569e0440c21a3e49ff9b35e6
lgope/python-world
/crash-course-on-python/week-4/video_exercise_dictionary.py
1,474
4.375
4
# The "toc" dictionary represents the table of contents for a book. Fill in the blanks to do the following: 1) Add an entry for Epilogue on page 39. 2) Change the page number for Chapter 3 to 24. 3) Display the new dictionary contents. 4) Display True if there is Chapter 5, False if there isn't. toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30} toc['Epilogue'] = 39 # Epilogue starts on page 39 toc['Chapter 3'] = 24 # Chapter 3 now starts on page 24 print(toc) # What are the current contents of the dictionary? print('Chapter 5' in toc) # Is there a Chapter 5? # Complete the code to iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary. cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} for ext, value in cool_beasts.items(): print(f"{ext} have {value}") # In Python, a dictionary can only hold a single value for a given key. To workaround this, our single value can be a list containing multiple values. Here we have a dictionary called "wardrobe" with items of clothing and their colors. Fill in the blanks to print a line for each item of clothing with each color, for example: "red shirt", "blue shirt", and so on. wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} for ward_ext, values in wardrobe.items(): for value in values: print(f"{value} {ward_ext}")
true
0dcd9fb38728ea5f8cf73c0650a4a0090d364781
ardus-uk/consequences
/p2.py
2,029
4.4375
4
#!/usr/bin/python """ Some examples of using lists """ # Author: Peter Normington # Last revision: 2013-11-18 example_number = 0 # The following is used to divide the sections of output print "--------------------------------------------\n" with open('./datafiles/Consequences', 'r') as f: # f is a file handle. # Read the whole file in one big slurp into a list contents_as_a_list_of_lines = f.readlines() example_number = example_number + 1 print "Example", example_number, "\n" # use the list indices print contents_as_a_list_of_lines[1] print contents_as_a_list_of_lines[6] print "--------------------------------------------\n" example_number = example_number + 1 print "Example", example_number, "\n" # Use the list indices in a loop # Note that the first argument to range() is the starting value; # the second agument is the number that the sequence goes up to (but is not included) for i in range(1,7): print contents_as_a_list_of_lines[i] print "--------------------------------------------\n" example_number = example_number + 1 print "Example", example_number, "\n" # Use the list indices in a loop # Note that the third argument to range() is the increment for i in range(6,0, -1): print contents_as_a_list_of_lines[i] print "--------------------------------------------\n" example_number = example_number + 1 print "Example", example_number, "\n" # Get rid of those pesky newline characters! for i in range(6,0, -1): print contents_as_a_list_of_lines[i].strip() print "--------------------------------------------\n" example_number = example_number + 1 print "Example", example_number, "\n" # We can shuffle the order by using the "shuffle" function from the "random" package from random import shuffle indexes = range(1,7) print "Before shuffling: " print indexes shuffle(indexes) print "After shuffling: " print indexes for i in indexes: print contents_as_a_list_of_lines[i].strip() print "--------------------------------------------\n"
true
6b74455e85c5d3c0b9cd7fa3d32f9e52dbf3ed47
AlAaraaf/leetcodelog
/offer/offer24.py
863
4.1875
4
""" 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。 """ from util import createListNode, printListNodes # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None: return head preNode = None currentNode = head nextNode = currentNode.next while nextNode != None: currentNode.next = preNode preNode = currentNode currentNode = nextNode nextNode = nextNode.next currentNode.next = preNode return currentNode test = Solution() tree = [1,2,3,4,5] root = createListNode(tree) printListNodes(test.reverseList(root))
false
f0c79b529e1f66b89f5c55859926cb724d249871
tayyabmalik4/MatplotlibWithTayyab
/2_line_plot_matplotlib.py
663
4.5
4
# (2)*************line plot in matplotlib************* # ///////to show the graphical line plot than we use line plot function in matplotlib # ////import matplotlib import matplotlib.pyplot as plt days =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] tem=[36.6,37,37.7,39,40,36.8,43,44,45,45.5,40,44,34,47,46] # //////start the ploting using matplotlib plt.plot(days,tem) # ////when we want to determine the axis lengh than we use axis function # -----------plt.axis([xmin,xmax,ymin,ymax]) plt.axis([0,20,30,50]) # /////to creating the title plt.title("Kara Temperature") # ////showuing name of x-axis and y-axis plt.xlabel("Day") plt.ylabel("Temperature") plt.show()
true
2234f9ba4e9cda121f2687d48597af84fc34a325
seshgirik/python-practice
/class_emp.py
811
4.125
4
class Employee(): raise1 = 10 def __init__(self, name, age): self.name = name self.age = age def increment(self): print(f'increment is percentage {self.raise1}') # to access class variable we should use either class name or class instance rama = Employee('rama', 10) rama.increment() print(Employee.__dict__) # class variables are displayed print(f'===================================') print(f'raise variable not created for instance,it uses class variable, {rama.__dict__}') # instance varaibles are displayed rama.raise1 = 100 # This is applicable only for instance rama not for other instances print(f'===================================') print(f'raise variable created for instance with above statement {rama.__dict__}') # instance varaibles are displayed
true
e7c0dd843e7796e421ea851be0f68da63ead1a7a
seshgirik/python-practice
/.ipynb_checkpoints/super2.py
833
4.15625
4
# # class A: # # classvar1 = 'class variable' # # def __init__(self): # # self.classvar1 = 'instance variable in class A' # pass # # class B(A): # classvar1 = 'instance variable in class B' # pass # # a= A() # b= B() # # print(b.classvar1) # class A: classvar1 = 'class variable' def __init__(self): self.classvar1 = 'instance variable in class A' self.special = ' special var' pass class B(A): def __init__(self): super().__init__() # super(A).__init__() self.classvar1 = 'instance variable in class B' super().__init__() pass a= A() b= B() print(b.classvar1) print(b.special) print(A.mro()) print(B.mro()) #watch below video to understand abvoe #https://www.youtube.com/watch?v=HfmFcj0NmHI&ab_channel=CodeWithHarry
false
d8c92b2103349901d28d57889043b362919ed592
dimashtasybekov/algorithms-and-data-structure
/Stack.py
582
4.125
4
class Stack: def __init__(self) : self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[self.size()-1] def size(self): return len(self.items) a = Stack() print("Stack is Empty: ", a.isEmpty()) a.push(1) a.push(8) a.push(78) print("Push 3 element and look at stack", a.peek()) a.pop() print("Pop last element of Stack then looking at stack", a.peek()) print("Size of Stack: ",a.size())
false
b2d62e50e037afeab6ba538f8caad7bb209f2195
LeeRHuang/PythonSprider
/Baseic/Function.py
1,085
4.1875
4
def sayHello(): print 'It\'s a simple function!' def getMax(a,b): if a > b: print a,'is max value' else: print b,'is max value' getMax(10,20) x = 200 y = 280 getMax(x,y) # '''global''' # def func(): # global x # print x # x = 10 # print 'local x is changed to',x # # x = 2 # func() # print 'x is',x # # def printMessgae(message,times = 1,value = 2): # print message * times # # printMessgae('Hello') # printMessgae('Hello',2) # # # def func(a, b=5, c=10): # print 'a is', a, 'and b is', b, 'and c is', c # # func(3, 7) # func(25, c=24) # func(c=50, a=100) # def getMax(x,y): # if x > y: # return x # elif x < y: # return y # else: # return None # # max = getMax(9,9) # print max # # def someFunc(): # pass # # someFunc() def printMax(x,y): '''Print the maximun of the two numbers. The two values must be interge''' x = int(x) y = int(y) if x > y: print x,'is the maxValue!' else: print y,'is the maxValue!' printMax(1,3) print printMax.__doc__
false
1d405709b22651faa97ed4089bd12053148fbe8e
nguyenmuoi157/VietSearchCodeChallenges
/Chanllenge_P3.py
1,001
4.1875
4
from Challenge_P1 import string_normalize def ngrams_genarate(input_string): word_normalize = string_normalize(input_string) word_array = word_normalize.split() unigrams = [] bigrams = [] trigrams = [] arr_length = len(word_array) for item in word_array: unigrams.append([item]) if arr_length <= 2: bigrams.append(word_array) else: for i in range(0, arr_length - 1): bigrams.append([word_array[i], word_array[i + 1]]) if arr_length <= 3: trigrams.append(word_array) else: for i in range(0, arr_length - 2): trigrams.append([word_array[i], word_array[i + 1], word_array[i + 2]]) return unigrams, bigrams, trigrams if __name__ == '__main__': input_str = "I like to Program in Python Language. Don’t you?" unigrams, bigrams, trigrams = ngrams_genarate(input_str) print("unigrams= ", unigrams) print("bigrams = ", bigrams) print("trigrams = ", trigrams)
false
062dff1462afeaa24db16aec458b7313f8d41a55
Zoxas/Test
/Leetcode/length Of Longest Substring.py
1,809
4.125
4
# -*- coding: utf-8 -*- """ Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. """ class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int 維護兩個指針,保證兩個指針之間的串沒有重複字符, 後指針掃到某個字符重複時就將前指針向後移到第一個和當前字符相同的字符之後 """ dict, ans, p1, p2 = {}, 0 , 0 , 0 # P1 前指標 P2 後指標 lst = [] while p2 < len(s): p = dict.get(s[p2] , None ) # p 回傳 是否有有重複字母 -> 有就回傳index if p == None : dict[s[p2]] = p2 p2 += 1 ans = max(ans, p2 - p1) # ans 目前存的最大length 和 新的length做比較 else : lst.append(s[p1:p2]) while p1 <= p: #遇到重複的字母 將最一開始出現重複字母之前的字串都拋棄 dict.pop(s[p1]) p1 += 1#移到第一個和當前字符相同的字符之後 lst.append(s[p1:p2]) index = 0 LongestSubstring = "" for i in range(len(lst)): if len(lst[i]) >= len(LongestSubstring): LongestSubstring = lst[i] index = i return ans,lst,LongestSubstring,index if __name__ == "__main__": s = Solution() string = "abcabcbb" string2 = "abcdaefg" print s.lengthOfLongestSubstring(string)
false
4acf87250bceca5272504bf41db84899509f6a66
roblivesinottawa/object_oriented_code_python
/code/Person.py
1,489
4.25
4
class Person: def __init__(self, first_name, last_name, age, height, ehtnicity): self.first_name = first_name self.last_name = last_name self.age = age self.height = height self.ethnicity = ehtnicity def __str__(self): return f"{self.first_name} {self.last_name} is {self.age} years old. They are {self.height} tall and {self.ethnicity}." class Student(Person): def __init__(self, first_name, last_name, age, height, ehtnicity, graduation): super().__init__(self, first_name, last_name, age, height, ehtnicity) self.graduation = graduation def __str__(self): return f"student {self.first_name} is currently taking {self.graduation} classes at UCLA." class Employee(Person): def __init__(self, first_name, last_name, age, height, ehtnicity, graduation): super().__init__(self, first_name, last_name, age, height, ehtnicity, college, company_name, salary, position) self.college = college self.company_name = company_name self.salary = salary self.position = position def __str__(self): return f"Employee {self.first_name} {self.last_name} has been an employee at {self.company} for 5 years. {self.first_name} is a graduate of {self.college}." # create instances of the class Person iron_man = Person("Tony", "Stark", 45, "6ft", "White") captain_america = Person("Sam", "Wilson", 35, "6ft", "Black") print(iron_man) print(captain_america)
false
be8eee178a6fc4354447d46ee616ab2716209ff6
rizkariz/dental_school
/sialolit, sialadeni, mukolel.py
853
4.125
4
# sialolithiasis, sialadenitis, or mukokel print("Answer the question with y/n") while True: num_1 = input("Does the swelling painful?") if num_1 == "y": num_1a = input("Is there any prodromal sympton?") if num_1a == "y": print("It might be Sialadenitis") break elif num_1a == "n": print("might be sialolithiasis") break else: print("Invalid answer") elif num_1 == "n": num_1b = input("Is it located in the tongue?") if num_1b == "y": print("might be mukokel") elif num_1n == "n": print("Look out for the other anamnesis component") else: print("invalid answer") else: print("invalid answer")
true
2dcf55a666a4d134eba54a7c4b350e676270b91e
GabrielVSMachado/42AI_Learning
/00/text_analyzer/count.py
724
4.125
4
def text_analyzer(text=None, *args) -> str: """Return a string with the number of characters and other elements: number of upper_cases, lower_cases, punctuation_marks and spaces""" if len(args) != 0: return "ERROR" while text is None: text = input("What is the text to analyse?\n") punctuation_marks = len([i for i in text if not (i.islower() or i.isspace() or i.isupper() or i.isdigit())]) return f"""The text contains {len(text)} characters:\n - {len([i for i in text if i.isupper()])} upper letters\n - {len([i for i in text if i.islower()])} lower letters\n - {punctuation_marks} punctuation marks\n - {len([i for i in text if i.isspace()])} spaces"""
true
99f465d787dc0d99c03575b767478dbe2aa0d17a
Pallavi2000/adobe-training
/day1/p1.py
263
4.15625
4
#Program to check if integer is a perfect square or not number = int(input("Enter a number ")) rootNum = int(number ** 0.5) if rootNum * rootNum == number: print(number,"is a perfect square number") else: print(number, " is not a perfect square number")
true
1a448b44238155775a082e047e89035bb645de6a
Pallavi2000/adobe-training
/day2/p3.py
259
4.15625
4
#Program to find series of n + n(2) + n(3) + ... n(m) m = int(input("Enter the value of m ")) number = int(input("Enter the number ")) sum_of_series = 0 for i in range(1, m + 1): sum_of_series += pow(number, i) print("Sum of Series is ",sum_of_series)
false
c1412481b55052471dc56ced35b17fb48f18c904
otaviocv/spin
/spin/distances/distances.py
1,987
4.25
4
"""Distances module with utilities to compute distances.""" import numpy as np def general_distance_matrix(X, dist_function): """General distance matrix with custom distance function. Parameters ---------- X : array, shape (n, k) The first set of column vectors. This is a set of k vectors with dimension of n. dist_function: array, shape (n, n) The custom function that will calculate distance between vectors. It must be a two argument fucntion that returns a number. """ n = X.shape[1] dist_matrix = np.zeros((n, n), dtype=float) for i in range(0, n): for j in range(i, n): dist = dist_function(X[:, i], X[:, j]) dist_matrix[i, j] = dist dist_matrix[j, i] = dist def l2_distance_matrix(X, Y): """Fast L2 distance matrix between two sets of columns vectors. The final matrix will contain the distances between all X vectors and all Y vectors. For instances, if we have two sets of three dimensional vectors, one with 10 vectors and the second with 5 vectors, the output matrix will be of shape 10x5. Parameters ---------- X : array [n, k] The first set of column vectors. This is a set of k vectors with dimension of n. Y : array [n, l] The second set of column vectors. This is a set of l vectors with dimension of n. Retruns ------- distance_matrix: array [k, l] The matrix distance. Each element d[i, j] will represent the L2 distance between the i-th vector from X and the j-th vector from Y. d[i, j] = l2_distance(X[:, i], Y[:, j]) """ dists = -2 * X.T.dot(Y) + \ np.sum(X**2, axis=0) + \ np.sum(Y**2, axis=0).reshape(1, -1).T dists[dists < 0] = 0 distance_matrix = np.sqrt(dists) return distance_matrix def l1_distance_matrix(X, Y): """Fast L1 distance matrix between two sets of columns vectors.""" pass
true
95258c4e533cda362105cb844888cfa7f8aa8629
joycecodes/problems
/collatz.py
836
4.15625
4
""" The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def collatz(n, cache): if n not in cache: if n == 1: cache[n] = 1 elif n % 2 == 0: cache[n] = 1 + collatz(n/2, cache) else: cache[n] = 1 + collatz(n * 3 + 1, cache) return cache[n] cache = {} print(collatz(1000000, cache))
true
ed1ae18ed0aaa1b1ecfeac5a9357fe376ab69deb
almcd23/python-textbook
/ex4.py
960
4.1875
4
#tells number of cars cars = 100 #tells the amount of people a car can hold space_in_a_car = 4.0 #tells the number of people to drive the cars drivers = 30 #tells the number of passengers needing cars passengers = 90 #subtracts the number of cars from the number of drivers cars_not_driven = cars - drivers #there is one car driven per one driver cars_driven = drivers #the passenger capacity is the number of cars driven multiplied by how much a car can hold carpool_capacity = cars_driven * space_in_a_car #averages the passengers divided by number of cars driven average_passengers_per_car = passengers / cars_driven print 'There are', cars, 'cars available.' print 'There are only', drivers, 'drivers available.' print 'There will be', cars_not_driven, 'empty cars today.' print 'We can transport', carpool_capacity, 'people today.' print 'We have', passengers, 'to carpool today.' print 'We need to put about', average_passengers_per_car, 'in each car.'
true
7d5ad77f9b30edfc698bed052baf7300cf668bc9
jorge-gx/dsi-minicourse
/004_ml_example.py
1,331
4.40625
4
""" Supervised learning example: An overview of the scikit-learn library for Machine Learning in Python """ import pandas as pd # importing model type and other useful techniques and eval metrics from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score # import raw data # no preprocessing needed here data_for_model = pd.read_csv("data_for_model.csv") # known input and known output X = data_for_model[["input_var1", "input_var2", "input_var3"]] y = data_for_model["output_var"] # splitting our X and y objects into training and test sets # we specify the ration of this split, 80% train, remaining 20% test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Create an object using the class of model regressor = LinearRegression() # Train our model (regressor object) using the fit method # using only training data! regressor.fit(X_train, y_train) # Applying the trained model to the test set input variables # using the predict method # getting predicted output values y_pred = regressor.predict(X_test) # Evaluate the accuracy of the model # based on difference between predicted output values # and actual output values for the test set print(r2_score(y_test, y_pred))
true
e427debab3fb641525ed5c97a0f086ee194b60d3
AugPro/Daily-Coding-Problem
/Airbnb/e009.py
615
4.125
4
"""This problem was asked by Airbnb. Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. Follow-up: Can you do this in O(N) time and constant space?""" def main(li): score = dict() for i,val in enumerate(li): score[i] = max(score.get(i-1,0),score.get(i-2,0)+val) return score[len(li)-1] if __name__ == '__main__': assert main([2, 4, 6, 2, 5])==13 assert main([5, 1, 1, 5])==10
true
7c906dd3ebe98d9a50c9130f238ffe76ed4289d7
Pravin2796/python-practice-
/chapter 3/assignmet 3/2.py
229
4.40625
4
letter = '''Dear <|name|> you are selected ! date : <|date|> ''' name = input("enter the name: \n") date = input("enter the date: \n") letter=letter.replace('<|name|>',name) letter=letter.replace('<|date|>',date) print(letter)
false
02b919b015d4c6dcb841f834707d0c89ab7daa80
Pravin2796/python-practice-
/chapter 2/operators.py
457
4.1875
4
a = 3 b = 4 # Arithematic operator print("value of 3+4 is", 3 + 4) print("value of 3+4 is", 3 - 4) print("value of 3+4 is", 3 * 4) print("value of 3+4 is", 3 / 4) # Assignment operators a= 20 a += 2 print (a) # comparison operator a = (4>5) print(a) #logical operator bool1= True bool2= False print("the value of bool1 and bool2 is", bool1 and bool2) print("the value of bool1 or bool2 is", bool1 or bool2) print("the value of not bool1 is", not bool1)
true
ed233d7c5c7b0885f4fbeaabda7e9d957da30e10
surajbnaik90/devops-essentials
/PythonBasics/PythonBasics/Sets/set1.py
1,156
4.28125
4
#Creating sets companies = {"Microsoft", "Amazon", "Google"} print(companies) for company in companies: print(company) print("-" * 100) companies_set = set(["Microsoft", "Amazon", "Google"]) print(companies_set) for company in companies_set: print(company) #Add item to a set companies.add("VMWare") companies_set.add("VMWare") print(companies) print(companies_set) #Create an empty set emptyset = set() emptyset2 = {} emptyset.add("test") #emptyset2.add("test") - throws an error #Creating set from other objects even = set(range(0,10,2)) print(even) odd_tuple = (1,3,5,7,9) odd = set(odd_tuple) print(odd) print("-" * 100) #Union of sets setA = {4, 12, 36, 8, 20} setB = {2, 4, 6 , 8, 10} print("Set A : {}".format(setA)) print("Set B : {}".format(setB)) print("Union of sets...") print(setA.union(setB)) print("Length of the union of sets : {}".format(len(setA.union(setB)))) #Intersection of sets print("Intersection of sets...") setA.intersection(setB) print(setA & setB) #Subtraction of sets print("Subtraction of sets...") print("A - B = {}".format(sorted(setA.difference(setB)))) print("B - A = {}".format(sorted(setB-setA)))
true
e1a6ae9518a2dbf164af4691fe0f5b1d7fee7838
surajbnaik90/devops-essentials
/PythonBasics/PythonBasics/Challenges/challenge2.py
450
4.1875
4
#Write a program to guess a number between 1 and 10. import random highest = 10 randomNumber = random.randint(1, highest) print("Please guess a number between 1 and {}: ".format(highest)) guess = 0 while guess!= randomNumber: guess = int(input()) if guess < randomNumber: print("Please guess higher") elif guess > randomNumber: print("Please guess lower") else: print("Well done, you guessed it correctly")
true
05368d6c238aced1d80909d6f546363caf05df48
riddhi-jain/DSAready
/Arrays/Reverse a List.py
714
4.15625
4
#Problem Statement : Reversing a List. #Approach : """ Step1 : Find the "mid" of the List. Step2 : Take two pointers. initial >> start pointer , last >> end pointer Step3 : Keep running the loop until initial < last or mid-1 does not equals to zero. Step4 : Swap the element at initial position with the element at the last position. Step5 : increment mid, initial by 1 and decrement last by 1. Note : It will reverse the existing list, won't take a new list. """ #Below is the code: List = [23 , 12, 11, 10 , 76] mid = len(List) // 2 initial = 0 last = -1 while (mid-1) > -1: temp = List[initial] List[initial] = List[last] List[last] = temp mid -= 1 last -=1 initial += 1 print(List)
true
03f32157fc9a2383fd6d1e3f27db19134b1e6ab9
G00398347/programming2021
/week04/w3schoolsOperators.py
1,263
4.625
5
#This is for trying out python operators #assignment operator example x = 5 x += 3 print (x) #this prints x as 8 #in and not in- membership operators example x = "Just for fun" y = {1:"a", 2:"b"} print ("J"in x) print ("just" not in x) print (1 in y) print ("a" in y) #identity operators is and is not example 1 a = True b = False print ("a and b is ", a and b) print ("a or b is ", a or b ) print ("not b is ", not b) #identity operators is and is not example 2 x = ["apple", "banana"] y = ["apple", "banana"] z = x print (x is not z) print (x is not y) #returns true because x is not the same object as y print (x != y) #demonstratest the difference between is not equal to and is not- #the above line returns false becaue x has the same conted as y so they are equal #logical operators- and/or/not a = 5 print (a > 3 and a < 10) #returns true because both conditions are met print (a > 3 or a < 10) #returns true because one of the conditions is true print (not(a > 3 and a < 10)) #returns false because not reverses the result i.e. returns false if the result is true print (not(a > 3 or a < 10)) #returns false because not reverses the result i.e. returns false if the result is true
true
9e20d191a2fbbfadc803c6e46a873f92add4dc8d
G00398347/programming2021
/week02/lab2.3.1testTypes.py
633
4.1875
4
#This programme uses type function in python to check variable types #Author: Ruth McQuillan #varialbes are assigned names i = 3 fl = 3.5 isa = True memo = "how now Brown Cow" lots = [] #command to output the variable name, type and value print ("variable {} is of type:{} and value:{}" .format ("i", type(i), i)) print ("variable {} is of type:{} and value:{}" .format ("fl", type(fl), fl)) print ("variable {} is of type:{} and value:{}" .format ("isa", type(isa), isa)) print ("variable {} is of type {} and value:{}" .format ("memo", type(memo),memo)) print ("variable {} is of type {} and value:{}" .format ("lots", type(lots),lots))
true
42fbfbc90c1385626001445374b671011d236107
G00398347/programming2021
/week03/lab3.3Strings/lab3.3.3normalise.py
1,200
4.6875
5
#This programme reads in a string, strips any leading or trailing spaces, #converts the string to lowercase #and outputs length for the input and output strings #Author: Ruth McQuillan #This question was also asked in lab2.3.5 string1 = input (str( " Please enter a string: " )) #required - a string normalisedString1 = string1.strip () .lower () #strips out spaces and coverts string to all lower case lenString1 = len(string1) #counts the number of characters in the input string lenNormString1 = len (normalisedString1) #counts the number of characters in the normalised string print ("That String normalised is :{}".format (normalisedString1)) #prints normalised string print ("We reduced the input string from {} to {} characters".format(lenString1,lenNormString1)) #outputs the reduction in the length of #characters due to normalisation
true
1e917fbfdfa0fa76e94a7c509f3dd9126b24f110
sticktoFE/imooc
/apps/ml/DimensionalityReduction.py
1,521
4.1875
4
""" 9.降维算法(Dimensionality Reduction Algorithms) 在过去的4-5年里,可获取的数据几乎以指数形式增长。公司/政府机构/研究组织不仅有了更多的数据来源,也获得了更多维度的数据信息。 例如:电子商务公司有了顾客更多的细节信息,像个人信息,网络浏览历史,个人喜恶,购买记录,反馈信息等,他们关注你的私人特征, 比你天天去的超市里的店员更了解你。 作为一名数据科学家,我们手上的数据有非常多的特征。虽然这听起来有利于建立更强大精准的模型,但它们有时候反倒也是建模中的一大难题。 怎样才能从1000或2000个变量里找到最重要的变量呢?这种情况下降维算法及其他算法,如决策树,随机森林,PCA,因子分析,相关矩阵, 和缺省值比例等,就能帮我们解决难题。 进一步的了解可以阅读Beginners Guide To Learn Dimension Reduction Techniques (https://www.analyticsvidhya.com/blog/2015/07/dimension-reduction-methods/) """ #Import Library from sklearn import decomposition #Assumed you have training and test data set as train and test # Create PCA obeject pca= decomposition.PCA(n_components=k) #default value of k =min(n_sample, n_features) # For Factor analysis #fa= decomposition.FactorAnalysis() # Reduced the dimension of training dataset using PCA train_reduced = pca.fit_transform(train) #Reduced the dimension of test dataset test_reduced = pca.transform(test)
false
97bdeb85fdd83fda25b2d25151df7c7495d1e323
Sarath-Kumar-S/Zigzag-pattern
/Zigzag.py
1,243
4.21875
4
# Python3 program to prthe given # zigzag pattern # Function to prthe zigzag pattern def printPattern(n): var = 0 var = 1 for i in range(1, n + 1): # for odd rows if(i % 2 != 0): # calculate starting value var = var + i - 1 for j in range(1, i + 1): if(j == 1): print(var, end = "") else: print("*", end = "") print(var, end = "") var += 1 else: # for even rows var1 = var + i -1 # calculate starting value for j in range(1, i + 1): if(j == 1): # prwithout star print(var1, end = "") else: # prwith star print("*", end = "") print(var1, end = "") var1 -= 1 print() # Driver code n = 5 printPattern(n)
false
be90a3c4fceba3d2dba6c93c898441ad503ca9de
ByeongGil-Jung/Python-OOP
/src/exercise_3/C_MagicMethod.py
1,445
4.125
4
# 매직 메소드 """ 매직 메소드 (Magic Method) -> __init__ 과 같이 오브젝트 안에서 실행되는 기본 클래스 메소드 -> 효율적인 코딩을 위해선 꼭 알아둬야 함! """ class Dog(object): def __init__(self, name, age): print('Name : {}, Age : {}'.format(name, age)) """ 일반적으로 사용하는 a + b 와 같은 오퍼레이터도 사실 내부적으로 a.__add__(b) 라는 매직 메소드가 동작하는 것이다. """ class MyInt(int): pass class MyInt2(int): # __add__ 변경 (int 에서 string) 으로 def __add__(self, other): return '{} plus {} is {}'.format(int(self), int(other), int(self) + int(other)) """ 즉, 클래스의 매직 메소드를 잘 오버라이딩 하면 정말 효율적이고 편리한 객체지향을 만들 수 있다. """ class Food(object): def __init__(self, name, price): self.name = name self.price = price def __str__(self): return 'Item : {}, Price : {}'.format(self.name, self.price) """ lt (less than) :: < 등의 오퍼레이터의 return 값도 수정할 수 있다. """ class Food2(object): def __init__(self, name, price): self.name = name self.price = price def __lt__(self, other): if self.price < other.price: return True else: return False def __add__(self, other): return self.price + other.price
false
4275495d3b83a80169a04e060967a6fdca27bbad
DavidFliguer/devops_experts_course
/homework_3/exercise_7_8_9_10.py
731
4.125
4
import os def print_file_content(path_to_file, ec): # Read content with open(path_to_file, "r", encoding=ec) as file: content = file.read() # Print the content print(content) encoding = "utf-8" file_name = "words.txt" # If file exists delete it (So we can run same script multiple times) if os.path.exists(file_name): os.remove(file_name) # Create a file in write mode and write to it with open(file_name, "w") as file: file.write("David \n") # Print the file content print_file_content(file_name, encoding) # Append hebrew content with open(file_name, 'a', encoding=encoding) as file: file.write('שלום לכולם') # Print the file content print_file_content(file_name, encoding)
true
2dc59d61d74d7cb8acefdb1114d91daefa139d2d
Moly-malibu/MIT_6.00SC_VPT_Learn_Together
/Problem_Set4_Caesar_Cipher/Problem_Set4_Caesar_Cipher_Encoder.py
2,721
4.125
4
import string def build_coder(shift): """ apply a Caesar cipher to a letter returns a dict shift: int -27-27 Example: >>> build_coder(3) {' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'} (The order of the key-value pairs may be different.) """ upper_letters = " " + string.ascii_uppercase lower_letters = " " + string.ascii_lowercase result = {} for i in upper_letters: index = upper_letters.index(i) #if shift < 0: if 0 <= index + shift < len(upper_letters): result[i] = upper_letters[index + shift] else: result[i] = upper_letters[abs(len(upper_letters) - abs(index + shift))] for i in lower_letters: index = lower_letters.index(i) if 0 <= index + shift < len(lower_letters): result[i] = lower_letters[index + shift] else: result[i] = lower_letters[abs(len(lower_letters) - abs(index + shift))] return result def build_encoder(shift): """Returns a dict that can be used to encode a plain text. shift: 0 <= int < 27 returns: dict """ return build_coder(shift) def build_decoder(shift): """Returns a dict that can be used to decode an encrypted text shift: 0 <= int < 27 returns: dict """ return build_coder(-shift) def apply_coder(text, coder): """Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text Example: >>> apply_coder("Hello, world!", build_encoder(3)) 'Khoor,czruog!' >>> apply_coder("Khoor,czruog!", build_decoder(3)) 'Hello, world!' """ # NOTE: python str is immutable text_copy = list(text) result = [] for letter in text_copy: result.append(coder.get(letter, letter)) return ''.join(result) def apply_shift(text, shift): """Given a text, returns a new text Caesar shifted by the given shift offset. The empty space counts as the 27th letter apply_shift('This is a test.', 8) 'Apq hq hiham a.' """ res = apply_coder(text, build_encoder(shift)) return res
false
8870d8bd5e38c5c28bf81fa4737e0582daa0bab3
aliu31/IntroToProgramming17
/Day26/textprocessing78b.py
830
4.1875
4
import string text = "I hope that in this year to come, you make mistakes. Because if you are making mistakes, then you are making new things, trying new things, learning, living, pushing yourself, changing yourself, changing your world. You're doing things you've never done before, and more importantly, you're doing something.".lower() def clean_text(text_to_clean, forbidden): """take a string to clean and a string of forbidden characters. print out a version that does not include forbidden characters""" clean_string = '' for letter in text_to_clean: if letter not in forbidden: clean_string += letter return clean_string words = clean_text(text, 'aeiou').split() print(words) # cleaned_text = '' # split_text = cleaned_text.split() # split_text.sort() # print(split_text)
true
c1e9826eaa6eb14e1943fd42f94c923533e82752
Lava4creeper/RockPaperScissors
/User_Choice.py
760
4.1875
4
#Functions def choice_checker(question): valid = False error = 'Error. Please enter Paper, Scissors or Rock' while not valid: #Ask user for choice response = input(question).lower() if response == 'r' or response == 'rock': response = 'Rock' print('You selected {}'.format(response)) elif response == 'p' or response == 'paper': response = 'Paper' print('You selected {}'.format(response)) elif response == 's' or response == 'scissors': response = 'Scissors' print('You selected {}'.format(response)) else: print(error) #Main Routine user_choice = "" rps_list = ['rock', 'paper', 'scissors'] while user_choice != 'xxx': user_choice = choice_checker("Choose rock, paper, or scissors: ")
true
18ea1470ebed93614532e2c8e55515dec1e31fef
Kasimir123/python-projects
/games/hangman.py
2,662
4.1875
4
import re print ("Welcome to Hangman, please enter a word which you would like to use for the game, and then enter how many failed guesses you wish to give to the players.") # Initializes constants for the program word = input("What is the word?") # Checks to see if the player actually put a word or phrase into the input if len(word) <= 0: print ("Please write a word or phrase") while len(word) <= 0: word = input("What is the word?") # Storage for all the letters that were already guessed guesses = [] # The number of incorrect guesses that the players will get counter = input("How many missed guesses do you want to give the players?") # Makes sure the user inputs a reasonable number of incorrect guesses if counter <= 0 or counter >= 10: print ("Number of guesses must be greater than 0 and less than 10") while counter <= 0: counter = input("How many missed guesses do you want to give the players?") # Shows what letters have been revealed and which ones still need to be guessed reveal = [] # creates a space between the original questions and the game - i = the number of spaces wanted i = 30 for each in word: reveal.append("_") while i > 0: print ("|") i -= 1 # Checks if there are spaces in the phrase, if yes, then it replaces the empty spaces with a space if " " in word: for m in re.finditer(" ", word): m = m.start() reveal[m] = " " print (reveal) # The loop will not start again if there are no incorrect guesses left while counter > 0: # If there have been previous guesses then this if loop will print them if len(guesses) != 0: print ("Guesses so far: ") print (guesses) # Asks the player for their next guess guess = input("What is your guess?") # Checks if the guess is only 1 letter, if the letter has been guessed before, if the user wishes to quit the game if len(guess) == 1 : if guess not in guesses: guesses.append(guess) # This if statement and for loop find if the letter is in the word or phrase and replace the spaces in reveal with the correct letter based on their position if guess in word: for m in re.finditer(guess, word): m = m.start() reveal[m] = guess else: print ("You have guessed incorrectly") counter = counter - 1 else: print ("You have already used this letter") elif guess == "quit": break else: print ("Your guess is longer than 1 letter") # Shows the incorrect guesses left and leters revealed print (reveal) print ("Incorrect guesses left:") print (counter) # Checks if the player has won or lost if "_" not in reveal: print ("Congrats, you have won") break elif counter == 0: print ("You have lost") break
true
45be00401b1fcf6095e7fb3a219ae39abb76f368
jpsalviano/ATBSWP_exercises
/chapter7/strongPasswordDetection.py
1,718
4.25
4
# Strong Password Detection ''' A strong password is defined as one that: -is at least 8 characters long -contains both uppercase and lowercase characters -has at least 1 digit You may need to test the string against multiple regex patterns to validade its strength. ''' import re passRegex1 = re.compile(r'[a-z]+[A-Z]+[0-9]+') passRegex2 = re.compile(r'[a-z]+[0-9]+[A-Z]+') passRegex3 = re.compile(r'[A-Z]+[a-z]+[0-9]+') passRegex4 = re.compile(r'[A-Z]+[0-9]+[a-z]+') passRegex5 = re.compile(r'[0-9]+[A-Z]+[a-z]+') passRegex6 = re.compile(r'[0-9]+[a-z]+[A-Z]+') def passRegexes(password): if passRegex1.search(password) != None: return True if passRegex2.search(password) != None: return True if passRegex3.search(password) != None: return True if passRegex4.search(password) != None: return True if passRegex5.search(password) != None: return True if passRegex6.search(password) != None: return True def isPasswordStrong(): while True: password = input('Type a password:\n') if len(password) >= 8: if passRegexes(password) == True: passwordConfirmation(password) break else: print('Your password must contain both uppercase and lowercase letters, and at least 1 digit.') else: print('Your password must be at least 8 characters long.') def passwordConfirmation(password): confirmPass = input('Type your password again:\n') if confirmPass == password: print('Your password has been set.') else: print('Passwords typed are different.') isPasswordStrong() isPasswordStrong()
true
cfc0e00ea288974044d513f9fab21c417f1dcd71
azuluagavarios/Python
/palindromo.py
1,323
4.21875
4
def palindromo(palabra): # Tambien se puede utilizar la funcion strip, pero solo quita los del inicio o el final palabra = palabra.replace(" ", "") palabra = palabra.lower() print(palabra) # El uso de corchetes, tambien permite ubicar un caracter especial [0], trae el primer caracter # Tambien permite traer en un subconjunto [1:3] # Tabien se puede traer un subconjunto saltando cada ciertos caracters [1:6:2] # Dado lo anterior, es por eso que lo siguiente permite invertir caracteres [::-1] palabra_invertida = palabra[::-1] print(palabra_invertida) # En Python se pueden comparar cadenas de caracteres con == if(palabra == palabra_invertida): return True else: return False def separar(palabra, separador): palabra = palabra.split(separador) return palabra # Estandar en la comunidad, de la funcion principal, tambien puede ser main() # Pero se ha definido que es run() def run(): palabra = input("Escribe una plabra: ") es_palindromo = palindromo(palabra) if(es_palindromo): print("Es palindromo") else: print("No es un palindromo") palabra = separar(palabra, ",") print(palabra) # Forma estandar de indicar, donde comienza a ejecutar un programa if __name__ == '__main__': run()
false
cd7d01e883759a9234932a317d22838fc47c71e7
chutki-25/python_ws
/M1_Q/q6.py
261
4.1875
4
"""Write a program to accept a number from the user; then display the reverse of the entered number.""" num=int(input("Enter a number: ")) temp=num rem=0 rev=0 while num!=0: rem=num%10 rev=rev*10+rem num=num//10 print(f"Reverse of {temp} is {rev}")
true
41993386ffc1730a981a99d01f3c6830166c4f2e
dglo/dash
/IntervalTimer.py
1,275
4.375
4
#!/usr/bin/env python "Timer which triggers each time the specified number of seconds has passed" from datetime import datetime class IntervalTimer(object): """ Timer which triggers each time the specified number of seconds has passed. """ def __init__(self, name, interval, start_triggered=False): self.__name = name self.__is_time = start_triggered self.__next_time = None self.__interval = interval def is_time(self, now=None): "Return True if another interval has passed" if not self.__is_time: secs_left = self.time_left(now) if secs_left <= 0.0: self.__is_time = True return self.__is_time def reset(self): "Reset timer for the next interval" self.__next_time = datetime.now() self.__is_time = False def time_left(self, now=None): "Return the number of seconds remaining in this interval" if self.__is_time: return 0.0 if now is None: now = datetime.now() if self.__next_time is None: self.__next_time = now dtm = now - self.__next_time secs = dtm.seconds + (dtm.microseconds * 0.000001) return self.__interval - secs
true
10b6d0ecc6acc199ea3f15eff3b229bbb4f9d26e
jstev680/cps110
/examples/guess/guess_inclass.py
827
4.125
4
import random def generateSecretNumber(): """returns a random number from 1 to 10""" # generate secret number secretNum = random.randrange(1, 11) return secretNum def giveFeedback(guess, secretNum): """compares `guess` to `secretNum` and gives appropriate feedback""" # Give feedback on guess if guess < secretNum: print("Your guess is too low.") elif guess > secretNum: print("Your guess is too high.") else: print("You got it!!") def main(): secretNum = generateSecretNumber() numGuesses = 0 guess = 0 while guess != secretNum: guess = int(input("Enter your guess: ")) numGuesses += 1 giveFeedback(guess, secretNum) print("It took you", numGuesses, "guesses.") if __name__ == '__main__': main()
true
0feeab54988a6274ba965f51c10d241086a1cd99
boragungoren-portakalteknoloji/METU-BUS232-Spring-2021
/Week 3 - More on Variables and Operations/Week 3 - Numerical Operations.py
2,040
4.28125
4
# License : Simplified 2-Clause BSD # Developer(s) : Bora Güngören # Let's begin with some basics a = 2 b = 3 c = a + b print("a:",a,"b:",b,"c:",c) # So how did this work? # operator+ (summation) works and its result is passed as RHS of operator= (assignment) # operator= assigns the results to variable c. # Values of a and b are not changed. # Then some more calculations c = a * b + b * c # Multiplication is done before summation # 2 x 3 + 3 x 5 # 6 + 15 # 21 print("a:",a,"b:",b,"c:",c) c = ( a - 1) * b # Paranthesis is done before all # 1 * 3 # 3 print("a:",a,"b:",b,"c:",c) c = a / b # Division is not necessarily yielding an integer value # the result is floating point value # Because Python is dynamically typed, c becomes a floating point (real number) variable print("a:",a,"b:",b,"c:",c) # See if you explicitly make a and b integers a = int(2) b = int(3) c = a / b # Division is not necessarily yielding an integer value again print("a:",a,"b:",b,"c:",c) # So if you want to have an integer value for the result, convert it c = int( a / b) print("a:",a,"b:",b,"c:",c) # Integer conversion is not rounding c = -1.5 # -1.5 should be rounded to what? print("c:",c, "int(c)",int(c)) # For rounding, there are many methods. # See - https://realpython.com/python-rounding/ # Math operations # 1- Order: Paranthesis, mult/div over add/subtract, left over right when equal # 2- Type of result: Integers divided can end up as floats a = 2.0 # a became a float b = 3.0 # b became a float c = a + b print("a:",a,"b:",b,"c:",c) # 5.0 in the output means c became a float d = c + 1 # c is a float, 5.0 and 1 is an integer print("d:",d) # e = d / 0 # divide by zero crashes your program # ZeroDivisionError: float division by zero e = d / 0.00000000001 # divide by near-zero does not crash your program print("e:",e) f = 5.0001 g = 4.9999 difference = f - g # floats are not necessarily exact print ("difference:", difference) e = d / difference print("e:",e) # Many people round the result of float operations
true
377b578cff00723a50624c78e010a659e6923acc
bjmarsh/insight-coding-practice
/daily_coding_problem/2020-08-22.py
1,130
4.28125
4
""" Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid. """ def encode(s: str) -> str: istart = 0 enc = "" while istart < len(s): iend = istart while iend < len(s) and s[iend] == s[istart]: iend += 1 enc += str(iend-istart) + s[istart] istart = iend return enc def decode(s: str) -> str: dec = "" istart = 0 dig = set(list('0123456789')) while istart < len(s): iend = istart while s[iend] in dig: iend += 1 n = int(s[istart:iend]) dec += s[iend] * n istart = iend+1 return dec if __name__ == "__main__": print(encode("AAAABBBCCDAA")) print(decode(encode("AAAABBBCCDAA"))) print(decode("4A10B1C"))
true
5fe85104289ab957ad5e755eee09c056616aa398
bjmarsh/insight-coding-practice
/daily_coding_problem/2020-09-08.py
817
4.3125
4
""" Given a string, find the longest palindromic contiguous substring. If there are more than one with the maximum length, return any one. For example, the longest palindromic substring of "aabcdcb" is "bcdcb". The longest palindromic substring of "bananas" is "anana". """ def find_palindromic_substring(s): max_s = None max_len = 0 i = 0 while i + max_len < len(s): for j in range(i + max_len + 1, len(s)+1): ss = s[i:j] if ss==ss[::-1]: max_len = len(ss) max_s = ss i += 1 return max_s if __name__ == "__main__": print(find_palindromic_substring("")) print(find_palindromic_substring("abc")) print(find_palindromic_substring("aabcdcb")) print(find_palindromic_substring("bananas"))
true
7996c5bc03affa4cca148438229aaa9c592a3ac6
bjmarsh/insight-coding-practice
/daily_coding_problem/2020-08-03.py
668
4.28125
4
""" Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. """ class Queue: def __init__(self): self.data = [] # a stack def enqueue(self, val): self.data.append(val) # push onto stack def dequeue(self): temp_stack = [] while len(self.data) > 0: temp_stack.append(self.data.pop()) val = temp_stack.pop() while len(temp_stack) > 0: self.data.append(temp_stack.pop()) return val if __name__ == "__main__":
true
b05924b936ae42c05b7c36ffb9a0c9cde6cc261c
Marcus-Jon/common_algroithms_python
/prime_checker.py
601
4.125
4
# common prime checker # import in other programs to make use of this function # place in same directory as the file calling it def prime_check(): x = 2 is_prime = False prime = input('Enter a prime number: ') while is_prime != True and x < prime: print '\r', prime % x, x, if prime % x != 0 and x == (prime - 1): is_prime = True elif prime % x == 0: print '\n' prime = input('Not Prime. Enter a prime number: ') x = 1 x += 1 print 'Prime found' print '\n' return prime
true
cf5767864913ce69d767036259df39dc3a7bc444
NataFediy/MyPythonProject
/codingbat/make_pi.py
306
4.125
4
#! Task from http://codingbat.com: # Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}. # # Example: # make_pi() → [3, 1, 4] def make_pi(): pi = {0:3, 1:1, 2:4} str_pi = [] for i in range(len(pi)): str_pi.append(pi[i]) return str_pi print(make_pi())
true
f49c940491bbb3361cfe5bb6bc109288086f29ef
NataFediy/MyPythonProject
/hackerrank/functions_filter.py
2,404
4.40625
4
#! You are given an integer N followed by N email addresses. # Your TASK is to print a list containing only valid email addresses # in lexicographical order. # # Valid email addresses must follow these rules: # It must have the username@websitename.extension format type. # The username can only contain letters, digits, dashes and underscores. # The website name can only have letters and digits. # The maximum length of the extension is 3. # # Concept: # A filter takes a function returning True or False and applies it # to a sequence, returning a list of only those members of the sequence # where the function returned True. # A Lambda function can be used with filters. # # Let's say you have to make a list of the squares of integers from 0 to 9 # (both included). # # >> l = list(range(10)) # >> l = list(map(lambda x:x*x, l)) # Now, you only require those elements that are greater than 10 but # less than 80. # # >> l = list(filter(lambda x: x > 10 and x < 80, l)) # # Input Format: # The first line of input is the integer N, the number of email addresses. # N lines follow, each containing a string. # # Output Format: # Output a list containing the valid email addresses in lexicographical # order. If the list is empty, just output an empty list, []. # # Sample Input: # 3 # lara@hackerrank.com # brian-23@hackerrank.com # britts_54@hackerrank.com # Sample Output: # ['brian-23@hackerrank.com', 'britts_54@hackerrank.com', 'lara@hackerrank.com'] def fun(s): if '@' not in s: return False else: username, other = s.split('@') name = str(username) arr = list(str(other).split('.')) if len(arr) < 2: return False else: web_site_name = str(arr[0]) extension = str(arr[1]) if len(extension) > 4: return False elif len(web_site_name) == 0: return False elif web_site_name.isalnum() is False: return False elif len(name) == 0: return False elif '_' not in name and '-' not in name and name.isalnum() is False: return False else: return True def filter_mail(e_mails): return list(filter(fun, e_mails)) if __name__ == '__main__': n = int(input()) emails = [] for _ in range(n): emails.append(input()) filtered_emails = filter_mail(emails) filtered_emails.sort() print(filtered_emails)
true
3a9de00f8bf616d76899e1655611a9f24d37c320
yash1th/ds-and-algorithms-in-python
/string processing/is_palindrome_permutation.py
818
4.1875
4
def is_palindrome_permutation(s): ''' for strings of - * even length - all characters should be of even count * odd length - all characters should be of even count except one which have odd count ''' s = s.replace(' ', '').lower() ht = dict() for i in s: if i in ht: ht[i] += 1 else: ht[i] = 1 odd_count = 0 for k, v in ht.items(): if v % 2 != 0 and odd_count == 0: odd_count += 1 elif v % 2 != 0 and odd_count != 0: return False return True palin_perm = "Tact Coa" not_palin_perm = "This is not a palindrome permutation" print(is_palindrome_permutation(palin_perm)) print(is_palindrome_permutation(not_palin_perm)) print(is_palindrome_permutation('ACCCA'))
false
11d23110fd02fb40f1c5f652cbde07968864dfe1
pastqing/wangdao
/LearnPython/ex3.py
972
4.1875
4
# -- coding: utf-8 - # + plus # - minus # / slash # * asterisk # % percent # < less-than # > greater-than # <= less-than-equal # >= greater-than-equal print "I will now count my chickens:" # count The Hens nums print "Hens", 25 + 30.0 / 6 # count The Roosters nums print "Roosters", 100 - 25 *3 % 4 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6 # 9 #浮点数的输出 print 1.0 / 4 print "Is it true that 3 + 2 < 5 - 7?" # not true print 3 + 2 < 5 - 7 #False print "What is 3 + 2?", 3 + 2 # 5 print "What is 5 - 7?", 5 - 7 # -2 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal", 5 >= -2 # 浮点数的格式化输出 print ('%.3e %.3f %.3g' %(0.00033333, 0.00033333, 0.00033333)) # e/f/g都指定了精度为3, e输出了4位有效数字(包括3位小数),f输出了3位小数, g输出了3位有效数字
false
e3f173cb7d8ae4c1dc91802446a426eb00c02a37
alex9985/python-and-lists
/find-smallest-item.py
252
4.1875
4
#find smalest number in a list # my_list = [] num = int(input("Enter number of elements to put into the list ")) for i in range(1, num + 1): elem = int(input("Enter elements: ")) my_list.append(elem) print("Smallest element is ", min(my_list))
true
36fe802656d0878d7af3dd94830128672790afb7
vasu19126/introduction
/samples/input.py
516
4.25
4
print("write your information") name = input("what is your name : ") age = input("how old are you: ") fname =input("ur father's name: ") mname =input("ur mother's name: ") hobby =input("urs hobby: ") phoneno = int(input("ur phone no.: ")) email =input("ur e-mail id: ") enter=input("type ok for regisetration: ") def ok(): return "your regisetration is successful" print(ok()) #name = input("Enter your name : ") #age= input("how old are you {0}:".format(name)) #print("hello", name, ' u r', age , 'years old')
false
833df1679a2e17553a52eec241801873078d1e79
cychug/projekt3
/006_Operacje_arytmetyczne.py
721
4.15625
4
# 3. Arithmetic Operations # x = 3; y = 2 x, y = 3, 2 print(x + y) print(x - y) print("mnoenie x * y", x * y) print("dzielenie x / y", x / y) print("dzielenie w dół //", x // y) print("modulo %", x % y) # Przykład: 20 mod 3 = 2, ponieważ 20 / 3 = 6 z resztą 2. (6 * 3) + 2 = 18 + 2 = 20 print("wartość przeciwna -x", -x) # przeciwna = -3 print("wartość bezwzględna", abs(-x)) # wartność bezwzględna print(int(3.9)) # wartość całkowita 3 print(int(-3.9)) # wartość całkowita - 3 print(float(3)) # wartość zmiennoprzecinkowa print(x ** y) # potęgowanie
false
790786a09d8a57b423fb745270f23bd1e8e8c4ad
hmol/learn-python
/learn-python/dragon.py
1,545
4.125
4
import random import time # In this game, the player is in a land full of dragons. The dragons all live in caves with their large # piles of collected treasure. Some dragons are friendly and share their treasure with you. Other # dragons are hungry and eat anyone who enters their cave. The player is in front of two caves, one # with a friendly dragon and the other with a hungry dragon. The player must choose between the # two. def print_intro(): print('You are in a land full of dragons. In front of you,'+ '\nyou see two caves. In one cave, the dragon is friendly'+ '\nand will share his treasure with you. The other dragon'+ '\nis greedy and hungry, and will eat you on sight.') def choose_cave(): cave = '' while cave != '1' and cave != '2': print('Which cave will you go into? (1 or 2)') cave = input() return cave def enter_cave(cave_number): print('You approach the cave...') time.sleep(2) print('It is dark and spooky...') time.sleep(2) print('A large dragon jumps out in front of you! He opens his jaws and ...') print() time.sleep(2) friendlyCave = random.randint(1, 2) if cave_number == str(friendlyCave): print('Gives you his treasure!') else: print('Gobbels you down in one bite!') playAgain = 'yes' while playAgain == 'yes' or playAgain == 'y': print_intro() cave_number = choose_cave() enter_cave(cave_number) print('Do you want to play again? (yes or no)') playAgain = input()
true
aedf715fa42a5e904b36cfbac5b33c54d6da583e
kartikmanaguli/sample
/1.py
327
4.15625
4
def computegrade(x): if x>=0.0 and x<=1.0: if x>=0.9: print('A') elif x>=0.8: print('B') elif x>=0.7: print('C') elif x>=0.6: print('D') else: print('F') else: print('Out of range!') x=float(input('Enter the grade:')) computegrade(x)
false
66c321fdcf40d1145a14d1aac44186bbbd743873
Alex1992coyg/project4
/src/shape_calculator.py
1,177
4.125
4
#!/usr/bin/env python3 class Rectangle: def __init__ (self,width,height): self.width = width self.height = height def set_width(self,value): self.width =value def set_height(self,value): self.height =value def get_area (self): return(self.width * self.height) def get_perimeter (self): return(2*self.width + 2*self.height) def get_diagonal(self): return ((self.width ** 2 + self.height ** 2) ** .5) def get_picture(self): if self.width > 50 or self.height > 50 : return ( "Too big for picture.") else: return ((("*" * self.width + "\n" ) * self.height)) def get_amount_inside(self,Shape): return ( self.get_area() // Shape.get_area()) def __str__ (self): return f"Rectangle(width={self.width}, height={self.height})" class Square(Rectangle): def __init__ (self,side): Rectangle.width = side Rectangle.height = side def set_side (self,value): Rectangle.set_width(self,value) Rectangle.set_height(self,value) def __str__ (self): return f'Square(side={self.width})'
false
7aa018723ff8f18fd78e55eed042888448177111
shoaib-intro/algorithms
/primetest.py
511
4.15625
4
''' Prime Test ''' def is_prime(n): 'prime started 2,3,5 ....' if (n>=2): 'divides number by its whole range numbers' for i in range(2,n): 'if whole dividisible returns false=0' if not(n%i): return False else: return False return True 'Test Number' count=0 for i in range(int(input("Enter number for prime test! "))): if(is_prime(i)): count+=1 print(i) print('There '+str(count)+' prime number/s found!')
true
84b93b4f2ca4b9804d502a1557a51595cd49dd1c
tanni-Islam/test
/partial_func.py
349
4.15625
4
'''from functools import partial def multiply(x,y): return x * y dbl = partial(multiply,2) print dbl(4) ''' #Following is the exercise, function provided: from functools import partial def func(u,v,w,x): return u*4 + v*3 + w*2 + x #Enter your code here to create and print with your partial function dbl = partial(func,5,6,7) print dbl(8)
true
1994dd456f674002a0921d23f6212d6d92a68112
kamyanskiy/demo
/yield_from_two_gen.py
711
4.34375
4
# Python 3.3+ - yield from gen1 = (print(x) for x in range(0,5)) gen2 = (print(x) for x in range(5,10)) """ def gen3(): for i in gen1: yield i for j in gen1: yield j """ def gen3(): print("First generator starts") yield from gen1 print("Second generator starts") yield from gen2 # init generator gen = gen3() print("Show type gen:", type(gen)) # First's generator iteration next(gen) next(gen) next(gen) next(gen) next(gen) # Second's generator iteration next(gen) next(gen) next(gen) next(gen) next(gen) """ next(gen) Traceback (most recent call last): File "/home/biceps/work/demo/yield_from_two_gen.py", line 30, in <module> next(gen) StopIteration """
false
a936801bafe2ad2bf0cac1ff53aec16feddd8be6
unsilence/Python-function
/数据结构与算法/线性表/single_link_list_recurrent.py
2,513
4.125
4
from 线性表.single_linked_list import Node class RecurrentLinkList: def __init__(self, node=None): self._head = node if node: node.next = node def add(self, item): node = Node(item) self._head = node node.next = node def append(self, item): if self.is_empty(): self.add(item) else: node = Node(item) first_node = self._head current_node = self._head while current_node.next != first_node: current_node = current_node.next current_node.next = node node.next = first_node def travel(self): cur = self._head if self.is_empty(): print('当前链表为空!') # print(cur.ele, end=' ') while cur.next != self._head: print(cur.ele, end=' ') cur = cur.next print(cur.ele) # print('0') def insert(self, pos, ele): if pos <= 0 : node = Node(ele) cur = self._head first_node = self._head while cur.next != self._head: cur = cur.next cur.next = node self._head = node node.next = first_node elif pos > self.length(): self.append(ele) else: current_node = self._head node = Node(ele) count = 0 while count < (pos - 1): current_node = current_node.next count += 1 node.next = current_node.next current_node.next = node def is_empty(self): return self._head == None def length(self): if self._head == None: return 0 else: count = 1 current_node = self._head first_node = self._head while current_node.next != first_node: count += 1 current_node = current_node.next print(count) return count def list2rll(self, list): for i in list: self.append(i) def delete_node(self, node): pass if __name__ == '__main__': # a = Node(2) ll = RecurrentLinkList() # ll.travel() ll.add('a') ll.length() ll.append('b') ll.travel() ll.length() ll.append('c') ll.travel() ll.length() ll.insert(10, 'd') ll.travel() ll.length() # ll.insert(2, 'd') # ll.travel()
false
b43f3646d54bffa29d4640e018bf66f27764d8b8
Sangram19-dev/Python-GUI-Projects
/lived.py
2,522
4.40625
4
# Python Programming Course:GUI Applications sections # - Sangram Gupta # Source code for creating the age calculator from tkinter import * from datetime import datetime # Main Window & Configuration App = Tk() App.title("Age Calculator") App['background'] = 'white' App.geometry('300x300') # 'Enter Your DOB' Label lbl = Label(App, text='Enter Your DOB', background='white', foreground='black') lbl.grid(row=0, column=0, columnspan=2) # Date Label & Entry widget dateL = Label(App, text='Date:', background='white', foreground='black') dateE = Entry(App, background='white', foreground='black', width=2) # Month Label & Entry widget monL = Label(App, text='Month:', background='white', foreground='black') monE = Entry(App, background='white', foreground='black', width=2) # Year Label & Entry widget yrL = Label(App, text='Year:', background='white', foreground='black') yrE = Entry(App, background='white', foreground='black', width=4) # Placing the widgets using grid dateL.grid(row=1, column=0) dateE.grid(row=1, column=1) monL.grid(row=1, column=2) monE.grid(row=1, column=3) yrL.grid(row=1, column=4) yrE.grid(row=1, column=5) # Finding Total days and creating it's Label def find_days(): year = int(yrE.get()) month = int(monE.get()) day = int(dateE.get()) dob = datetime(year=year, month=month, day=day) time_now = datetime.now() time_dif = time_now - dob msg = Label(App, text='You lived ' + str(time_dif.days) + ' days!', background='white', foreground='black') msg.grid(row=3, column=0, columnspan=3) # Finding Total seconds and creating it's Label def find_sec(): year = int(yrE.get()) month = int(monE.get()) day = int(dateE.get()) dob = datetime(year=year, month=month, day=day) time_now = datetime.now() time_dif = time_now - dob msg = Label(App, text='You lived ' + str(time_dif.total_seconds()) + ' seconds!', background='white', foreground='black') msg.grid(row=4, column=0, columnspan=6) # Buttons for finding total days & seconds daysB = Button(App, text='Total days', command=find_days, background='white', foreground='black') scndB = Button(App, text='Total seconds', command=find_sec, background='white', foreground='black') # Placing the buttons daysB.grid(row=2, column=0, padx=5, pady=5, columnspan=3) scndB.grid(row=2, column=3, padx=5, pady=5, columnspan=3) App.mainloop()
true
90714eeaf5e4fc0e98499de79496c93d12f78e16
clacap0/simple
/counting_vowel.py
351
4.25
4
""" Count the vowels in a string """ def count_vowels(phrase): vowels = 'aeiou' counter = 0 for letter in phrase: for vowel in vowels: if vowel==letter: counter += 1 return f'There are {counter} vowel(s) in your phrase.' print(count_vowels(input('What phrase would you like to input? ').lower()))
true
4a96e3b5613b5b414e010c18a046113c54191ca2
TANADONsim/CP1404_Practicals
/prac_05/color_hex.py
615
4.21875
4
COLOR_NAMES = {"ALICEBLUE": "#f0f8ff", "ANTIQUEWHITE": "#faebd7", "BEIGE": "#f5f5dc", "BLACK": "#000000", "BLANCHEDALMOND": "#ffebcd", "BLUEVIOLET": "#8a2be2", "BURLYWOOD": "#deb887"} # print(STATE_NAMES) color = input("Enter color name: ") color = color.upper() while color != "": if color in COLOR_NAMES: print(color, "is", COLOR_NAMES[color]) elif color == "ALL": for color in COLOR_NAMES: print("{0:<4} is {1}".format(color, COLOR_NAMES[color])) else: print("Invalid color name") color = input("Enter color name : ") color = color.upper()
false
f42055a17f024c6985169a32686cfcec7fd8ad6d
akmishra30/python-projects
/python-basics/file-handling/file-reader.py
1,099
4.5
4
#!/usr/bin/python # This program is to show basic of python programming # I'm opening a file using python # import os import sys import time from datetime import datetime # This function is to open a file def open_file(fileName): print('Hello First Python program', fileName) _currDir = os.getcwd() + os.sep + 'resource' + os.sep + fileName; print('---> ', _currDir) with open(_currDir, 'r') as _fileObject: _fileText = _fileObject.read() print('---->' + _fileText) # This function is to traverse the dir def traverse_dir(tar_dir): for root, dirs, files in os.walk(tar_dir): print('-----------------------------') print('Root --', root) print('dirs -- ', dirs) t_relpath = os.path.relpath(root, tar_dir) print('t_relpath -- ', t_relpath) if t_relpath != '.': #skipped base folder processing for file in files: print('File Name: -- ', t_relpath + os.sep + file) print('-----------------------------') #open_file('readme.md') traverse_dir('/Users/makhir/Downloads/watch/')
true
03a0f66855fd2aeac2218d0cf662e0dd357e728b
LouStafford/My-Work
/RevisionLabsInputCommand.py
1,152
4.28125
4
# This is for my own practice only and revision by following Andrews lectures re input prompts # & to practice push/pull/commit on Github (also commands) without having to refer to notes from inital lessons # Here we will ~ Read in a Name/Age & print it out # Author Louise Stafford # input('Please enter your name: ') # input needs to be stored as variable name = input('Please enter your name: ') # Line 5 is only requesting input so at this point when I run, there is no output - I need a print function print ('Hello ' + name) # read in age as well as name # input ('Ok to say your age too?: ') # I need to add a variable to age so moving line 10 to a comment and 13 to correct format age = input('Ok to say your age too?: ') # Now need to also output age print('Happy days you are only ' + str(age) ) print ('Many more days to enjoy so!:)') # something I noticed from this excersise is that if I enter text along with my age integer, it repeats the string # so I need to look at that e.g I said in one run 'Yes I am 40' and it gave back all - so probably need to # use foramt brackets? will check out. I'm pulling string and not identifying number only
true
4e66d77b7aca629d9dd0fa24af512e17aa128225
agiri801/python_key_notes
/_05_Data_type_intro/_03_Different_nums_conv.py
800
4.1875
4
''' Default number system is decimal number system.So, it convert any number system to decimal. '0b' prefix numbers are 'Binary number' '0o' prefix numbers are 'Octal-decimal number' '0x' prefix numbers are 'Hexa-decimal number' ''' a=0b10101001 b=0x1589acf c=0O75642 x=int(a) y=int(b) z=int(c) print(a,type(a)) print(b,type(b)) print(c,type(c)) print('----------------------------------') print(x,type(x)) print(y,type(y)) print(z,type(z)) print('------------------------------------') s=bin(1856) n=bin(0o75652) k=bin(0x48569abf) print(s) print(n) print(k) print('------------------------------------') j=oct(1213) l=oct(0b10101001) i=oct(0x4859621abf) print(j) print(l) print(i) print('------------------------------------') m=hex(0b10100011) p=hex(0o57461) q=hex(1856) print(m) print(p) print(q)
false
b8db05cb708fcb42f0ef742779075f96ece1193d
Rosebotics/PythonGameDesign2018
/camp/SamuelR/Day 1 - The Game Loop, Colors, Drawing and Animation/01-HelloWorld.py
636
4.21875
4
# Authors: David Mutchler, Dave Fisher, and many others before them. print('Hello, World') print('Samuel Ray can make Python programs!!!!') print('one', 'two', 'through my shoe') print(3 + 9) print('3 + 9', 'versus', 3 + 9) # DONE: After we talk together about the above, add PRINT statements that print: # DONE: 1. A Hello message to a friend. print('hello Sir Ryland') # DONE: 2. Two big numbers, followed by their sum. print('7009 + 803 = 7812') # DONE: 3. The result of 3,607 multiplied by 34,227. (Hint: the result is interesting.) print(3607 * 34227) # DONE: 4. Anything else you like! print('I LIKE TRAINS !!!!') print('cat' * 65)
true
dcc7fc7191a34a963fd8ebf2a06dfd9f0e0d001f
edharcourt/CS140
/python/string_slices.py
273
4.1875
4
print("Enter three numbers separated by a comma") s = input("> ") comma1 = s.find(',') comma2 = s.find(',', comma1+1) num1 = int(s[:comma1]) num2 = int(s[comma1+1:comma2]) num3 = int(s[comma2+1:]) avg = (num1 + num2 + num3) / 3 print("Average:", round(avg,2))
false
655313660a5bc48feacc71232bf51942b0021bea
richardlam96/notepack2
/notepack/output.py
431
4.21875
4
""" Output functions Functions to aid in outputting messages to the console in specified format. Console logger with datetime and spacing. """ from datetime import datetime def print_welcome_message(): """Print a welcome message to the output.""" now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Welcome message (this can be ASCII-art later). print("Welcome to Notepack App 2.0") print(f"It's {now}")
true
7ac0798213c0e010dc86ef10f746e7274a49340a
sauuyer/python-practice-projects
/day2.py
696
4.34375
4
# Ask the user for their name and age, assign theses values to two # variables, and then print them. name = input("Name, please: ") age = input("Now age: ") print("This is your name: ", name) print("This is your age: ", age) # Investigate what happens when you try to assign a value # to a variable that you’ve already defined.Try printing the variable # before and after you reuse the name. first = "first" print(first) first = "not actually first" print(first) # Code edit prompt hourly_wage = input("Please enter your hourly wage: ") hours_worked = input("How many hours did you work this week? ") print("Hourly wage: ") print(hourly_wage) print("Hours worked: ") print(hours_worked)
true
cd4c089f7bdd43d3bcea05709f0afc962715e005
mrdbourke/LearnPythonTheHardWay
/ex15.py
734
4.25
4
from sys import argv #This tells that the first word of argv is the script (ex15.py) #The second part of argv (argv[1]) is the filename script, filename = argv #This sets up the txt variable to open the previously entered filename txt = open(filename) #This prints the filename print "Here's your file %r:" % filename #Using the .read() function the file is read print txt.read() txt.close() #The user is asked for the filename again (same name as before) print "Type the filename again:" file_again = raw_input("> ") #This sets txt_again to the second filename that the user entered txt_again = open(file_again) #This reads the second entering of the filename and prints the contents print txt_again.read() txt_again.close()
true
238ee5e9a26c8ae49590894032cf49d02fa2a28d
ucsd-cse-spis-2019/spis19-lab04-Emily-Jennifer
/recursiveDrawings.py
2,337
4.375
4
#Turtle draws a spiral depending on initialLength, angle, and multiplier #Also draws a tree. A very nice tree #Emily and Jennifer import turtle def spiral(initialLength, angle, multiplier): '''draws a spiral using a turtle and recursion''' if initialLength < 1 and multiplier < 1: return if initialLength > 200 and multiplier > 1: return turtle.forward(initialLength) turtle.right(angle) spiral(initialLength * multiplier, angle, multiplier) def tree(trunkLength, height): """Draws a recursive tree based off how long you want it to be and how many times you want it to repeat""" if height == 1: turtle.forward(trunkLength) turtle.right(45) turtle.forward(trunkLength // 2) turtle.backward(trunkLength // 2) turtle.left(90) turtle.forward(trunkLength // 2) turtle.backward(trunkLength // 2) turtle.right(45) #Recurses on tree branch else: #turtle moves forward and right turtle.forward(trunkLength) turtle.right(45) tree(trunkLength//2, height-1) #Return of the turtle and then it turns left turtle.backward(trunkLength // 2) turtle.left(90) tree(trunkLength//2, height-1) #Return of the Turtle 2: Uprising turtle.backward(trunkLength // 2) turtle.right(45) def snowflakeSide(sidelength, levels): '''Draws one side of a snowflake recursively depending on sidelength and levels''' #base case - draw one line segment if levels == 0: turtle.forward(sidelength) #recurse four times for snowflake side else: snowflakeSide(sidelength//3, levels-1) turtle.left(60) snowflakeSide(sidelength//3, levels-1) turtle.right(120) snowflakeSide(sidelength//3, levels-1) turtle.left(60) snowflakeSide(sidelength//3, levels-1) def snowflake(sidelength, levels): '''Calls snowflakeSide three times to draw triangle''' snowflakeSide(sidelength,levels) turtle.right(120) snowflakeSide(sidelength,levels) turtle.right(120) snowflakeSide(sidelength,levels) turtle.speed(0) #Test case tree #spiral(1, -45, 1.1) #turtle.left(90) #tree(200, 4) #Test case snowflake #snowflakeSide(100, 2) snowflake(100, 4)
true
651059909198066b6791c7cc18be6a9e0ed96d7f
hayesmit/PDXCodeGuildBootCamp
/lab17-Palindrome_and_anagram.py
875
4.28125
4
#lab17-Palindrome_and_anagram.py import string alpha = string.ascii_lowercase def check_palindrome(word): word = list(word) forward = word word.reverse() palindrome = word if forward == palindrome: print("yes this is a palindrome") def check_anagram(arg1, arg2): arg1 = list(arg1) arg2 = list(arg2) letters1 = [i for i in arg1 if i in alpha] letters1.sort() letters2 = [i for i in arg2 if i in alpha] letters2.sort() if letters1 == letters2: print("yep this is an anagram. ") else: print("Nope, not an anagram") PorA = input("want to check for palindrome or anagram? >> ") if PorA == "palindrome": check_palindrome(input("what do you want to check to see if it is a palindrome? >> ")) elif PorA == "anagram": check_anagram(input("first cluster? >> "), input("second cluster? >> "))
false
acabf73ae50a5983b6be3dbf46b5bad20a911167
hayesmit/PDXCodeGuildBootCamp
/lab12-Guess_the_Number.py
1,099
4.1875
4
#lab12-Guess_the_Number.py import random #user guesses code lines 5-25 #computer = random.randint(1, 10) # #last_guess = 1000 #x = 1 #while x: # my_guess = int(input("guess number " + str(x) + " >> ")) # if last_guess < 100 and abs(my_guess-computer) > abs(last_guess-computer): # print("you are further from the answer than your previous guess.") # elif last_guess < 100 and abs(my_guess-computer) < abs(last_guess-computer): # print("You are getting closer") # if computer == my_guess: # print("You got it and it only took you " + str(x) + " guesses.") # break # elif my_guess > computer: # print("too high!") # x += 1 # last_guess = my_guess # else: # print("to low!") # x += 1 # last_guess = my_guess my_choice = int(input("pick a number 1-10 and lets see how long it takes a computer to guess it. >> ")) x = 1 while x: computerGuess = random.randint(1, 10) if my_choice == computerGuess: print("Got it and it only took " + str(x) + " guesses.") break else: x += 1
true
f7196ceae00207be96fa5fd58abe00e8bd9fec5b
sasca37/PythonPrac
/dfsbfs/ex1.py
762
4.15625
4
stack = [] stack.append(5) stack.append(4) stack.append(4) print(stack[::-1]) #큐를 쓰기위한 deque 라이브러리 사용 from collections import deque queue = deque() queue.append(5) queue.append(2) queue.append(3) queue.append(6) queue.popleft() print(queue) queue.reverse() print(queue) def recursive_function(i): if i == 100: return print(i+1,'번째 재귀 함수를 호출합니다.') recursive_function(i+1) recursive_function(5) def factorial_iterative(n): result=1 # 1부터 n까지의 수곱하기 for i in range(1, n+1): result *= i return result print(factorial_iterative(5)) def factorial_recursive(n): if n <= 1: return 1 return n * factorial_recursive(n-1) print(factorial_recursive(6))
false
9b87dce51612568e0b1b769f6ed776d77897d4b2
lentomurri/python
/pw.py
1,434
4.25
4
#! python3 # PASSWORD MANAGER PROJECT # command line arguments: takes what we insert in the command line and store them as arguments to be used in the program import sys, pyperclip, json with open("C:\\Users\\Lento\\personalBatches\\dict.json", "r") as read_file: data = json.load(read_file) read_file.close() #if there's no argument after the sys argument (the name of the file), we remind the user to insert the name of the account they want to # search the password list for, or they want to enter a new password for if len(sys.argv) < 2: print("Usage: pw " + sys.argv[0] + "[account] - copy account password") sys.exit() account = sys.argv[1] if len(sys.argv) == 3: #use pyperclip to add password to clipboard data[account] = sys.argv[2] print('Password for ' + account + " saved in dictionary") with open("C:\\Users\\Lento\\personalBatches\\dict.json", "w") as write_file: json.dump(data, write_file) sys.exit() # if the arg is there #check if the account is already in password: in that case, return the password if account in data: #use pyperclip to add password to clipboard pyperclip.copy(data[account]) print('Password for ' + account + " copied to clipboard.") with open("C:\\Users\\Lento\\personalBatches\\dict.json", "w") as write_file: json.dump(data, write_file) else: print("there is no account named " + account)
true
1b6717f643047565037b73b36de95e78eba121d5
lentomurri/python
/searchRegex.py
1,554
4.5625
5
#! python3 # This program will ask for a folder where the files are stored. # It will find all .txt files and apply the regex search the user entered. # It will display the results in the terminal and even paste them automatically in the clipboard for storage purposes. import re, sys, os, pyperclip # write folder path to access files. enter absolute path. filePath = sys.argv[1] try: filedir = os.listdir(filePath) except: print("Invalid path. Please check the provided path is the absolute one.") input("Press any key to exit") def regexSearch(filedir): finalResult = "" for item in filedir: # the string to find the .txt files endTxt = r"[\w]+(\.txt)$" # the string that the user wants to match in the files # CHANGE THIS STRING TO MATCH YOUR REGEX SEARCH. matching = r"[\w]+\." # if file is a text file if re.match(endTxt, item)!= None: # search for item in absolute path entered by user currentFile = open(filePath + "\\" + item) currentFile = currentFile.read() # matches all occurrences, indicating which file they come from string = item + "\n" + str(re.findall(matching, currentFile)) # stores all the result together, divided by files finalResult += "\n" + string # return results and paste them on the clipboard pyperclip.copy(finalResult) print(finalResult) input("The contents have been saved on the clipboard. Press any key to exit") regexSearch(filedir)
true
cbedd5e4f8d5aa909b919665c1fd66257851c24b
Danyalah/Dana-Felixon-Portfolio
/portfolio/List_challenge.py
500
4.125
4
from random import * ###Create a Haiku generator #Create a list of three syllable lines first = ["I am cool", "Your are tall", "Ally is"] #Create a list of five syllable lines second = ["She is so pretty", "My mom is lovely", "I have a brother"] #Initialize Haiku Haiku = "" ### x = randint(0, len(first)-1) y = randint(0, len(second)-1) #Put the lines together Haiku =x = randint(0, len(first list)-1) " \n"+ second[y] "\n"+ #Print Haiku print("Your Haiku is" + Haiku)
false
8a5da6d101f861aa6f522ef789cd0d335f6a5e83
mira0993/algorithms_and_linux_overview
/Python/Graphs/floyd_warshall_algorithm.py
2,384
4.34375
4
''' The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. Input: graph[][] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} } which represents the following graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 Note that the value of graph[i][j] is 0 if i is equal to j And graph[i][j] is INF (infinite) if there is no edge from vertex i to j. Output: Shortest distance matrix 0 5 8 9 INF 0 3 4 INF INF 0 1 INF INF INF 0 Floyd Warshall Algorithm 1. Initialize the solution matrix same as the input graph matrix as a first step. 2. Update the solution matrix by considering all vertices as an intermediate vertex. The idea is to one by one pick all vertices and update all shortest paths which include the picked vertex as an intermediate vertex in the shortest path. For every pair (i, j) of source and destination vertices respectively, there are two possible cases. 2.1) k is not an intermediate vertex in shortest path from i to j. Keep the value of dist[i][j] as it is. 2.2) k is an intermediate vertex in shortest path from i to j. Update the value of dist[i][j] as dist[i][k] + dist[k][j]. ''' # Number to represent infinite INF = 999999 graph = [ [0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ] def floydWarshall(graph, num_vertices): shortestDistances = [] for v in range(num_vertices): shortestDistances.append(list(graph[v])) for k in range(num_vertices): for i in range(num_vertices): for j in range(num_vertices): # If vertex k is on the shortest path from # i to j, then update the value of dist[i][j] shortestDistances[i][j] = min(shortestDistances[i][j], shortestDistances[i][k]+ shortestDistances[k][j]) print(shortestDistances) def print_graph(graph): for i in graph: print(i) floydWarshall(graph, 4)
true
4356f13dd09f59459789cee8dd71487597fb4a37
ArkaprabhaChakraborty/Datastructres-and-Algorithms
/Python/OptimalmergePattern.py
1,152
4.1875
4
class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def insert(self, data): self.queue.append(data) # for popping an element based on Priority def delete(self): try: min = 0 for i in range(len(self.queue)): if self.queue[i] < self.queue[min]: min = i item = self.queue[min] del self.queue[min] return item except IndexError: print() exit() def optimalpattern(sarr): pq = PriorityQueue() for i in sarr: pq.insert(i) cost = 0 while(len(pq.queue) > 1): a = pq.delete() b = pq.delete() t = a+b cost = cost + t pq.insert(t) print(f"Total Cost (Minimum computations): {cost}") print(f"Final element after merging {pq}") sarr = [1,2,3,4,10] optimalpattern(sarr)
true
0aa2272fd5db353f938d6604ba80388fa66cb042
walyncia/ConvertString
/StringConversion.py
1,234
4.15625
4
import time def StringToInt (): """ This program prompts the user for a string and converts it to a integer if applicable. """ string = input('Desired Number:') print('The current state:\nString:',string,' ->', type(string)) if string == '': #handle no input raise Exception ('Invalid input!') #throws exception elif '-' in string: #handle non-positive inputs raise Exception('No negative numbers') # throws exception else: num=0 #initialize int value of string string =string[::-1] #reverse the string var = 1 #placeholder #print (isinstance(string,str)) #precaution to check if the string is a string for x in range (len(string)): # determine the number of places if x is 0: num += int(string[x]) else: num += int(string[x]) * var var = var * 10 #concatenate placeholder #print (isinstance(num,int)) #precaution to check if the string is converted to is a integer print('\nConverting your string.....') time.sleep(len(string)/2) print('\nConverted State: \nNum:', num,'->', type(num)) StringToInt()
true
9d0c358d5e51ebd04f5e21d43f1a316d9243390b
yved/python_lesson2
/week3/week3-3.py
572
4.34375
4
#商管程式設計二第三周上課內容 #python 特別有的函數 # def f1(x): # return x**2 # print(f1(8)) # #用lambda 函數 # f2 = lambda x : x**2 # print(f2(8)) #zip 函數 a = [1,2,3] b = [4,5,6] zipped = zip(a,b) tuple_zip = tuple(zipped) print(type(tuple_zip[0][0])) # #搭配map函數 可以重複執行某個函數 # list1 = [3,5,2,4,9] # #要讓list裡面的每個東西都平方 # out1 = map(f1,list1) # print(list(out1)) # out2 = map(lambda x: x**2,list1) # print(list(out2)) # # print(list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
false
d8a519673a68f8c8e09824826c1fc1d50eaa2c67
Elijah3502/CSE110
/Programming Building Blocks/Week 3/08Team.py
254
4.3125
4
num_of_col_row = int(input("How many columns and rows would you like? : ")) col = 1 row = 1 while(col <= num_of_col_row): print() while(row <= num_of_col_row): print(f"{(row) * col:3}", end=" ") row += 1 col += 1 row = 1
true
7f79b41806cc8bb4b3c2ff61230421cb33c411f3
Elijah3502/CSE110
/Programming Building Blocks/Week 4/07Checkpoint.py
345
4.28125
4
#Ask positive number user_num = int(input("Enter a number that is not negative : ")) while user_num < 0 : user_num = int(input("Try again!\nEnter a number that is not negative : ")) ask_candy = input("Can I have some candy? : ").upper() while ask_candy != "YES": ask_candy = input("Can I have some candy? : ").upper() print("Thanks!!")
false
dae01c802a2d232d17e9194f2dd7dce4fcc5eb4d
Elijah3502/CSE110
/Programming Building Blocks/Week 2/04Teach.py
2,111
4.25
4
""" Team Activity Week 04 Purpose: Determine how fast an object will fall using the formula: v(t) = sqrt(mg/c) * (1 - exp((-sqrt(mgc)/m)*t)) """ import math print("To calculate how fast an object will fall, enter these informations:") #input mass (in kg) m = float(input("Mass (in kg): ")) #input acceleration due to gravity g = float(input("Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): ")) #input time (in seconds) t = float(input("Time (in seconds): ")) #input density of fluid p = float(input("Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): ")) #input cross sectional area of projectile (in square meters) A = float(input("Cross sectional area (in m^2): ")) #input drag constan C = float(input("Drag constant (0.5 for sphere, 1.1 for cylinder): ")) #Compute the value for the inner value c c = (1 / 2) * p * A * C #show value of c print(f"The inner value of c is: {c:.3f}") #Compute and display the overall velocity v = math.sqrt(m * g / c) * (1 - math.exp((-1*(math.sqrt(m * g * c) / m ))*t)) print(f"The velocity after 10.0 seconds is : {v:.3f}") #Stretch 1 """ .75kg Alexa speaker g = 9.8 csa = 25.51 To calculate how fast an object will fall, enter these informations: Mass (in kg): 0.75 Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): 9.8 Time (in seconds): 10 Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): 1.3 Cross sectional area (in m^2): 25.51 Drag constant (0.5 for sphere, 1.1 for cylinder): 0.5 The inner value of c is: 8.291 The velocity after 10.0 seconds is : 0.942 Boulder = 68kg Mass (in kg): 68 Gravity (in m/s^2, 9.8 for Earth, 24 for Jupiter): 9.8 Time (in seconds): 10 Density of the fluid (in kg/m^3, 1.3 for air, 1000 for water): 1.3 Cross sectional area (in m^2): 0.676 Drag constant (0.5 for sphere, 1.1 for cylinder): 0.5 The inner value of c is: 0.220 The velocity after 10.0 seconds is : 45.781 """ #Stretch 2 """ Alexa Speaker : Earth V = 0.942 Jupiter V = 1.473 Boulder : Earth V = 45.781 Jupiter V = 80.865 """ #Stretch 3 #Terminal Velocity = print("\n\nTHE TERMINAL VELOCITY IS : " + str(math.sqrt(m * g / c)))
true
bf9e9ea38ce0b81cedef651ba98c0b4499a8a9b8
francisamani/RockPaperScissors
/automated_rps.py
1,631
4.1875
4
# Name: Francis Oludhe # Homework on coding Rock, Paper, Scissors import random print "Welcome to a game of Rock, Paper, Scissors\nMake your choice?\n" """ Placing suitable inputs for both players """ right = ["rock", "paper", "scissors"] one = raw_input("Your choice? \n") comp = random.choice(right) """ Making a condition for the input """ while one not in right: print "Please pick between rock, paper and scissors" one = raw_input("Your choice? \n") """" The actual rules to the game """ if (one == "rock" and comp == "rock"): print "\n\nYou both tied.\n\nBoth of you chose", one+"." if (one == "rock" and comp == "scissors"): print "\n\nYou win.\n\nYou chose", one, "and the computer chose", comp+"." if (one == "rock" and comp == "paper"): print "\n\nThe computer wins.\n\nYou chose", one, "and the computer chose", comp+"." if (one == "scissors" and comp == "rock"): print "\n\nThe computer wins.\n\nYou chose", one, "and the computer chose", comp+"." if (one == "scissors" and comp == "scissors"): print "\n\nYou both tied.\n\nBoth of you chose", one+"." if (one == "scissors" and comp == "paper"): print "\n\nYou win.\n\nYou chose", one, "and the computer chose", comp+"." if (one == "paper" and comp == "rock"): print "\n\nYou win.\n\nYou chose", one, "and the computer chose", comp+"." if (one == "paper" and comp == "scissors"): print "\n\nThe computer wins.\n\nYou chose", one, "and the computer chose", comp+"." if (one == "paper" and comp == "paper"): print "\n\nYou both tied.\n\nBoth of you chose", one+"."
true
104680466515101a786087ce40a0e3de562a9c2f
ULYSSIS-KUL/ulyssisctf-writeups
/2018/reverse/one-step-beyond/final.py
651
4.28125
4
#!/usr/bin/env python3 def fibonacci(i: int, previous: int = 1, past_previous: int = 0) -> int: for _ in range(i): previous, past_previous = previous + past_previous, previous return previous + past_previous def rotate(character: str, n: int) -> str: return chr((ord(character) - 32 + n) % 95 + 32) def encrypt(string: str) -> str: array = list() for index,char in enumerate(string): array.append(rotate(char, fibonacci(index))) return "".join(array) import sys to_encrypt = None if len(sys.argv) < 2: to_encrypt = input("enter input: ") else: to_encrypt = sys.argv[1] print(encrypt(to_encrypt))
false
19de4e48ed2c15fa5f713b5292f34cccc9de4199
chengxxi/dailyBOJ
/2021. 2./4714.py
1,523
4.15625
4
# 4714: Lunacy while True: weight = float(input()) if weight < 0: break print(f'Objects weighing {weight:.2f} on Earth will weigh {(weight * 0.167):.2f} on the moon.') # Objects weighing 100.00 on Earth will weigh 16.70 on the moon. """ # ㅠ제컴에선 # ㅠ되는데요 nums = list(map(float, input().split())) for n in nums: if n < 0: break else: earth = n moon = round(earth/6, 2) print("Objects weighing %.2f on Earth will weigh %0.2f on the moon." % (earth, moon)) """ """ After several months struggling with a diet, Jack has become obsessed with the idea of weighing less. In an odd way, he finds it very comforting to think that, if he had simply had the luck to be born on a different planet, his weight could be considerably less. Of course, the planets are far out of reach, but even the Earth’s moon would yield a dramatic weight loss. Objects on the moon weight only 0.167 of their weight on Earth. Input consists of one or more lines, each containing a single floating point number denoting a weight (in pounds) on the Earth. The end of input is denoted by a negative floating point number. For each line of input data, your program should print a single line of the form Objects weighing X on Earth will weigh Y on the moon. where X is the weight from the input and Y is the corresponding weight on the moon. Both output numbers should be printed to a precision of 2 digits after the decimal point. """
true
56249a0afb87df8d6603ef943e52466e80773279
Kushagar-Mahajan/Python-Codes
/slicer.py
840
4.28125
4
#slice is to take out particular text from a string using their indexes word = "Encyclopedia" a = word[0] #will print out word written at index 0 print(a) #here [a:b:c] is the format a = word[0:3:1] #where a is starting index, b is ending index and c is step print(a) a = word[0:3:2] print(a) #it can be matched with previous output #here [a:b:c] is the format a = word[:5:1] #where a is blank indicating that string should start form beginning print(a) #here [a:b:c] is the format a = word[::-1] #where -1 is used to reverse the string print(a) # this is automated slicing in case of avoiding error and counting long path word = 'Encyclopedia' a = word.index("cyc") #getting index of start b = word.index("dia") #getting index of end c = word[a:b] #declearing variable for storing the particular index print(c) #printing sliced data
true
214ccd8211e8e78fd1c3ddc237c4a7b6969edb37
Kushagar-Mahajan/Python-Codes
/variables.py
356
4.28125
4
#Variables are used to store stuff #It has name and value and used to store value for later in easy and convenient way. number = 1 print("Number is",number) #prints the variable print("Type of the number is",type(number)) #tells the type of variable number= "hello" # will overwrite the previous variable print("Overwritten of variable number is",number)
true
858e3823bf27b0060d1cccde85b0623f44c2ab78
forabetterjob/learning-python
/01-data-types-and-structures/numbers.py
949
4.1875
4
import math import random # integer will convert up to float result = 1 + 3.14 print "1 + 3.14 is " + str(result) # 4.14 # order of operations result = 1 + 2 * 3 print "1 + 2 * 3 is " + str(result) # 7 # order of operations result = (1 + 2) * 3 print "(1 + 2) * 3 is " + str(result) # 9 # exponential result = 10 ** 3 print "10 ** 3 is " + str(result) # 1000 # modulo result = 346 % 37 print "346 % 37 is " + str(result) # 13 # exponential result = math.pow(10, 3) print "math.pow(10, 3) is " + str(result) # 1000.0 # square root result = math.sqrt(144) print "math.sqrt(144) is " + str(result) # 12.0 # floor result = math.floor(3.999) print "math.floor(3.999) is " + str(result) # 3.0 # ceiling result = math.ceil(3.0001) print "math.ceil(3.0001) is " + str(result) # 4.0 # random result = random.random() print "random.random() is " + str(result) # random result = random.randint(1, 50) print "random.randint(1, 50) is " + str(result)
true
a823de068433836d63fc055ed5f465958c92b819
doper0/firstcode
/ff2.py
345
4.15625
4
num=int(raw_input("write number between 50 to 100 ")) if 50>num : #The program shows all the numbers that divide by three with no remainder print ('you cant enter that number') elif num>100 : print ('you cant enter that number') else : i=-1 for i in xrange(50,num+1) : if i%3==0: print i
true
fe7af938d21a96ebdc8e36709688891eb24a1622
ariamgomez/8-14-2015
/bisection.py
856
4.28125
4
## This square root calculator will depict the 'Bisection Method' ## to calculate the root and will compare to 'Exhaustive Enumeration' (Brute Force approach) ## Python 2.7.9 # Error epsilon = 0.01 # Counters ans = 0.0 count = 0.0 # My algorithmic boundaries low = 0.0 high = 0.0 x = raw_input ("Please enter a number, we will find its root ") x = float(x) # Notice that the max that the ans can be is the square root of x, since we are depicting # the square root here we will avoid using the square root function itself # Here's what I mean: epsilon <= x - ans*ans if epsilo is zero, then ans^2 <= x high = max (x,1) while epsilon <= abs(x-(ans*ans)): ans = (low + high) / 2 count = count + 1 if ans**2 > x: high = ans else: low = ans print ("We tried this many times "), count print ("The root is"), ans
true
ed86be3cda08c69bd5d8e455fc8db610d7d0b777
liurong92/python-exercise
/exercises/number/one.py
711
4.21875
4
''' Let's assume you are planning to use your Python skills to build a social networking service. You decide to host your application on servers running in the cloud. You pick a hosting provider that charges $0.51 per hour. You will launch your service using one server and want to know how much it will cost to operate per day and per month. Write a Python program that displays the answers to the following questions: How much does it cost to operate one server per day? How much does it cost to operate one server per month? ''' cost_per_hour = 0.51 cost_per_day = 24 * cost_per_hour cost_per_month = 30 * cost_per_day print('day: {:.2f}'.format(cost_per_day)) print('month: {:.2f}'.format(cost_per_month))
true
b32016104985b870b9ca81114f17fefacfc47ea1
liurong92/python-exercise
/exercises/files/one.py
431
4.5
4
''' Create a program that opens file.txt. Read each line of the file and prepend it with a line number. The contents of files.txt: This is line one. This is line two. Finally, we are on the third and last line of the file. Sample output: 1: This is line one. 2: This is line two. 3: Finally, we are on the third and last line of the file. ''' with open('./one.txt', 'r') as ones: for line in ones: print(line.rstrip())
true
c10ae30c238bf9e6398c771aadd511a28c0d2228
paddumelanahalli/agile-programming
/factorial.py
685
4.28125
4
factorial=1 #To store the factorial of a no. num=int(input("Enter a no. whose factorial is needed: ")) #Accepting a no. from user if(num<0): print("Its an negative integer so factorial is not possible") #Checking for a negative integer entered from user elif(num==0): print("Factorial of 0 is 1") #Factoral of zero is one else: for i in range(1,num+1): factorial=factorial*i #Storing factorial of the number factorial="{0:.2f}".format(factorial) #Mathematical function to store the number to two decimal place print("Factorial of a number",num,"is ",factorial) #Printing the factorial of the no.
true
9da5403525bbd225046b635766faf107353b1d28
susyhaga/Challanges-Python
/Udemy python/control_structure/Intersection_SET_10.py
692
4.1875
4
#Create a constant with a set of forbidden words. #Then create a list with some phrases. #Check if these prohibited words are inside the sentences and point out those words, #Otherwise the text will be authorized. #Intersection set FORBIDDEN_WORDS = {'asshole', 'bastard', 'Bolsonaro', 'hate', 'garlic'} phrases = [ "Bolsonaro is an asshole and bastard!", "Brazilian love beans with garlic and germans hate it", "Ramones is an amazing band", ] for text in phrases: intersec = FORBIDDEN_WORDS.intersection(set(text.lower().split())) if intersec: print("This phrase is forbidden:", intersec) else: print("This phrase is allowed:", text)
true
5e81439854d2f4fa8a4996e3cda2b10f37852e4b
TomScavo/python
/student2.py
313
4.21875
4
import csv from student import Student students=[] for i in range(3): name=input("name: ") dorm=input("dorm: ") students.append(Student(name,dorm)) file=open("student.csv","w") writer=csv.writer(file) for student in students: writer.writerow((student.name,student.dorm)) file.close
true
76d1f9a00c06094d82ce75ddbc3b9982e5582e76
TomScavo/python
/calculation.py
447
4.15625
4
# prompt user int x x=int(input("please enter int x: ")) # prompt user int y y=int(input("please enter int y: ")) # a list of calculations print("{} plus {} is {} ".format(x,y,x+y)) print("{} minus {} is {} ".format(x,y,x-y)) print("{} times {} is {} ".format(x,y,x*y)) print("{} divided by {} is {:.55f} ".format(x,y,x/y)) print("{} divided by{}(floor) is {} ".format(x,y,x//y)) print("remainder of{} divided by {} is {} ".format(x,y,x%y))
true
47318c5a413efdba95e40927e1159e30af82eae7
striveman1379/Algorithm_Python
/little_examples/python实现斐波那契数列.py
1,246
4.28125
4
# 程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、…… ''' 在数学上,费波那契数列是以递归的方法来定义: F0 = 0 (n=0) F1 = 1 (n=1) Fn = F[n-1]+ F[n-2](n=>2) ''' #方法一: #!/usr/bin/python # -*- coding: UTF-8 -*- # 斐波那契数列 def fib(n): a, b = 1, 1 for i in range(n-1): a, b = b, a+b return a # 输出了第10个斐波那契数列 print fib(10) #方法二: #!/usr/bin/python # -*- coding: UTF-8 -*- # 斐波那契数列 # 使用递归 def fib(n): if n == 1 or n == 2: return 1 return fib(n - 1) + fib(n - 2) # 输出了第10个斐波那契数列 print fib(10) # 方法三: 如果你需要输出指定个数的斐波那契数列,可以使用以下代码: #!/usr/bin/python # -*- coding: UTF-8 -*- # 斐波那契数列 def fib(n): if n == 1: return [1] if n == 2: return [1, 1] fibs = [1, 1] for i in range(2, n): fibs.append(fibs[-1] + fibs[-2]) return fibs # 输出前10个斐波那契数列 print fib(10) #以上程序运行输出结果为: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
false