blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b76780fd70fe884f8d4b9ca258fb2660c4fceeec
sabines1/SheCodes
/Lesson #10.1 - Cows and Bulls/1.2 count_match.py
362
4.3125
4
str1 = 'abcde' str2 = 'acdzr' #-------------------calculate count of matches ----------------------- def calc_match (str1, str2): count = 0 for i in str1: # I will trace each element of str1 string if i in str2: # If that I is present in str2 then enter the loop count = count + 1 return(count) print(calc_match(str1, str2))
true
634260da93d62c46a1935dff387b573e576fbfb7
RyanYoak/Structure-of-Programming-Languages-Project
/main.py
2,818
4.1875
4
class Node: # Here one can see Python's pass by reference vs pass by value methods, if data is a basic data type it will be # pass by value, however if it is a more complex data type then it will be pass by reference. def __init__(self, data, next = None): self.data = data self.next = next def __str__(self): return str(self.data) class LinkedList: def __init__(self, data=None): if data == None: self.firstNode = None else: node = Node(data) self.firstNode = node def __str__(self): if self.firstNode == None: return "[ ]" Lstr = "[ " + str(self.firstNode.data) currentNode = self.firstNode.next while currentNode != None: Lstr = Lstr + ", " + str(currentNode.data) currentNode = currentNode.next Lstr = Lstr + " ]" return Lstr # Here you can see how Python is dynamically typed, here the type of node is not known at # compile time and only known at run time (not quite how Python works), a block of memory # is allocated in the heap and assigned a value once the code runs. def add(self, data, position = None): node = Node(data) currentNode = self.firstNode if position == None: while currentNode.next != None: currentNode = currentNode.next currentNode.next = node else: if position == 0: node.next = self.firstNode self.firstNode = node return counter = 1 while counter != position: if currentNode.next == None: currentNode.next = node return currentNode = currentNode.next counter = counter + 1 temp = currentNode.next node.next = temp currentNode.next = node # Here you can see Python's garbage collection at work, instead of having to manually delete # data on the heap, Python's data collection will be able to detect when the references to an # object are no longer used and be able to delete the object for the programmer. def remove(self, data): if self.firstNode.data == data: self.firstNode = self.firstNode.next return previousNode = self.firstNode currentNode = self.firstNode.next while currentNode.data != data: if currentNode.next == None: return currentNode = currentNode.next previousNode = previousNode.next nextNode = currentNode.next previousNode.next = nextNode ll = LinkedList(1) ll.add(2) ll.add(2.5) ll.add(2.75) ll.add(3,1) print(ll) ll.remove(3) print(ll)
true
96123b4d2d2dae10794847a1558f60707263adaf
Portojowsky/bigoofmaboi
/ISD Assignment/Week 4/task 1.py
260
4.15625
4
#Task 1: radius = input("Radius: ") x = 3.14 pi = x area = pi * radius ** 2 #The radius input isn't converted to an integer. radius = int(input("Radius: ")) x = 3.14 pi = x area = pi * radius ** 2 #This is the correction of task 1
true
c32845565fdad92351084a6f79c2c84f57af9cdf
brettvanderwerff/ebay-Buy-It-Now-Search-Tool
/get_UPC.py
777
4.1875
4
'''The get UPC module contains the get_UPC function, which gets input from the user in the form of a UPC. ''' def get_UPC(): '''Gets a UPC from the user, which will be used to guide the product search. ''' while True: user_UPC = input( 'Please enter the UPC of the product you would like to search for and press \'enter\' when finished! \n' 'Note that many resources for searching UPC\'s exist such as http://upcdatabase.org/search and note that \n' 'multiple UPCs may pertain to your product of interest.') if not (user_UPC).isdigit() or len(user_UPC) != 12: print('Sorry. UPCs consist of only 12 digits, please look at your input again.') else: return user_UPC
true
a87f6a615ac76c0e83b9c4708ed9879b48eeee2f
vijoin/AtosPythonCourseExamples
/ex17-compute_age.py
736
4.15625
4
from datetime import datetime from dateutil.relativedelta import relativedelta def compute_age(date): current_date = datetime.now() birthday_date = datetime.strptime(date, '%d/%m/%Y') age = relativedelta(current_date, birthday_date).years return age #Given a birthday date, calculate the age def person_age(name, lastname, birthday): age = compute_age(birthday) return " Nombre: {}\n Apellido: {}\n " \ "Edad: {}".format(name, lastname, age) def run(): name = input("Ingrese su nombre: ") lastname = input("Ingrese su apellido: ") birthday = input("Ingrese su fecha de nacimiento (dd/mm/yyyy): ") print(person_age(name, lastname, birthday)) if __name__ == '__main__': run()
true
bc89902301d53dcd9b9ae4d422cf9de64e7b288a
vijoin/AtosPythonCourseExamples
/ex13-Operators.py
1,093
4.40625
4
def print_operators(): x = 7 y = 3 # Arithmetic operators print(x + y) #Addition print(x - y) #Subtraction print(x * y) #Multiplication print(x / y) #Division print(x % y) #Modulus print(x ** y) #Exponentiation print(x // y) #Floor division # Assignment operators x += 7 #Same as x = x + 7 x -= 7 #Same as x = x - 7 x *= 7 #Same as x = x * 7 x /= 7 #Same as x = x / 7 x %= 7 #Same as x = x % 7 x //= 7 #Same as x = x // 7 x **= 7 #Same as x = x ** 7 # Comparison operators print(x == y) # Equal print(x != y) # Not equal print(x > y) # Greater than print(x < y) # Less than print(x >= y) # Greater than or equal to print(x <= y) # Less than or equal to # Logical operators print(x < 5 and x < 10) print(x < 5 or x < 4) print(not (x < 5 and x < 10)) # Identity operators print(x is y) print(x is not y) # Membership operators x = [1, 5, 10, 7, 6] print(7 in x) print(12 not in x) if __name__ == '__main__': print_operators()
true
4e796273d05ef82492767becd7ee2a68c4a5f2ef
dominiquecuevas/data-structures
/stacks.py
2,508
4.21875
4
class Stack: """Define a stack class with the operations push pop peek is_empty size Chose a built-in python list as data structure for items attribute and the end as the top of the stack. push is O(1) constant time pop is O(1) for removing from the end of a python list peek is O(1) for indexing is_empty is O(1) for checking if the list is empty size is O(1) since native lists If the beginning of the list was the top of the stack, pop would be O(n) and push would also be O(n) and not the best runtime """ def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def is_empty(self): return self.items == [] def size(self): return len(self.items) def __repr__(self): return f"<Stack items={self.items}>" def revstring(string): """using a stack return a string reversed""" s = Stack() for letter in string: s.push(letter) reversedstr = "" while not s.is_empty(): reversedstr += s.pop() return reversedstr def parens_balanced(string): """are parenthese balanced use a stack to easily keep track of parentheses loop through string add a beginning parentheses to stack when there is a closing parentheses, pop one of the open parentheses in stack the stack should be empty if parenthese are balanced """ parens_stack = Stack() for char in string: if char == "(": parens_stack.push(char) elif char == ")": if parens_stack.is_empty(): # check for matching begin "(" return False # fail quick and fall out of loop if failed to match else: parens_stack.pop() return parens_stack.is_empty() # stack should be empty if balanced if __name__ == "__main__": print("revstring 'Nikki':", revstring('Nikki')) print("revstring 'Millenium':", revstring("Millenium")) print("balanced? ((4+2)-(2+1)(1-3))/((4-3)-(2+9)",parens_balanced("((4+2)-(2+1)(1-3))/((4-3)-(2+9)")) print("balanced? ((4+2)-(2+1)(1-3)))/(4-3)-(2+9)",parens_balanced("((4+2)-(2+1)(1-3)))/(4-3)-(2+9)")) print("balanced? ((4+2)-(2+1)(1-3))/(4-3)-(2+9)",parens_balanced("((4+2)-(2+1)(1-3))/(4-3)-(2+9)"))
true
43ccb3edc8ca2c955e6387e0e0def13b69b3d0b7
ziyeZzz/python
/introduction_to_python/introduction_to_python/advanceIdea/c3.py
1,144
4.1875
4
#map and reduce and filter #reduce返回的是list, map和filter返回类似(map/filter object)需用list来转换返回类型便于输出查看 def square(x): return x*x list_x = [1,2,3,4,5,6,7,8] #用循环 for x in list_x: square(x) #用map r = map(square, list_x) print(r) print(list(r)) #map的优势,与lambda表达式结合 r = map(lambda x:x*x, list_x) print(list(r)) #another example list_x = [1,2,3,4,5,6,7,8] list_y = [1,2,3,4,5,6,7,8] r = map(lambda x,y:x*x+y, list_x,list_y) print(list(r)) #reduce -> 用来连续计算 from functools import reduce List_x = [1,2,3,4,5,6] #progress: (((1+2)+3)+4)+.. r = reduce(lambda x,y:x+y, list_x) print(r) # location = [(1,2),(2,-2),(-2,3),(3,4)] # r = reduce(lambda x,y:(x+a),(y+b), location) # print(r) #filter,返回结果必须代表真和假 #要求,把所有0都剔除 list_x = [0,1,1,0,1,0] r = filter(lambda x:True if x==1 else False, list_x) r = filter(lambda x:x, list_x)#同上一个结果 print(list(r)) import re list_u = ['a','B','v','F','e'] r = filter(lambda x:len(re.findall('[a-z]',x)), list_u) print(list(r))
false
ea54565c43d0c782f3c6fdaec622b1e82cea3abc
ziyeZzz/python
/LeetCode/189_旋转数组.py
470
4.125
4
# -*- coding:utf-8 -*- ''' 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] ''' def rotate(nums, k): nums = nums[-k:]+nums[:-k] return nums if __name__=='__main__': nums = [1,2,3,4,5,6,7] k = 3 print(rotate(nums,k))
false
27f759bb29032ff4f72c25dc7f15c0feee3b6ac8
EbunAlabi/PythonMaster
/Dictionaries.py
1,045
4.28125
4
#lists are used to store similar items #sets are similar to lists, but you cant access individual indexex #dict are ordered and accessed by key value pairs #split amd join will be introduced - fuctions fruit = {"orange": "a good orange citrus juice", "apple": "good fr making cider", "lemon": "good for lemonade", "grape": "a smal, sweet fruit groing in bunches", "lime": "a sour, green citrus growing in bunches"} veg = {"cabbage": "every child's favourite", "sprouts": "mmmm, Lovely", "spinach": "can i have some more fruits please"} print(veg) #cobine two dictionaries together veg.update(fruit) print(veg) nice_copy = veg.copy() nice_copy.update(fruit) print(nice_copy) print(fruit) print(fruit["lemon"]) fruit["pear"] = "an odd shaped apple" print(fruit) fruit["pear"] = "an odd shaped apple and great with tequiila" del(fruit["lemon"]) print(fruit) for f in sorted(fruit.keys()): print (f + " - " + fruit[f]) print(fruit.items()) f_tuple = tuple(fruit.items()) print(f_tuple)
true
628a95990455011008302325d7b4ad240cfaaa7e
sranjani47/LetsUpgrade-AI-ML
/files/solution/day3/d3.py
1,760
4.15625
4
#!/usr/bin/env python # coding: utf-8 Q1. Subtraction of Complex number # In[1]: cn1 = complex(input("Enter first complex number - ")) cn2 = complex(input("Enter second complex number - ")) cn = cn1 - cn2 print('The subtraction of given complex number is',cn) Q2. 4th Root # In[2]: n = int(input("Enter the number to find 4th square root: ")) print("solution type 1", n**0.25) print("solution type 2", n**(1/4)) import math print("solution type 3", math.sqrt(math.sqrt(n))) Q3. Swapping two Numbers using temporary variable # In[3]: a = int(input("Enter first number a - ")) b = int(input("Enter second number b - ")) print("Before swapping a =",a," b =",b) c = a a = b b = c print("After swapping a =",a," b =",b) Q4. Swapping two Numbers without temporary variable # In[4]: a = int(input("Enter first number a - ")) b = int(input("Enter second number b - ")) print("Before swapping a =",a," b =",b) a = a + b b = a - b a = a - b print("After swapping a =",a," b =",b) Q5. Calculating kelvin and celcius from Fahrenheit # In[5]: F = int(input("Enter temperature to be converted into kelvin and celcius - ")) print("Temperature in Kelvin ( K ) = {:.3f}".format(273.5 + ((F - 32.0) * (5.0/9.0)))) print("Temperature in Celcius ( C ) = {:.3f}".format((F - 32) * 5 / 9)) Q6. Demonstration of variable data types # In[6]: x_str = "Hello World" print(type(x_str)) x_int = 20 print(type(x_int)) x_float = 20.5 print(type(x_float)) x_complex = 1j print(type(x_complex)) x_list = ["apple", "banana", "cherry"] print(type(x_list)) x_tuple = ("apple", "banana", "cherry") print(type(x_tuple)) x_dict = {"name" : "John", "age" : 36} print(type(x_dict)) x_set = {"apple", "banana", "cherry"} print(type(x_set)) x_boolean = True print(type(x_boolean))
false
2997eadf831ab6f24437a65bfac625e50aeb9e58
snanoh/Python-Algorithm-Study
/Tree/InvertTree.py
1,504
4.1875
4
"""트리를 반전 시켜라""" import collections class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def invertTree(root: TreeNode) -> TreeNode: if root: root.left, root.right = invertTree(root.right), invertTree(root.left) return root return None #BPS 구조 def invertTree2(root: TreeNode) -> TreeNode: queue = collections.deque([root]) while queue: node = queue.popleft() # 부모 노드부터 하향식 스왑 if node: node.left, node.right = node.right, node.left queue.append(node.left) queue.append(node.right) return root #DFS 구조 def invertTree3(root: TreeNode) -> TreeNode: stack = collections.deque([root]) while stack: node = stack.pop() # 부모 노드부터 하향식 스왑 if node: node.left, node.right = node.right, node.left stack.append(node.left) stack.append(node.right) return root root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(9) print(invertTree3(root).val) print(invertTree3(root).left.val) print(invertTree3(root).right.val) print(invertTree3(root).left.left.val) print(invertTree3(root).left.right.val) print(invertTree3(root).right.left.val) print(invertTree3(root).right.right.val)
false
1677dfa6a8d5adac3b8a7c90698c9e766477d0b9
subidb/Algorithms-in-Python
/Python_Algos/bubblesort.py
286
4.1875
4
def bubbleSort(arr): n = len(arr) for i in range(n): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] arr1 = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr1) print("Sorted array is:") print(arr1)
false
8ced1bda0f0f7aba8b4f33fbf1d65fa1631cc38a
caresppen/wookies-wears-pants
/Space Invaders/spaceinv_Part3.py
1,655
4.1875
4
#Space Invaders - Part 3 #Set up the screen #Python 3.7 on Windows import turtle import os #Set up the screen wn = turtle.Screen() wn.bgcolor('black') wn.title('Space Invaders') #Draw a border border_pen = turtle.Turtle() border_pen.speed(0) border_pen.color('white') border_pen.penup() border_pen.setposition(-300,-300) border_pen.pendown() border_pen.pensize(3) for side in range(4): border_pen.fd(600) border_pen.lt(90) border_pen.hideturtle() #Create the player turtle player = turtle.Turtle() player.color('blue') player.shape('triangle') player.penup() player.speed(0) player.setposition(0, -250) player.setheading(90) playerspeed = 10 #Create the enemy enemy = turtle.Turtle() enemy.color('red') enemy.shape('circle') enemy.penup() enemy.speed(0) enemy.setposition(-200, 250) enemyspeed = 1 #Move the player left and right def move_left(): x = player.xcor() x -= playerspeed if x < -280: x = -280 player.setx(x) def move_right(): x = player.xcor() x += playerspeed if x > 280: x = 280 player.setx(x) #Create keyboard bindings turtle.listen() #-->Use onkey when you don't want to habilitate long press turtle.onkeypress(move_left, 'Left') turtle.onkeypress(move_right, 'Right') #Main game loop while True: #Move the enemy x = enemy.xcor() x += enemyspeed enemy.setx(x) #Move the enemy back and down if enemy.xcor() > 280: y = enemy.ycor() y -= 40 enemyspeed *= -1 enemy.sety(y) if enemy.xcor() < -280: y = enemy.ycor() y -= 40 enemyspeed *= -1 enemy.sety(y) turtle.done()
true
5c018738a4305363a9b350584f291c45b53e4f6e
VidalMiquel/Python
/CLASE_PERSONA/persona.py
1,274
4.15625
4
#Primer exemple de la POO en Python class Persona: #Atribut de classe vida = 5 #Atribut d'instànica #Constructor def __init__(self): self.nom = "" self.edad = "0" self.DNI = "" def inicialitzar_Dades(self): self.edad = input("Introdueix la edat: ") self.DNI = input("Introdeuix el DNI: ") self.nom = input("Introdeuix el nom: ") #Mètodes d'instància def imprimir_Dades(self): print("L'edat de la persona és: " + self.edad + " anys") print("El seu DNI és: " + self.DNI) print("El seu nom és: " + self.nom) def set_edad(self, edad): self.edad = edad def get_edad(self): return self.edad def set_nom(self, nom): self.nom = nom def get_nom(self): return self.nom def set_DNI(self, DNI): self.DNI = DNI def get_DNI(self): return self.DNI #Mètodes de clase @classmethod def correr(cls): print("Método de clase") #Mètodes estàtics @staticmethod def brincar(): vida = 10 #Lliberam els recursos de memoria que ja no són utilitzats per la instància. def __del__(self): print("Eliminam instànices ja no utilitzades \n ")
false
e36a8a51d2bfdf4f366b171edb4d23d369ac13b3
muhammednazeer/pyexercise
/electricalHeatEffect.py
1,938
4.46875
4
''' This program calculate the heating effect of electricity The program accept 3 parameta via Current in amp, Resistance in ohms, Time in Minutes.''' #Preamble text declaration welcome = ''' Welcome to Program that Calculate the heating effect of electricity. Presented by: ALIYU IDRIS M. Faculty of Computer Science and Information Technology.\n''' intro = ''' HEATING EFFECT OF ELECTRICITY: When electric current flows through a conductor, the resistance of the conductor changes electrical enerygy into heat energy just as friction changes mechanical energy into heat. It is this heating effect of an electric current that is utilized in such devices as electric pressig iron, electric toaster, electric coil, hair dryer and incadescent lamps.\n''' print(welcome) print(intro) text = " " # variable to test the user input while text != "quit": text = input("Press any key to continue (or 'quit' to exit): ") if text == "quit": #If the user type quit, the program will exit print ("...exiting program\n") print ("GOODBYE!") else: # If any key or value is entered apart from quit, the program will continue executing print("Enter the parametas in the following order;\n current (i), Resistance(R), Time (S)\n") current = float(input("Enter the value of Current in Amp: ")) resistance = float (input("Enter the value of Resistance in Ohms: ")) time = float (input("Enter the time in Minutes: ")) heat = current**2*resistance*(time*60) # convrting time to second before calculation print ("The value of current :{0}amp; value of resistance is {1}Ohm and the value of time is{2} minutes".format(current, resistance, time)) print ("The Heating effect is ", heat/1000, "KJ") #Heating effect will be zero if any of the inputed value is zero
true
b99d5f1c20d1bdbe075405d609341c53a45679e3
muhammednazeer/pyexercise
/birthday.py
1,133
4.34375
4
def days_difference (day1, day2): return day2 - day1 def get_weekday (current_weekday, days_ahead): return (current_weekday + days_ahead - 1) % 7 + 1 def get_birthday_weekday(current_weekday, current_day, birthday_day): days_differce = days_difference(current_day, birthday_day) return get_weekday(current_weekday, days_differce) current_weekday = int(input("Enter current day of the week (1-7): ")) current_day = int(input("Enter the day of the year (1-365): ")) birthday_day = int(input("Enter your birthday day (1-365): ")) birthday = get_birthday_weekday(current_weekday, current_day, birthday_day) if birthday == 1: print ("Your next Birthday is on Sunday") elif birthday == 2: print ("Your next Birthday is on Monday") elif birthday == 3: print ("Your next Birthday is on Tuesday") elif birthday == 4: print ("Your next Birthday is on Wednesday") elif birthday == 5: print ("Your next Birthday is on Thursday") elif birthday == 5: print ("Your next Birthday is on Friday") elif birthday == 7: print ("Your next Birthday is on Saturday") else: print("Your input was wrong!")
false
e6fef5dacacdc916cd4b60084d99b53baa9f5ae4
CristianSifuentes/Pythonlabs
/18_tuples.py
1,336
4.125
4
# creating a tuple using () # number tuple number_tuple = (10, 20, 25.75, 10, 20,25.75 ) print(number_tuple) # (10, 20, 25.75) # string tuple string_tuple = ('Jessa', 'Emma', 'Kelly') print(string_tuple) # print('0 => ', string_tuple[0]) # 0 => Jessa print('-1 => ', string_tuple[-1]) # -1 => Kelly # mixed type tuple sample_tuple = ('Jessa', 30, 45.75, [25, 78]) print(sample_tuple) # create a tuple using tuple() constructor sample_tuple2 = tuple(('Jessa', 30, 45.75, [25, 78])) print(sample_tuple2) # without coma single_tuple = ('Hello') print(type(single_tuple)) # <class 'str'> print(single_tuple) # Hello # with comma single_tuple1 = ('Hello',) print(type(single_tuple1)) # <class 'tuple'> print(single_tuple1) # ('Hello',) # Crud # number_tuple.append(10) # AttributeError: 'tuple' object has no attribute 'append' # number_tuple[1] = 4 # print(number_tuple) # TypeError: 'tuple' object does not support item assignment print(number_tuple.index(20)) # 1 print(number_tuple.index(25.75)) # 2 print(number_tuple.count(25.75)) # 2 becaus exists 2 elements '25.75' my_list = list(number_tuple) print(my_list) # [10, 20, 25.75, 10, 20, 25.75] print(type(my_list)) # <class 'list'> my_list[1] = 56 print(my_list) # [10, 56, 25.75, 10, 20, 25.75] my_tuple = tuple(my_list) print(my_tuple) # (10, 56, 25.75, 10, 20, 25.75)
false
757827e5f496a76d3d5313d43e8870ce32873391
preethi-ammulu/Python_practise
/List.py
583
4.34375
4
#List #List is created by placing all elements inside square brackets. marks = [100,67,89,45,76] print(marks) #Add 50 at position #Syntax-list.insert(postion,element) #list.insert() marks.insert(2, 50) print(marks) #format specifier #syntax='{}'.format() marks1='{}'.format(marks) print(marks1) #Remove 45 element-POP Method #syntax-list.remove() marks.remove(45) print(marks) #Sort list in ascending order #syntax-list.sort() marks.sort() print(marks) #Finding position of ele 89 #syntax-list.index() x=89 position=marks.index(x) print(position)
true
79caef25d2f886f43cbbfbbc1d15f97f1ff97c9b
drstrangeknows/recursion_backtrack
/power.py
1,744
4.4375
4
''' Rather than the naive recursive approach where we reduce n by 1 at every recursion, we try the binary search approach. e.g. if we have 2^6, then rather than going by 2*2^5, then 2*2*2^4 ... 2*2*2*2*2*2*2^0, we try to do it in a way 2^3*2^3. This way no. of steps is reduced by half at every step. Earlier we had O(n) complexity. By reducing into half, the complexity becomes O(nlogn). Focus on the base case - for +ve n we will get 0 on dividing by 2, so the base comes is n==0, however for negative 'n', we can never get 0 on dividing by 2 (mathemarical reasons), so the base case is for n==-1. Afterwards, when recursion completes from base case, then we if n is odd or even and simplify the return value accordingly e.g. n==3, so 2^3 can be put as 2 * 2^2 OR 2^5 can be put as 2*2^2*2^2 - thus we have x*result*result ''' # def main(): # x = 21 # n = -6 # if n>0: # result = findPositive(x, n) # else: # result = findNegative(x, n) # print("The result", result) # def findNegative(x, n): # if n==-1: # return 1/x # res = findNegative(x, n//2) # if n%2 == 0: # return 1/res * 1/res # else: # return 1/x * 1/res * 1/res # def findPositive(x, n): # if n==0: # return 1 # res = findPositive(x, n//2) # if n%2 == 0: # return res * res # else: # return x * res * res # if __name__=='__main__': # main() def power(x, y): if(y == 0): return 1 temp = power(x, int(y / 2)) if (y % 2 == 0): #if y is even number return temp * temp else: if(y > 0): return x * temp * temp #if y is odd number else: return (temp * temp) / x x, y = 2, -6 print(power(x, y))
true
442788c4532d92354a338af84484aed19d3b85fc
frason88/Python_Lab_MU
/Exp-2b.py
1,232
4.15625
4
""" Write a python program to input a multiline string or a paragraph & count the no. of words & characters in string. Also check for a substring & replace each of its occurrences by some other string. """ lines = [] #Getting multi-line input from the user while True: line = input() if line: lines.append(line) else: break text = '\n'.join(lines) print('-'*80) print(text) # word count total_char = 0 #total char total_w = 1 #total words for i in range(len(text)): if(text[i] == ' ' or text[i] == '\n'): total_w += 1 print("Total no. of words: ",total_w) #char count for j in range(len(text)): total_char += 1 print("The total number of characters: ",total_char) # print("Final list: ",lines) # Driver Code x = input("Enter the word you wanna replace: ") def countX(text, x): return text.count(x) #occurance count print('{} has occurred {} times: '.format(x, countX(text, x))) print("------------------The new string after occurance----------------------") string_replace = text.replace("Python", "Java") print(string_replace)
true
67c96114da645b04573018c3c9b439e020b12be3
sonichuang/My-py-file
/回文联T2.py
282
4.21875
4
#老师的第二个方法:用reversed() def palindrome(string): list1 = list(string)#把字符串转化为列表 list2 = reversed(list1)# if list1 == list(list2): return '是回文联!' else: return '不是回文联!' print(palindrome('上海自来水来自海上'))
false
6375ce8d05c41fff91c4ad2749e5a548ad0265b1
jsines/Collatz-conjecture
/main.py
370
4.21875
4
def collatz(x): print(x) if x <= 1: print ("Finished!") return elif x % 2 == 0: return collatz(x // 2) else: return collatz((3 * x) + 1) print("Type an integer to see its Collatz conjecture series. Type 0 to quit.") while 1: userInput = int(input()) if userInput <= 0: exit() print("Performing Collatz conjecture on", userInput) collatz(userInput)
true
b6c14b48676dc361551f55a50c3d3d176905e521
hejiawang/PythonCookbook
/src/four/5.py
624
4.125
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 4.5 反向迭代 Created on 2016年9月1日 @author: wang ''' a = [1,2,3,4] for x in reversed(a): print(x) f = open('../two/somefile.txt') for line in reversed(list(f)): print(line, end='') #实现_reversed__()方法即可反向迭代 class Countdown: def __init__(self, start): self.start = start def __iter__(self): n = self.start while n > 0: yield n n -= 1 def __reversed__(self): n = 1 while n < self.start: yield n n += 1
false
0a8733ed0ce42674850e46987296660e83766c44
crakex-90/CompSci-Projects
/Lab7.py
1,604
4.1875
4
#Dominic Colella #10/31/21 #Lab 7-3 - Dice Game (Not Squid Game) import random def main(): print('This program will ask you to input two names \ and then generate a random number between 1 and \ 6 for each. The name of the winner will then \ display.') #initialize variables endProgram = 'no' or 'n' playerOne = 'NO NAME' playerTwo = 'NO NAME' #call to inputNames playerOne, playerTwo = inputNames(playerOne, playerTwo) #while loop to run program again while endProgram == 'no' or 'n': #populate variables winnerName = 'NO NAME' p1number = 0 p2number = 0 #call to roll dice winnerName = rollDice(p1number, p2number, playerOne, playerTwo, winnerName) #call to display info displayInfo(winnerName) endProgram = input('Do you want to end the program? Enter yes or no: ') #player name function def inputNames(playerOne, playerTwo): playerOne = input('Type the name of player One: ') playerTwo = input('Type the name of player Two: ') return playerOne, playerTwo #function for random values def rollDice(p1number, p2number, playerOne, playerTwo, winnerName): p1number = random.randint(1,6) p2number = random.randint(1,6) if p1number > p2number: winnerName = playerOne elif p2number > p1number: winnerName = playerTwo elif p2number == p1number: winnerName = print('You tied!') return winnerName #display winner function def displayInfo(winnerName): print(winnerName) #calls main main()
true
7cb9a371fb431d8ef9c076e5904899d0f4b49e77
aarongertler/euler
/85.py
2,935
4.15625
4
# By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles. # Although there exists no rectangular grid that contains exactly two million rectangles, # find the area of the grid with the nearest solution. # Formula for the number of rectangles: # Number of "spaces" (rows * columns) + number of rows + number of columns + 1 # Plus the smaller rectangles, which means: # For a small A x B rectangle, it can fit into a large M x N rectangle as follows: # Going in "horizontally" (A and M are horizontal dimensions), (A + 1 - M) * (B + 1 - N) # Going in "vertically", (A + 1 - N) * (B + 1 - M) # For example, a 2x1 goes into a 3x2 four times "horizontally" (2 * 2) and three times "vertically" (3 * 1) # And a 2x2 goes into a 3x2 twice (3 + 1 - 2) * (2 + 1 - 2) (but we don't double-count it, because it doesn't rotate) # Note: You struggled with the formula a bit because you only tested 3*2 and 3*3, not 2*4. Broaden your horizons! def rectangles(a, b): # Count smaller rectangles that fit into a large A x B rectangle count = 0 # The loop below catches everything, including 1 x 1 rectangles and the whole rectangle for m in range(1, a+1): for n in range(1, b+1): # Had a range of m to b+1 before, but 3x1 works differently than 1x3! count += (a + 1 - m) * (b + 1 - n) # We'll count 1x1 once, 2x1 once, 1x2 once --> that's the right move # print("Counted", m, "and", n, "there are now", count, "rectangles") return count # print(rectangles(50,60)) # This is close to 2 million, I'll set a range of 100 as a starting point min_difference = 1000000 min_x, min_y = 0, 0 for x in range(1, 100): for y in range(x, 100): # Don't double-count any sizes difference = abs(rectangles(x, y) - 2000000) if difference < min_difference: # print("New difference found:", difference, "for x=", x, "and y=", y) min_difference = difference min_x = x min_y = y print("Minimum difference at X =", min_x, "Y =", min_y, "area =", min_x * min_y) # This gets the answer in less than 3 seconds, but there's math to make it faster: # Sum(1..X) = (x^2 + x) / 2 # Summing up the rectangles in an A x B grid means we multiply the sum of the counting numbers for each dimension # For example, a 5 x 7 would be (25 + 5)/2 * (49 + 7)/2 # The reasoning behind this is a lot of fun! For example, if we look at a 2 x 4 rectangle... # ...we can multiply counting sums to find 1*1 + 1*2 + 1*3 + 1*4 + 2*1 + 2*2 + 2*3 + 2*4 # Each term in this equation describes the number of rectangles of the INVERSE size. # For example, there is 1*1 = 1 2*4 rectangle, and there are 1*3 = 3 2*2 rectangles # This matches up perfectly with the manual math we were doing: For each rectangle of a given size, we multiply by the inverse of those sizes to get the total # of rectangles # And it just so happens that doing this math is the same as multiplying (1 + 2 ... + A)*(1 + 2 ... + B)
true
e49d66ef51a87b57cf714f694f4caa7c0b3ae661
aarongertler/euler
/64.py
1,444
4.25
4
# Too long to copy-paste # All square roots can be written as periodic continued fractions: # sqrt(23) = 4 + 1 / (1 + (1 /(1 + 1/(...) + 1) + 3) + 1) # Eventually, these will all repeat: sqrt(23) is 4 + this fraction with 1, 3, 1, 8, repeating forever # The "period" = the number of digits before we repeat (23 has a period of 4) # How many continued fractions for N <= 10000 have an odd period? from math import sqrt, floor # def period(n): # root = floor(sqrt(n)) # remainder = sqrt(n) - root # next_digit = ceiling(1 / remainder) # next_fraction = sqrt(n) + root - (n - root**2) / n - root**2 # Trying the "algorithm" section of this: # https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Continued_fraction_expansion (thanks to Dreamshire for the link) odd_periods = 0 for n in range(2, 10000): root = floor(sqrt(n)) if root**2 == n: continue else: m, d, a = 0, 1, root # Dreamshire implemented a single-variable algorithm, I'll stick to the book period = 0 while a != 2*root or period == 0: # I've seen this with d != 1, not sure why that works m = (d * a) - m d = (n - (m * m)) / d a = floor((root + m) / d) period += 1 if period % 2 == 1: odd_periods += 1 print("Number of odd periods:", odd_periods) # Testing for n = 23: # 1: 0, 1, 4 # 2: 4, 7, 1 # 3: 3, 2, 3 # 4: 3, 7, 1 # 5: 4, 1, 8 (d is 1, terminate) (also, a is 2*4, terminate) # 6: 4, 7, 1 (pattern begins to repeat)
true
6a2b2e18292834862f96f774b4de5ea2ce50b72e
aarongertler/euler
/139.py
2,558
4.25
4
# Let (a, b, c) represent the three sides of a right angle triangle with integral length sides. # It is possible to place four such triangles together to form a square with length c. # For example, (3, 4, 5) triangles can be placed together to form a 5 by 5 square with a 1 by 1 hole in the middle # and it can be seen that the 5 by 5 square can be tiled with twenty-five 1 by 1 squares. # However, if (5, 12, 13) triangles were used then the hole would measure 7 by 7 and these could not be used to tile the 13 by 13 square. # Given that the perimeter of the right triangle is less than one-hundred million, how many Pythagorean triangles would allow # such a tiling to take place? # The math: hypotenuse^2 - 4*area = smaller square area # And you can tile the bigger square if bigger square / smaller square is itself a square number # As usual, let's start with brute force... from math import sqrt, floor limit = 10**8 total = 0 def square(n): return sqrt(n) % 1 == 0 def tile(bigger, smaller): # return square(bigger / smaller) return(sqrt(bigger) % sqrt(smaller) == 0) # Seems a bit faster # Pythagorean generator from 75.py: # for m in range(2, floor(sqrt(limit / 2))): # Double-check this limit if you aren't getting a working answer for m in range(2, floor((sqrt(1 + 2*limit) / 2) - 1)): for n in range (m-1, 0, -2): a = 2*m*n b = m**2 - n**2 perimeter = (2 * m**2) + 2*m*n big_area = a**2 + b**2 small_area = (a - b)**2 # if m == 12: # print("Testing n = ", n) # print("Big and small:", big_area, small_area) # print("Testing a square of", big_area, "with an inner square of", small_area) # if tile(big_area, small_area): # Just an indentation error the whole time... was only finding one working number for each m # print("Triangle sides:", big_area, "Square area:", small_area, "m and n =", m, n) if small_area == 1: # The "tile" function double-counts certain working numbers, since everything that tiles with a number greater than 1 is (I think?) derived from a primitive that tiles with 1 total += limit // perimeter # All non-primitives derived from a working primitive will also work, and we can multiply our sides until the perimeter is just under the limit print("Total:", total) # The area of the big square = a**2 + b**2 (since c = the root of that, but then we square c) # The area of the small square = (a - b)**2 (where a is the longer of the two short sides) # So we need to find that a**2 + b**2 can be tiled by a**2 - b**2 - 2ab # Editing the above equation to reflect this
true
9a7e7fa93bd5c0404ce94cf4a8f893ac6a1808b4
grgoswami/Python_202004
/source/ap5.py
472
4.25
4
import random num = int(input('Enter what number you want to guess up to, greater than 3: ')) done = False throw = random.randrange(1, num) while not done: guess = int(input('Enter your guess for the face on the dice : ')) if guess < throw: print('The number is bigger than ' + str(guess)) elif guess > throw: print('The number is less than ' + str(guess)) else: print('You got it right') done = True
true
ba4e9b32830d42e851fd33e051d48428da3b9d67
grgoswami/Python_202004
/source/reader.py
2,296
4.25
4
import pandas as pd # For now let's only consider three kinds of separators: , or \t or | class XSV_Reader: def __init__(self, separator=','): self.separator = separator def read_using_pandas(self, filepath): self.filepath = filepath print('Will read from: filepath=' + filepath) return pandas.read_csv(self.filepath, sep=self.separator) # Functions that solve sub problems and are not part of the # interface should have an '_' in the end, this reminds you # that these are helper functions def read(self, filepath): self.filepath = filepath print('Will read from: filepath=' + filepath) self.read_lines_from_file_() return self.create_data_frame_from_lines_() def read_lines_from_file_(self): with open(self.filepath, 'r') as infile: self.lines = infile.readlines() print(self.lines) def create_data_frame_from_lines_(self): self.set_header_() return self.set_rows_() def set_header_(self): # The following process of splitting the header line # into the column names is also called parsing the # header line header_line = self.lines[0] self.columns = header_line.split(self.separator) print(self.columns) # List comprehension: create a list by doing col.trim() # for each element of the list self.columns self.columns = [col.strip() for col in self.columns] print(self.columns) def set_rows_(self): self.cells = {} for column in self.columns: self.cells[column] = [] print(self.cells) return self.parse_lines_() def parse_lines_(self): for line in self.lines[1:]: print(line) values = line.split(self.separator) values = [val.strip() for val in values] print(values) for column_number, column in enumerate(self.columns): self.cells[column].append(values[column_number]) print(self.cells) ret = pd.DataFrame() for column, values in self.cells.items(): ret.loc[:,column] = values return ret
true
a8e881e45e96e8466fba025743241938f9b7fa0d
grgoswami/Python_202004
/source/Shraddha0.py
496
4.1875
4
letter = input('Enter a word : ') guess = input ('Enter a letter') if guess == letter: print('you got it right') else: print('Try again') guess2 = input ('Enter another guess') if guess2 == letter: print('you got it right') else: print('You lost 1 point so to bad for you') guess3 = input('Enter another guess') if guess3 == letter: print('Yay! You got another point') else: print('Nah nah nah boo boo') # if all guesses are wrong, nah nah nah boo boo!
true
fc2b7fd91cc5deb2a17c0b3bf799382f1606fc00
zhxy0091/halo-word-count
/halo-word-count.py
1,507
4.4375
4
#!/usr/bin/env python import re import collections import string import sys expected = ['the', 'and', 'to', 'of', 'i', 'you', 'a', 'my', 'hamlet', 'in'] def count_words(): # TODO Please implement code here to analyze the hamlet.txt file and # return an array the 10 most frequently found words in descending order of frequency. # Strip punctuation and make your comparisons case-insensitive. fname = "hamlet.txt" try: text = open(fname,'r').read() text = string.lower(text) except: print "\nfile does not exist or I/O error" sys.exit() #ignore all punctuation for c in string.punctuation: text=text.replace(c," ") #split into each word words = string.split(text) counts = {} #count freq of word using dict for w in words: counts[w] = counts.get(w,0) + 1 #sort by value using comparator items = counts.items() items.sort(compareItems) #construct result res = [] for i in range(10): #print items[i] res.append(items[i][0]) return res #comparator order by freq in descending order def compareItems((w1,c1), (w2,c2)): if c1 > c2: return -1 elif c1 == c2: return cmp(w1, w2) else: return 1 if __name__ == '__main__': print('Most Frequent Words...') answer = count_words() print('Answer: %s' % answer) assert(answer == expected) print('SUCCESS!')
true
5fc14c440079923decd9c052539542135ce9180e
xmhGit/exercise_python_summer_school
/python/ex2_earth.py
1,275
4.15625
4
import numpy as np from sys import argv def cal_cir(r): cir = 2*np.pi*r*10**3 return cir # script,r = argv # r = float(r) # argv's method also input the type of string # pi=3.14 # constant pi # r=6378 # the radius of the earth's equator, unit: km\ # r = float(raw_input("Input the radius of the earth(unit:km):\n")) # force to invert the string to float # when using raw_input() and argv simultaneously, it also can work. But the # second raw_input() will replace the first argv. # c=2*pi*r*10**3 # consistence of the earth's equator # c_p=2*np.pi*r*10**3 # another method to get pi earth_r = float(raw_input("Input the radius of the Earth(unit:km):\n")) earth_cir = cal_cir(earth_r) print "The circumference of the earth's equator is %r." % earth_cir Mar_r = float(raw_input("Input the radius of the Martian(unit:km):\n")) Mar_cir = cal_cir(Mar_r) print "The circumference of the Mar's equator is %r." % Mar_cir # surface_area = 4*np.pi*r**2*10**6 # unit:m**2 # print("Earth Information:") # print("The circumference of the earth's equator is %.1f m" % c) # print("\tThe circumference of the earth's equator is\n\t %.3f m" % c_p) # print("\tThe surface area of the earth is\n\t %.3f m^2" % surface_area) # print "\n" # print 7/4 # print 7/4.0
true
51a36232b27b02cfd7bbc3cabcc0f689271ef010
adonovan7/PythonBasics
/Textbook/Exercises/PartA/ex3.py
878
4.21875
4
print "I will now count my chickens:" # dont forget order of operations: PEDMAS # / operator rounds down print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 # recall that the "%" character is a modulus, not a percent # its the remainder from division of two numbers # ex: 25 * 3 % 4 = 75 % 4 = 3 since 4 goes into 75 18 times (72) # remainder: 3 # therefore the expression returns 100-3 = 97 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2 print 7.0 / 4.0 # floats point number gives decimal 1.75 print 7/4 # returns 1
true
2fc4901a862324cdc518df3a27fdab73fa46ab38
surya3217/Machine_learning
/Linear_Regression/IQ_size.py
2,759
4.1875
4
""" Q1. (Create a program that fulfills the following specification.) iq_size.csv Are a person's brain size and body size (Height and weight) predictive of his or her intelligence? Import the iq_size.csv file It Contains the details of 38 students, where Column 1: The intelligence (PIQ) of students Column 2: The brain size (MRI) of students (given as count/10,000). Column 3: The height (Height) of students (inches) Column 4: The weight (Weight) of student (pounds) 1. What is the IQ of an individual with a given brain size of 90, height of 70 inches, and weight 150 pounds ? 2. Build an optimal model and conclude which is more useful in predicting intelligence Height, Weight or brain size. """ import pandas as pd import numpy as np # Importing the dataset data = pd.read_csv('All CSV/iq_size.csv') data.info() features= data.iloc[:, 1:].values labels= data.iloc[:,0].values # Dataset is small so no splitting # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split features_train, features_test, labels_train, labels_test= train_test_split(features, labels, test_size= 0.2, random_state= 1) # Fitting Multiple Linear Regression to the Training set # Whether we have Univariate or Multivariate, class is LinearRegression from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features, labels) # y = ax + by + cz + d # Here a, b and c are the coefficients and d is the intercept print(regressor.intercept_) print (regressor.coef_) print (regressor.score(features, labels)*100) # 29.49 % # We cannot show a line on a graph as we did for 2D data, since we have 5D data # Predicting the Test set results Pred = regressor.predict(features_test) print (pd.DataFrame(zip(Pred, labels_test), columns= ['Predicted', 'Actual'] )) print (regressor.score(features_test, labels_test)*100) x= np.array([90,70,150]) x= x.reshape(1,3) out = regressor.predict(x) print('Iq size of student:',out) ################################# """ 2. Build an optimal model and conclude which is more useful in predicting intelligence Height, Weight or brain size. """ # code to automate the p value removing import statsmodels.api as sm import numpy as np features_obj = features[:, [0,1,2]] features_obj = sm.add_constant(features_obj) while (True): regressor_OLS = sm.OLS(endog = labels,exog =features_obj).fit() p_values = regressor_OLS.pvalues if p_values.max() > 0.05 : features_obj = np.delete(features_obj, p_values.argmax(),1) else: break print(features_obj) ## Brain size regressor_OLS.summary() print('From the OLS method we conclude that "Brain size" is most significant in predicting intelligence.')
true
eb95409d7b07b2c20b99cdac06230fc329b1ba9f
Ldarrah/edX-Python
/PythonII/3.3.4 Coding Exercise 2 threewhile.py
829
4.34375
4
mystery_int_1 = 2 mystery_int_2 = 3 mystery_int_3 = 4 #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Above are three values. Run a while loop until all three #values are less than or equal to 0. Every time you change #the value of the three variables, print out their new values #all on the same line, separated by single spaces. For #example, if their values were 3, 4, and 5 respectively, your #code would print: # #2 3 4 #1 2 3 #0 1 2 #-1 0 1 #-2 -1 0 #Add your code here max_num = max(mystery_int_1, mystery_int_2, mystery_int_3) count = 0 while count < max_num: mystery_int_1 -= 1 mystery_int_2 -= 1 mystery_int_3 -= 1 print(mystery_int_1, mystery_int_2, mystery_int_3) count += 1
true
700ee9093a2dbd55ebf6fb1028ca1c44eee76a9f
Ldarrah/edX-Python
/PythonII/3.3.3 Coding Problem sumloop.py
947
4.125
4
mystery_int = 7 #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Use a loop to find the sum of all numbers between 0 and #mystery_int, including bounds (meaning that if #mystery_int = 7, you add 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7). # #However, there's a twist: mystery_int might be negative. #So, if mystery_int was -4, you would -4 + -3 + -2 + -1 + 0. # #There are a lot of different ways you can do this. Most of #them will involve using a conditional to decide whether to #add or subtract 1 from mystery_int. # #You may use either a for loopor a while loop to solve this, #although we recommend using a while loop. #Add your code here! sumnum = 0 if mystery_int <= 0: for i in range(mystery_int,0): sumnum = sumnum + i print (sumnum) else: for i in range(0, mystery_int +1): sumnum += i print(sumnum)
true
be3463338f931f6b32315b3e71f82b6a0f952fdb
franciscojt/codewars
/reverse_str.py
471
4.4375
4
''' Complete the solution so that it reverses all of the words within the string passed in. Example: reverseWords("The greatest victory is that which requires no battle") // should return "battle no requires which that is victory greatest The ''' def reverseWords(str): string = str.split(" ") string.reverse() print string str="" for word in string: str += word str += " " return str.strip() print(reverseWords("Hello World!"))
true
53e725094777e8744124cdf41235556c7f439e3a
julieHillside/Python-Projects-2021-2022
/if problem.py
681
4.34375
4
message = input("enter a word, 'north, 'south', 'east', 'west'") while True: if message == 'east': message = input('choose a new topic') elif message == 'west': message= input('you typed West, now tell me y or n') if message == 'y': print('you typed Y') elif message == 'n': print('you typed N') else: message = input('You did not type y or n, do you wish to choose a direction?') elif message == 'north': print('you typed North') elif message == 'south': message = input('you typed South') else: message = input('you need to type a direction')
false
9c23841214bcbd4df917dec8d44b5d06d92b208b
julieHillside/Python-Projects-2021-2022
/modulo.py
315
4.3125
4
# modulo operator from Python Crash Course print(11%3) while True: number=input("Enter a number, and I'll tell you if it's even or odd: ") number = int(number) if number % 2 ==0: print("The number " + str(number) + " is even") else: print("The number " + str(number) + " is odd")
true
58d36fa68611d9fd1c922c4364ec1d3df65c4f47
mmadala95/kg_mmadala95_2020
/main.py
1,076
4.125
4
import sys def isValidMapping(str1,str2): if(len(str1)!=len(str2)): return False # dictionary to map string one mapping=dict() for str1_char,str2_char in zip(str1,str2): #validate if entry is there in mapping if str1_char in mapping: #validate if existing mapping value and new value for the string are same if mapping[str1_char]==str2_char: continue else: return False #if not include string one character in mapping else: mapping[str1_char]=str2_char #incase of checking one on one mapping from both sides use this in else part # if str2_char not in mapping.values(): # mapping[str1_char] = str2_char # else: # return False return True if __name__=="__main__": if(len(sys.argv)<3): print ("Not enough arguments provided") sys.exit(1) stringOne=sys.argv[1] stringTwo=sys.argv[2] result=isValidMapping(stringOne,stringTwo) print(result)
true
9f168637abbca81a3f8fc3086f2d8971175f437e
manudubinsky/bigdata-2016-2c
/practicas/practica2/resolucion/Ejercicio 1-B.py
252
4.375
4
#!/usr/bin/python import re str = input ("ingrese un nombre,apellido,dni") tupla = re.findall(r'[A-Z][a-z]+', str) print (tupla) i = 0 while (i < len(tupla)-1): print ("Nombre: " + tupla[i] + " Apellido:" + tupla[i+1]) i = i + 2
false
b72b0fde0767799f2652a4c8bfb11656d5fc2f89
Cpharles/Python
/CursoEmVideo/Aula_07/ex006 - Dobro_tiplo_raiz quadrada.py
339
4.125
4
#Escreva um algoritimo que leia um número e mostre o seu dobro, triplo e raiz quadrada # n = int(input('Entre com um número:_ ')) db = n * 2 tr = n * 3 raiz = n ** (1/2) print('O dobro do numero {} é:_ {}'.format(n, db)) print('O tripo do numero {} é:_ {}'.format(n, tr)) print('A raiz quadada do número {} é:_ {}'. format(n, raiz))
false
307f0be8aea0195b7a01ef32fe488bdcfcd1ac6e
Cpharles/Python
/CursoEmVideo/Aula_12/ex044-Gerenciador de Pagamento.py
1,587
4.1875
4
"""Exercício Python 044: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: Considere as opçºoes de escolha para definir o valor a ser mostrado - à vista dinheiro/cheque: 10% de desconto - à vista no cartão: 5% de desconto - em até 2x no cartão: preço formal - 3x ou mais no cartão: 20% de juros""" print("{:=^40}".format(' LOJAS GUANABARA ')) valProduto = float(input('Qual o valor da compra: R$')) print('''FORMAS DE PAGAMENTOS: [ 1 ] à vista no dinheiro/cheque [ 2 ] à vista no cartão [ 3 ] 2x no cartão [ 4 ] 3x no cartão''') op = int(input('Qual é a opção? ')) if op == 1: Avista = valProduto - (valProduto * 0.1) print('Sua compra de R${:0.2f} sair à vista por R${:0.2f}'.format(valProduto, Avista)) print('Desconto de 10%') elif op == 2: cartao = valProduto - (valProduto * 0.05) print('Sua compra de R${:0.2f} vai sair no cartão por R${:0.2f}'.format(valProduto, cartao)) print('Desconto de 5%') elif op == 3: parcela2 = valProduto / 2 print('Sua compra de R${:0.2f} será parcelado em 2x de R${:0.2f}'.format(valProduto, parcela2)) print('Não tem desconto, é o valor da compra') elif op == 4: Nparcela = int(input('Quantas parcelas? ')) parcelaX = (valProduto + (valProduto * 0.2)) / Nparcela total = parcelaX * Nparcela print('Sua compra será parcela em {}x de R${:0.2f} com juros de 20%'.format(Nparcela, parcelaX)) print('Sua compra de R${:0.2f} após o pagamento das parcelas vai sair por R${:0.2f}'.format(valProduto, total))
false
266edbf6789f50f9d38247f7ebbe7e276baed739
codigosChidosFunLog/DevLogica
/mpp/mpp.py
1,184
4.3125
4
""" # Programación Lógica # Modus ponendo ponens "el modo que, al afirmar, afirma" P → Q. P ∴ Q Se puede encadenar usando algunas variables P → Q. Q → S. S → T. P ∴ T Ejercicio Defina una funcion que resuelva con verdadero o falso segun corresponada Laura esta en Queretaro Alena esta en Paris Claudia esta en San Francisco Queretaro esta en Mexico Paris esta en Francia San Francisco esta en EUA Mexico esta en America Francia esta en Europa EUA esta en America def esta(E1,E2): pass print(esta("Alena","Europa")) # true print(esta("Laura","America")) # true print(esta("Laura","Europa")) # false """ Base = [ ["Laura","Queretaro"], ["Alena","Paris"], ["Claudia","San Francisco"], ["Queretaro","Mexico"], ["Paris","Francia"], ["San Francisco","EUA"], ["Mexico","America"], ["Francia","Europa"], ["EUA","America"] ] def esta(E1,E2, Base): if not Base: return False else: if E1 == Base[0][0]: if E2 == Base[0][1]: return True else: return esta(Base[0][1],E2,Base[1:]) else: return esta(E1,E2,Base[1:]) print(esta("Alena","Europa",Base)) print(esta("Laura","America",Base)) print(esta("Laura","Europa",Base))
false
4f9c54bb27b3f9784bef52566e0e202094446b9b
SAYANTAN-SANYAL/Python-Development-Task-2-by-Sayantan-Sanyal
/Question 4.py
318
4.21875
4
sample = {'physics':88 , 'maths':75, 'chemistry':72, 'Basic electrical':89} print("The original dictionary is: " + str(sample)) minimum = min(sample.values()) res = [key for key in sample if sample[key] == minimum ] print("Minimum value is: ", minimum) print("Key corresponding to minimum value is: " + str(res))
true
f5244616c63d2b7c2b22a86790445fc6a6da216a
guilhermejcmarinho/Praticas_Python_Elson
/02-Estrutura_de_Decisao/02-Positivo_Negativo.py
229
4.25
4
numero1 = int(input('Digite um número:')) if numero1 > 0: print('O número: {} é positivo.'.format(numero1)) elif numero1 < 0: print('O número: {} é negativo.'.format(numero1)) else: print('Você digitou zero.')
false
94165869735f3353b7ac9968eb7a24eb11771e73
guilhermejcmarinho/Praticas_Python_Elson
/02-Estrutura_de_Decisao/07-Maior_Menor_de_tres.py
930
4.21875
4
numero01 = int(input('Informe o primeiro numero:')) numero02 = int(input('Informe o segundo numero:')) numero03 = int(input('Informe o terceiro numero:')) if numero01>numero02 and numero01>numero03: if numero02>numero03: print('Primeiro numero {} é o maior, terceiro {} menor.'.format(numero01, numero03)) else: print('Primeiro numero {} é o maior, segundo {} menor.'.format(numero01, numero02)) elif numero01<numero02 and numero02>numero03: if numero01>numero03: print('Segundo numero {} é o maior, terceiro {} menor.'.format(numero02, numero03)) else: print('Segundo numero {} é o maior, primeiro {} menor.'.format(numero02, numero01)) elif numero01 < numero02 and numero01 < numero03: print('Terceiro numero {} é o maior, primeiro {} menor.'.format(numero03, numero01)) else: print('Terceiro numero {} é o maior, segundo {} menor.'.format(numero03, numero02))
false
9f10d9f3f43d1efa04a222c3f6a79028f2fe47a1
Sahu-Ayush/Data_Structure_and_Algorithms_450_Target
/array/reverse_array_slicing.py
481
4.15625
4
# Write a program to reverse an array ''' Input : arr[] = [1, 2, 3] Output : arr[] = [3, 2, 1] Input : arr[] = [4, 5, 1, 2] Output : arr[] = [2, 1, 5, 4] Approach: Slicing arr[::-1] Time Complexcity is O(n) ''' # Implementation import sys # by default return a list of string so map, list-int arr = list(map(int, sys.stdin.readline().strip().split())) # reading using input() function and list comprehension #arr = [int(ele) for ele in input().split()] print(arr[::-1])
true
3dbb3fe0efbcbd3cd87b36d573692d43af5c8d29
alexcarcar/WebLayout
/app/src/main/assets/jsexamples/py/ch16/exercises.py
2,338
4.125
4
# Time (p 181) class Time(object): """Represents the time of day. attributes: hour, minute, second """ time = Time() time.hour = 11 time.minute = 59 time.second = 30 # Exercises 16-1 def print_time(t): print "%.2d:%.2d:%.2d" % (t.hour,t.minute,t.second) print_time(time) # 11:59:30 # Exercises 16-2 def is_after(t1, t2): return t1.hour>t2.hour or (t1.hour==t2.hour and (t1.minute>t2.minute or (t1.minute==t2.minute and t1.second>t2.second))) time2 = Time() time2.hour = 11 time2.minute = 59 time2.second = 31 print is_after(time, time2) # False print is_after(time2, time) # True print is_after(time2, time2) # False print is_after(time, time) # False # Exercise 16-3 def increment(time, seconds): time.second += seconds if time.second >= 60: m = int(time.second/60) time.second -= 60*m time.minute += m if time.minute >= 60: h = int(time.minute/60) time.minute -= 60*h time.hour += h print_time(time) # 11:59:30 increment(time, 832033) print_time(time) # 243:06:43 z = Time() z.hour = 0 z.minute = 0 z.second = 0 increment(z,832033) print_time(z) # 231:07:13 # Exercise 16-4 time.hour = 11 time.minute = 59 time.second = 30 import copy def add_increment(t, seconds): time = copy.copy(t) time.second += seconds if time.second >= 60: m = int(time.second/60) time.second -= 60*m time.minute += m if time.minute >= 60: h = int(time.minute/60) time.minute -= 60*h time.hour += h return time print_time(time) # 11:59:30 t = add_increment(time, 2033) print_time(t) # 12:33:23 print_time(time) # 11:59:30 # Exercise 16-5 def time_to_int(time): minutes = time.hour*60 + time.minute seconds = minutes*60 + time.second return seconds def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time def increment_time(time, seconds): print "*****" print_time(time) print seconds print "*****" return int_to_time(time_to_int(time) + seconds) t1 = Time() t1.hour = 3 t1.minute = 14 t1.second = 25 t2 = increment_time(t1, 543) print_time(t1) print_time(t2) print time_to_int(t2) - time_to_int(t1) # ***** # 03:14:25 # 543 # ***** # 03:14:25 # 03:23:28 # 543
true
4e7fd858df730b5f6ac761e6b6990cfd4222085e
alexcarcar/WebLayout
/app/src/main/assets/jsexamples/py/ch5/examples.py
1,663
4.125
4
# Modulous Operator (p 49) quotient = 7/3 print quotient # 2 remainder = 7%3 print remainder # 1 # Boolean Expressions (p 49) print 5 == 5 # True print 5 == 6 # False print type(True) # <type 'bool'> print type(False) # <type 'bool'> # Relational Operators (p 50) # ==, !=, >, <, >=, <= # Logic Operators: and, or, not (p 50) n = 9 print n%2==0 or n%3==0 # True print 17 and True # True (any non zero number is interpreted as "true") # Conditional Execution (p 50) if n > 0: print 'n is positive' # n is positive m = -9 if m < 0: pass # "pass" does nothing, i.e. need to handle negative cases # Alternative Exeuction (p 51) x = 2 if x%2 == 0: print 'x is even' # x is even else: print 'x is odd' # Chained Conditionals (p 51) x = 15; y = 7; if x < y: print 'x is less than y' elif x > y: print 'x is greater than y' # x is greater than y else: print 'x and y are equal' # Nested Conditionals (p 52) if x == y: print 'x and y are equal' else: if x < y: print 'x is less than y' else: print 'x is greater than y' # x is greater than y if 0 < x and x < 10: print 'x is a positive single-digit number' else: print 'or it is not!' # or it is not! # Recursion (p 53) def countdown(n): if n <= 0: print 'Blastoff!' else: print "--> " + str(n) countdown(n-1) countdown(3) # 3 2 1 Blastoff! def print_n(s, n): if n <= 0: return print s print_n(s, n-1) print_n("Alex", 3) # Alex Alex Alex # Infinite Recurision (p 55) def recurse(): recurse() # recurse() # RuntimeError: maximum recursion depth exceeded # Keyboard input (raw_input) name = raw_input('What...is your name?\n') print name speed = raw_input('Speed?') print int(speed)
false
8fbfd9ad6840ba8098e194ba60db90ed507b53a7
alexcarcar/WebLayout
/app/src/main/assets/jsexamples/py/ch7/exercise7-1.py
356
4.21875
4
# Exercise 7-1 (p. 78): Rewrite print_n from "Recursion" (p. 54) using iteration # print_n using "recursion" (p. 54) def print_n(s, n): if n <= 0: print "" return print s, print_n(s, n-1) print_n("test", 3) # test test test def print_n_while(s, n): while n > 0: print s, n = n - 1 print "" print_n("alex", 5) # alex alex alex alex alex
false
33db42e6f3e91993ce83c21019f89c93a0c32397
LucasXS/Mundo3Python
/Desafios/Funcoes/exer097.py
305
4.15625
4
"""DESAFIO 097 - Faça um programa qye tenha uma FUNÇÃO chamada ESCREVA(), que receba um texto qualquer como PARÂMENTRO e mostre uma mensagem com tamanho adaptável.""" def escreva(txt): print('-' * len(txt)) print(txt) print('-' * len(txt)) txt = str(input('Seu texto: ')) escreva(txt)
false
a4ebc03824d98be888fc5fec0229dbb9567a01bd
bendixondavis/roll-dice
/dice_roll.py
331
4.28125
4
import random num_sides = 0 result = 0 flip_again = 'y' #the int() around the input casts the string input to an int num_sides = int(input("How many sides do you want die to have? ")) while flip_again == 'y': result = random.randint(1,num_sides) print("You rolled a : ",result) flip_again = input("Play Again(y/n)")
true
927edb4da224aa650898b1ab1a5ec4e3557a4f3d
xprime480/projects
/examples/python/circlepoints.py
914
4.1875
4
#!/usr/bin/env python3 """ Generate and print points on the radius of a circle. """ import random import math def main(radius, count) : points = make_points(radius, count) print (count_quadrant(points)) for x in points : print (x[0], x[1]) def count_quadrant(points) : quad = [0,0,0,0] for x in points : if x[0] >= 0 : if x[1] >= 0 : quad[0] += 1 else: quad[3] += 1 else : if x[1] >= 0 : quad[1] += 1 else : quad[2] += 1 return quad def make_points(radius, count) : points = [] for x in range(count) : p = make_point(radius) points.append(p) return points def make_point(radius) : point1d = 2.0 * random.random() * math.pi return (radius * math.cos(point1d), radius * math.sin(point1d)) main(1000, 1000)
true
fea836f02d8b435c8fe32a13834fcb9c8f5f6f71
robbinsa530/MazeSolver
/main.py
1,790
4.125
4
""" main.py ------- Alex Robbins, Andrew Hart Intro to AI Section 1 Final Project (Maze Solver) This is the main file to be called on startup. It creates a new GUI window and does everything else that needs to be done. HOW-TO: 1.) Start this program 2.) Point camera at a maze image on a flat surface 3.) Adjust the 3 sliders until solution is constantly overlayed on top of the maze image 3a.) Threshold slider controls what level of lightness in a pixel corresponds to a path 3b.) Minimum Allowed Bounding-Box slider controls the minimum bounding box to be considered as valid when the program is searching for the maze. If for example, there is a small amount of noise in the field of view of the camera that is being surrounded by a green box and thus being included in the final bounding box of the maze (in turn messing up the finding of the maze), raise the value of this slider until that small box is ignored. 3c.) Erosion Level slider controls how much of the path is eroded away before trying to solve the maze. For mazes with thick white paths, set this to a high value. For mazes with a skinny white path, set this to a low value. RULES: 1.) Maze should be completely within the field of view of the camera 2.) Maze must be rectangular in shape 3.) Maze must have EXACTLY 2 entry points (an entrance/start and an exit/end) 3a.) Entry points do not need to be labeled in any way. They just need to exist 4.) Travelable path must be a light color and walls must be a dark color """ from Tkinter import * import mazeSearch import util import argparse import imaging import view import cam vc = cam.VideoCamera() root = Tk() root.title("Maze Solver") app = view.Application(vc, master=root) root.after(0, app.loop) app.mainloop() vc.__del__()
true
0f46a68e9b463a26913bfbfa193cc07d3afe9bbd
rahulkhoond/rahul_repo
/vowel.py
214
4.125
4
n=raw_input("enter the character") if(n=='a'or n=='A'or n=='e'or n=='E'or n=='i'or n=='I' or n== 'o' or n=='O' or n== 'u' or n== 'U'): print("character is vowel") else: print("character is consonent")
false
8c21f0c6be13bcb68647ace520bc16e8da0b6826
seniroberts/Expressions
/Python/Leetcode/Easy/Removeduplicates.py
955
4.125
4
""" Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length. """ def removeDuplicates(an_array): if len(an_array) == 0: return 0 an_array[:] = list(sorted(set(an_array))) return len(an_array) print(removeDuplicates([1, 1, 2, 2, 4, 4])) print(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
true
a82e46fc1ca5227886d60e90593802ee2ca61e13
seniroberts/Expressions
/Python/Leetcode/Easy/sortByParity.py
1,066
4.28125
4
""" Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted """ def sortByParity1(an_array): evenList = [] oddList = [] for i in range(len(an_array)): if an_array[i] % 2 == 0: evenList.append(an_array[i]) else: oddList.append(an_array[i]) evenList.extend(oddList) return evenList def test(): original_array = [3, 1, 2, 4] print("Original Array-->", original_array) print("Sorted by parity:--->", sortByParity1(original_array)) test() def sortByParity2(an_array): return [i for i in an_array if i % 2 == 0] + [i for i in an_array if i % 2 != 0] def test(): original_array = [3, 1, 2, 4] print("Original Array-->", original_array) print("Sorted by parity2:--->", sortByParity2(original_array)) test()
true
7a917dc1cee4d2e6c85f8201909a74a2b7ae1162
VegetaPn/MyLeetCode
/flatten_nested_list_iterator.py
1,796
4.28125
4
#!/usr/bin/env python # encoding: utf-8 # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # "" # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.item_arr = [] self.counter = 0 self.load_arr(nestedList) self.list_len = len(self.item_arr) def load_arr(self, item): for ite in item: if ite.isInteger(): self.item_arr.append(ite.getInteger()) else: self.load_arr(ite.getList()) def next(self): """ :rtype: int """ res = self.item_arr[self.counter] self.counter += 1 return res def hasNext(self): """ :rtype: bool """ return self.counter < self.list_len # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
true
bbdd299a0be8e24c8b044d6d75198b806b844cad
popovanaz/fogstream_vl
/функции 1.py
597
4.21875
4
Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). Считайте четыре действительных числа и выведите результат работы этой функции. def distance(x1, y1, x2, y2): d = ((x2-x1)**2 + (y2-y1)**2)**0.5 return d x1, y1, x2, y2 = [float(i) for i in input('Введите четыре целых числа:\n').split()] print(distance(x1, y1, x2, y2))
false
a0bd4be986b1dc50455819c64c2d7936d6194f11
Vestenar/PythonProjects
/venv/02_Codesignal/01_Intro/043_isBeautifulString.py
1,511
4.1875
4
def isBeautifulString(inputString): alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') n = inputString.count(alphabet[0]) for i in alphabet: if inputString.count(i) > n: return False n = inputString.count(i) return True #реализация через сравнение массивов и метод string, в котором содержится константа # import string # def isBeautifulString(s): # l = [s.count(i) for i in string.ascii_lowercase[::-1]] # return l == sorted(l) #реализация метода через map # def isBeautifulString(inputString): # # counts = list(map(inputString.count, 'abcdefghijklmnopqrstuvwxyz')) #создает массив количества вхождений # print(counts) # return all(x >=y for x, y in zip(counts, counts[1:])) task = "abcdefghijklmnopqrstuvwxyz" print(isBeautifulString(task)) ''' A string is said to be beautiful if b occurs in it no more times than a; c occurs in it no more times than b; etc. Given a string, check whether it is beautiful. Example For inputString = "bbbaacdafe", the output should be isBeautifulString(inputString) = true; For inputString = "aabbb", the output should be isBeautifulString(inputString) = false; For inputString = "bbc", the output should be isBeautifulString(inputString) = false. '''
false
913277c7325fd32ee96b8fa2a2e774c4dba713b7
Vestenar/PythonProjects
/venv/02_Codesignal/02_The Core/054_isCaseInsensitivePalindrome.py
708
4.4375
4
def isCaseInsensitivePalindrome(inputString): return inputString[::-1].lower() == inputString.lower() print(isCaseInsensitivePalindrome("AaBaa")) ''' Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters. Example For inputString = "AaBaa", the output should be isCaseInsensitivePalindrome(inputString) = true. "aabaa" is a palindrome as well as "AABAA", "aaBaa", etc. For inputString = "abac", the output should be isCaseInsensitivePalindrome(inputString) = false. All the strings which can be obtained via changing case of some group of letters, i.e. "abac", "Abac", "aBAc" and 13 more, are not palindromes. '''
true
621a082e32b70244a10321197f990919a720b5af
Vestenar/PythonProjects
/venv/01_Stepik/Python_Programmirovanie/2.6_1.py
742
4.15625
4
''' Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор, пока сумма введённых чисел не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел. Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать не нужно. ''' cont = True nSum = 0 nSumSq = 0 while cont: a = int(input()) nSum += a nSumSq += a ** 2 if nSum == 0: cont = False print(nSumSq)
false
2d31489a3f37944bf886198c3a2e25b1d8de8c8b
Vestenar/PythonProjects
/venv/02_Codesignal/02_The Core/031_increaseNumberRoundness.py
816
4.375
4
def increaseNumberRoundness(n): while n % 10 == 0: n //= 10 return "0" in str(n) #return '0' in str(n).rstrip('0') print(increaseNumberRoundness(11661100)) ''' Define an integer's roundness as the number of trailing zeroes in it. Given an integer n, check if it's possible to increase n's roundness by swapping some pair of its digits. Example For n = 902200100, the output should be increaseNumberRoundness(n) = true. One of the possible ways to increase roundness of n is to swap digit 1 with digit 0 preceding it: roundness of 902201000 is 3, and roundness of n is 2. For instance, one may swap the leftmost 0 with 1. For n = 11000, the output should be increaseNumberRoundness(n) = false. Roundness of n is 3, and there is no way to increase it. '''
true
9de5f249f14058c610daeca73f4b0f8c52274c69
Vestenar/PythonProjects
/venv/02_Codesignal/02_The Core/100_reverseOnDiagonals.py
1,073
4.3125
4
def reverseOnDiagonals(matrix): l = len(matrix) diag1 = [matrix[i][i] for i in range(l)][::-1] diag2 = [matrix[i][-i-1] for i in range(l)][::-1] for i in range(l): for j in range(l): if i == j: matrix[i][j] = diag1[i] elif j == l-i-1: matrix[i][j] = diag2[i] return matrix matrix = [[43,455,32,103], [102,988,298,981], [309,21,53,64], [2,22,35,291]] print(reverseOnDiagonals(matrix)) ''' The longest diagonals of a square matrix are defined as follows: the first longest diagonal goes from the top left corner to the bottom right one; the second longest diagonal goes from the top right corner to the bottom left one. Given a square matrix, your task is to reverse the order of elements on both of its longest diagonals. Example For matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the output should be reverseOnDiagonals(matrix) = [[9, 2, 7], [4, 5, 6], [3, 8, 1]] '''
false
3caf51b13b56fcab09dba935bf30f9172d73d3e7
Vestenar/PythonProjects
/venv/02_Codesignal/03_Python/019_newStyleFormatting.py
934
4.25
4
def newStyleFormatting(s): s1 = re.sub('%%', '@!', s) s2 = re.sub(r'%[bcedfgnosx]', '{}', s1) s3 = re.sub('@!','%',s2) return(s3) '''You came to work in a big company as a Senior Python Developer. Unfortunately your team members seem to be quite old-school: you can see old-style string formatting everywhere in the code, which is not too cool. You tried to force the team members to start using the new style formatting, but it looks like it will take some time to persuade them: old habits die hard, especially in old-school programmers. To show your colleagues that the new style formatting is not that different from the old style, you decided to implement a function that will turn the old-style syntax into a new one. Implement a function that will turn the old-style string formating s into a new one so that the following two strings have the same meaning: s % (*args) s.format(*args) '''
true
4e8fc700ffd89c329d7c6b1414e9819fce9efea0
Vestenar/PythonProjects
/venv/02_Codesignal/03_Python/032_wordPower.py
780
4.53125
5
def wordPower(word): num = dict([(i, ord(i)-96) for i in word]) print([(i, ord(i)-96) for i in word]) return sum([num[ch] for ch in word]) print(wordPower("abcde")) ''' You've heard somewhere that a word is more powerful than an action. You decided to put this statement at a test by assigning a power value to each action and each word. To begin somewhere, you defined a power of a word as the sum of powers of its characters, where power of a character is equal to its 1-based index in the plaintext alphabet. Given a word, calculate its power. Example For word = "hello", the output should be wordPower(word) = 52. Letters 'h', 'e', 'l' and 'o' have powers 8, 5, 12 and 15, respectively. Thus, the total power of the word is 8 + 5 + 12 + 12 + 15 = 52. '''
true
35357ee0abfb4bb93edd63a3053c45bd625600c7
MaciejAZak/TicTacToe
/Problems/Spellchecker/task.py
377
4.125
4
dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal', 'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize', 'sign', 'the', 'to', 'uncertain'] inp = input() list = inp.split() i = 0 for word in list: if word not in dictionary: print(word) else: i += 1 if i == len(list): print("OK")
false
b14ee17b26137f2422c7daee6663edb554a4c879
rashmitallam/PythonPrograms
/remove_punc_from_string.py
261
4.59375
5
#Python Program to Remove Punctuations From a String punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' str1 = input("Enter a string:") op_str = "" for char in str1: if char not in punctuations: op_str = op_str + char print(op_str)
false
621dcb3fa0ce8c0d986bda54fab21c291d0948b6
rashmitallam/PythonPrograms
/count_words_in_para.py
627
4.15625
4
#WAP to accept a paragraph from user and return a dict of count of words def DictWords(p): res=dict() for ch in p.split(): if res.get(ch) != None: res[ch] += 1 else: res[ch] = 1 return res def main(): p1=input('Enter a paragraph:') d1=DictWords(p1) print d1 if __name__ == '__main__': main() ''' >>> RESTART: C:/Users/Admin/Desktop/Python_2019/Dictionary/count_words_in_para.py Enter a paragraph:'Hi hello how are you hello all of you' {'all': 1, 'of': 1, 'how': 1, 'Hi': 1, 'are': 1, 'you': 2, 'hello': 2} >>> '''
false
3bc80a09ba1314531e7f6129a99960081757233e
rashmitallam/PythonPrograms
/string_iteration.py
223
4.53125
5
#Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a string. cnt=0 for letter in 'Hello World': if(letter == 'l'): cnt +=1 print(cnt,'letters found')
true
77393bd9e1c9182e16e79e8f55255932ad0b9770
portableDD/alx-higher_level_programming
/0x01-python-if_else_loops_functions/12-fizzbuzz.py
540
4.28125
4
#!/usr/bin/python3 """ This prints the numbers from 1 to 100 multiples of three print Fizz instead of the number and multiples of five print Buzz numbers which are multiples of both three and five print FizzBuzz """ def fizzbuzz(): for num in range(1, 101): if num % 3 == 0 and num % 5 == 0: print("FizzBuzz ", end="") elif num % 3 == 0: print("Fizz ", end="") elif num % 5 == 0: print("Buzz ", end="") else: print("{} ".format(num), end="")
true
08b11b13cca44406f19cb3dcbd7113c5040edaf5
mauraqoonitah/moutarRecruitmentTest
/Sorting Logic Task/quicksort.py
1,260
4.1875
4
# QUICK SORT # There will be an array of integers as input. # implement the sorting algorithm to make it sorted (ASC). # Select middle element as pivot, # find element which is greater than pivot, # find element which is smaller than pivot, # if we found the element on the left side which is greater than pivot # and element on the right side which is smaller than pivot: # Swap them, and increase the left and right # and then Recursion on left and right of the pivot to get the sorted array def partition(arr, low, high): i = (low-1) # index of smaller element pivot = arr[high] # select middle element as pivot for j in range(low, high): # find element which is smaller than pivot or equal than pivot if arr[j] <= pivot: i = i+1 #increment the smaller element arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return (i+1) def quickSort(arr, low, high): if len(arr) == 1: return arr if low < high: pi = partition(arr, low, high) quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) #input your array to be sorted here: arr = [10,2,1,5,3,6] print("your input to be sorted: ") print(arr) n = len(arr) quickSort(arr, 0, n-1) print("Sorted array ASC using QuickSort Algortihm:") print(arr)
true
749bee7b9dd1dcf25d451ad3e8ff95b473b9fa5c
chrisr1896/Exercises
/algorithms/dynamic_programming/is_palindrome/solution/solution.py
441
4.3125
4
def is_palindrome(string): # a string of len 1 is by defnition a palindrome so we return True if len(string) <= 1: return True else: # if the first and last charaters are equal # we recurse in the rest of the string removing the # first and last character to check if the rest of # the string is a palindrome. return string[0] == string[-1] and is_palindrome(string[1:-1])
true
9a082d01f4c5e172ce8b9ab804c037e216ac04ed
chrisr1896/Exercises
/algorithms/greedy_and_divide_and_conquer/lemonade_stand/solution/solution.py
1,824
4.3125
4
def lemonade_change(customer_bills): # we create a dictionary to keep track of all the bills # of each denomination in our register. # we start with 0 of each bill. register = {5: 0, 10: 0, 20: 0} # we itterate through the list of customer_bills for bill in customer_bills: # if the bill is 5, we don't need any change # so we serve them lemodane and add the 5$ bill # to our register updating the dictionary at 5 by 1. if bill == 5: register[5] +=1 # if the bill is 10, we need to check if we have any # 5$ bills to make change for the customer. elif bill == 10: # If we have a 5, # we update the register removing a 5 an adding a 10$ bill. if not register[5] == 0: register[5] -= 1 register[10] += 1 else: # if we have no 5 bills we cannot make change and return false. return False # if the customer has a 20$ bill we need to try and make change with 10s or 5s. elif bill == 20: # if we have no 10s we need 3 5$ bills if register[10] == 0: if register[5] >= 3: register[5] -= 3 register[20] +=1 else: return False # if we have a 10, we also need one 5$ bill. elif register[10] >= 1 and register[5] >= 1: register[10] -= 1 register[5] -= 1 register[20] += 1 else: return False # once we've itterated through all customers, we were able to make all # the change so we return True. return True print(lemonade_change([5, 20, 5, 20]))
true
d96584c1d1e88b653211415f5380ca5b56eb6293
chrisr1896/Exercises
/algorithms/dynamic_programming/shortest_path_to_1/solution/solution.py
1,205
4.4375
4
def shortest_path_to_1(n): # if n is 1 we need 0 steps to get to 1 if n == 1: return 0 # if n is 2 or 3, we only need one step to get to 1 if n == 2 or n == 3: return 1 # create a memo list. memo[i] will store the number of steps # to get to the ith stair. We initialise the values to -1. memo = [-1 for i in range(n+1)] memo[1] = 0 memo[2] = 1 memo[3] = 1 for i in range(4, n+1): # if i is divisible by 2 and 3 the shortest path will be # 1 + the minimum path for i-1, i/2 or i/3. We already # have those values calculated and stored in our memo list. if i%3 == 0 and i%2 == 0: memo[i] = 1 + min(memo[i-1], memo[i//3], memo[i//2]) # if i is divisible by 3 the shortest path will be # 1 + the minimum path for i-1, or i/3. elif i%3 == 0: memo[i] = 1 + min(memo[i-1], memo[i//3]) # if i is divisible by 2 the shortest path will be # 1 + the minimum path for i-1, or i/2. elif i%2 == 0: memo[i] = 1 + min(memo[i-1], memo[i//2]) else: memo[i] = 1 + memo[i-1] return memo[n]
false
d718e80cf6f49e42dcfeb495329198d6f48a0af6
rusantsovsv/CookBook
/3_num_date_time/3.13_lastfri.py
2,616
4.15625
4
""" Вы хотите создать общее решение для поиска даты ближайшего прошедшего дня недели – например, последней прошедшей пятницы. В модуле datetime есть полезные функции и классы, которые помогают проводить такого рода вычисления. Хорошее обобщенное решение этой задачи выглядит как-то так: """ from datetime import datetime, timedelta weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] def get_previous_byday(dayname, start_date=None): if start_date is None: start_date = datetime.now() day_num = start_date.weekday() day_num_target = weekdays.index(dayname) days_ago = (7 + day_num - day_num_target) % 7 if days_ago == 0: days_ago = 7 target_date = start_date - timedelta(days=days_ago) print(target_date) print(datetime.today()) get_previous_byday('Monday') get_previous_byday('Friday') """ Необязательный параметр start_date может быть предоставлен с использовани- ем другого экземпляра datetime. Например: """ get_previous_byday('Sunday', datetime(2012, 12, 21)) """ Этот рецепт работает путем отображения стартовой и интересующей даты на но- мера их позиций в неделе (где понедельник – это 0). Далее используется модуль- ная арифметика, с ее помощью мы вычисляем, сколько дней назад была нужная дата. Потом нужная дата высчитывается от стартовой даты путем вычитания со- ответствующего экземпляра timedelta. Если вы выполняете много подобных вычислений, рекомендуем установить пакет python-dateutil. Например, вот так можно выполнить аналогичную работу с использованием функции relativedata() из модуля dateutil: """ from dateutil.relativedelta import relativedelta from dateutil.rrule import * d = datetime.now() print(d) # следующий понедельник print(d + relativedelta(weekday=MO)) # предыдущий понедельник print(d + relativedelta(weekday=MO(-1)))
false
645a36b7351585844aa1963eabbe38fcdff7798e
rusantsovsv/CookBook
/3_num_date_time/3.1_roundnum.py
2,790
4.28125
4
""" Вы хотите округлить число с плавающей точкой до заданного количества знаков после точки. Для простого округления используйте встроенную функцию round(value, ndigits). Например: """ print(round(1.23, 1)) print(round(1.27, 1)) print(round(-1.27, 1)) print(round(1.25361, 3)) """ Когда значение попадает точно между двух возможных выборов для округле- ния, эта функция будет округлять к ближайшему четному значению. То есть 1.5 или 2.5 будут округлены до 2. Количество знаков, которое передается функции round(), может быть отрица- тельным. В этом случае округление будет идти до десятков, сотен, тысяч и т. д. """ a = 1627731 print(round(a, -1)) print(round(a, -2)) print(round(a, -3)) """ Не перепутайте округление с форматированием значения для вывода. Если вы хотите просто вывести число с некоторым определенным количеством знаков после точки, обычно вам не требуется round(). Вместо этого просто задайте при форматировании, сколько знаков выводить. Пример: """ x = 1.23456 print(format(x, '0.2f')) print(format(x, '0.3f')) print('value is {:0.3f}'.format(x)) """ Сопротивляйтесь желанию округлить числа с плавающей точкой, чтобы испра- вить проблемы с точностью вычислений. Например, вы можете подумывать по- ступить так: """ a = 2.1 b = 4.2 c = a + b print(c) c = round(c, 2) # "Исправленный" результат (???) print(c) """ Для большинства программ, работающих с числами с плавающей точкой, просто не нужно (и не рекомендуется) этого делать. Хотя есть незначительные ошибки в вычислениях, поведение этих ошибок понятно и терпимо. Если необходимо из- бежать таких ошибок (например, это может быть важно для финансовых прило- жений), попробуйте модуль decimal, который обсуждается в следующем рецепте. """
false
2ad4517d671641e860e121073a311f588c924c74
rusantsovsv/CookBook
/7_functions/7.6_anon_func.py
2,463
4.53125
5
""" Вам нужно предоставить короткую функцию обратного вызова для использова- ния в операции типа sort(), но вы не хотите определять отдельную однострочную функцию с помощью инструкции def. Вместо этого вам бы пригодился способ определить функцию «в строке». Простые функции, которые просто вычисляют результат выражения, могут быть заменены инструкцией lambda. Например: """ add = lambda x, y: x + y print(add('hello', ' world')) """ Использование lambda абсолютно равноценно такому примеру: >>> def add(x, y): ... return x + y ... >>> add(2,3) 5 >>> Обычно lambda используется в контексте какой-то другой операции, такой как сортировка или свертка (reduction) данных: """ names = ['David Beazley', 'Brian Jones', 'Raymond Hettinger', 'Ned Batchelder'] print(sorted(names, key=lambda name: name.split()[-1].lower())) """ Хотя lambda позволяет определить простую функцию, ее возможности сильно ограничены. В частности, может быть определено только одно выражение, ре- зультат которого станет возвращаемым значением. Это значит, что никакие дру- гие возможности языка, в т. ч. множественные инструкции, условия, итерации и обработка исключений, использоваться не могут. Вы можете замечательно писать код на Python без использования lambda. Од- нако вы наверняка натолкнетесь на них в написанной кем-то программе, в ко- торой используется множество маленьких функций для вычисления результатов выражений, или же в программе, которая требует от пользователей предоставлять функции обратного вызова (callback 7_functions). """
false
7a7f12025e6d7ee32cda5b8566de8b23c10268b6
Mavus/daily-programmer
/Python/easy002.py
1,157
4.4375
4
#!/usr/bin/python """ Create a calculator application that has use in your life. It might be an interest calculator, or it might be something that you can use in the classroom. For example, if you were in physics class, you might want to make a F = M * A calc. EXTRA CREDIT: make the calculator have multiple functions! Not only should it be able to calculate F = M * A, but also A = F/M, and M = F/A! [MAIN] : DONE [EXTRA]: DONE """ # Constants (edit for real values) FIXED_PRICE = 1.50 INITIAL_VALUE = 3000 SHARES = INITIAL_VALUE // FIXED_PRICE def get_current_capital(shares): price = input("Enter today's share price: ") return shares * price def get_desired_price(shares): capital = input("Enter desired capital: ") return float(capital) / shares def mode(): mode = raw_input("Select function (v)alue, (p)rice, (e)xit: ") if mode == 'v': value = get_current_capital(SHARES) print "The value of your shares is", value elif mode == 'p': price = get_desired_price(SHARES) print "The price you need is", price elif mode == 'e': exit() else: pass while True: mode()
true
678665ce16a4988f2c898d1954ad909b39064f19
Malfunction13/Rotten-Apples
/RA-v3_fixed.py
2,888
4.15625
4
import copy #take user input for crate size rowsXcolumns = [input("Please insert your crate size as ROWSxCOLUMNS:")] #intialize list with crate size in rowsXcolumns format and add the measures as separate list entries by splitting based on "x" crate_size = [] for measures in rowsXcolumns: for measure in measures.split("x"): if measure.isnumeric(): crate_size.append(int(measure)) #strictly for better readability - declare the vars that hold the measures by index number in the list rows = crate_size[0] columns = crate_size[1] #initialazie the 2d matrix based on the dimensions from user input matrix = [["O" for i in range(columns)] for j in range(rows)] #function used to print the matrix in more readable format def Beautify(): for row in matrix: print(*row, sep=" ") Beautify() #get the coordinates of the rotten apples from the user, remove unnecessary characters and store in a list as integers rotten_coordinates = input("Please insert the coordinates of the rotten apples as (X,Y) (X,Y) etc.:") r_c = rotten_coordinates.replace("(", "").replace(")", "").replace(",", " ") raw_coordinates = [int(i) for i in r_c.split(" ")] #now we need to grab coordinate X and coordinate Y and translate them to coordinates applicable to python lists coordinates_X = raw_coordinates[0::2] coordinates_Y = raw_coordinates[1::2] change_A = [(y-1) for y in coordinates_Y] change_B = [(x-1) for x in coordinates_X] for a, b in zip(change_A, change_B): matrix[a][b] = "X" Beautify() #count how many times will the rotting loop run based on the user input of days away #every 3 days all the adjacent in x.y.z axis apples will rot t = int(input("Please insert the days away: "))+1 # for every day for day in range(1, t): print('day ' + str(day)) # need a temp list so we don't influence the result temp_matrix = copy.deepcopy(matrix) # traverse list from top to bottom if ((day % 3) != 0): print("No apples have rotten today!") else: print("Every 3 days adjacent apples rot!") for y in range(len(matrix)): # traverse list from left to right for x in range(len(matrix[y])): # check if element is rotten if (matrix[y][x] == 'X'): # rot all surrounding elements, but check if each element exists first if y-1 >= 0: if x-1 >= 0: temp_matrix[y-1][x-1] = 'X' temp_matrix[y-1][x] = 'X' if x+1 < len(matrix[y]): temp_matrix[y-1][x+1] = 'X' if x-1 >= 0: temp_matrix[y][x-1] = 'X' temp_matrix[y][x] = 'X' if x+1 < len(matrix[y]): temp_matrix[y][x+1] = 'X' if y+1 < len(matrix): if x-1 >= 0: temp_matrix[y+1][x-1] = 'X' temp_matrix[y+1][x] = 'X' if x+1 < len(matrix[y]): temp_matrix[y+1][x+1] = 'X' matrix = copy.deepcopy(temp_matrix) Beautify()
true
4905e4eebb367d0038a27aa29a06798ff7118310
quasney24/Python-Challenge
/PyBank/PyHW.py
2,232
4.21875
4
''' The total number of months included in the dataset The total amount of revenue gained over the entire period The average change in revenue between months over the entire period The greatest increase in revenue (date and amount) over the entire period The greatest decrease in revenue (date and amount) over the entire period Example: Financial Analysis ---------------------------- Total Months: 25 Total Revenue: $1241412 Average Revenue Change: $216825 Greatest Increase in Revenue: Sep-16 ($815531) Greatest Decrease in Revenue: Aug-12 ($-652794) ''' import os import csv #build path to CSV 1 & 2 PyBank_CSV_1 = os.path.join("raw_data", "budget_data_1.csv") #Read CSV with open (PyBank_CSV_1, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") #ignore headers next(csvreader) #empty lists for date and revenue date = [] revenue = [] #Start of Loop for row in csvreader: #append date & revenue to empty list date.append(row[0]) revenue.append(int(row[1])) #calculate the total months & total revenue total_months = len(date) total_revenue = sum(revenue) #Calculate the difference between months and store in a list total_diff_list = [j-i for i,j in zip(revenue[:-1], revenue[1:])] #Find the average of the list average_diff = float(sum(total_diff_list))/len(total_diff_list) #find the max increase greatest_increase = max(total_diff_list) #store the index where max is position_increase_index = total_diff_list.index(greatest_increase) #find the min increase greatest_decrease = min(total_diff_list) #store the index where min is position_decrease_index = total_diff_list.index(greatest_decrease) #print for days print("Financial Analysis") print("--------------------------") print ("Total Months: ", total_months) print ("Total Revenue: ", "$",total_revenue) print ("Average Revenue Change: ", average_diff) print ("Greatest Increase in Revenue: ", date[position_increase_index], "($" , greatest_increase, ")") print ("Greatest Decrease in Revenue: ", date[position_decrease_index], "($", greatest_decrease, ")")
true
32cf63accfab6ab4c233573c1ee85b9fee13fd87
jpaulo-kumulus/KumulusAcademy
/Exercícios José/Python Numeric Operations/challenge5.py
2,011
4.125
4
print('Simple calculator!') firstNumber = input() if firstNumber.isnumeric() == False: print('Please input a number') exit() else: secondNumber = input() if secondNumber.isnumeric() == False: print('Please input a number') exit() else: print('Operation: ') operation = input() if operation == '+': firstNumber = int(firstNumber) secondNumber = int(secondNumber) resultValue = (firstNumber + secondNumber) print(resultValue) exit() elif operation == '-': firstNumber = int(firstNumber) secondNumber = int(secondNumber) resultValue = firstNumber - secondNumber print(resultValue) exit() elif operation == '*': firstNumber = int(firstNumber) secondNumber = int(secondNumber) resultValue = firstNumber * secondNumber print(resultValue) exit() elif operation == '/': firstNumber = int(firstNumber) secondNumber = int(secondNumber) resultValue = firstNumber / secondNumber print(resultValue) exit() elif operation == '%': firstNumber = int(firstNumber) secondNumber = int(secondNumber) resultValue = firstNumber % secondNumber print(resultValue) exit() elif operation == '**': firstNumber = int(firstNumber) secondNumber = int(secondNumber) resultValue = firstNumber ** secondNumber print(resultValue) exit() else: print('Operation not recognized')
false
97fd628f6be153b8b10d9d6047453a0fd4031491
jpaulo-kumulus/KumulusAcademy
/Exercícios Joao/Python/python-while/challenge.py
551
4.15625
4
# import random # value = random.randint(1, 5) # guess = 0 # count = 0 # while guess != value: # guess = int(input("Guess a number between 1 and 5 ")) # count += 1 # print(f"You guessed it in {count} tries!") import random value = random.randint(1, 15) guess = 0 count = 0 while guess != value: guess = int(input("Guess a number between 1 and 15 ")) if guess < value: print("Your guess is too low") elif guess > value: print("Your guess is too high") count += 1 print(f"You guessed it in {count} tries!")
true
0e713eb90a02a7ec5eece69c05618883626e8b87
Diznar/curso-python
/12-POO-capitulo-1.py
1,897
4.125
4
class Camiseta: """ Clase camiseta: Representa una camiseta de la vida real. ======================================================= Atributos: ---------- - precio -> (float) almacena el precio de la camiseta. - marca -> (str) almacena el marca de la camiseta. - talla -> (str) almacena el talla de la camiseta. - color -> (str) almacena el color de la camiseta. - rebajada -> (bool) inidica si está o no rebajada. Métodos: -------- - __init__(precop, marca, talla, color) -> (Camiseta) constructor de la clase. - aplicarDescuento(porcentaje) -> descuenta el *porcentaje* al precio de la camiseta. - teñir(color) -> cambia el color de la camiseta - infoCamiseta() -> (str) retorna la descripción de la camiseta """ def __init__(self, precio, marca, talla, color): self.precio = precio self.marca = marca self.talla = talla self.color = color self.rebajada = False def aplicarDescuento(self, porcentaje): nuevoPrecio = self.precio - self.precio*porcentaje/100 self.precio = nuevoPrecio if porcentaje < 100: self.rebajada = True def teñir(self, color): self.color = color def infoCamiseta(self): info = f"Camiseta:\nTalla: {self.talla}\nPrecio: {self.precio:.2f}€\nMarca: {self.marca}\n" if self.rebajada: info += "Actualmente esta camiseta está rebajada" return info camiseta = Camiseta(19.99, "Gucci", "XL", "Negro") print(camiseta.infoCamiseta()) camiseta.aplicarDescuento(20) print(camiseta.infoCamiseta()) print("\n####################\n") camisetaAdimas = Camiseta(300, "Adimas", "M", "Rojo") print(camisetaAdimas.color) print(camisetaAdimas.marca) camisetaAdimas.teñir("Verde") print(camisetaAdimas.color)
false
6965249e4d8fe67e7af03f582b315df2179b12e2
moonlimb/interview_prep
/challenges/codility_solution.py
735
4.25
4
def is_reverse(left_str, right_str): """returns true if left_str is reverse of right_str""" if (not left_str) and (not right_str): return True else: len_substr = len(left_str) for index in xrange(len_substr): if left_str[index] != right_str[len_substr-1-index]: return False return True def symmetryPoint ( S ): """returns the symmetry point in string S about whichthe substring before the point is the reverse of that after the point; returns -1 if there is no such point""" if not S: return '' if len(S)%2 != 0: pivot = len(S)/2 if is_reverse(S[0:pivot], S[pivot+1:]): return pivot return -1
true
b83d951bc1d3446c9d130c7099b9c2718f962890
sebutz/java-to-python-in-100-steps
/python-code/oops/newshit/functional_prog1.py
909
4.375
4
# a function is an object # lambda way (anonymous, simpler definition of a function) def multiply_by_2(data): return data * 2 print(type(multiply_by_2)) # <class 'function'> def do_something_and_print(func, data): print(func(data)) # it's taking the function as arguments do_something_and_print(multiply_by_2, 12) # 24 # we can have reference to that function-object func_example_ref = multiply_by_2 print(func_example_ref(23)) # 46 # we need to define first the method def multiply_by_3(data): return data * 3 do_something_and_print(multiply_by_3, 34) # 102 # how can we create methods directly : lambda comes as rescue do_something_and_print(lambda data: data * 3, 124) # 372 # so you don't need to create first the function # cube do_something_and_print(lambda data: data ** 3, 100) # # length of data do_something_and_print(lambda data: len(data), "Tutankamon") # 10
true
752fffbb24dd343712a9de57fb95242e2e334164
sebutz/java-to-python-in-100-steps
/python-code/oops/newshit/abstract_class_example.py
877
4.125
4
from abc import ABC, abstractmethod ''' ABC : abstract base class ''' class AbstractRecipe(ABC): def execute(self): self.get_ready() self.do_the_dish() self.cleanup() @abstractmethod def get_ready(self): pass @abstractmethod def do_the_dish(self): pass @abstractmethod def cleanup(self): pass #recipe = AbstractRecipe() #recipe.execute() ''' recipe = AbstractRecipe() TypeError: Can't instantiate abstract class AbstractRecipe with abstract methods cleanup, do_the_dish, get_ready ''' class Recipe1(AbstractRecipe): def get_ready(self): print("Get raw materials") print("Get utensils") def do_the_dish(self): print("Do the dish") def cleanup(self): print("clean up") recipe1 = Recipe1() recipe1.get_ready() #recipe1.execute() recipe1.cleanup()
true
98f4632f784bd769456f9c1e709fa2821aa089be
sebutz/java-to-python-in-100-steps
/python-code/oops/newshit/oops_puzzles.py
925
4.3125
4
''' -- self is mandatory you need to have on a constructor or instance method self or at least some parameter with the same meaning ''' class Country: ''' you cannot overload constructors there is no such a concept as overloading - when the compiler sees the same name for a method, removes the old one -- the only way 'to emulate' overloading is to use default values for parameters ''' # def __init__(self): # print('constructor') def __init__(self, name="Default"): self.name = name def instance_method(self): print("instance method") pakistan = Country() india = Country("India") print(india.name) print(pakistan.name) india.instance_method() pakistan.instance_method() class Country2: def __init__(this): print('constructor') def instance_method(this): print("instance method") romania = Country2() print(romania)
true
bb55a29c8cda12cb6993f9b1f36b3322d9700fe6
GoodnessEzeokafor/practice_python
/guessing_game.py
990
4.34375
4
''' Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise) Extras: - Keep track of how many guesses the user has taken, and when the game ends, print this out. ''' import random def guess_number(): my_number = random.randint(1,3) tries = 0 while tries < 3: your_number = int(input('Enter Your Number: ')) if your_number > my_number: print("Too High!!") print("My number was",my_number) elif your_number < my_number: print('Too Low!!') print("My number was", my_number) elif your_number == my_number: print('Correct!!') print('Impressive!!') print('Number of tries', tries) break tries += 1 if __name__ == '__main__': guess_number()
true
0432d04cba357f2abfb07d7e4281e8ca603c2839
ThibaMahlezana/data-structures-and-algorithms-in-python
/SortedLinkedList.py
1,864
4.15625
4
class Node(object): def __init__(self, value): self.info = value self.link = None class SortedLinkedList(object): def __init__(self): self.start = None def insert_in_order(self, data): temp = Node(data) # list empty or node to be inserted before first node if self.start == None or data < self.start.info: temp.link = self.start self.start = temp return p = self.start while p.link is not None and p.link.info <= data: p = p.link temp.link = p.link p.link = temp def create_list(self): n = int(input("Enter the number of nodes : ")) if n == 0: return for i in range(n): data = int(input("Enter the element to be inserted : ")) self.insert_in_order(data) def search(self, x): if self.start is None: print("List is empty") return p = self.start position = 1 while p is not None and p.info <= x: if p.info == x: break position += 1 p = p.link if p is None or p.info != x: print(x, " not found in the list") else: print(x, " is at position ", position) def display_list(self): if self.start is None: print("List is empty") return print("List is : ") p = self.start while p is not None: print(p.info, " ", end='') p = p.link print() ################################################################ list = SortedLinkedList() list.create_list() while True: print("1. Display list") print("2. Insert") print("3. Search for an element") print("4. Quit") option = int(input("Enter your choice : ")) if option == 1: list.display_list() elif option == 2: data = int(input("Enter the element to be inserted : ")) list.insert_in_order(data) elif option == 3: data = int(input("Enter the element to be searched : ")) list.search(data) elif option == 4: break else: print("Wrong option") print()
true
eeb8d3e0b0d0218ad23e1cc6a0e3a8e10f2dc3a5
u01217013/Python
/Learn/package.py
583
4.125
4
#搭配教學第12集 #封包就是包含模組的資料夾:用來整理、分類模組程式 > 檔案對應到模組,資料夾對應到封包 #專案的檔案配置 #專案資料夾 #-主程式.py #--封包資料夾 #---_init_.py #一定要有這個檔案,才會讓整個資料夾變成封包 #---模組一.py #使用封包 #import 封包名稱.模組名稱 #import 封包名稱.模組名稱 as 模組別名 #主程式在此 import main.point result=main.point.distance(3,4) print("距離:",result) import main.line result1=main.line.slope(1,1,3,3) print("斜率:",result1)
false
70e4f9788ef01cbc21b242f08a78b131df58f841
u01217013/Python
/Learn/set-dictionary.py
1,446
4.125
4
# -*- coding: utf-8 -*- #集合=一群資料,沒有順序性 用{} #判斷資料是否存在,使用in、not in 運算符號 #交集&,聯集| #差集-,反交集^ #字串可以拆解成集合 set=(字串) s1={3,4,5} print(3 in s1) print(10 not in s1) s1={3,4,5} s2={4,5,6,7} s3=s1&s2 #s1交集s2 &=交集,取兩個集合中,重疊的資料 s4=s1|s2 #s1聯集s2 |=聯集,取兩個集合中全部的資料,但不重複取 s5=s1-s2 #s1差集s2 -=差集,從s1中,減掉跟s2重疊的資料 s6=s1^s2 #s1反交集s2 ^=反交集,取兩個集合中,不重疊的資料 print(s3) print(s4) print(s5) print(s6) s=set("hello") #set(字串),可以自動把字串中的字母拆解成集合(會自動去掉重複的值),因為集合沒有順序性,所以print出來的資料是沒有順序性的 print(s) print("h" in s) #字典觀念,key-value Pair,key對應Value,字典[key],字典[key]=Value #字典使用{} #同集合,可使用in、not in判斷資料(key)是否存在,可用del刪除字典中的配對,也可以從列表建立字典 dic={"Apple":"蘋果","Bug":"蟲蟲"} print(dic["Apple"]) dic["Apple"]="小蘋果" print(dic["Apple"]) print("Apple" in dic) #判斷Key值是否存在 del dic["Apple"] #刪除字典中的key-value Pair(鍵值對) print(dic) #從列表的資料產生字典 dic={x:x*2 for x in [3,4,5]} #for跟in是固定的,in後面要放的是列表資料 print(dic)
false
ceb40a98b541f4c4d4f57e4dc8f0b55fddbe1e77
JKThanassi/2016_Brookhaven
/matplotLibTest/scatter_plot.py
716
4.1875
4
#import matplotlib.pyplot as plt def scatter_plt(plt): """ This function gathers input and creates a scatterplot and adds it to a pyplot object :param plt: the pyplot object passed through :return: Void """ #list init x = [] y = [] #get list length list_length = int(input("How many data sets would you like to enter")) #get input for i in range(0, list_length): x.append(int(input("enter x var for dataset " + str(i)))) y.append(int(input("enter y var for dataset " + str(i)))) print() #create scatterplot plt.scatter(x, y, marker='*') plt.xlabel("x") plt.ylabel("y") plt.title("Test scatter plt") #plt.show(
true
4719996798b9af38d079c61027de06311fecd766
PrinceCada/python-beginners
/HourglassPattern.py
891
4.25
4
#Hourglass Pattern def pattern(n): k = n - 2 for i in range(n, -1, -1): # This loop is for our outer rows for j in range(k, 0, -1): # This loop is for column print(end=" ") k = k + 1 for u in range(0, i + 1): # I do this loops because it is moving forward print("* ", end="") print("\r") k = 2 * n - 2 for i in range(0, n+1): # This loop is for our outer rows for j in range(0, k): # This loop is for column print(end=" ") k = k - 1 for u in range(0, i + 1): # I do this loops because it is moving forward print("* ", end="") print("\r") pattern(5) #Output * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
false
3a35d9cd924c6601a4caa47dbaaa88da5b8f51ac
RickSobreira/4LinuxPython
/aula01/ex01.py
1,395
4.15625
4
# x= int(input("Digite o primeiro valor da soma: ")) # y= int(input("Digite o segundo valor da soma: ")) # print( x + y) # num1 = 10 # num2 = 30 # print (num1 < num2) # num1 = 10 # num2 = 1 # if num1 > num2: # print("O primeiro valor é maior!") # else: # print("O primeiro valor na verdade é menor!") #x = int(input("Digite sua idade: ")) #if x >= 18: # y = input("Responda com Sim ou Não. Possui habilitação? ") # if y == "Sim": # print("Você pode dirigir!") # else: # print("Você precisa tirar a CNH!") #else: # print("Você ainda não tem idade para dirigir!") #x = int(input("Digite sua idade: ")) #y = input("Responda com Sim ou Não. Possui habilitação: ") #if x >=18 and y == "Sim": # print("Você está apto a dirigir!") #else: # print("Você precisa ser maior de idade ou tirar sua CNH!") #x = int(input("Digite sua idade: ")) #y = input("Responda com Sim ou Não. Possui habilitação: ") #if x >=18 or y == "Sim": # print("Você está apto a dirigir!") #else: # print("Você precisa ser maior de idade ou tirar sua CNH!") #nota1 = 5 #nota2 = 5.5 #nota3 = 4 #media = float(nota1 + nota2 + nota3)/3 #if media > 6: # print("Aprovado com: ",media) # if media < 4: # print("Reprovado com: ",media) #else: # print("Recuperação com: ",media)
false
ae0609e324953c971b69d8cec8b387fd85d4eab5
parthnvaswani/Hacktoberfest-2020-FizzBuzz
/Python/tddschn-fizzbuzz.py
888
4.3125
4
#!/usr/bin/env python3 # author: @tddschn # checking if a num is the multiples of 3 or 5 or 15 with simple math. import math import re def is_mul_of_15(num: int) -> bool: """ check if num is multiples of 15. :param num: the integer to check the integer must not be larger than 100. """ for i in range(1, math.ceil(100/15)+1): if num == i * 15: return True break return False def fb() -> None: """ Prints the required FizzBuzz """ for i in range(1, 101): s = str(i) if is_mul_of_15(i): print("FizzBuzz") elif re.search('[05]$', s): print("Buzz") continue elif sum((int(digit) for digit in s)) % 3 == 0: print("Fizz") else: print(i) def main() -> None: fb() if __name__ == '__main__': main()
true
901102cf12081a6b0b5f725a9182c738e9e23998
parthnvaswani/Hacktoberfest-2020-FizzBuzz
/Python/ElementaryMathFizzBuzz.py
965
4.21875
4
# Used elementary math techniques for checking if divisible by 3 and 5 # Added digits to check if it will be divisible by 3 # checked last digit if 0 or 5 to be divisible by 5 # author : @mikenmo def checkThree(digits): digitSum = 0 for i in digits: digitSum = digitSum + i if(digitSum > 9): digitSumDigits = list(map(int, list(str(digitSum)))) return(checkThree(digitSumDigits)) else: if(digitSum == 3 or digitSum == 6 or digitSum == 9): return True else: return False def checkFive(digits): if(digits[len(digits)-1] == 0 or digits[len(digits)-1] == 5): return True else: return False for i in range(1,101): ans = [] digits = list(map(int, list(str(i)))) if(checkThree(digits)): ans.append("Fizz") if(checkFive(digits)): ans.append("Buzz") if not ans: ans.append(i) print(''.join(str(i) for i in ans))
true
01ffc9ab85cbc85859bd84f0534a3077f1447bb4
parthnvaswani/Hacktoberfest-2020-FizzBuzz
/Python/FizzBuzz with Logical Indexing.py
629
4.15625
4
# FizzBuzz program in Python 3, to print numbers from 1 to 100 (with "Fizz" instead of multiples of 3, "Buzz" in place of multiples of 5, "FizzBuzz" against multiples of both 3 and 5 (i.e., multiples of 15)) # Author: @Git-Harshit # One way for logical indexing (done with list) for i in range(1, 100+1): print( [ i, [ "Buzz", ["Fizz", "FizzBuzz"][i%5==0] ][i%3 == 0] ][not(i%3 and i%5)] ) print() # Just a newline separator # Another way of logical indexing (done with tuple) for i in range(1, 100+1): print( ( (i, "Buzz")[i%5==0], ("Fizz", "FizzBuzz")[i%5==0] )[i%3==0] )
true