blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e765c6e1452e0b3003d3315f731920e531e1770f
DhruvBajaj01/HacktoberFest-Python
/codes/reverse.py
263
4.21875
4
# Python program to reverse a entered number n = int(input('please give a number : ')) print 'Number before being reversed : %d' % n reverse = 0 while n != 0: reverse = reverse * 10 + n % 10 n = n // 10 print 'Number after being reversed : %d' % reverse
false
97aab11a2321acae95ce0ea3b92d4f82984b695e
DhruvBajaj01/HacktoberFest-Python
/codes/Asciicode.py
329
4.15625
4
# python program to print ASCII(decimal system) value of a given character(one character string) trfl=True while trfl: a=input("Enter any character : ") print("ASCII value of " + a +" is = ", ord(a)) x=input("For re-do, type Y and to exit type N - ") if x=='n': trfl=False print("See you next time.")
true
44628e21bfac9c454c5d3e5a6fce37a4b14ff82f
lssxfy123/PythonStudy
/udacity_test/udacity_test5.py
819
4.21875
4
# Copyright(C) 2018 刘珅珅 # Environment: python 3.6.4 # Date: 2018.12.6 # python练习测试5:input测试 names = input("Enter names separated by commas: ") assignments = input("Enter assignment counts separated by commas: ") grades = input("Enter grades separated by commas: ") names = names.split(',') assignments = assignments.split(',') grades = grades.split(',') for name, assignment, grade in zip(names, assignments, grades): message = "Hi {},\n\nThis is a reminder that you have {} assignments left to submit before you can graduate. Your" \ " current grade is {} and can increase to {} if you submit all assignments before " \ "the due date\n".format(name, assignment, grade, int(grade) + 2 * int(assignment)) print(message) def func(): print("udacity test 5")
true
6dbf47273132737c84acbc56a07b62feacf017a1
lssxfy123/PythonStudy
/if_test/if_test1.py
647
4.25
4
# Copyright(C) 2018 刘珅珅 # Environment: python 3.6.4 # Date: 2018.3.30 # 条件测试 cars = ['audi', 'bmw', 'subaru'] for car in cars: if car == 'bmw': print(car == 'bmw') print(car.upper()) else: print(car.title()) print() # 判断不相等 age = 18 if age != 42: print("That is not the answer") # 多条件判断 # 与:and if 16 <= age and 20 >= age: print("Age is ok") # 或:or if 15 <= age or 25 >= age: print("Age is ok") # 判断是否在列表中 print('audi' in cars) print('toyota' in cars) # 判断是否不在列表中 if 'toyota' not in cars: print('you can add toyota')
false
152b8df35e5f3954d006958772130d3d6ab09712
asmelash/asme1_N16
/n7_count_vow.py
946
4.34375
4
#7. Write a function that counts the number of vowels # (both, lower and upper case) used in a given string def count_vowels(string): """Count the number of vowels given a string as an argument """ count = 0 for char in string.lower(): if char in 'aeiou': count += 1 return count def example(): #string = 'Sphinx of black quartz, judge my vow' #string = 'Asmelash Haftu is a student of Prof Prabhu Ramachandran' string = 'pneumonoultramicroscopicsilicovolcanoconiosis' #string = 'the quick brown fox jumps over a lazy dog' print('The number of vowels in the string is', count_vowels(string)) def test_count_vowels(): assert count_vowels('asdfx') == 1 assert count_vowels('aeiou') == 5 assert count_vowels('AEIOU') == 5 if __name__ == '__main__': test_count_vowels() example() #unittest.main() ##########################################################################
true
626b92dbba741edfcf1939d4df30ee1538e0b30e
SirObi/exercism-python
/binary-search/binary_search.py
578
4.28125
4
def binary_search(list_of_numbers, number): """Searches sorted list of numbers for given number.""" if len(list_of_numbers) <= 0: raise ValueError("Empty array") left_index = 0 right_index = len(list_of_numbers) - 1 while left_index <= right_index: middle = (left_index + right_index) // 2 if list_of_numbers[middle] == number: return middle if number > list_of_numbers[middle]: left_index = middle + 1 else: right_index = middle - 1 raise ValueError("Number not in array")
true
66a4d342c9ee1e800f7625d289f763066aafbf33
emodatt08/Python-Basics
/tuples.py
850
4.40625
4
tuples are different form list because they cannot be changed, they are represented with paranthesis tup1 = ('mathematics', 'physics', 'accounting') print(tup1) tup2 = ('1', '2', '3') print(tup2) tup3 = (1, 2.98, 'uiloo') print(tup3) tup4 = (4,) print(tup4) tup5 = ('Renji Abarai','Ichigo Kurasaki') tup6 = (18.000, 400) tup7 = tup5 + tup6 print tup7 #delete a tuple del tup1 print tup1 #length of a tuple print len(tup1) tupString = ('Hi') print(4 * tupString) tupInt = (1,2,3,4,5,6) print 5 in tupInt #for loop through a tuple for i in tupInt: print i #indexing a tuple L = ('spam', 'Logger', 'Mails') print L[-2] #slicing print L[:1] #compare two tuples tup1 = (1,2,3,4,5,6) tup2 = (4,6,7,2,1,8) print cmp(tup1, tup1) #maximmum value print max(tup1) #minimum value print min(tup2) #convert list to tuple lists = [1,2,3,4,5] print tuple(lists)
true
d2bd0daeaa5f3aab5ac9fed05761b22c6be98610
emodatt08/Python-Basics
/lists.py
583
4.34375
4
#lists of integer values #lists of string values names = ['Sadat', 'Hillary', 'Robert', 'Juanita'] lists of different datatypes myList = [21, "Sam", 10.6] print(squares[0], names[2], myList[1]) #concantenating lists a= [1, 5] b= [5, 7] c= a + b print(c) #changing the value of a list squares = [1, 3, 45, 34] squares[1] = 36 print(squares) #placing a list in a list myList = [1, [2, 3], 4] print(myList) #appending a list x = [1, 2, 3, 4] x.append(5) print(x) #sorting a list in ascending order y = [4, 5, 9, 1, 88] y = y.sort() print(y) #reverse list values print(5 in y)
true
2eb09492ed0f143c440e827784592d8f7de5025b
mayank888k/Python
/enumeratee.py
458
4.21875
4
lst=["Aaloo","Bhindi","Gajar","Mooli","Adrak"] print(list(enumerate(lst))) print() for index, value in enumerate(lst): print(f"Vegetable {value} is at index {index} in Basket") print() for index, value in enumerate(lst,100): print(f"Vegetable {value} is at index {index} in Basket") # Enumerate is used to get index of the iteration in a loop # You can change starting index accordingly as above # Enumerate function make index and value a tuple
true
03d5bf6dbb54a7feaeb84db71c90f7667aab6ca2
j3ffyang/ai
/scripts/cipher/p091_caesarCipher.py
1,171
4.46875
4
# caesar cipher # import pyperclip message = 'This is my secret message.' key = 13 mode = 'encrypt' # set to 'encrypt' or 'decrypt' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' translated = '' message = message.upper() for symbol in message: if symbol in LETTERS: # get the encrypted (or decrupted) number for this symbol num = LETTERS.find(symbol) # get the number of the symbol print(num) if mode == 'encrypt': num = num + key elif mode == 'decrypt': num = num - key # handle the wrap-around if num is larger than length of # LETTERS or less than 0 if num >= len(LETTERS): num = num - len(LETTERS) elif num < 0: num = num + len(LETTERS) # add encrypted/ decrypted number's symbol at the end of translated translated = translated + LETTERS[num] else: # just add the symbol without encrypting/ decrypting translated = translated + symbol # print the encrypted/ decrupted string to the screen print(translated) # copy the encrypted/ decrypted string to the clipboard # pyperclip.copy(translated)
true
73b630d82b3f7b76974f3d66d6aad76b1bbed670
j3ffyang/ai
/scripts/pandas/57join_inner_outer_leftright.py
531
4.1875
4
# https://www.udemy.com/learn-data-analysis-using-pandas-and-python/learn/v4 import pandas as pd df1= pd.DataFrame({ "employee": ["ABC", "XYZ", "MNO"], "age": ["22", "25", "44"] }) df2= pd.DataFrame({ "employee": ["ABC", "XYZ", "PQR"], "salary": ["10000", "125000", "30000"] }) # inner join df3= pd.merge(df1, df2, on= "employee") print(df3) # outer join df4= pd.merge(df1, df2, on= "employee", how= "outer") print(df4) # left join df5= pd.merge(df1, df2, on= "employee", how= "left") print(df5)
false
c63583f3fc60db397f100cbb9dacef0ed7b68332
shlomi-pev/ex10
/space_object.py
2,801
4.1875
4
from vector import Vector from math import radians, sqrt from copy import copy class SpaceObject: """ this class is the basic representation of an object floating in 2D space """ def __init__(self, location=None, velocity=None, heading=0.0, radios=0): """ :param location: Vector representing the object location :param velocity: Vector representing the object location :param heading: heading in degrees :param radios: radios in int """ self.location = location if location else Vector() self.velocity = velocity if velocity else Vector() self.heading = heading self.radios = radios def get_location(self): """ :return: the location in the form (x,y) """ return self.location.get_as_tuple() def has_intersection(self, obj): """ this function check if to space object are close enough to collide :param obj: the other object :return: true if collided else false """ obj_x, obj_y = obj.get_location() my_x, my_y = self.get_location() # calculating the distance distance = sqrt((obj_x - my_x) ** 2 + (obj_y - my_y) ** 2) return distance <= self.radios + obj.radios def get_heading_rad(self): """ :return: heading converted to radians """ return radians(self.heading) def get_heading(self): """ :return: heading in degrees """ return self.heading def get_velocity(self): """ :return: a tuple in the form (speed_in_x, speed_in_y) """ return self.velocity.get_as_tuple() def move(self, min_v, max_v): """ this function calculates and updates a new location according to the boundaries of the screen and the objects velocity :param min_v: a Vector representing the lower left corner of the screen :param max_v: a Vector representing the upper right corner of the screen :return: """ delta_x = max_v.get_x() - min_v.get_x() delta_y = max_v.get_y() - min_v.get_y() # calculates new location in x axis new_x = min_v.get_x() + \ (self.location.get_x() + self.velocity.get_x() - min_v.get_x()) % delta_x # calculates new location in y axis new_y = min_v.get_y() + \ (self.location.get_y() + self.velocity.get_y() - min_v.get_y()) % delta_y self.location = Vector(new_x, new_y) def __copy__(self): """ :return: a copy of the instance """ return SpaceObject(copy(self.location), copy(self.velocity), self.heading)
true
57bbf29e52893a18ac3f279c65041f93fd5ae9df
tucpy/advanced_py
/Chap_1_OOP/triangle.py
890
4.125
4
from polygon import * #Neu khong bo cac lenh ben polygon vao main, thi khi goi class trong triangle, cac lenh do se duoc thuc thi print("Tinh cv, dt tam giac") class Triangle(Polygon): def __init__(self): Polygon.__init__(self,3) def find_area(self): a, b, c = self.sides s = (a+b+c)/2 area = (s*(s-a)*(s-b)*(s-c))**0.5 print("The area of the triangle is %.2f" %area) def find_perimeter(self): a, b, c = self.sides perimeter = a + b + c print("The perimeter of the triangle is %.2f" %perimeter) #Overriding Method from Polygon def display_sides(self): print("Triangle has 3 sides:") Polygon.display_sides(self) if __name__ == "__main__": triangle = Triangle() triangle.input_sides() triangle.find_area() triangle.find_perimeter()
false
f62b6fe08688be3d1ef6e33f9526d1449c6eb02b
Ashutosh-gupt/HackerRankAlgorithms
/Polar Angles.py
2,786
4.21875
4
""" A point (x,y), on the cartesian plane, makes an angle theta with the positive direction of the x-axis. Theta varies in the interval [0 ,2PI) radians, i.e, greater than or equal to zero; but less than 2*PI radians. For example, the polar angle of the point (1,2) as marked in this plane below, is (approximately) 63.4 degrees (multiply by PI/180 to convert to radians) Ref http://eldar.mathstat.uoguelph.ca/dashlock/Outreach/Articles/images/PRfig1.jpg The Task Given a list of points in the 2D plane, sort them in ascending order of their polar angle. In case multiple points share exactly the same polar angle, the one with lesser distance from the origin (0,0) should occur earlier in the sorted list. Input Format The first line contains an integer N. This is followed by N lines containing pairs of space separated integers, x and y which represent the coordinates of the points in the cartesian plane. """ import math __author__ = 'Danyang' class Solution(object): def solve(self, cipher): """ main solution function :param cipher: the cipher """ cipher.sort(cmp=self.cmp) def cmp_polar(self, a, b): """ cross product, but what if \pi? error, can only sort by clockwise """ x1 = a[0] y1 = a[1] x2 = b[0] y2 = b[1] # (0, 0) as anchor point cross_product = x1 * y2 - x2 * y1 if cross_product > 0: return -1 elif cross_product < 0: return 1 else: if x1 * x1 >= 0 and y1 * y1 >= 0: return x1 * x1 + y1 * y1 - x2 * x2 - y2 * y2 else: if y1 > 0: return -1 if y2 > 0: return 1 if y1 == 0 and x1 > 0: return -1 else: return 1 def cmp(self, a, b): """ polar coordinate """ x1 = a[0] y1 = a[1] x2 = b[0] y2 = b[1] r1 = x1 * x1 + y1 * y1 r2 = x2 * x2 + y2 * y2 phi1 = math.atan2(y1, x1) phi2 = math.atan2(y2, x2) if phi1 < 0: phi1 += math.pi * 2 if phi2 < 0: phi2 += math.pi * 2 if phi1 < phi2: return -1 elif phi1 > phi2: return 1 else: return r1 - r2 if __name__ == "__main__": import sys f = open("1.in", "r") # f = sys.stdin N = int(f.readline().strip()) cipher = [] for t in xrange(N): # construct cipher cipher.append(map(int, f.readline().strip().split(' '))) # solve Solution().solve(cipher) for point in cipher: print "%d %d" % (point[0], point[1])
true
ef79acb9eca4e9fe0e4f290eed4e4f65dcdf2e12
haseebali1/python
/crash_course/ch_2_variables/2.4.py
441
4.5
4
# Name Cases # assign a name to a variable name = "Bruce lee" # print the name how it is stored print ( f"This is the name without any case chaging: {name}") # print the name in all lowercase print (f"this is the name all lowercase: {name.lower()}") # print the name all uppercase print (f"this is the name all uppercase: {name.upper()}") # print the name with normal uppercase print (f"this is the name how it should be: {name.title()}")
true
18fb3f2734a327d9821c555314acca0fdbb31290
kamalikam/Letsupgrade_Python_Assignments
/Day2/Day2Assgn2.py
969
4.25
4
#Day2 Assignment 2 #Five different functions of lists numlist1=[12,34,1,-6,8.4,-9.6,0,4] numlist2=numlist1 #Made a duplicate of numlist1 strlist1=['Harry','Sunaina','Orange','Laptop'] strlist2=strlist1 #Made a duplicate of strlist1 numlist1.extend(strlist1) #extend() to extend 1st string by 2nd string print('\nList1 extended by list2 is: ',numlist1) ind=numlist1.index(-6) #index() for returning index of -6 print('\nThe index of -6 in numlist1 is: ',ind) numlist1.pop(3) #pop() for removing 4th item of the list print('\nAfter popping 4th item of numlist1: ',numlist1) numlist3=numlist2.clear() #clear() for deleting all elements of a list print('\nnumlist2 is cleared: ',numlist3) strlist2.insert(0,'Ghana') #insert() adds a specified value to a specified position of a list print('\nAdded Ghana to 1st position of strlist2: ',strlist2)
true
5ff6588864acfaf1b3edd33a511a6169f8ffc30c
suneelsonti/pythonprac
/moshs-utube-course-prac/arthematic_operators.py
759
4.28125
4
# arthematic operations supported in python # Basic math opertors print(10+10) print(10-1) print(10*2) print(10/6) # output can be either int or float based on the numbers being divided print(10//6) # output is always an integer print(10%3) # % sign denotes modulus, basically reminder of the division. the value should be 1 in this case print(2**3) # to the power off. ** denotes exponent value. #Augument assignment operator # used to enhance the code #regular code: x = 5 x = x+3 # incremented x's value print(x) x += 3 # += is the enhancement print(x) x -= 6 print(x) # Operator precedence: Python applies the same basic math rules - BODMAS - paranthesis, exponent, division, # multiplication, addition, subtraction print(x := 4 + 8**2 * (30 / 5))
true
5a4924fe51b1ea9bcd5a665ddf834c0882852eab
Keerthana0309/LeetCode
/ImplementstrStr().py
485
4.15625
4
#Implement strStr(). #Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. #Example 1: #Input: haystack = "hello", needle = "ll" #Output: 2 #Example 2: #Input: haystack = "aaaaa", needle = "bba" #Output: -1 class Solution: def strStr(self, haystack: str, needle: str) -> int: if len(needle) == 0: return 0 if needle in haystack: return haystack.index(needle) return -1
true
3fc33d3bea1a79ec16ba91207b3a25cd0093c5ad
Keerthana0309/LeetCode
/ValidParentheses.py
1,420
4.125
4
#Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. #An input string is valid if: #1.)Open brackets must be closed by the same type of brackets. #2.)Open brackets must be closed in the correct order. class Solution(object): def isValid(self, s): stack, pairs = [], {"(":")", "{":"}", "[":"]"} for char in s: # if the char is an open bracket, it'll append to our stack list if char in pairs: stack.append(char) # if the character is a closed bracket, it won't append. And if it happens that # there is nothing in the list because we have an unpaired closed bracket # we return false elif len(stack) <= 0: return False # if the character is a closed bracket AND it's not equal to the key-value pair # of the last item in the stack (remember pop takes the last item in a list), then we return false. # HOWEVER. If the character does match the key-value pair of the last item in stack, we have an empty stack list. # We continue with the for-loop until we are finished. elif char in pairs.values() and char != pairs[stack.pop()]: return False # After the for-loop our stack is empty, we succesfully matched all our brackets. return True if stack == [] else False
true
53ea6cbfb9e69bebd2b7dfa7bd0db3285c244694
sharathk91/Python-2018
/LabAssignment1/Source/ValidatePassword.py
1,493
4.375
4
import re #import regular expressions text = input("Enter the Password to validate: ") #take input password string from user flag = 0 #assign flag to zero while True: #loop until the value is false if (len(text) < 6): #check if the length of password is less than 6 chars flag = -1 print("Password size should be greater than 6") break elif (len(text) > 16): #check if the length of password file is greater than 6 characters flag = -1 print("Password size should be lesser than or equal to 16") break elif not re.search("[a-z]", text): #check if the password contains lower case letter flag = -1 print("password should have atleast one lower case letter") break elif not re.search("[A-Z]", text): #check if password contains atleast one upper case letter flag = -1 print("password should have atleast one upper case letter") break elif not re.search("[0-9]", text): #check if password contains atleast one digit flag = -1 print("password should have atleast one digit") break elif not re.search("[*!@$]", text): #check if password contains atleast one special char flag = -1 print("password should have atleast one special character") break else: #if above one is not true, then it is a valid password flag = 0 print("Valid Password") break if flag == -1: print("Invalid Password")
true
f5710c7511d6bdf2b36fc34972c55a309f256b07
pranav1698/Python
/Problems/Datastructure_and_Algorithms/DeterminingMostFrequent.py
1,403
4.3125
4
# You have a sequence of items, and you’d like to determine the most frequently occurring items in the sequence. """The collectiosn.Counter class is designed for just such a problem We can use the most_common() method here, """ words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) print(word_counts) top = word_counts.most_common(1) top_three = word_counts.most_common(3) print(top) print(top_three) word_counts.update(words) print(word_counts) # You have a list of dictionaries and you would like to sort the entries according to one or more of the dictionary values. """ Sorting a list of dictionaries is done using the operator module's itemgetter function. """ rows = [ {'fname':'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname':'David', 'lname': 'Beazley', 'uid': 1002}, {'fname':'John', 'lname': 'Cleese', 'uid': 1001}, {'fname':'Big', 'lname': 'Jones', 'uid': 1004} ] from operator import itemgetter rows_by_fname = sorted(rows, key=itemgetter('fname')) rows_by_uid = sorted(rows, key=itemgetter('uid')) print(rows_by_fname) print(rows_by_uid) rows_by_lfname = sorted(rows, key=itemgetter('lname', 'fname')) print(rows_by_lfname)
true
07990b742fd4ec0be8cc4a2876bf22ce46403f7a
rshiva/DSA
/codeschool_dsa/stack.py
1,470
4.1875
4
class Node(): def __init__(self,value): self.value = value self.next = None #pop -> remove first node #push -> add new in the top #top -> return first item value #isEmpty? -> check if the list is empty class LinkedList(): def __init__(self): self.head = None def push(self,value): current = self.head if self.head == None: self.head = value else: while current.next: current = current.next current.next = value def pop(self): current = self.head previous = None if self.head == None: print("list is empty") while current.next: previous = current current = current.next if self.head.next == None: self.head = None else: previous.next = None def top(self): current = self.head if self.head != None: while current.next: current = current.next print("--top- %s",current.value) else: print("list is empty") def isEmpty(self): if self.head == None: return True else: return False l= LinkedList() l.push(Node(2)) l.push(Node(3)) l.push(Node(5)) l.pop() l.top() l.isEmpty() l.pop() l.top() l.pop() l.isEmpty() l.top() #Selection Sort #Bubble Sort #Insertion Sort #Merge Sort # Quick Sort # Heap Sort # Counting Sort # Radix Sort # Topological Sort # Dijkstra's Algorithm # Hash Table Collision Resolution # Rabin-Karp Substring Search # AVLTrees # Red-BlackTrees # MapReduce
true
c714c16c23902103e90ca13c223d845119424aac
neetiv/BabaPythonProjects
/fibonacci.py
526
4.15625
4
terms = int(input('''Enter the number of terms you want: ''')) n1 = 0 n2 = 1 if terms < 1: print(''' Please enter a positive integer instead. ''') elif terms == 1: print("Fibonacci sequence up to",terms,":") print(n1) elif terms == 2: print("Fibonacci sequence up to",terms,":") print(n1) print(n2) elif terms > 2: print("Fibonacci sequence up to",terms,":") print(n1) print(n2) for x in range(0, terms-2): ans = n1 + n2 print(ans) n1 = n2 n2 = ans
true
27ddd183cef147d69ea7912a448d9e5eee274656
ivSaav/Programming-Fundamentals
/FPRO - Play/palindrome_index.py
460
4.15625
4
''' PALINDORME INDEX This function receives a string and return -1 if the string is a palindrome; otherwise it returns the index of the first letter that if removed causes the string to be palindrome. ''' def palindrome_index(s): result = -1 if s == s[::-1]: return -1 else: for i in range(len(s)): new = s[:i] + s[i+1:] if new == new[::-1]: result = i return result
true
5662b9730281a4134786ab0cc05d9f69941055b4
kyrsjo/SixtrackTools
/DUMPfilters/DUMPfilter_filterS.py
677
4.28125
4
import sys if len(sys.argv) != 3: print "Usage: DUMPfilter_filterS lowS hiS" print "The program expects input in DUMP format #2 on STDIN," print "and will write the comment lines + lines where s \in [lowS,hiS] to stdout" print print "Example usage:" print "cat ALL_DUMP.dat | python ~/path/to/DUMPfilter_filterS.py 0 10 > ALL_DUMP.filter.dat" print exit(1) lowS = float(sys.argv[1]) hiS = float(sys.argv[2]) while True: line = sys.stdin.readline() if line == "": break elif line.startswith(" #"): print line, continue s = float(line.split()[2]) if s >= lowS and s<= hiS: print line,
true
cf329bd66984363335967ab9159fb532f40690ad
SherylA/Archivo_Fundamentos
/Semestre_2018_2/Taller/Python/punto2_5.py
323
4.125
4
import math caracter = input("Ingrese un caracter: ") if len(caracter)!=1: print("Error") exit() if caracter>='a' and caracter<='z': print("Es una minúscula") elif caracter>='A' and caracter<='Z': print("Es una mayúscula") elif caracter>='0' and caracter<='9': print("Es un digito") else: print("Es un simbolo")
false
7c980fcfa610b2210fa6e59f06af52dbdc3e54d7
GhiffariCaesa/basic-python-b6-b
/dictionary.py
731
4.1875
4
# dictionary created pelanggan_dict = { "nama" : "nafi", "umur" : 21, #key # value } # list created example pelanggan_list = [] # change data pelanggan_dict["nama"] = "joni" # akses dictionary print(pelanggan_dict["nama"]) print(pelanggan_dict["umur"]) # input data dictionary data lebih dari 1 for i in range(1): nama = input("Masukkan Nama anda : ") umur = input("Masukkan Umur anda : ") data = { "nama" : nama, "umur" : umur, } pelanggan_list.append(data) for i in pelanggan_list: print("Nama Pelanggan : ",i["nama"]) print("Umur Pelanggan : ",i["umur"]) #data = pelanggan_list[0] #print("Nama pelanggan : ",data["nama"]) #print("Umur pelanggan : ",data["umur"])
false
89a94f787ecc4f5c465e9aed1808fa6f7f18d4bf
vircabading/learning_flask_templates
/server.py
1,356
4.3125
4
# ///////////////////////////////////////////////////////////////////// # Subj: Coding Dojo > Python > Flask > Fundamentals: Understanding Routing # By: Virgilio D. Cabading Jr. Created: October 27, 2021 # ///////////////////////////////////////////////////////////////////// from flask import Flask, render_template # Import Flask to allow us to create our app app = Flask(__name__) # Create a new instance of the Flask class called "app" # **** Default App Route ********************************************** @app.route('/') # The "@" decorator associates this route with the function immediately following def index(): return render_template('index.html') # **** Create a route that responds with the given word repeated as many times as specified in the URL **** @app.route('/repeat/<int:iterations>/<string:message>') def repeat_message (iterations, message): return render_template('repeat.html', message=message, iterations=iterations) # **** Handle invalid routes ****************************************** @app.errorhandler(404) def invalid_route(e): return "Sorry! No response. Try again." if __name__=="__main__": # Ensure this file is being run directly and not from a different module app.run(debug=True) # Run the app in debug mode.
true
42f42fae24488b11659fc8cb5e1b1a34a8f09490
jeffsouza01/PycharmProjects
/Ex006 - DobroTriploRaiz.py
737
4.375
4
''' Exercício Python 006: Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. ''' import math num = int(input('Digite um número: ')) #Utilizando váriaveis para soma dos valores, sendo possível inserir diretamente no Print. dobro = num * 2 tri = num * 3 raiz = num ** (1/2) print(f'O dobro de {num} é igual a {dobro}.') print(f'O triplo de {num} é igual a {tri}.') print(f'A Raiz Quadrada de {num} é igual a {raiz:.2f}') #Segundo método utilizando a biblioteca MATH para raiz quadrada print(f'A Raiz Quadrada de {num} é igual a {math.sqrt(num):.2f}') #Terceiro método utilizando a função de Power (potencia) para raiz quadrada print(f'A Raiz Quadrada de {num} é igual a {pow(num, (1/2)):.2f}')
false
1901e6b04b5800a91322a2a3bb7d9e42fc951d85
UlyanaLes/Genesis
/oop_Task5.py
2,739
4.4375
4
# Task 5 # # Create hierarchy out of birds. # Implement 4 classes: # * Birds class with an attribute "name" and methods "fly" and "walk". # * flying bird class with same attribute "name" and with the same methods. # Implement the method "eat" which will describe it's typical ration. # * nonflying bird class with same characteristics but which obviously will # not have the "fly". # Add same "eat" method but with other implementation regarding # the swimming bird tastes. # * a bird class which can do all of it: walk, fly, swim and eat. # But be careful which "eat" method you inherit. # # Implement str() function call for each class. # # Example: # # ```python # >>> b = Bird("Any") # >>> b.walk() # "Any bird can walk" # # p = Penguin("Penguin") # >> p.swim() # "Penguin bird can swim" # >>> p.fly() # AttributeError: 'Penguin' object has no attribute 'fly' # >>> p.eat() # "It eats mostly fish" # # c = Canary("Canary") # >>> str(c) # "Canary can walk and fly" # >>> c.eat() # "It eats mostly grains" # # s = SeaGull("Gull") # >>> str(s) # "Gull bird can walk, swim and fly" # >>> s.eat() # "It eats fish" # ``` # # Have a look at `__mro__` method of your last class. from abc import ABC, abstractmethod class BirdABC(ABC): def __init__(self, abstract_name): self.name = abstract_name @abstractmethod def fly(self): pass @abstractmethod def walk(self): pass @abstractmethod def __str__(self): pass class Bird(BirdABC): # def __init__(self, abstract_name): # self.name = abstract_name def fly(self): print(self.name, 'can fly') def walk(self): print(self.name, 'can walk') def __str__(self): return f'{self.name} can walk and fly' class Penguin(Bird): def fly(self): print(self.name, 'can\'t fly') # ! def swim(self): print(self.name, 'can swim') def eat(self): print(self.name, 'eats mostly fish') def __str__(self): return f'{self.name} can walk and swim' class Canary(Bird): def eat(self): print(self.name, "eats mostly grains") class SeaGull(Penguin, Bird): # fly?? def __str__(self): return f'{self.name} can fly, walk and swim' b = Bird("Any") b.walk() # "Any bird can walk" print(b.__str__()) b.fly() p = Penguin("Penguin") p.swim() # "Penguin bird can swim" p.fly() # AttributeError: 'Penguin' object has no attribute 'fly' p.eat() # "It eats mostly fish" p.walk() print(p.__str__()) c = Canary("Canary") print(str(c)) # "Canary can walk and fly" c.eat() # "It eats mostly grains" c.walk() c.fly() s = SeaGull("Gull") print(str(s)) # "Gull bird can walk, swim and fly" s.eat() # "It eats fish" s.fly() s.walk() s.swim()
true
bb0912b3146a6b3dd31098c3517cb1d6e54f14dc
SajuJohn/Python_OOPS_Concepts
/python_class_concept.py
1,655
4.4375
4
#!/bin/python """ Case1: Class Creation. Object creation will trigger __init__ which is similar to constructor in CPP. This initializes the properties defined for the class. self is the pointer to that instance which will be unique for each object do_work is the method defined in the class. """ class Human: def __init__(self,n,o): self.name = n self.occupation = o def do_work(self): if self.name == "Saju": print (self.name + " is a " + self.occupation + " attempting to learn OOPs") else: print (self.name + " is not Saju") # Case 2: Inheritance. Vehicle is the base class and Car/Bike is inherited class class Vehicle: def __init__(self): print ("Vehicle init") def general_info(self): print ("General is Transportation") class car(Vehicle): def __init__(self): print ("I am Car init") self.name = "Car" self.wheels = "4" def specific_use(self): print (self.name + " used for Family Trip") print (self.name + " has" + self.wheels + " wheels") class bike(Vehicle): def __init__(self): print ("I am Bike init") self.name = "Bike" self.wheels = "2" def specific_use(self): print (self.name + " used for Road Trip") print (self.name + " has" + self.wheels + " wheels") print ("START") """ #Case 1: obj1 and obj2 are 2 different instances to class "Human" obj1 = Human("Saju","Programer") obj2 = Human("S1","something") obj1.do_work() obj2.do_work() """ c = car() b = bike() c.general_info() c.specific_use() b.general_info() b.specific_use() print ("END")
true
a6b8df1f7abaa6a10bcbd744dee5fc5a0121e2f0
lilyyyyyyyyy/Python_Self_Learning
/Print_function.py
359
4.1875
4
n = int(input()) print(*range(1,n+1), sep = '') # or: print(*range(1, int(input())+1), sep='') # # Read an integer . # # Without using any string methods, try to print the following: # # # Note that "" represents the values in between. # # Input Format # The first line contains an integer . # # Output Format # Output the answer as explained in the task.
true
67e2fe0bec2a75716c127dd82c44efe43b31b3a0
vimkaf/Learning-Python
/exercises/excercise1.py
201
4.3125
4
""" This is a program to test if a number is a multiple of 4 """ for n in range(1,10): if n%4 == 0: print(n,"is a multiple of 4") else: print(n,"is not a multiple of 4")
true
cbca007466171f6c2e73e189d4b1da52ea6cf92e
wurde/Sorting
/src/recursive_sorting/recursive_sorting.py
1,107
4.15625
4
# # Define methods # def merge(left, right): elements = len(left) + len(right) merged_arr = [0] * elements return merged_arr def merge_sort(arr): if len(arr) > 1: left = arr[:int(len(arr)/2)] right = arr[int(len(arr)/2):] merge_sort(left) merge_sort(right) i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i = i + 1 else: arr[k] = right[j] j = j + 1 k = k + 1 while i < len(left): arr[k] = left[i] i = i + 1 k = k + 1 while j < len(right): arr[k] = right[j] j = j + 1 k = k + 1 return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort(arr): return arr arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7] print(arr1) merge_sort(arr1) print(arr1)
false
6d809fb001c5479b2037d813229e050d43434e76
AngelPedroza/holbertonschool-interview
/0x03-minimum_operations/0-minoperations.py
401
4.25
4
#!/usr/bin/python3 """ Initialize the file """ def minOperations(n): """ Function to return the minimum operations neccesary to copy and paste n times """ if not n or n < 2: return 0 mov = 0 min_op = 2 while min_op <= n: if n % min_op == 0: mov += min_op n = n // min_op else: min_op += 1 return mov
true
997bac264aa873f71ed14c19362f21e545f44838
Brambleberry4/Python-programming-exercises
/Solutions/task8.py
356
4.1875
4
""" Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world """ li = input("").split(",") li.sort() print(li, sep=",")
true
ffb093ee0d833bf2db18b4b2a1c86fc703039962
Litajong/Python_Practise
/007_BMI.py
469
4.15625
4
print("") print("Calculate your BMI to find whether you are too skinny or too fat") print("Just put your weight and height") w = float(input("Weight(kg.): ")) h = float(input("Height(cm.): ")) bmi = w / ((h/100) ** 2) print("") print("Your BMI is", bmi) print("") if bmi >= 18.5 and bmi <= 25 : print("Your body is perfect!!") elif bmi < 18.5 : print("Oh....you are too skinny T^T ") else : print("Ummm you are too chubby =_='") print("")
true
af2eb6e99b05c1ba2c5a8bfe8d70f56c5ea376f3
44746/Assignment
/setting up a placeholder.py
500
4.40625
4
#George west #9/9/14 #Setting up a placeholder print("hello world") #this is telling the computer to output the string that is between the brackets. first_name = input("please enter your name:") #this is outputing the string between the brackets and asking the user to input their name. print(first_name) #this will output the infromation stored under the variable called first_name print( "Hi {0}!".format (first_name)) #this will retrieve the infromation and output it using a placeholder.
true
894c6e47f3c276cc0f82161cad2ea788f33862e2
DavidRymer/Python-Exercises
/IntermediateExercises/LibrarySystem/Interface.py
2,568
4.125
4
from IntermediateExercises.LibrarySystem.InterfaceLogic import * def interface(): choice = input("Would you like to: \nA) Add a resource. " " \nB) Remove a resource. " "\nC) Add a person. " "\nD) Remove a person. " "\nE) Check in a resource. " "\nF) Check out a resource." "\nG) Show people. " "\nH) Show resources. \n").upper() if choice == "A": add_resource() elif choice == "B": remove_resource() elif choice == "C": add_person() elif choice == "D": remove_person() elif choice == "E": check_in() elif choice == "F": check_out() elif choice == "G": show_people() elif choice == "H": show_resources() else: print("Please choose one of the options") interface() end_prompt() def add_resource(): choice = input("Would you like to: \nA) Add a book. " " \nB) Add a newspaper " "\nC) Add a magazine. \n").upper() if choice == "A": add_book() elif choice == "B": add_newspaper() elif choice == "C": add_magazine() else: print("Please choose one of the options") add_resource() def add_person(): choice = input("Would you like to: \nA) Add a customer. " " \nB) Add an employee. \n").upper() if choice == "A": add_customer() elif choice == "B": add_employee() else: print("Please choose one of the options.") add_person() def end_prompt(): choice = input("Would you like to: \nA) Continue." " \nB) Logout. \n").upper() if choice == "A": interface() elif choice == "B": print("Goodbye.") else: print("Please choose one of the options") end_prompt() def prompt_load_files(): choice = input("Would you like to: \nA) Load resources from a file. " " \nB) Load people from a file. " "\nC) Both. " "\nD) Neither. ").upper() if choice == "A": load_resources_from_file() elif choice == "B": load_people_from_file() elif choice == "C": load_resources_from_file() load_people_from_file() elif choice == "D": print("You chose neither. \n") else: print("Please choose one of the options") prompt_load_files() prompt_load_files() interface()
false
0ba816d93f0ade4fbbe85b43a3420f9a3d41b58a
gustavo-almeida/python_lessons
/somador_unidades.py
215
4.125
4
valor = int(input("Digite o valor a ter as unidades somadas: ")) soma = 0 while valor != valor % 10: soma = soma + valor % 10 valor = valor // 10 soma = soma + valor % 10 print("Soma das unidades: ", soma)
false
127f38729580ba434856fc428ba1053e04a3e7c2
ofbennett/ds-and-algos
/python/recursion_and_dynamic_programming/radp_algos.py
2,613
4.1875
4
from collections import deque class Fibonacci: # Dynamic programming methods for O(N) calculation of the Nth Fibonacci number. Recursive algorithm is ~O(1.6^N). def __init__(self): pass def tabulationMethod(self, n): # Bottom up method if n in [0,1]: return n memo = {} memo[0] = 0 memo[1] = 1 for i in range(2, n+1): memo[i] = memo[i-1] + memo[i-2] return memo[n] def memoizationMethod(self, n): # Top down method memo = {} return self._memoizationMethod(n, memo) def _memoizationMethod(self, n, memo): if n in [0,1]: return n if n not in memo.keys(): memo[n] = self._memoizationMethod(n-1, memo) + self._memoizationMethod(n-2, memo) return memo[n] class TowersOfHanoi: # Recursive algorithm which solves the Towers of Hanoi puzzle. Time complexity O(2^N) where N is number of disks. # Dynamic programming isn't very helpful in this case as all O(2^N) moves have to be enumerated # regardless of the method used to find them. def __init__(self, n): self.n = n self.origin = deque() self.buffer = deque() self.destination = deque() for i in reversed(range(n)): self.origin.append(i) # Set verbose = True in order to print the solution move sequence to screen def solve(self, verbose=False): if verbose: print("Game begins in current state:") self.printTowerStates() print("Sequence of moves to solve:") print("******************") self.moveDisks(self.n, self.origin, self.destination, self.buffer, verbose) def moveDisks(self, n, origin, destination, buffer, verbose=False): if n <= 0: return elif n == 1: if len(destination) > 0: assert(origin[-1] < destination[-1]) # Rule check: ensure disk is being placed on top of larger disk destination.append(origin.pop()) if verbose: self.printTowerStates() else: self.moveDisks(n-1, origin, buffer, destination, verbose) self.moveDisks(1, origin, destination, buffer, verbose) self.moveDisks(n-1, buffer, destination, origin, verbose) def printTowerStates(self): print("origin: ", list(self.origin)) print("buffer: ", list(self.buffer)) print("destination: ", list(self.destination)) print("******************")
true
6fc9fc5d308f181d10606a9759ba338cbd5e55a5
markidtm/python-challenges
/countdown.py
728
4.1875
4
# All Imports: import datetime # Printing Current Time: now = datetime.datetime.now() print ("-" * 25) print (now) print (now.year) print (now.month) print (now.day) print (now.hour) print (now.minute) print (now.second) # Printing The Time Before: print ("-" * 25) print ("1 week ago was it: ", now - datetime.timedelta(weeks=1)) print ("100 days ago was: ", now - datetime.timedelta(days=100)) print ("1 week from now is it: ", now + datetime.timedelta(weeks=1)) print ("In 1000 days from now is it: ", now + datetime.timedelta(days=1000)) # Setting The Birthday: birthday = datetime.datetime(2012,11,4) #Printing If The Given Birthday is Now: print ("-" * 25) print ("Birthday in ... ", birthday - now) print ("-" * 25)
true
191a8d1e9e68d386100517235ddb8e044e577932
ravi4all/Python_AugReg_11-1
/CorePython/03-Loops/04-Break.py
256
4.125
4
##for i in range(0,11): ## print(i) ## if i == 6: ## print("Break the loop") ## break for i in range(0,11): print(i) if i >= 6: i += 2 print("Continue the loop") print(i) continue
false
816d1ad879ec0b211d1d1c9800d1fb241a9a1ff2
ichbinhandsome/sword-to-offer
/树/树的子结构.py
1,953
4.15625
4
''' 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A:      3     / \    4   5   / \  1   2 给定的树 B:    4    /  1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: def recur(A, B): if not B: return True if not A or A.val != B.val: return False return recur(A.left, B.left) and recur(A.right, B.right) return bool(A and B) and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)) # self.res = False # def pre_order(node): # if not node: # return # if node.val == B.val: # # print(node.val) # self.res += judge(node,B) # pre_order(node.left) # pre_order(node.right) # def judge(node,B): # if not B and not node: # return True # if B and not node: # return False # elif not B and node: # return True # if node.val != B.val: # return False # else: # l = judge(node.left, B.left) # r = judge(node.right, B.right) # return l and r # pre_order(A) # return True if self.res>0 else False
false
69fbb57bbbd50856a97890ae410e9422ec6e0223
mbasaran77/pyqt_app
/keypadTk.py
1,319
4.125
4
# create a calculator key pad with Tkinter # tested with Python 3.1.2 and Python 2.6.5 # vegaseat try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk # needs Python25 or higher from functools import partial def click(btn): # test the button command click s = "Button %s clicked" % btn root.title(s) root = tk.Tk() root['bg'] = 'green' # create a labeled frame for the keypad buttons # relief='groove' and labelanchor='nw' are default lf = tk.LabelFrame(root, text=" keypad ", bd=3) lf.pack(padx=15, pady=10) # typical calculator button layout btn_list = [ '7', '8', '9', '*', 'C', '4', '5', '6', '/', 'M->', '1', '2', '3', '-', '->M', '0', '.', '=', '+', 'neg' ] # create and position all buttons with a for-loop # r, c used for row, column grid values r = 1 c = 0 n = 0 # list(range()) needed for Python3 btn = list(range(len(btn_list))) for label in btn_list: # partial takes care of function and argument cmd = partial(click, label) # create the button btn[n] = tk.Button(lf, text=label, width=5, command=cmd) # position the button btn[n].grid(row=r, column=c) # increment button index n += 1 # update row/column position c += 1 if c > 4: c = 0 r += 1 root.mainloop()
true
282c569d70da5fdcf093446bcd7102c5cefd3f7c
tishacodes/Sprint-Challenge--Algorithms
/recursive_count_th/count_th.py
1,023
4.3125
4
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): #base case if len(word) < 1: return 0 #if "th" is found (find returns the index where the substring is found, it returns -1 if it is not found) elif word.find("th") >= 0: #store the starting index where it was found in found_index found_index = word.find("th") #find returns the starting index, so add 2 to define the starting point of the next search new_index = found_index + 2 #start the next search from the new starting point to the end of the string new_word = word[new_index: len(word)] #if "th" is found call count_th with the "new word" return 1 + count_th(new_word) else: #if it is not found return 0 return 0
true
107b9b82b58be32a47ad4b8ea138d0310b9d5929
wangxinyufighting/algorithom
/CodingInterViewGuide/chapter8_Array&Matrix/question2_Rotate Image.py
1,552
4.125
4
''' 给定一个 n × n 的二维矩阵表示一个图像。 将图像顺时针旋转 90 度。 LeetCode 48 https://leetcode-cn.com/problems/rotate-image/ 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rotate-image ''' #-------------------------------------------------------------------------- ''' 中心思想是: 根据矩阵的左上角(hx,hy)和右下角(tx,ty)确定一个矩阵(注意,不一定是方阵) 然后对于外圈,调整元素顺序 1 2 3 7 4 1 4 6 -> 8 2 7 8 9 9 6 3 ''' class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ if not matrix: return None hx = 0 hy = 0 tx = len(matrix) - 1 ty = len(matrix[0]) - 1 while hx < tx and hy < ty: self.rotate_(matrix, hx, hy, tx, ty) hx += 1 hy += 1 tx -= 1 ty -= 1 return matrix def rotate_(self, matrix, hx, hy, tx, ty): times = tx - hx temp = 0 for i in range(times): temp = matrix[hx][hy + i] matrix[hx][hy + i] = matrix[tx - i][hy] matrix[tx - i][hy] = matrix[tx][ty - i] matrix[tx][ty - i] = matrix[hx + i][ty] matrix[hx + i][ty] = temp
false
79e89da491df1b01cf2db1375aa85bf04472dfce
ajpiter/UdacityDeepLearning
/NeuralNetworks/l-IntroToNeuralNetworks/Perceptrons.py
1,764
4.15625
4
#Perceptrons #Also known as neurons #Inputs #Weights #Start out as random values, then as the neural network learns more about the input data and results the network adjusts the weights #The process of adjusting the weights is called training the neural network #The higher the weight the more important it is in determining the output # 'W' represents a matrix of weights # 'w' represents an indivdual weight #Linear combination #Multiple weights times inputs and sum them #Start at i = 1 #Evaluate (w1 * x1) and remember the results #move to i = 2 #Evaluate (w2 * x2) and add these results to (w1 * x1) #Continue repeating that process until i = mi where m is the number of inputs #Example, if we had two inputs, (w1 * x1) + (w2 * x2) #Output signal #Done by feeding the linear combination into an activation function #Activation functions are functions that decide, given the inputs to the node what should be the nodes outputs. #The output layer is referred to as activations #Heaviside step function #An activation function that returns a 0 if the linear combination is less than 0. #It returns a 1 if the linear combination is positive or equal to zero. #Think of 1 as yes and 0 as no or True/False #Bias #one way to get a function to return 1 for more inputs is to add a value to the results of the linear combination #Bias is represented in equations as b #Similar to weights the bias can be updated and changed by the neural network durning training #weights and bias are initially assigned a random value and then they are updated using a learning algorithm like gradient descent. #The weights and biases change so that the next training example is more accurate and patterns are learned by the neural network.
true
5e8639cd0d9de96713b45abbc2678fc73e77c8de
sivasai66/Python-Programs
/program9.py
255
4.1875
4
#python script to display the largest number among three numbers a=10 b=2 c=13 if(a>b): if(a>c): print("A is the big number",a) else : print("C is the big number",c) else: print("B is the big number",b)
true
50f0af0cef9c54b3fc6cb69a1cf9f7c2c0a7271c
SfilD/Michael_Dawson__Python_Programming
/ch03_guess_my_number_ex_1.py
1,482
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Отгадай число # # Компьютер выбирает случайное число в диапазоне от 1 до 100 # и пытается отгадать это число и компьютер говорит # предположение больше/меньше, чем загаданное число # или попало в точку import random print("Добро пожаловать в игру 'Отгадай число'!") print("Я загадал натуральное число из диапазона от 1 до 100.") print("Постараюсь отгадать его за минимальное число попыток.") # начальные значения first_num, last_num = 1, 100 number = random.randint(first_num, last_num) tries = 1 # цикл отгадывания while True: guess = (first_num + last_num) // 2 print("Попытка #%d" % tries) print("Предполагаю, что это число %d" % guess) if guess > number: print("Меньше...") last_num = guess elif guess < number: print("Больше...") first_num = guess elif guess == number: print("Вам удалось отгадать число! Это в самом деле %d." % number) print("Вы затратили на отгадывание всего лишь %d попыток." % tries) break tries += 1
false
e384a1b1b1d580e7bbee7bc54ea8e7f8328983cb
SfilD/Michael_Dawson__Python_Programming
/ch04_no_vowels.py
575
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Только согласные # Демонстрирует создание новых строк из исходных с помощью цикла for message = input("Введите текст: ") new_message = "" VOWELS = "eyuioaёуеыаоэяию" print() for letter in message: if letter.lower() not in VOWELS: new_message += letter print("Создана новая строка:", new_message) print("\nВот ваш текст с изъятыми гласными буквами:", new_message)
false
f2dc2cfac393a87e275815a2b8a4f9a1fbc8f9bd
brentrmckay/FinalExam
/Q1.py
471
4.34375
4
import math class Circle: def desccircle(self, radius): """desc circle will take in a radius and calculate circumference, diameter and area""" print("Circumference is : " + str(2 * math.pi * radius)) print("Diameter is : " + str(2 * radius)) print("Area is : " + str(math.pi * radius**2)) if __name__ == "__main__": myCircle = Circle() myCircle.desccircle(int(input("What is the radius of your circle? ")))
true
500d95e997c2e987db8fe61c2c9cde760afbd052
SveikiBatareiki/Python
/7th_lesson.py
2,482
4.5
4
# defining function def go_eat(): print("Go eat") print("Let's order food") #calling function go_eat() go_eat() #requirement that order_food is given an argument def order_food(dish): dish = str(dish) print(f"I'm ordering {dish}") print(f"{dish.capitalize()} should be pretty tasy") # so dish stops working here # no dish here order_food("potatoes") order_food("ice cream") order_food(555) #print(dish) this won't work because this doesn't exist here - outside function def eat(food_list): print("Hello") for food_item in food_list: order_food(food_item) order_food("ice cream") print("Let's eat") print("Let's leave and be happy") eat(["soup", "potatoes", "ice cream"]) def mult(a, b): print(f"Look, I'm multiplying {a} with {b} result is {a*b}") return a*b#with this it is possible also to print result afterwards, when function is called mult(5,10) print(mult(7,20)) mult("Beer", 3) result = mult(10,50) print(result) def add(a=50, b=10):# this means that a and b are defined if user doesn't give other values inner_result = a+b result = add(5,6) print(result) print(add(100))#this means that a = 100, but b is still 10 print(add())#this means that a is still a = 100, but b is still 10 print("Done adding") #print(mult(add(3,5),mult(2,1))) def greeter(first, last, is_upper=False, add_suffix=""):#mandatory parameters are those, which are not definede already in function """ Prints greeting Options - is_upper - whether to capitalize add_suffix - what suffix to add """ if is_upper: print(f"Hello {first.upper()} {last.upper()} {add_suffix}") else: print(f"Hello {first} {last} {add_suffix}") greeter("Māra", "Kārkliņa") greeter("Jānis", "Bērziņš", is_upper=True) greeter("Diāna", "Siliņa", add_suffix="sveicam kursā!") greeter("Viktor", " ", True)#is_upper is not necessary, but nice to include for clarity print(min(1,2,-6,6,20,30)) def adder(*args): # so a list of arguments of any lenght print(f"My adder with {len(args)} arguments") for arg in args: print(arg) adder(5,2, "Valdis") def mult(*args, multiplier=1): result = multiplier for arg in args: #could add an if here to check data type if we are not sure of nombers result *=arg return result print(mult(2,10,5)) print(mult(2,10,5,-3.6)) print(mult(2,10,5,-3.6, multiplier=1000)) print(mult(2,10,5,-3.6, multiplier=0))
true
31368e7ff48e0a1d2eeb468f6f47fc77bf6f0074
that-cisco-guy/devasc_crash_course
/Python code/grade.py
282
4.15625
4
score = int(input('What was your test score?: ')) if score >= 90: print('Your grade is A') elif score >= 80: print('Your grade is B') elif score >= 70: print('Your grade is C') elif score >= 60: print('Your grade is D') else: print('Your Grade is F')
false
396120dc1f2ccf702bfff1b488a771e47440ce02
shubhi13/Python_Scripts
/Algorithms/BubbleSort.py
617
4.40625
4
def bubble_sort(arr): """Returns the array arr sorted using the bubble sort algorithm >>> import random >>> unordered = [i for i in range(5)] >>> random.shuffle(unordered) >>> bubble_sort(unordered) [0, 1, 2, 3, 4] """ for i, j in enumerate(arr): if i + 1 >= len(arr): continue if j > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return bubble_sort(arr) return arr if __name__ == "__main__": import random unordered = [i for i in range(5)] random.shuffle(unordered) sort = bubble_sort(unordered) print(sort)
false
4e82616b46858fd11eae9bb793af5cef809b6eb0
shubhi13/Python_Scripts
/Automation/JpgToAnyFormatConvertor/JpgToAllFormatConvertor.py
2,412
4.125
4
''' Script uses Pillow module to read the image and convert it to png. sys module for accepting inputs from terminal and os module for operations on pathnames. Install Pillow module through "pip install pillow" ''' import sys,os from PIL import Image source_folder = sys.argv[1] # Accepts source folder given in terminal destination_folder = sys.argv[2] # Accepts destination folder given in terminal if not os.path.exists(destination_folder): #Check if destination folder exists,if not creates one os.makedirs(destination_folder) choice=1 while choice!=5: print("Press 1 -> To convert to PNG") print("Press 2 -> To convert to SVG") print("Press 3 -> To convert to GIF") print("Press 4 -> To Exit") choice=int(input("Enter your Choice: ")) print() if choice==1: for filename in os.listdir(source_folder): # For each file present in Source folder file = os.path.splitext(filename)[0] # Splits file name into as tuple as ('filename','.extension') img = Image.open(f'{source_folder}/{filename}') img.save(f'{destination_folder}/{file}.png','png') #Converts to png format print("Image converted to PNG!") print() elif choice==2: for filename in os.listdir(source_folder): # For each file present in Source folder file = os.path.splitext(filename)[0] # Splits file name into as tuple as ('filename','.extension') img = Image.open(f'{source_folder}/{filename}') img.save(f'{destination_folder}/{file}.svg','svg') #Converts to svg format print("Image converted to SVG!") print() elif choice==3: for filename in os.listdir(source_folder): # For each file present in Source folder file = os.path.splitext(filename)[0] # Splits file name into as tuple as ('filename','.extension') img = Image.open(f'{source_folder}/{filename}') img.save(f'{destination_folder}/{file}.gif','gif') #Converts to gif format print("Image converted to GIF!") print() else: sys.exit() ''' Sample input to run in terminal: ->Python3 JpgToPngConvertor.py Source_Images Destination_Images Output: Press 1 -> To convert to PNG Press 2 -> To convert to SVG Press 3 -> To convert to GIF Press 4 -> To Exit Enter your Choice: 1 Images converted to PNG! '''
true
a7c48ba01a7e4214911c790fb9bcf65458447c2d
Raul765/100-Days-of-Python
/Day 01 - Band name generator/Band name generator.py
559
4.28125
4
#1. Create a greeting for your program. #2. Ask the user for the city that they grew up in. #3. Ask the user for the name of a pet. #4. Combine the name of their city and pet and show them their band name. #5. Make sure the input cursor shows on a new line, see the example at: # https://band-name-generator-end.appbrewery.repl.run/ print("Hello, and welcome to the band name generator") city=input("Which city did you grow up in?\n") pet=input("What's the name of a pet you've had?\n") band_name=city+" "+pet print("Your band name could be " + band_name)
true
8469a717671cb67db8cbc97c9f950eb1415764b1
QuietSup/lab2-p2
/2p2-4.py
2,886
4.28125
4
class Node: """Contains a binary tree with info about product code and price""" def __init__(self, data): """Checks if entered data isn't empty and if it has the correct type :param data: info about product code and price :type data: tuple(int, int) """ if not data: raise ValueError("empty data") if not isinstance(data, tuple): raise TypeError("data must be tuple") if not data[0] or not data[1]: raise ValueError("empty code number or price") if not isinstance(data[0], int) or not isinstance(data[1], int): raise TypeError("price and must be tuple") self.left = None self.right = None self.data = data def insert(self, data): """Inserts new data into the binary tree :param data: info about product code and price :type data: tuple(int, int) """ if not self.data: raise Exception("Tree doesn't exist") if self.data == data: return if data[0] < self.data[0]: if self.left: self.left.insert(data) return self.left = Node(data) return if self.right: self.right.insert(data) return self.right = Node(data) def inorder(self, all_data=[]): """Traverses the tree :param all_data: collects the info while traversing the tree to return it :type all_data: list(int, int) """ if self.left is not None: self.left.inorder(all_data) if self.data is not None: all_data.append(self.data) if self.right is not None: self.right.inorder(all_data) return all_data def findval(self, to_find): """Finds the value, if can't - raises an error""" if to_find < self.data[0]: if self.left is None: raise ValueError("No item with this product code found") return self.left.findval(to_find) elif to_find > self.data[0]: if self.right is None: raise ValueError("No item with this product code found") return self.right.findval(to_find) else: return self.data[1] def printTree(node, level=0): """Draws a binary tree""" if node != None: printTree(node.left, level + 1) print(' ' * 4 * level + '->', node.data) printTree(node.right, level + 1) x = Node((6, 87)) x.insert((7, 93)) x.insert((4, 34)) x.insert((5, 25)) x.insert((3, 65)) x.insert((8, 23)) x.insert((2, 71)) print(x.inorder()) code = 3 # int(input('Product code:')) amount = 4 # int(input('Amount: ')) print(x.findval(code) * amount) printTree(x)
true
00dff77e37200dd6cd073fdfafe158d4fde7b042
thijsdijkwel/references
/conditionals-booleans.py
1,321
4.5
4
# Comparisons: (boolean) # Equal: == # Not Equal: != # Greater than: > # Less Than: < # Greater or Equal: >= # Less or Equal: <= # Object Identity: is language = 'Java' if language == 'Python': print ('Language is Python') # the elif statement is used as an additional 'if' elif language == 'Java': print ('Language is Java') elif language == 'Ruby': print ('Language is Ruby') # Else is used as a null. If none of the conditions are met, else statement will print else: print ('No match') a = [1, 2, 3] b = [1, 2, 3] # is figues out the ID of a function # you can use the ID function shown below to find exact ID print (id(a)) print (id(b)) print (a == b) print (a is b) # and - both need to be true # or - only one needs to be true # not - changes true to false and false to true user = 'Admin' logged_in = True if user == 'Admin' and logged_in: print ('Admin Page') else: print ('Insufficient Credentials') # example of not function if not logged_in: print ('Please log in') else: print ('Welcome') # False Values: # False # None # Zero of any numeric type # Any empty sequence. For exmaple, '', (), [. # Any empty mapping. For example, {}. condition = 'Test' if condition: print('Evaluated to True') else: print ('Evaluated to False')
true
b9f9f48763e679d57dac822631d24c710134ac52
rizkyprilian/purwadhika-datascience-0804
/Module1-PythonProgramming/comparisonoperator.py
447
4.28125
4
# --------------------------- print('\n####################\n') # --------------------------- x = 5 y = '5' print(x == y) # false print(x > int(y)) # false print(x >= int(y)) # true print(x < int(y)) # false print(x <= int(y)) # true # --------------------------- print('\n####################\n') # --------------------------- x = 5 y = '5' z = 6 print(x==int(y) and int(y)<z) print(x==int(y) or int(y)<z) print(not(x==int(y) or int(y)<z))
false
81625cbfb6c8cee34334c18857ac132db8f3cab9
chapman-phys220-2018f/cw08-late_for_class
/sinesum.py
949
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ### # Name: Abby Wheaton and Frank Entriken # Student ID: 2299246, 2298368 # Email: wheaton@chapman.edu, entriken@chapman.edu # Course: PHYS220/MATH220/CPSC220 Fall 2018 # Assignment: CW07 ### import numpy as np def s(t,n, T=2*np.pi): """ The s function computes the fourier series expansion of the original function f Parameters: t = alpha*T (float) n = number of terms to evaluate (int) T = constant used in the Fourier Series Expansion (float) """ k = np.arange(1, n) s = ((1/(2*k-1))*np.sin((2*(2*k-1)*np.pi*t)/ T)) return ((4/np.pi)*np.sum(s)) def f(t, T=2*np.pi): """ the f function is a piece-wise function with three distinct values Parameters: t = alpha*T (float) T = constant that t is compared to in order to produce an output (float) """ if t==0: return(0) if 0<t<T/2: return(1) if -T/2<t<0: return (-1)
true
ad7dbaf22e5b761b436e7d2b020dfe40aaf2b389
dkern27/CollegeProgramming
/Python/Epics2IntegrationComparison/trapezoid.py
1,436
4.1875
4
''' This code is specifically for evaluating finite integrals using the trapezoidal rule. It will accept discrete points as the input rather than a continuous function. It will find the first and second integrals of those points. It will output the final values for both integrations as well as graphs of the original points and both integrations. Code by Jordan Schmerge. ''' #import numpy as np #import matplotlib.pyplot #def f(x): #making a test function # return x**2 ''' Basically the function described in the header comment. ''' def trapezoidal( t, y1): #takes in array of points to integrate as a parameter #t = [] y2, y3 = [], [] #initialize empty arrays #t = np.linspace(0,2,10000) z = 0 #y1 = f(t) for i in range(len(t)-1): #actually using trapezoidal rule (v) integral = ((t[1]-t[0])/2)*(y1[i]+y1[i+1]) z+=integral y2.append(float(z)) #print y2[-1] #value of the first integral z2 = 0 for i in range(len(t)-2): #finding the second integral (x) integral2 = ((t[1]-t[0])/2)*(y2[i]+y2[i+1]) z2+=integral2 y3.append(float(z2)) #print y3[-1] #value of the second integral #matplotlib.pyplot.plot(t, y1,label='a') #making all the output graphs #matplotlib.pyplot.plot(t[:-1],y2,label='v') #matplotlib.pyplot.plot(t[:-2],y3,label='x') #matplotlib.pyplot.legend() #matplotlib.pyplot.show() return t[:-1], y2, t[:-2], y3
true
df7e627dc3de0f30fdd961acadb41bebf8825c8b
purusoth-lw/my-work
/20.nested for.py
1,274
4.21875
4
""" #program1 for i in range(1,6): for j in range(1,6): print(i,j,sep="",end=" ") print() #program2 for i in range(1,6): for j in range(5,0,-1): print(i,j,sep="",end=" ") print() #program3 for i in range(5,0,-1): for j in range(1,6): print(i,j,sep="",end=" ") print() #program4 for i in range(5,0,-1): for j in range(5,0,-1): print(i,j,sep="",end=" ") print() #program5 * * * * * * * * * * * * * * * * * * * * * * * * * #program6 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 """ for i in range(1,6):#outer loop----row for j in range(1,6):#inner loop---column print(j,end=" ") print() """ #program7 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 #program8 for i in range(1,6): for j in range(1,i+1): print(i,j,sep="",end=" ") print() #program9 * * * * * * * * * * * * * * * #program 10: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 #program11 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 #Program12 for i in range(1,6): for j in range(1,6-i+1): print(i,j,sep="",end=" ") print() """
false
9467d886f9730414947b9a50478a4f27e3dec793
purusoth-lw/my-work
/39.Data Encapsulation.py
1,165
4.375
4
""" Data Encapsulation: =================== Wrapping up to information. Ex:class secure the data. class Human: def __init__(self): self.name=input("Enter name : ") self.fname=input("Enter Father name : ") dob=input("Enter Date of Birth : ") age=int(input("Enter age : ")) Address=input("Enter Address") self.mobile=input("Enter mobile number : ") print("Your data inserted successfully....") def showDetails(self): print("name of student : ",self.name) print("mobile : ",self.mobile) """ class Encapsulation: data1=25#public var--->it can use anywhere of the program(own class,new class,main) __data2=50#private var---cant use outside the class(own class) def showDetails(self): print("Data1 : ",self.data1) print("Data2 : ",self.__data2) self.data1=10001 data1=50 __data2=100 self.__data2=100 print(data1,__data2 ) print("Data1 : ",self.data1) print("Data2 : ",self.__data2) obj=Encapsulation() obj.showDetails() print(obj.data1) #print(obj.__data2)
true
ce528b3feba1b4070c9fea7b93634e02ab562c2d
purusoth-lw/my-work
/33.inheritance.py
906
4.40625
4
""" Inheritance: ============ To access the one class information into another class #parent class/base class/super class #child class/sub class/derived class syntax: ======= class class1:#parent class statements class class2(class1):#child class statements """ #program class Class1:#parent class---it can access itself data and provide itself data to child clkass #but it cant access child class data to here. name1="janani" def show1(self): print("name : ",self.name1) class Class2(Class1):#child class---access their parent property name2="jeeva" def show2(self): print("name : ",self.name1) print("name : ",self.name2) c1=Class1() c1.show1() #c1.show2()#class1 cant access class 2 information c2=Class2() c2.show1()#class 2 can access the information for itself and herited class also c2.show2() """
true
73c38cf2f32ebc924a1ee376ddf21eaf1f06db78
Exeltor/Deep-Learning-AZ
/Get the Machine Learning basics/Classification Template/logistic_regression_mine.py
1,982
4.15625
4
# -----Data Preprocessing # -----Library imports (most common for machine learning) import numpy as np import matplotlib.pyplot as plt import pandas as pd # -----Import the dataset # Save data into variable using pandas dataset = pd.read_csv('Social_Network_Ads.csv') # The dependent variable is the one to be predicted # The independent variables are the predictors # We split the dependent and independent variables into X and Y X = dataset.iloc[:, [2, 3]].values # Predictors Y = dataset.iloc[:, 4].values # What we are trying to predict # -----Splitting the dataset into the Training Set and Test Set from sklearn.model_selection import train_test_split # Splitting library # All the arrays are initialized at the same time # Normally the test_size is a small percentage X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0) # 25% for test set # -----Feature scaling (Important to make all variables equally important) from sklearn.preprocessing import StandardScaler # Instantiate the scaler for X sc_X = StandardScaler() # Apply the scaler for the X sets X_train = sc_X.fit_transform(X_train) # No need to fit the Scaler, it has already been done for X_train X_test = sc_X.transform(X_test) # We dont need to apply scaling for Y in this case, because there is only 0 or 1 (its normalized) # -----Fitting Logistic Regression to the Training Set from sklearn.linear_model import LogisticRegression # Create classifier with the Logistic Regression Object classifier = LogisticRegression(random_state = 0) # Fit to training sets X and Y classifier.fit(X_train, Y_train) # -----Predicting the test set results Y_pred = classifier.predict(X_test) # Predictions based on the test set # -----Making the confusion matrix (evaluate if the model understood the evaluation) from sklearn.metrics import confusion_matrix cm = confusion_matrix(Y_test, Y_pred) #Import real and predicted results # -----Visualising the training set results
true
2699b729b03c01871bf9f173b5cfb3ab2804f948
drStacky/neural_net
/neural_net_Nlayer.py
2,006
4.125
4
# n Layer neural network (input, hidden layer, output) # Based on tutorial: https://iamtrask.github.io/2015/07/12/basic-python-network/ import numpy as np import matplotlib.pyplot as plt # For plotting results # Activation function def sigmoid(f, deriv=False): if deriv: return f*(1-f) else: return 1/(1+np.exp(-f)) # Training set inputs # Perfect correlation b/w 1XOR2 and output x = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) # Training set outputs y = np.array([[0, 1, 1, 0]]).T # Seed random numbers for predictability in testing code np.random.seed(314) # Total number of layers (first layer is 0) n = int(input("How many hidden layers? ")) # Synapse, this matrix is the connection between input and out that "learns" # Start with random values between -1 and 1 (mean 0) syn = [] for i in range(0, n): syn.append(2 * np.random.random((3, 3)) - 1) syn.append(2 * np.random.random((3, 1)) - 1) layers = [] errors = [[], []] for epoch in range(0, 10000): # Make guess of output # Feed through hidden layers layers = [x] for j in range(0, n+1): layers.append(sigmoid(np.dot(layers[j], syn[j]))) # Calculate error in guess error = y - layers[n + 1] # Save epoch vs error for plotting later errors[0].append(epoch) errors[1].append(np.linalg.norm(error)) # dJ/dtheta delta = [y]*(n+1) delta[n] = error * sigmoid(layers[n + 1], True) for j in range(n-1, -1, -1): delta[j] = np.dot(delta[j+1], syn[j+1].T) * sigmoid(layers[j+1], True) # Synapse learns for j in range(0, n+1): syn[j] += np.dot(layers[j].T, delta[j]) # Final guess print(layers[n + 1]) # Plot the error (should be decreasing towards 0) plt.figure() plt.scatter(errors[0], errors[1]) plt.title('Neural Net Error Convergence') plt.xlabel('Epoch') plt.ylabel('Error magnitude') plt.show()
true
dbb3b9694a30524062c9c4f6af6e36deeb3298d7
tomasznazarenko/python-exercises
/conversion_to_boolean_merge_sorted_lists.py
1,034
4.5625
5
# The merge_arrays(a, b) function, takes two sorted lists of integers, merges them into one sorted list, and returns the result. # The function should work in the following way: create an empty list c which will store the result; # keep finding the smallest remaining element in a and b and moving it to the list c; stop when there are no elements left in a and b. # # Try to use non-boolean values in logical expressions when possible. # # Your program shouldn't read any input or call the function, just implement it. # Sample Input 1: # # 1 2 3 # 2 3 4 4 # # Sample Output 1: # # 1 2 2 3 3 4 4 def merge_arrays(a, b): # "c" will contain the result of merging arrays "a" and "b" c = [] while a or b: if not b or (a and b and a[0] < b[0]): # removing the first element from "a" and adding it to "c" c.append(a[0]) a.pop(0) else: # removing the first element from "b" and adding it to "c" c.append(b[0]) b.pop(0) return c
true
e60dcd8962053678ccb2251a3c43b7295496621d
tomasznazarenko/python-exercises
/bytes_ceaser_cipher.py
501
4.28125
4
# Write a code that reads a string from the input, adds 1 to the code point of every character and outputs the encrypted string. # # Sample Input 1: # # I love ord function! # # Sample Output 1: # # J!mpwf!pse!gvodujpo" print("".join(chr(ord(letter) + 1) for letter in input())) # inp = input() # return_value = [] # for char in inp: # code_point = ord(char) # code_point += 1 # char_cipher = chr(code_point) # return_value.append(char_cipher) # print("".join(return_value))
true
2a05c0b50fdb22a7babf74699233e25cc820ad01
tomasznazarenko/python-exercises
/sum_of_elements_in_a_list.py
1,045
4.3125
4
# If you think about it, many standard operations can be thought of in terms of recursion. # Take the sum of elements, for example. It's not hard to notice that the sum of the first element of a list and the sum of the rest of the elements in this list gives you the sum of all the elements. # Taking this fact into account, finish the template for a recursive function list_sum(). # It takes a list of numbers as its input and outputs their sum. You need to determine the condition for the base case and the action that needs to be performed in the recursive step. # Sample Input 1: # 5 # Sample Output 1: # 5 # Sample Input 2: # 5 2 3 # Sample Output 2: # 10 def list_sum(some_list): if some_list == []: return 0 if len(some_list) == 1: # base case return some_list[0] return some_list.pop() + list_sum(some_list) # def list_sum(some_list): # if some_list == []: # return 0 # if len(some_list) == 1: # base case # return some_list[0] # return some_list[0] + list_sum(some_list[1:])
true
da3b0ec23b9d23deff90012820e5e2b28de3b663
candyer/exercises
/rotate.py
1,291
4.125
4
def rotate1(l, n): """create a function that return a rotated list. l is a list; n is an int """ if len(l) == 0 or len(l) == 1: return l if n <= 0: for i in range(abs(n)): l.append(l[0]) l.pop(0) return l else: for i in range(len(l) - n%len(l)): l.append(l[0]) l.pop(0) return l print rotate1([], 3) #[] print rotate1([1], 2) #[1] print rotate1(range(8), 0) #[0, 1, 2, 3, 4, 5, 6, 7] print rotate1(range(8), -2) #[2, 3, 4, 5, 6, 7, 0, 1] print rotate1(range(8), -10) #[2, 3, 4, 5, 6, 7, 0, 1] print rotate1(range(8), 2) #[6, 7, 0, 1, 2, 3, 4, 5] print rotate1(range(8), 10) #[6, 7, 0, 1, 2, 3, 4, 5] print rotate1(range(8), 8) #[1, 2, 3, 4, 5, 6, 7, 0] #better solution. complexity is O(n) def reverse(l): return l[::-1] def rotate2(l, n): if not l: return l n = -n % len(l) first = l[:n] second = l[n:] return reverse(reverse(first) + reverse(second)) print rotate2([], 3) #[] print rotate2([1], 2) #[1] print rotate2(range(8), 0) #[0, 1, 2, 3, 4, 5, 6, 7] print rotate2(range(8), -2) #[2, 3, 4, 5, 6, 7, 0, 1] print rotate2(range(8), -10) #[2, 3, 4, 5, 6, 7, 0, 1] print rotate2(range(8), 2) #[6, 7, 0, 1, 2, 3, 4, 5] print rotate2(range(8), 10) #[6, 7, 0, 1, 2, 3, 4, 5] print rotate2(range(8), 8) #[0, 1, 2, 3, 4, 5, 6, 7]
false
bbf0d12af90754f3d49c4e01a11fabf1f89c2e81
dilipksahu/Python-Programming-Example
/Array programs/monotonicArray.py
372
4.25
4
# Program to check if given array is Monotonic # An array is monotonic if it is either monotone increasing or monotone decreasing. def isMonotonic(arr): return ( all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) or all(arr[i] >= arr[i+1] for i in range(len(arr)-1)) ) A = [6, 5, 4, 4] B = [10,15,20,12] print(isMonotonic(A)) print(isMonotonic(B))
true
720e85851c9e1a9f09f9f6ef9fbb7fb2da61b4c3
dilipksahu/Python-Programming-Example
/String Programs/stringSliceToRotate.py
524
4.40625
4
# String slicing in Python to rotate a string # Input : s = "GeeksforGeeks" # d = 2 # Output : Left Rotation : "eksforGeeksGe" # Right Rotation : "ksGeeksforGee" def string_slice(string, d): Lfirst = string[0:d] Lsecond = string[d:] Rfirst = string[0: len(string)-d] Rsecond = string[len(string)-d: ] # now concatenate two parts together print("Left Rotation : ",Lsecond + Lfirst) print("Right Rotation :", Rsecond + Rfirst) s = "GeeksforGeeks" d = 2 string_slice(s, d)
false
c69642a26cbb9a6b7fbcd26e16f15c9e6e2d6f1a
dilipksahu/Python-Programming-Example
/String Programs/substringInString.py
706
4.25
4
# Check if a Substring is Present in a Given String print("====== Using find() method ========") def checkByFind(string,substring): # find() function returns -1 if it is not found, else it returns the first occurrence. if string.find(substring) == -1: print("NO") else: print("YES") string = "geeks for geeks" sub_str ="geek" checkByFind(string,sub_str) print("========= using count() method =======") def checkByCount(str1,str2): if str1.count(str2) > 0: print("YES") else: print("NO") checkByCount(string,sub_str) print("======= using Regex search() method ======") import re if re.search(sub_str,string): print("Yes") else: print("No")
true
5fccec887212271a3ea10f5bd2b0d85780b3a037
dilipksahu/Python-Programming-Example
/Matrix Programs/addTwoMatrix.py
714
4.1875
4
# Python program to add two Matrices print("========= using for loop ===========") X = [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Z = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # rows = 3 # iterate through columns for j in range(len(X[0])): # columns = 3 Z[i][j] = X[i][j] + Y[i][j] for i in Z: print(i) print("======== List Comp ============") res = [ [ X[i][j] + Y[i][j] for j in range(len(X[0])) ] for i in range(len(X)) ] for i in res: print(i) print("=========== zip and sum ===========") result = [ list(map(sum, zip(*t))) for t in zip(X, Y)] for i in result: print(i)
false
a6fc91766aaa541173bc48c37f53e0d10fcf26a8
dilipksahu/Python-Programming-Example
/Dictionary Programs/orderedDict.py
443
4.40625
4
# Given an ordered dict, write a programm to insert items in beginning of ordered dict. # Input: # original_dict = {'akshat':1, 'manjeet':2} # item to be inserted ('nikhil', 3) # Output: {'nikhil':3, 'akshat':1, 'manjeet':2} from collections import OrderedDict ini_dict = OrderedDict({'akshat':1, 'manjeet':2}) ini_dict.update([('nikhil',3)]) # Adding beginning of ordered dict ini_dict.move_to_end('nikhil', last= False) print(ini_dict)
true
90ea6aa57ad1314fd981f61cf18f39a3457c21bb
iliadubinsky/Homework-3
/2a_seq.py
867
4.5
4
#Пользователь вводит количество цифр и потом любые цифры #Сохранить цифры в список #Получить новый список в котором будут только уникальные элементы исходного # ...(уникальным считается символ, который встречается в исходном списке только 1 раз) #Вывести новый список на экран #Порядок цифр в новом списке не важен number_elements = int(input("Please enter number of elements in the list ")) lst = [int(input("Enter any number ")) for i in range(1,number_elements+1)] print("You created the following list:") print(lst) lst_unique = set(lst) print("Your list, but only with unique elements:") print(lst_unique)
false
191c6606d3eaa3ba307b29793f45d068c054eb76
gopikris83/PyPrograms
/Utils/src/graphicsCreator/graphicsCreator.py
611
4.15625
4
# Program that generate visual graphics to draw any shape and design with colors import tkinter as TK import random import turtle colors = ['red', 'blue', 'yellow', 'green', 'white', 'grey', 'brown', 'purple'] t = turtle.Turtle() t.speed(15) # Set the spiral rotation speed in secs turtle.bgcolor("black") length = 100 angle = 50 rad = 5 for i in range(length): color = random.choice(colors) t.pencolor(color) t.fillcolor(color) t.penup() t.forward(i+50) t.pendown() t.left(angle) t.begin_fill() t.circle(rad) t.end_fill() turtle.exitonclick() turtle.bgcolor("black")
true
f1ea922329d9f133564193d7c00f4d93b48caba6
nflondo/myprog
/python/python_in_24_hours/basic_string_find.py
385
4.1875
4
#!/usr/bin/python # if string contains emergency, then ask if email is urgent # If string contains joke, then ask if email is non-urgent #email_1="This is an urgent message" email_1="This is a good joke" if email_1.find('urgent') != -1: print "Do you want to send as urgent message?" elif email_1.find('joke') != -1: print "Do you want to send as non-urgent message?"
true
c364933291ec566525312e123cfd5081d6c60095
nflondo/myprog
/python/crash_course/ch4/ex_ch4-10.py
520
4.28125
4
num_list = [] for num in range(0,14,2): num_list.append(num) print(num_list) print("first three items:" + str(num_list[0:3])) print("three items from middle:" + str(num_list[2:5])) print("last three items:" + str(num_list[-3:])) print("*" * 10) pizzas = ['pepperoni', 'meat', 'hawaiian'] friend_pizzas = pizzas[:] pizzas.append('artchoke') friend_pizzas.append('supreme') print("My fav pizzas are:") for pizza in pizzas: print(pizza) print("Friend's fav pizzas are:") for pizza in friend_pizzas: print(pizza)
false
79c19b2b45c18d3026cdd315c0e4afa4d6169466
nflondo/myprog
/python/online-tutorials/freecodecamp-inte/lec_copying.py
842
4.28125
4
#!/usr/bin/env python3 # Copy mutable elements with built in module. and copies of custom objects import copy org = 5 cpy = org # this does not make a real copy, creates a new var pointing to same num cpy = 6 # creates a new variable print(cpy) print(org) org2 = [0,1,2,3,4] cpy = org2 cpy[0] = -10 print(cpy) print(org2) # - shallow copy: one level deep, only references of nested child objects # - deep copy: full independent copy # shallow (the original is not affected) orig = [1,2,3] cpy = copy.copy(orig) # cpy = orig.copy() # this also works # cpy = list(orig) # this is possible # cpy = orig[:] # this also makes an actual copy cpy[0] = -10 print(cpy) print(orig) # nested list (deep copy), dict or tuple orig3 = [[1,2,3], [4,5,6]] cpy = copy.deepcopy(orig3) # original is not affected cpy[0][1]= -10 print(cpy) print(orig3)
true
eb61ff97ccf7737592cc2ee3b268c7e36e8ccd57
nflondo/myprog
/python/python_in_24_hours/restaurant_project/main.py
2,798
4.125
4
#!/usr/bin/python # Main # Recipe and Inventory program. The inventory part reads inventory from a file 'inventory.txt' and sticks that information into # a dictionary where more items can be added or remove. Still have to add a way to save the modified inventory back into a file. from classes.ingredient import Ingredient from classes.recipe import Recipe from classes.inventory import Inventory def main(): #Recipe instantiation and printing i = Ingredient( title =" egg") r = Recipe( title ="Scrambled eggs", ingredients =[ i], directions =['Break egg', 'Beat egg', 'Cook egg']) r.print_recipe() oats = Ingredient(title = "Oats") oatmeal = Recipe(title = "Oatmeal", ingredients = [oats], directions =['cook oatmeal in a pan', 'serve oatmeal']) oatmeal.print_recipe() ''' item1 = Inventory(items = {'salt':2, 'eggs':5}) print "Before adding:" item1.print_inventory() item1.add(item = "eggs") print "After adding:" item1.print_inventory() item1.check(item="salt") item1.check(item="onions") item1.remove(item="eggs") item1.print_inventory() ''' #Inventory part. Open file and put it in a dictionary f = open('/home/myprog/python/restaurant_project/inventory.txt') lines = f.readlines() items = {} for l in lines: l = l.strip('\n') l = l.split('\t') items[l[0]]=int(l[1]) #These were the original lines from book(didn't work) #i = Ingredient(title=l[0]) # items[i]= int(l[1]) #For debugging could print the items in the dictionary #for a in items: # print a,items[a] inventory = Inventory(items) # User Menu while True: choice=raw_input( "\t1- Add items\n\t2- Remove Items\n\t3- Print Inventory\n\tq - Quit\n\t Please choose: ") if choice.lower() in ['q','quit']: print "Good Bye" break #int(choice) if choice == '1': inv_add = raw_input("New inventory item: ") #inv_add = inv_add.strip('\n') #inv_qty = raw_input("New amount: ") inventory.check(item=inv_add) inventory.add(item=inv_add) elif choice == '2': inv_remove = raw_input("Inventory remove: ") exists=inventory.check(item=inv_remove) print "exists:", exists if exists: inventory.remove(item=inv_remove) print "DEBUG: Ran inventory.remove" elif choice == '3': inventory.print_inventory() ''' f = open('inventory.txt','r+w') for a in items: f.write(a,items[a]) f.close #help(i) #help(oatmeal) #help(item1) ''' if __name__ == "__main__": main()
true
6c44fc2824bdd53460ce6419fa55239f311cdf62
nflondo/myprog
/python/crash_course/ch4/ex_ch4-6.py
440
4.28125
4
odd_numbers = list(range(1,20,2)) for odd in odd_numbers: print(odd) print("*" * 10) multiple_three = [] for multiple in range(3,31): multiple_three.append(multiple * 3) for number in multiple_three: print(number) print("*" * 10) cubes = [] for cube in range(1,11): cubes.append(cube ** 3) for cube in cubes: print(cube) print("*" * 10) cubes_comp = [cube ** 3 for cube in range(1,11) ] for cube in cubes_comp: print(cube)
false
b6415d8028150c5261f6cd18d8ab61b4331e46b7
nflondo/myprog
/python/hardwaybook/functions_return_ex21.py
1,322
4.15625
4
#!/usr/bin/python # def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a / b def mycomparison(a,b): print "Comparing %d and %d" % (a,b) if a > b: print "A > B" return "A" elif b > a: print "B > A" return "B" else: print "A and B must be equal" return "Equal" print "Let's do some math with just functions!" num_1 = int(raw_input("Please give me first number: ")) print "Type: ", print (type(num_1)) #age = add(30, 5) age = add(num_1, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) # A puzzle for the extra credit, type it in anyway. print "Here is a puzzle." # The return value of a function, can be used as the input to another # function what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print "That becomes: ", what, "Can you do it by hand?" # This is a silly test for a return string compare_result = mycomparison(20,20) print "compare_result: %s" % compare_result
true
a6f256dc3fc362775d15b6e4f65ea1b4fb8dd5b1
nflondo/myprog
/python/crash_course/ch7/lecture-input.py
828
4.15625
4
# input() python considers everything entered a String message = input("Tell me something: ") print(message) # long text, then prompt prompt = ("If you tell us who you are, we can personalize the messages" " you see. This way is more personal. Understand?") prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, " + name + "!") # int() for numerical input height = input("How tall are you, in inches? ") height = int(height) if height >= 36: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when you're older") # Modulo operator. Even or odd numbers number = input("Enter a number: ") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.")
true
c340cd707ec09fecfa7426b0351ac59d2082add9
nflondo/myprog
/python/hardwaybook/ex15-reading-files.py
453
4.125
4
from sys import argv script, filename = argv # opens a file and returns a file object txt = open(filename) print "Here's your file %r:" % filename # This will print the file object to the screen print txt.read() #print txt.readlines() txt.close() print "Type the filename again:" file_again = raw_input("> ") #open a given file name txt_again = open(file_again) print txt_again.read() txt_again.close() # dump it to screen #print txt_again.read()
true
305d55dd381e29b780c54140b9b9450518efddf0
parfittchris/leetcodePython
/array/merge_sorted_arr.py
1,218
4.28125
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # Note: # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space(size that is equal to m + n) to hold additional elements from nums2. def mergeSorted(arr1, arr2, m, n): # set pointer to length of arr1 - 1 pointer = len(arr1) - 1 # while loop that moves pointer backwards. while pointer >= 0: nextVal = None # fill current idx of arr1 with the greater of arr1[m]/arr2[n] # decrement m/n depending on whatever is used # if m or n is 0 choose other if m == 0: nextVal = arr2[n - 1] n -= 1 elif n == 0: nextVal = arr1[m - 1] m -= 1 elif arr2[n - 1] > arr1[m - 1]: nextVal = arr2[n - 1] n -= 1 else: nextVal = arr1[m - 1] m -= 1 arr1[pointer] = nextVal # decrement pointer pointer -= 1 # return arr1 return arr1 nums1 = [1, 2, 3, 0, 0, 0] m = 3 nums2 = [2, 5, 6] n = 3 print(mergeSorted(nums1, nums2, m, n)) # Output: [1, 2, 2, 3, 5, 6]
true
a3a5092f91fb2daf9fdaddd7623a0a9b3d4f8fd1
dannyjew/Data21Notes
/working_with_files.py
1,023
4.375
4
def open_and_print_file(file): try: # opens file opened_file = open(file, "r") # default opens to read mode however we put "r" there to confirm its in read mode file_line_list = opened_file.readlines() for i in file_line_list: print(i.strip()) # closes file opened_file.close() except FileNotFoundError as errmsg: print("There has been an error opening your file!") print(errmsg) raise finally: print("Execution Complete") # write a function which writes to a file def write_to_file(file, order_item): try: # this is another way to make the file close once it has been processed. "w" means to open in write mode, "a" means to append with open(file, "a") as opened_file: opened_file.write(order_item + "\n") except FileNotFoundError: print("file cannot be found") # now lets use the two functions write_to_file("order.txt", "lettuce") open_and_print_file("order.txt")
true
3a66547e81d4c09b2e59ed56c7560f1500e5b312
ChefBoyarDumbass/papitas_fritas
/decode/base64/b64decode.py
1,351
4.15625
4
#!/usr/bin/python import base64 ''' This script will allow the user to decode a base64 encoded string multiple times. *User inputs a base64 encoded string. *The string is decoded by default once, or as many times as entered by the user. *The decoded base64 string is output as a result. Author: r4mzih4x Tested on: Python 2.7.14 ''' # Function to decode the user base64 string multiple times def b64dcode (userString): global b64converted b64converted = base64.b64decode(userString) # Store the user input of a base64 encoded string b64string = raw_input("Enter base 64 encoded string: ") print ("\nYou entered the following string:\n " + b64string) # Initial function call with user input b64dcode(b64string) # Will decode strings encoded up to 1000 times count = 1000 # Add a counter to track the amount of attempts to decode attempts = 0 while (count > 1): print ("\nNext Decoded String:\n " + b64converted) attempts += 1 try: b64dcode(b64converted) except: # Base64 string has been fully decoded break count -= 1 print ("\nFinal Decoded String:\n " + b64converted) print ("Base64 decoded text has been saved to b64decoded.txt") # Create a text file to store the decoded base64 text txtFile = open("b64decoded.txt", "w") txtFile.write(b64converted) txtFile.close()
true
21bf2d9cce7c9bb97aec3da23fe24bb2a637a189
dishantkapadiya2694/CTC-Solutions
/Chapter 3/3.4 Queue via Stacks.py
777
4.125
4
"""Implement Queue using 2 Stacks""" from Stack import stack class MyQueue: def __init__(self, capacity): self.__capacity = capacity self.__Stack1 = stack(capacity) self.__Stack2 = stack(capacity) self.__activeStack = self.__Stack1 self.__passiveStack = self.__Stack2 def enqueue(self, val): if not self.__activeStack.spaceAvailable() and not self.__passiveStack.spaceAvailable(): print "Queue Full" return elif not self.__activeStack.spaceAvailable(): if self.__passiveStack.spaceAvailable(): self.__activeStack.push(val) def dequeue(self): if len(self.__activeStack)+len(self.__passiveStack) == 0: print "Queue empty" return
true
f5376ac23f3bc0f91f6d164e1bbe4ce787b1843e
brian29sg/python-simple-questionnaire
/Display.py
1,458
4.125
4
from familyMember import familyMember from Adult import Adult from Child import Child ''' The function displayInfo sorts out whether the user is an adult or child based on the age that was entered. Further prompts are issued to summarise the user's details. A 'try' method has been used when prompting the user for their allowance to ensure that what they have entered is valid. When everything is valid, a new instance of 'Child' or 'Adult' is made. ''' def displayInfo(arg1, arg2): if arg2 <= 20: education = raw_input("\nPlease enter your education (eg. Year 10, College): ") while True: try: allowance = int(raw_input("\nPlease enter your weekly allowance (NZD$): ")) except ValueError: print "\nPlease enter your allowance again. " else: member = Child(arg1, arg2, education, allowance) print member.getName() ,", aged", member.getAge(), "is in", member.getEducation(), "and gets $", member.getAllowance(), "weekly." break elif arg2 > 20: job = raw_input("\nPlease enter your job (eg. Engineer): ") while True: try: salary = int(raw_input("\nPlease enter your yearly salary (NZD$): ")) except ValueError: print "\nPlease enter your salary again." else: member = Adult(arg1, arg2, job, salary) print "\n",member.getName() ,", aged", member.getAge(), "has a job as an", member.getJob(), "and earns $", member.getSalary(), "per annum." break
true
e9c709629d0529ba6a6560958c8681244a6051fc
666syh/Learn_Algorithm
/10_Regular_Expression_Matching.py
2,492
4.21875
4
""" https://leetcode.com/problems/regular-expression-matching/ Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like . or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab" p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)". Example 4: Input: s = "aab" p = "c*a*b" Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". Example 5: Input: s = "mississippi" p = "mis*is*p*." Output: false """ class Solution: def isMatch(self, text, pattern): #dp数组 memo = {} def dp(i, j): #判断是否已经在数组中(之前计算过),若在直接返回 if (i, j) not in memo: #p已遍历完,s是否也遍历完 if j == len(pattern): ans = i == len(text) #若p未遍历完 else: #假设当前s字符串为:yS #当前p字符串为:xzP #若s也未遍历完,判断x与y是否相等 first_match = i < len(text) and pattern[j] in {text[i], '.'} #如果z是‘*’,那么判断P与yS是否匹配或者S和xzP是否匹配 if j+1 < len(pattern) and pattern[j+1] == '*': ans = dp(i, j+2) or first_match and dp(i+1, j) #如果z不是‘*’,且x与y相等的话,去掉x与y,判断zP与S else: ans = first_match and dp(i+1, j+1) #将判断过的保存在dp数组中 memo[i, j] = ans return memo[i, j] return dp(0, 0) x = Solution() print(x.isMatch("aaa", "a*a"))
true
4a2d13e2944891c236dbe5444b6ed384dc10838e
broshanravanAssignments/MyFirstPythonProject
/src/PythonExcersizes.py
620
4.125
4
def getStringLength(strIn): lenght = 0 lenght = len(strIn) return lenght def isNumber(strIn): isNum = True try: int(strIn) except: isNum = False return isNum def determineLenght(strIn): length = 0 if (isNumber(strIn)): print("This function is NOT applicable to numbers") else: length = getStringLength(strIn) print("Length of the String: '" + strIn + "' is:\n" + str(length)) return length ########################RUNNING FUNCTIONS########################### myString = input("Please enter a String: \n") determineLenght(myString)
true
e061e84d84d091d0e8916b1c28db7284653d0e5c
alanwutke/python
/isnumeric_e_try.py
573
4.21875
4
""" num1 = input('Digite um Número: ') num2 = input('Digite outro Número: ') # isnumeric, isdigit, isdecimal - estas funções retornam se o valor da variável é um numero # print() print(num1.isnumeric()) print(num2.isdecimal()) """ #exemplo de calculadora, verificando se é digitado apenas numeros num1 = input('Digite um Número: ') num2 = input('Digite outro Número: ') #try = tenta executar o bloco, se ocorrer erro ele pula para o except . try: num1 = float(num1) num2 = float(num2) print(num1 + num2) except: print('Digite apenas números')
false
e62a64aef5643ab52c492b498d38af6cf596c000
alanwutke/python
/split.py
687
4.1875
4
# Split - Dividir um string string = 'O Brasil é o Pais do futebol, o Brasil é penta.' lista1 = string.split(' ') lista2 = string.split(',') print(lista1) print(lista2) # contando as palavras: for valor in lista1: print(f'A palavra {valor} apareceu {lista1.count(valor)}x na frase.' ) palavra = '' contagem = 0 for valor in lista1: qtd_vezes = lista1.count(valor) if qtd_vezes > contagem: contagem = qtd_vezes palavra = valor print(f'A palavra que apareceu mais vezes é "{palavra}" ({contagem}x)') for valor in lista2: print(valor.strip().capitalize()) # strip() tira espaços em branco no começo e fim, capitalize() a 1ª letra fica maiúscula
false
5f9dbe79c3e20a69e7e0d1ec8063f5e97057c481
marceltoben/evandrix.github.com
/py/greplin-challenge/level2.py
2,714
4.5
4
#!/usr/bin/env python """ Level 2 ---------------------------------------- Congratulations. You have reached level 2. To get the password for level 3, write code to find the first prime fibonacci number larger than a given minimum. For example, the first prime fibonacci number larger than 10 is 13. When you are ready, go here or call this automated number (415) 799-9454. You will receive additional instructions at that time. For the second portion of this task, note that for the number 12 we consider the sum of the prime divisors to be 2 + 3 = 5. We do not include 2 twice even though it divides 12 twice. ---- next-part: Step 1. Use your code to compute the smallest prime fibonacci number greater than 227,000. Call this number X. Step 2. The password for level 3 is the sum of prime divisors of (X + 1). (parens i added) Note: If you call the number instead, it will check your answer for step 1. --notes the sum of the prime divisors of last answer plus 1 .... 514230 2 3 5 61 281 2 + 3 + 5 + 61 + 281 Out[39]: 352 <--- ANSWER """ import math def is_prime(num): """ assume num is positive integer it suffices to check if every number from 2 to ceil(sqrt(A)) does not divide into A to establish if A is prime """ for i in range(2, int(math.ceil(math.sqrt(num)))): # for i in range(2, num): #lazy :) if num % i == 0: return False return True def prime(): n = 2 while True: if is_prime(n): yield n n += 1 def fibo(): """a generator for Fibonacci numbers, goes to next number in series on each call""" a, b = 0, 1 while True: yield a a, b = b, a + b def next_fibo(num): """return the next fibo num *greater than* num""" f = fibo() next = f.next() while next <= num: next = f.next() return next def next_fibo_prime(num): next = next_fibo(num) while True: #don't run away loop! if is_prime(next): return next next = next_fibo(next) def first_prime_div(num): prm = prime() div = prm.next() while div <= num: if num % div == 0: return div div = prm.next() def prime_divs(num): divs = [] while True: div = first_prime_div(num) divs.append(div) if is_prime(num): break #print "num: %s div: %s" % (num, div) num /= div return divs if __name__ == '__main__': x = next_fibo_prime(227000) print "X + 1: %s" % (x + 1) x += 1 divs = prime_divs(x) print "sum(prime divisors of X+1) = %s" % reduce(lambda x, y: x + y, divs)
true
9678903ddae24b8576c120aeca8b4cfde2592600
maximus-sallam/Project
/guests.py
2,120
4.375
4
#!/usr/local/bin/python3.7 guests = [ 'Albert Einstein', 'Thomas Edison', 'Nikola Tesla', 'Elon Musk' ] # This is my list of guests num = len(guests) # This is how many guests are in the list i = 0 while i < num: # This itterates through each guest and prints the guests name with a message print("Please come over and eat my food, " + guests[i]) i = i + 1 print(len(guests)) print("") # This is white space print("Oh dear! It appears that " + guests[2] + " won't be joining us.") cant = guests.pop(2) # This removes Nikola Tesla from the list and stores it as cant guests.insert(2, 'Alexander Shulgin') # Inserts guest into the 2 position print("") # This is white space i = 0 while i < num: # This itterates through each guest and prints the guests name with a message print(guests[i] + ", I've found a bigger table!") i = i + 1 print(len(guests)) guests.insert(0, 'Richard Feynman') # Adds guest to the beginning of the list guests.insert(3, 'Pablo Escobar') # Inserts guest into the 3 position guests.append('Freddy Krueger') # Appends guest to the end of the list num = len(guests) print("") # This is white space print(len(guests)) i = 0 while i < num: # This itterates through each guest and prints the guests name with a message print("Please come over and eat my food, " + guests[i]) i = i + 1 print("") # This is white space print("Oh dear! The Hulk smashed the table and now I can only invite two people") #i = 5 #while i > 0: # sorry = guests.pop() # print("Sorry " + sorry + ". You're no longer invited") # i = i - 1 print(len(guests)) print("") sorry = guests.pop() print("Sorry " + sorry + ". You're no longer invited") sorry = guests.pop() print("Sorry " + sorry + ". You're no longer invited") sorry = guests.pop() print("Sorry " + sorry + ". You're no longer invited") sorry = guests.pop() print("Sorry " + sorry + ". You're no longer invited") sorry = guests.pop() print("Sorry " + sorry + ". You're no longer invited") num = len(guests) print("") i = 0 while i < num: # print("I hope to see you at dinner, " + guests[i]) i = i + 1 print(len(guests)) del guests[0] del guests[0] print(guests) print(len(guests))
true
1b763fa6fe37dcf06b47fcec97dfea49835592bb
maximus-sallam/Project
/dog.py
1,590
4.21875
4
class Dog(): """A simple attempt to model a dog.""" def __init__(self, name, age, owner): """Initialize name and age attributes.""" self.name = name self.age = age self.owner = owner def sit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate rolling over in response to a command.""" print(self.name.title() + " rolled over!") my_dog = Dog('riley', 3, 'max') venice_dog = Dog('bucky', 1, 'venice') venjovi_dog = Dog('deep fried', 2, 'venjovi') vennah_dog = Dog('alden', 4, 'vennah') print("\nThis dog's name is " + my_dog.name.title() + ".") print("This dog is " + str(my_dog.age) + " years old.") print(my_dog.name.title() + "'s owner is " + my_dog.owner.title()) my_dog.sit() my_dog.roll_over() print("\nThis dog's name is " + venice_dog.name.title() + ".") print("This dog is " + str(venice_dog.age) + " years old.") print(venice_dog.name.title() + "'s owner is " + venice_dog.owner.title()) venice_dog.sit() venice_dog.roll_over() print("\nThis dog's name is " + venjovi_dog.name.title() + ".") print("This dog is " + str(venjovi_dog.age) + " years old.") print(venjovi_dog.name.title() + "'s owner is " + venjovi_dog.owner.title()) venjovi_dog.sit() venjovi_dog.roll_over() print("\nThis dog's name is " + vennah_dog.name.title() + ".") print("This dog is " + str(vennah_dog.age) + " years old.") print(vennah_dog.name.title() + "'s owner is " + vennah_dog.owner.title()) vennah_dog.sit() vennah_dog.roll_over()
false
a610eb2b1fa21c3b633cc80df76822c4390e1416
Sidney-kang/Unit3-01
/guessing_game.py
594
4.125
4
#Created by : Sidney Kang #Created on : 5 Oct. 2017 #Created for : ICS3UR # Daily Assignment - Unit3-01 # This program shows how to use an if statement import ui NUMBER_COMPUTER_IS_THINKING_ABOUT = 5 def check_number_touch_up_inside(sender): #This checks the number of students entered versus the constant (25 stuents) #input number_entered = int(view['input_of_number_textbox'].text) #process if number_entered == NUMBER_COMPUTER_IS_THINKING_ABOUT: #output view['check_answer_label'].text = "Correct!!!" view = ui.load_view() view.present('sheet')
true
58a435a7fd12f8575bb72cea77df38285f0b161c
heitorchang/learn-code
/checkio/elementary/three_words.py
1,054
4.21875
4
description = """ Let's teach the Robots to distinguish words and numbers. You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string "start 5 one two three 7 end" contains three words in succession. Input: A string with words. Output: The answer as a boolean. Precondition: The input contains words and/or numbers. There are no mixed words (letters and digits combined). 0 < len(words) < 100 """ def isWord(s): return s.isalpha() def checkio(s): tokens = s.split() runningTotal = 0 for t in tokens: if isWord(t): runningTotal += 1 if runningTotal == 3: return True else: runningTotal = 0 return False def test(): testeql(isWord("albacore"), True) testeql(isWord("a123"), False) testeql(checkio("Hello world hello"), True) testeql(checkio("He is 123 man"), False) testeql(checkio("Hi"), False)
true