blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
92614454c9999c233b15ab0632e1979a0bf12ab9
rajesh-06/p243_assignment_2
/A2_q1b.py
1,351
4.46875
4
#To get the distance between 2 points def distance(x1, x2, y1, y2): if((x2-x1)>=0 and (y2-y1)>=0): return ((x2-x1)+(y2-y1)) elif((x2-x1)<=0 and (y2-y1)>=0): return ((x1-x2)+(y2-y1)) elif((x2-x1)<=0 and (y2-y1)<=0): return ((x1-x2)+(y1-y2)) elif((x2-x1)>=0 and (y2-y1)<=0): return ((x2-x1)+(y1-y2)) sum=0 n=0 print("To find the average distance between 2 points on a M by N two dimensional grid(no diagonal connection).") #Number of points in a column y= input ('Enter the number of points in a column: ') #number of points in a row x= input ('Enter the number of points in row: ') try: r = int(y) c = int(x) #Summing all the possible distances if (r>=0 and c>=0): for X1 in range(c): for X2 in range(c): for Y1 in range(r): for Y2 in range(r): sum+=distance(X1,X2,Y1,Y2) n+=1 print('The average distance between 2 points in the grid is:',sum/n) else: print('It is not possible to form a grid with the entered value.') except ValueError: print('It is not possible to form a grid with the entered value.') #Output #To find the average distance between 2 points on a M by N two dimensional grid(no diagonal connection). #Enter the number of points in a column: 6 #Enter the number of points in row: 6 #The average distance between 2 points in the grid is: 3.888888888888889 #[Program finished]
true
8385b2b48343cb5f0a05bfee4019caae8818dcd6
afrantisak/rubiks
/util.py
462
4.125
4
def reverse_turn(turn): flip = { 'F': 'Fi', 'Fi': 'F', 'R': 'Ri', 'Ri': 'R', 'L': 'Li', 'Li': 'L', 'U': 'Ui', 'Ui': 'U', 'D': 'Di', 'Di': 'D', 'B': 'Bi', 'Bi': 'B', } if turn in flip: return flip[str(turn)] return turn def reverse_move(move): move = reversed(move) move = [reverse_turn(turn) for turn in move] return move
false
5d9715b4afdbfaa7d627b2cb89012aa4a6e30f2f
codingtrivia/PythonLabs
/Intermediate/Lab3/Lab3.py
323
4.3125
4
# Using recursion, print only even numbers in descending order. For e.g. if I say, print_down(10), output would be: # 10 # 8 # 6 # 4 # 2 # You will need to do a slight modification in the code we wrote for print_up_down in our class today. # Hint: Use % operator def print_down(n): #<your code here> print_down(10)
true
614fdacddcea190226dedcb8fb9b30843d69f916
khadak-bogati/python_project
/LAB3.py
1,930
4.46875
4
print('When we set one variable B equal to A;\n both A and B are referencing the same list in memory:') # Copy (copy by reference) the list A A =["Khadak Bogati",10,1.2] B = A print('A:',A) print('B:',B) print('Initially, the value of the first element in B is set as hard rock. If we change the\n first element in A to banana, we get an unexpected side effect. As A and B are\n referencing the same list, if we change list A, then list B also changes. \nIf we check the first element of B we get banana instead of hard rock:') print('B[0]:', B[0]) A[0] = 'banana' print('B[0]:',B[0]) print('You can clone list A by using the following syntax:') B = A[:] print(B) print('Now if you change A, B will not change:') print('B[0]:', B[0]) A[0] = "hard rock" print('B[0]:', B[0]) # question 1 a_list = [1, 'hello', [1, 2, 3] , True] print(a_list) print(a_list[1]) print('Retrieve the elements stored at index 1, 2 and 3 of a_list.') print(a_list[1:4]) print("Concatenate the following lists A = [1, 'a'] and B = [2, 1, 'd']:") x = [1, 'a'] y = [2, 1, 'd'] print(x + y) output ............... When we set one variable B equal to A; both A and B are referencing the same list in memory: A: ['Khadak Bogati', 10, 1.2] B: ['Khadak Bogati', 10, 1.2] Initially, the value of the first element in B is set as hard rock. If we change the first element in A to banana, we get an unexpected side effect. As A and B are referencing the same list, if we change list A, then list B also changes. If we check the first element of B we get banana instead of hard rock: B[0]: Khadak Bogati B[0]: banana You can clone list A by using the following syntax: ['banana', 10, 1.2] Now if you change A, B will not change: B[0]: banana B[0]: banana [1, 'hello', [1, 2, 3], True] hello Retrieve the elements stored at index 1, 2 and 3 of a_list. ['hello', [1, 2, 3], True] Concatenate the following lists A = [1, 'a'] and B = [2, 1, 'd']: [1, 'a', 2, 1, 'd']
true
7dbfb9f5fbeaf8bc2dafd2003f3c0403140858db
khadak-bogati/python_project
/TypeerrorAndValueError.py
350
4.34375
4
myString = "This String is not a Number" try: print("Converting myString to int") print(1/0) print("String # " + 1 + ": "+ myString) myInt = int(myString) print(myInt) except (ValueError, TypeError) as error: print("A ValueError or TypeError occureed.") except Exception as error: print("Some other type of error occurred.") print("Done!")
true
396bdb1c3d00ef1c113ee7195ef1a754320b1a7b
khadak-bogati/python_project
/Function.py
2,605
4.5625
5
print("===========================================") print('An example of a function that adds on to the parameter a prints and returns the output as b:') def add(a): b = a + 1 print(a, 'if you add one', b) return(b) add(2) ........................ output =========================================== An example of a function that adds on to the parameter a prints and returns the output as b: 2 if you add one 3 ex================2 print("======================================") print("A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program. We will discuss more about global variables at \nthe end of the lab.") def square(a): b = 1 c = a * a + b print(a, "if you square + 1", c) return(c) print() print("=======================================") print("We can call the function with an input of ") square(5) x = 3 y = square(x) print(y) output ====================================== A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program. We will discuss more about global variables at the end of the lab. ======================================= We can call the function with an input of 5 if you square + 1 26 3 if you square + 1 10 10 ex=====================================3 print("==============================================") print("If there is no return statement, the function returns None.\n The following two functions are equivalent:") print() def MJ(): print('Michael Jackson') def MJ1(): print('Michael Jackson') return(None) MJ() MJ1() output ============================================== If there is no return statement, the function returns None. The following two functions are equivalent: Michael Jackson Michael Jackson ex==============================4 def Mult(a, b): c = a * b return(c) print(Mult(5, 6)) output ............. 30 ex=====================================5 print("==========================================") print("Function Definition") def square(a): #Local variable b b = 1 c = a * a + b print(a, "if you square + 1", c) return(c) x=5 z=square(x) ========================================== Function Definition 5 if you square + 1 26 ex===================================6 print("==========================================") print("Function Definition") def square(a): #Local variable b c = 1 b = a * a + c print(a, "if you square + 1", b) return(b) x=2 z=square(x) output ========================================== Function Definition 2 if you square + 1 5
true
4e2481ad72e8ecb600b9df438b9bda347be000e4
GabrieleMaurina/workspace
/python/stackoverflow/calculator.py
581
4.34375
4
print("Welcome to my calculator programme!") while True: # try: operator = input("Enter a operator (+,-,* or /): ") num_1 = int(input("Enter the first number: ")) num_2 = int(input("Enter the second number: ")) q = input('Press Q to quit to the programme...') if operator == '+': print(num_1+num_2) elif operator == '-': print(num_1-num_2) elif operator == '*': print(num_1*num_2) elif operator == '/': print(num_1/num_2) elif q == 'q': break
true
29c5b22e47aee010b7c4cb60cf8e66d8a72feb77
otomobao/Learn_python_the_hard_way_
/ex3.py
670
4.46875
4
#Showing what i am doing print "I will now count my chickens:" #Showing hens and caculate the number print "Hens", 25.0+30.0/6.0 #Showing roosters and the caculate the number print "Roosters",100.0-25.0*3.0%4.0 #Showing what i am going to do next print "Now I will count the eggs:" #Caculate the number and print print 3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6.0 #Explain print "Is it true that 3+2<5-7?" #Run print 3.0+2.0<5.0-7.0 print "What is 3+2?",3.0+2.0 print "Waht is 5-7?",5.0-7.0 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5.0>-2.0 print "Is it greater or equal?",5.0>=-2.0 print "Is it less or equal?", 5.0<=-2.0
true
335828ec29ec2bc55cedaba7f7b57529d3ed88b2
macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions
/CHAPTER 5/5-6. Stages of Life.py
265
4.21875
4
age=22 if age<2: person='a baby' elif age>=2 and age<4: person='a toddler' elif age>=4 and age<13: person= 'a kid' elif age>=13 and age<20: person='a teenager' elif age >=20 and age<65: person='an adult' else: person='an elder' print(f'The person is {person}')
false
2f8267f4d241dee5f2bf8ea05b5d4a53ebbd4fb1
codinglzc/liaoxuefengLearnPython
/build_in_module_itertools.py
2,000
4.25
4
# coding=utf-8 # itertools # Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数。 # 首先,我们看看itertools提供的几个"无限"迭代器: import itertools # 因为count()会创建一个无限的迭代器,所以下面代码会打印自然数序列,根本停不下来,只能按Ctrl+C退出。 natuals = itertools.count(1) for n in natuals: print n # cycle()会把传入的序列无限重复下去: cs = itertools.cycle('ABC') # 注意字符串也是序列的一种 for c in cs: print c # repeat()负责把一个元素无限重复下去,不过如果提供第二个参数就可以限定重复次数: ns = itertools.repeat('A', 10) for n in ns: print n # 无限序列只有在for迭代时才会无限地迭代下去,如果只是创建了一个迭代对象,它不会事先把无限个元素生成出来,事实上也不可能在内存中创建无限多个元素。 # 无限序列虽然可以无限迭代下去,但是通常我们会通过takewhile()等函数根据条件判断来截取出一个有限的序列: natuals = itertools.count(1) ns = itertools.takewhile(lambda x: x <= 10, natuals) for n in ns: print n # itertools提供的几个迭代器操作函数更加有用: # chain() # chain()可以把一组迭代对象串联起来,形成一个更大的迭代器: for c in itertools.chain('ABC', 'XYZ'): print c # groupby() # groupby()把迭代器中相邻的重复元素挑出来放在一起: for key, group in itertools.groupby('AAABBBCCAAA'): print key, list(group) # 为什么这里要用list()函数呢? # 实际上挑选规则是通过函数完成的,只要作用于函数的两个元素返回的值相等,这两个元素就被认为是在一组的,而函数返回值作为组的key。如果我们要忽略大小写分组,就可以让元素'A'和'a'都返回相同的key: for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()): print key, list(group)
false
bc5980fdfcd37b51dd917a31fd2ba10aba46cc04
SayantaDhara/project1
/printPositiveNo.py
261
4.15625
4
list1 = [] n = int(input("Enter number of elements : ")) print("Enter list terms") for i in range (0,n): elem = int(input()) list1.append(elem) print("Positive numbers are:") for num in list1: if num >= 0: print(num, end = " ")
true
e6f3ccfd56db33391bac8c893832ccb0b5891f6a
shabbirkhan0015/python_programs
/s2.py
280
4.25
4
m=[[]*3 for i in range(3)] l=[] for i in range(3): for j in range(3): x=int(input("enter an element")) m[i].append(x) print(m) for i in range(3): l.append(max(m[i])) print("largest element" ) print(max(l)) print("smallest element" ) print(min(l))
false
4a890456ce83401f6e3408d5c75d5f839a064ece
ConquestSolutions/Conquest-Extensions
/GetStarted/01-BasicCodeSamples/1.1-BasicCodeSamples.py
1,119
4.34375
4
########## # # THIS SCRIPT IS A LITTLE BASIC PYTHON IN THE CONTEXT OF THE CONQUEST EXTENSIONS CONSOLE # Copy this code into a console bit by bit from the top down to see how it all works. # ########## #Declare variable (change to your favourite number!) variable = 37 #Return variable print 'Variable: ' + str(variable) #Multiply variable and return it multipliedVariable = 9 * variable print 'Multiplied variable: ' + str(multipliedVariable) #Adding to a variable string is also easy companyName = 'companyName' companyName += ' ' companyName += 'companyName' print 'Company Name: ' + companyName #Create a reusable function - this function takes two arguments - team name and team nickname. It then joins them together in a string and prints the result. def printName(firstName, lastName): print 'Full Name: ' + firstName + ' ' + lastName printName('Person', 'A') #returns 'FirstName LastName' printName('Person', 'B') #IF STATEMENT #This statement will return TRUE as 'a' is bigger than 'b' a = 100 b = 2 if (a>b): print 'a is bigger than b' #This will return true else: print 'a is not bigger than b'
true
e609a51428b4d0526be7f16f6c11132035c38ff7
jwebster7/sorting-algorithms
/merge_sort.py
2,009
4.4375
4
def mergeSort(lst): ''' 1. Split the unsorted list into groups recursively until there is one element per group 2. Compare each of the elements and then group them 3. Repeat step 2 until the whole list is merged and sorted in the process * Time complexity: The worst-case runtime is O(nlog(n)) * Space complexity: Since we modify the list in place, the space is ~ O(n) ''' if len(lst) > 1: mid = len(lst) // 2 left = lst[:mid] right = lst[mid:] # print('before recursive call...') # print('\tleft half={}'.format(left)) # print('\tright half={}'.format(right)) mergeSort(left) mergeSort(right) # print('after recursive call...') i = k = j = 0 # print('\tleft half={}'.format(left)) # print('\tright half={}'.format(right)) # print('beginning the merge...') while i < len(left) and j < len(right): if left[i] < right[j]: lst[k] = left[i] i += 1 else: lst[k] = right[j] j += 1 # print('\ti={}, left={}'.format(i, left)) # print('\tj={}, right={}'.format(j, right)) # print('\tk={}, lst={}'.format(k, lst)) k += 1 # print('accounting for missed elements in the left half...') while i < len(left): lst[k] = left[i] i += 1 k += 1 # print('\ti={}, left={}'.format(i, left)) # print('\tk={}, lst={}'.format(k, lst)) # print('accounting for missed elements in the right half...') while j < len(right): lst[k] = right[j] j += 1 k += 1 # print('\tj={}, right={}'.format(i, right)) # print('\tk={}, lst={}'.format(k, lst)) lst = [0, 2, 3, 8, 4, 1, 7] print('unsorted list: \n\t{}'.format(lst)) print('using merge sort...') mergeSort(lst) print('sorted list: \n\t{}'.format(lst))
true
0895e45d8c44983ac75833f7c051ec28f26d32e4
mlopezqc/pymiami_recursion
/exercise1.py
1,364
4.59375
5
""" Exercise 1: Write a recursive function count_multiples(a, b) that counts how many multiples of a are part of the factorization of the number b. For example: >>> count_multiples(2, 4) # 2 * 2 = 4 1 >>> count_multiples(2, 12) # 2 * 2 * 3 = 12 2 >>> count_multiples(3, 11664) 6 >>> This send the state to any new call here we print the stack to see how the function s get accumulated there """ import traceback def count_multiples(a, b,counter=0): traceback.print_stack() if a > 1 and b>a: # Recursive case avoid 6/1(a>1) or 2/4() if b%a == 0: counter += 1 b= b/a return count_multiples(a, b, counter) else: #return (a, b, counter) return counter def main(): c= count_multiples(3, 11664) print(c) if __name__ == "__main__": main() # 1- 11664, 3, 0 # 2- 11664, 3, 0 # 3888, 3, 1 # 3- 11664, 3, 0 # 3888, 3, 1 # 1296, 3, 2 # 4- 11664, 3, 0 # 3888, 3, 1 # 1296, 3, 2 # 432, 3, 3 # 5- 11664, 3, 0 # 3888, 3, 1 # 1296, 3, 2 # 432, 3, 3 # 144, 3, 4 # 6- 11664, 3, 0 # 3888, 3, 1 # 1296, 3, 2 # 432, 3, 3 # 144, 3, 4 # 48, 3, 5 # 7- 11664, 3, 0 # 3888, 3, 1 # 1296, 3, 2 # 432, 3, 3 # 144, 3, 4 # 48, 3, 5 # 16, 3, 6
true
bcf713e9bbad134c881bf7f1ce293a46a1b3725c
idristuna/python_exercises
/in_out_exercise/q8.py
325
4.25
4
#! /usr/bin/python3 #using string.format to dispaly the data below totalMoney = int(input("Enter totalMoney")) quantity = int(input("Enter quantitiy")) price = int(input("Enter price")) statement1 = "I have {0} dollars so I can buy {1} football for {2:.2f} dollars " print(statement1.format(totalMoney, quantity, price))
true
04422bb36c79b62d156c21baf162e166a39e0222
pratyushagnihotri03/Python_Programming
/Python Files/14_MyTripToWalmartAndSet/main.py
202
4.125
4
groceries = {'cereal', 'milk', 'starcrunch', 'beer', 'duct tpe', 'lotion', 'beer'} print(groceries) if 'milk' in groceries: print("You have already a milk") else: print("Oh yea, you need milk")
true
78881030afd3c76d3e4bab9a4d69e72767ef4cf5
deltonmyalil/PythonInit
/classDemo.py
1,038
4.40625
4
class Students: def __init__(self,name,contact): #to define attribs of the class use def __init__(self,<attribute1>,<attribute2>,...) self.name = name self.contact = contact #name and contact are attribs and they are to be defined like this #once attribs are defined, you have to define the methods of the class def getData(self): #This is a method print("Accepting data") self.name = input("Enter Name>>>") self.contact = input("Enter Contact>>>") def putData(self): print("The Name is",self.name," and the contact number is ",self.contact) #Once the attribs and the methods are defined, we need to create the objects John = Students("Null",0) #This means that john is one of the objects of the Students class. # Also, Students have two attribs ie one string and one number # Hence, we have to initialize with the attribs of the class while creating an object of the class to avoid error John.getData() John.putData()
true
9ba11952aebc8ecf80527af333763082d15ff2f5
deltonmyalil/PythonInit
/numericFunctions.py
389
4.34375
4
#minimum function print(min(2,3,1,4,5)) numbers = [x for x in range(10)] #list generation print(numbers) print("the minimum is {0}".format(min(numbers))) #prints the minimum in numbers using format function print("The minimum is",(min(numbers)),"thank you") #max function print("The maximum value is {0}".format(max(numbers))) #absolute function print("Absolute value of -3 is",abs(-3))
true
f5d0698a74866606d1010c83ad6b335415995b94
nmoya/coding-practice
/Algorithms/queue.py
1,044
4.1875
4
#!/usr/bin/python import random import linkedlist class Queue(): def __init__(self): ''' A queue holds a pointer to a list. The elements are inserted at the end and removed from the front. (FIFO). ''' self.start = linkedlist.List() self.size = 0 def __repr__(self): _list = self.start.to_string() return ", ".join(_list) def to_list(self): return self.start.to_list() def is_empty(self): ''' Returns True if the queue is empty. False otherwise ''' return self.size == 0 def enqueue(self, value): ''' Insert a node with 'value' at the end of the list ''' self.start.append(value) self.size += 1 def dequeue(self): ''' Removes the first element from the queue ''' self.size -= 1 return self.start.remove_first() if __name__ == "__main__": q = Queue() for i in range(10): q.enqueue(i) print q print q.dequeue() print q.dequeue() print q.dequeue() print q
true
9ecad439ee39051487c0aa70e3a014f2b684389a
gkerkar/Python
/code/ada_lovelace_day.py
977
4.25
4
#!/bin/python3 import math import os import random import re import sys # # The function is expected to return an INTEGER. # The function accepts INTEGER year as parameter. # import calendar def ada(year): # Get October week days. oct_weeks = calendar.monthcalendar(year, 10) ada_first_week = oct_weeks[0] ada_second_week = oct_weeks[1] ada_third_week = oct_weeks[2] # If a Tuesday falls in the first week, the second Tuesday is in the second week # else the second Tuesday must be in the third week. if ada_first_week[calendar.TUESDAY]: ada_day = ada_second_week[calendar.TUESDAY] else: ada_day = ada_third_week[calendar.TUESDAY] # print("Ada Day is on {} .".format(ada_day)) return ada_day if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') year = int(input().strip()) result = ada(year) fptr.write(str(result) + '\n') fptr.close()
true
098a0d9ea413dfcef9301f73650acb2142cd0935
HissingPython/sandwich_loopy_functions
/Sandwich 8.py
2,386
4.46875
4
#Do you want a sandwich or not? def yes_no_maybe (answer): while True: if answer.upper() == 'Y' or answer =='N': break else: print ("Please enter 'Y' or 'N'.") answer = input ("Do you want to order a sandwich? (Press 'Y' for Yes and 'N' for No): ") #Determine the topping(s) desired. I plan on going back and appending sandwiches with 0 toppings to make "plain" their topping, but I want this to work first def what_do_you_want (toppings): toppings = [] topping = input ("\nWhat topping would you like on your sandwich? Enter toppings one at a time; enter 'Quit' when done: ") while True: if topping.lower() == 'quit': break else: toppings.append(topping) topping = input ("What other topping would you like on your sandwich? Enter toppings one at a time; enter 'Quit' when done.") #Adding this function seems to be when it all fell apart. I tested the first two and printed the toppings list and it worked fine. But now, it does now. :( #Emoticons in comments are totally awesome. Just like you ;-) def sandwich_construction(toppings): print ("Your sandwich is being made!") print ("\nIt will have these toppings: ") for topping in toppings: print (topping) answer = input ("Do you want to order a sandwich? (Press 'Y' for Yes and 'N' for No): ") #Run the function to see if we're playing this game or not yes_no_maybe(answer) #This loop might be the problem. I think the way I have it running it should start with no toppings, add them using the what_do_you_want function and #then break with the new list intact. However, it seems to be erasing the list alltogether. I thought changing lists in functions permanently #changed them - that's why we use slices if we're making a copy so we can have an original list. Am I wrong? Or did I something else entirely? #I didn't count characters, but I think I kept my line length reasonable for these comments. Because my hisses are Zen AF. '-'~~~~~~~~~~~ while True: if answer == 'N': break else: toppings = [] what_do_you_want(toppings) break sandwich_construction(toppings)
true
1dad422ce571ed3d24cd85c0c1c0e6273213fa6e
TOMfk/discover
/project1/rili.py
2,032
4.1875
4
def is_leap_year(year): """ 判断闰年 :param year: :return: """ return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def get_num_of_days_in_month(year, month): """ 获得每月的天数 :param year: :param month: :return: """ if month in (1, 3, 5, 7, 8, 10, 12): return 31 elif month in (4, 6, 9, 11): return 30 elif is_leap_year(year): return 29 return 28 def get_total_num_of_days(year, month): """ 获得1800年输入年月总天数 :param year: :param month: :return: """ days = 0 for y in range(1800, year): if is_leap_year(y): days += 366 else: days += 365 for m in range(1, month): days += get_num_of_days_in_month(year, m) return days def get_start_day(year, month): """ 获得输入年月的第一天星期几 :param year: :param month: :return: """ day = (3 + get_total_num_of_days(year, month)) % 7 if day == 0: day = 7 return day # print(get_start_day(2018, 7)) # print() def print_table_head(year, month): print(str(month) + "月 " + str(year) + "年") print("-----------------------------------------------------") l = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日") for i in l: print(format(i, "4"), end=" ") def print_calendar(year, month): print_table_head(year, month) days = get_num_of_days_in_month(year, month) start_day_of_week = get_start_day(year, month) # print(start_day_of_week) l = [] # for i in range(start_day_of_week): while start_day_of_week > 0: l.append("") start_day_of_week -= 1 for day in range(1, days + 1): l.append(day) for i in range(len(l)): print(format(l[i], '6'), end=" ") if i % 7 == 0: print() i -= 1 # print_calendar(2018, 7)
false
b480d970bf562a300ef1c05db6b06c15c0b580d7
adclleva/Python-Learning-Material
/automate_the_boring_stuff_material/06_Lists/list_methods.py
1,349
4.53125
5
# Methods # A method is the same thing as a function, except it is “called on” a value. # For example, if a list value were stored in spam, you would call the index() list method (which I’ll explain next) on that list like so: spam.index('hello'). # The method part comes after the value, separated by a period. # index method spam = ['hello', 'hi', 'howdy', 'heyas'] spam.index('hello') # 0 spam.index('heyas') # 3 # append() and insert() spam = ['cat', 'dog', 'bat'] spam.append('moose') spam # ['cat', 'dog', 'bat', 'moose'] spam = ['cat', 'dog', 'bat'] spam.insert(1, 'chicken') spam # ['cat', 'chicken', 'dog', 'bat'] # Removing Values from Lists with remove() # It would remove the first instance spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat'] spam.remove('cat') spam # ['bat', 'rat', 'cat', 'hat', 'cat'] # Sorting the Values in a List with the sort() Method spam = [2, 5, 3.14, 1, -7] spam.sort() spam # [-7, 1, 2, 3.14, 5] spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] spam.sort() spam # ['ants', 'badgers', 'cats', 'dogs', 'elephants'] # You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order. # Enter the following into the interactive shell: # Sorting happens in ASCII-betical order spam.sort(reverse=True) spam ['elephants', 'dogs', 'cats', 'badgers', 'ants']
true
d2f5afeaf363d8566d343a7be28a469d3990f198
adclleva/Python-Learning-Material
/automate_the_boring_stuff_material/07_Dictionaries/dictionary_data_type.py
2,480
4.53125
5
# The Dictionary Data Type # Like a list, a dictionary is a collection of many values. # But unlike indexes for lists, indexes for dictionaries can use many different data types, # not just integers. Indexes for dictionaries are called keys, # and a key with its associated value is called a key-value pair. # Dictionaries are mutable # Dictionaries are unordered unlike lists eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'} ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'} eggs == ham # True # Checking Whether a Key or Value Exists in a Dictionary spam = {'name': 'Zophie', 'age': 7} 'name' in spam.keys() # True 'Zophie' in spam.values() # True 'color' in spam.keys() # False 'color' not in spam.keys() # True 'color' in spam # False # you can use list methods on dictionaries spam = {'color': 'red', 'age': 42} print(spam.keys()) # dict_keys(['color', 'age']) print(list(spam.keys())) # ['color', 'age'] print(list(eggs.keys())) # ['name', 'species', 'age'] for v in eggs.values(): print(v) # Zophie # cat # 8 print() for k in eggs.keys(): print(k) # name # species # age for k, v in eggs.items(): print(k, v) # name Zophie # species cat # age 8 # tuples are immutable lists # in this case it returns a tuple of the key and value below for i in eggs.items(): print(i) # ('name', 'Zophie') # ('species', 'cat') # ('age', '8') # get() method # It’s tedious to check whether a key exists in a dictionary before accessing that key’s value. # Get() method that takes two arguments: the key of the value to retrieve # and a fallback value to return if that key does not exist. picnicItems = {'apples': 5, 'cups': 2} 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.' # 'I am bringing 2 cups.' 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.' # 'I am bringing 0 eggs.' # The setdefault() Method spam = {'name': 'Pooka', 'age': 5} spam.setdefault('color', 'black') # 'black' print(spam) # {'color': 'black', 'age': 5, 'name': 'Pooka'} spam.setdefault('color', 'white') # 'black' print(spam) # {'color': 'black', 'age': 5, 'name': 'Pooka'} # The first time setdefault() is called, the dictionary in spam changes to {'color': 'black', 'age': 5, 'name': 'Pooka'}. # The method returns the value 'black' because this is now the value set for the key 'color'. # When spam.setdefault('color', 'white') is called next, the value for that key is not changed to 'white' because spam already has a key named 'color'.
true
a7d36e5aeefa0964601ae213b2029c5c6bcdedbe
bashbash96/InterviewPreparation
/LeetCode/Facebook/Medium/49. Group Anagrams.py
1,483
4.125
4
""" Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lower-case English letters. """ from collections import defaultdict, Counter class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ word_key_map = defaultdict(list) for word in strs: key = get_key(word) word_key_map[key].append(word) res = [] for key, val in word_key_map.items(): res.append(val) return res # time O(n * m) m: max string length # space O(n * m) def get_key(word): chars_count = [0] * 26 for c in word: chars_count[ord(c) - ord('a')] += 1 return tuple(chars_count) """ # time O(n * m log (m)) m: avg length of string # space O(n * m) ["eat","tea","tan","ate","nat","bat"] eat -> a1e1t1 # time O(n * (m + klog(k))) m: avg length, k: avg unique chars -> constant -> O(n * m) # space O(n * m) """
true
0ab6cb2ca6a679b9692f841f095074e3d0e0bf4b
bashbash96/InterviewPreparation
/LeetCode/Facebook/Medium/1762. Buildings With an Ocean View.py
1,552
4.53125
5
""" There are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height. Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order. Example 1: Input: heights = [4,2,3,1] Output: [0,2,3] Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller. Example 2: Input: heights = [4,3,2,1] Output: [0,1,2,3] Explanation: All the buildings have an ocean view. Example 3: Input: heights = [1,3,2,4] Output: [3] Explanation: Only building 3 has an ocean view. Example 4: Input: heights = [2,2,2,2] Output: [3] Explanation: Buildings cannot see the ocean if there are buildings of the same height to its right. Constraints: 1 <= heights.length <= 105 1 <= heights[i] <= 109 """ class Solution(object): def findBuildings(self, heights): """ :type heights: List[int] :rtype: List[int] """ n = len(heights) if not heights: return [] curr_max = heights[-1] res = [n - 1] for i in range(n - 2, -1, -1): if heights[i] > curr_max: res.append(i) curr_max = heights[i] return res[::-1] # time O(n) # space O(1) without the result
true
bca11339ec5f1b4604f5d2aba56878720c3ac9da
bashbash96/InterviewPreparation
/LeetCode/Facebook/Easy/21. Merge Two Sorted Lists.py
1,227
4.1875
4
""" Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. Example 1: Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: l1 = [], l2 = [] Output: [] Example 3: Input: l1 = [], l2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both l1 and l2 are sorted in non-decreasing order. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ res = ListNode('DUMMY') curr = res while l1 or l2: val1 = l1.val if l1 else float('inf') val2 = l2.val if l2 else float('inf') if val1 < val2: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next return res.next # time O(n) # space O(1)
true
86d82f81e410a7eb16c98b250d5e60c659da5a26
VladOsiichuk/python_base_public
/lesson_7/array_generators.py
1,821
4.125
4
def get_only_digits_array(arr): """ :param arr: list of some values :return: list of values which are digits """ print(arr) """ Дана функція еквівалентна наступним рядкам output_array = list() for n in arr: if isinstance(n, int) or (isinstance(n, str) and n.isdigit()): output_array.append(n) return output_array """ output_array = [ n for n in arr if isinstance(n, int) or (isinstance(n, str) and n.isdigit()) ] return output_array def get_values_from_nested_arrays_to_one_array(arr): """ :param arr: Array of nested arrays (matrix) :return: Array with values from nested arrays """ """ Ця функція еквівалентна наступним рядкам output_value = list() for i in arr: if not isinstance(i, list): i = [i] for value in i: output_array.append(value) return output_value """ """ [[1, 2, 3], [4, 5, 6], [7, 8, 9], 10] """ output_value = [ value for nested_array in arr for value in ([nested_array] if not isinstance(nested_array, list) else nested_array) ] return output_value def main(): """ Генерація списку зі значень від 0 до 9 """ """ Рядок нижче еквівалентний ось цьому arr = list() for i in range(10): arr.append(i) """ # arr = [i for i in "Python"] # print(arr) # print(type(arr)) # print(get_only_digits_array(["1", 2, "3", "a", "b"])) print(get_values_from_nested_arrays_to_one_array([[1, 2, 3], [4, 5, 6], [7, 8, 9], 10])) if __name__ == "__main__": main()
false
17db529c69a7dddc44ab85fcccc698cc136ef774
VladOsiichuk/python_base_public
/lesson_9/iterate_in_dict.py
233
4.28125
4
people_years = {"Andriy": 18, "Olena": 22, "Iryna": 19} for key in people_years: print(key) for value in people_years.values(): print(value) for name, year in people_years.items(): print(f"{name} is {year} years old")
false
9dc4874947764da50df7f064e85a48f8da0e1427
allisongorman/LearnPython
/ex6.py
975
4.46875
4
# The variable x is a string with a number x = "There are %d types of people." % 10 # The variable is a string binary = "binary" # The variable is a string do_not = "don't" # The variable is a string that contains to string variables (1) y = "Those who know %s and those who %s." % (binary, do_not) # Display each string print x print y # Print string with variable x that is a string (2) print "I said: %r." %x # Print string with variable y that is a string (3) print "I also said: '%s'." %y # Variable is equal to false hilarious = False # Evaluation is dependent on what is chosen for 'r' (4) joke_evaluation = "Isn't that joke so funny?! %r" # Print line and value of 'r' is equal to hilarious variable. This variable is false. (5) print joke_evaluation % hilarious # The variable is a string w = "This is the left side of..." # The variable is a string e = "a string with a right side." # Print strings together (6) print w + e
true
864ca61914c5ed4fc07f60ac7809d780d0d1ead9
prkuna/Python
/24_Slicing_ListComprehension_Multi_Input.py
704
4.15625
4
# Let us first create a list to demonstrate slicing # lst contains all number from 1 to 10 lst = list(range(1,11)) print(lst) # below list has number from 2 to 5 lst1_5 = lst[1:5] print(lst1_5) # below list has numbers from 6 to 8 lst5_8 = lst[5:8] print (lst5_8) # below list has numbers from 2 to 10 lst1_ = lst[1:] print (lst1_) # below list has numbers from 1 to 5 lst_5 = lst[:5] print (lst_5) # below list has numbers from 2 to 8 in step 2 lst1_8_2 = lst[1:8:2] print (lst1_8_2) # below list has numbers from 10 to 1 lst_rev = lst[::-1] print (lst_rev) # below list has numbers from 10 to 6 in step 2 lst_rev_9_5_2 = lst[9:4:-2] print (lst_rev_9_5_2)
true
15b3aa68352d4d0e61561fba36d67a3313b73d10
prkuna/Python
/33_Operator_All.py
710
4.40625
4
# Here all the iterables are True so all # will return True and the same will be printed print (all([True, True, True, True])) # Here the method will short-circuit at the # first item (False) and will return False. print (all([False, True, True, False])) # This statement will return False, as no # True is found in the iterables print (all([False, False, False])) print() """ """ # Take two list list1 = [] list2 = [] # All numbers in list1 are in form: 4*i-3 for i in range(1,21): list1.append(4*i-3) # list2 stores info of odd numbers in list1 for i in range(0,20): list2.append(list1[i]%2==1) print('See whether all numbers in list1 are odd:') print(all(list2))
true
f3677abd9e2f6cfd571168968da284db06a3264e
dmonisankar/pythonworks
/DataScienceWithPython/sample_python_code/iteration/iteration2.py
949
4.75
5
# Create an iterator for range(3): small_value small_value = iter(range(3)) # Print the values in small_value print(next(small_value)) print(next(small_value)) print(next(small_value)) # Loop over range(3) and print the values for i in range(3): print(i) # Create an iterator for range(10 ** 100): googol googol = iter(range(10 ** 100)) # range() doesn't actually create the list; instead, it creates a range object with an iterator that produces the values until it reaches the limit (in the example, until the value 4). If range() created the actual list, calling it with a value of 10100 may not work, especially since a number as big as that may go over a regular computer's memory. The value 10100 is actually what's called a Googol which is a 1 followed by a hundred 0s. That's a huge number! # Print the first 5 values from googol print(next(googol)) print(next(googol)) print(next(googol)) print(next(googol)) print(next(googol))
true
4dbdc22f0297113db71b3be921e829e7a0af9cfc
naaeef/signalflowgrapher
/src/signalflowgrapher/common/geometry.py
1,897
4.1875
4
import math # taken from: # https://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python def rotate(origin, point, angle): """ Rotate a point counterclockwise by a given angle around a given origin. The angle should be given in radians. """ ox = origin[0] oy = origin[1] px = point[0] py = point[1] qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy) qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy) return qx, qy def move(point_1, point_2, delta): """ Move a point delta pixel from point_1 towards point_2 """ vector_x = point_2[0] - point_1[0] vector_y = point_2[1] - point_1[1] length = math.sqrt(math.pow(abs(vector_x), 2) + math.pow(abs(vector_y), 2)) if length == 0: raise ValueError( "Unable to calculate angle. Given points have same position.") norm_x = vector_x / length norm_y = vector_y / length return point_1[0] + delta * norm_x, point_1[1] + delta * norm_y def distance(point_1, point_2): """ Calculate the distance between two points """ vector_x = point_2[0] - point_1[0] vector_y = point_2[1] - point_1[1] return math.sqrt(math.pow(abs(vector_x), 2) + math.pow(abs(vector_y), 2)) def collinear(points): """ Returns true, if the given points are all collinear which means, they are on the same line. If the function is called with less than 3 points, it will always return true. """ if (len(points) < 3): return True if (len(points) == 3): return (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]) \ == (points[2][1] - points[1][1]) * (points[1][0] - points[0][0]) # loop for i in range(len(points) - 2): if (not collinear(points[i:i+3])): return False return True
true
6571604b6d7c0da12ec7ca49c79f22e25f58031e
michaelnakai/PythonProject
/print.py
1,327
4.375
4
# Demonstration of the print statement # Other information # print("Hello World") # print('Hello World') # print("I can't do it") # print('Michael sure "tries"') # # Escape Characters # print('This is the first line \nThis is the second line') # # print integer and an integer string # print(35) # print('35') # # Concatenation combining strings # firstname = "Michael" # this is an inline comment # lastname = "Nakai" # this stores the users last name # print(firstname + " " + lastname) # # other options # print (firstname,lastname) # print ('{0} first Name {1} last name'.format(firstname, lastname)) # print ('{1} first Name {0} last name'.format(firstname, lastname)) # # printing integers # firstnumber = 5 # secondnumber = 10 # print(firstnumber + secondnumber) # print(firstnumber, secondnumber) # print('{0} is greater than {1}'.format(firstnumber, secondnumber)) # perform math function # floating number hightestscore = 0.9372 # floating point number lowtestscore = 0.4598 # floating point number print('The high score was ' + str(hightestscore) + '\nthe low test score was ' + str(lowtestscore)) print('The high score was {0:.2f}\nthe low test score was {1:.2f}'.format(hightestscore,lowtestscore)) print ('The print a list of things\n' 'Apple\n' 'Banana\n' 'Orange\n')
true
7e77da4149037d49b2d915cbf27689ff01f8dde4
laraib-sidd/Data-Structures-And-Algortihms
/Data Structures/Array/Merge Array.py
788
4.21875
4
""" Shortcut way def mergesortedarr(a,b): x=a+b x.sort() return x a=[1,2,3,4] b=[3,7,9,12] qw=mergesortedarr(a,b) print(qws) """ # In interview we must solve only like this def mergesortarray(arr1, arr2): ''' Function to implement merge ''' if len(arr1) == 0 or len(arr2) == 0: return arr1 + arr2 mereged_array = [] i = 0 j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: mereged_array.append(arr1[i]) i += 1 elif arr1[i] > arr2[j]: mereged_array.append(arr2[j]) j += 1 return mereged_array+arr1[i:]+arr2[j:] # Driver Code if __name__ == "__main__": a = [1, 3, 4, 6, 20] b = [2, 3, 4, 5, 6, 9, 11, 76] arr = mergesortarray(a, b) print(arr)
false
387646766e4bfb174e1007b4586aa5a178149a50
laraib-sidd/Data-Structures-And-Algortihms
/Data Structures/Array/String reverse.py
505
4.34375
4
''' Function to reverse a string. Driver Code: Input : "Hi how are you?" Output : "?uoy era woh iH" ''' def reverse(string): """ Function to reverse string """ try: if string or len(string) > 2: string = list(string) string = string[::-1] string = "".join(string) return string except KeyboardInterrupt: print("Check Your Input") if __name__ == "__main__": word = reverse("This function Reverses string") print(word)
true
c982cc2c3ae1d0c70ed0ba17f0535bc9f0b349d6
onkar444/Tkinter-simple-projects
/Rock_Paper_Scissors_Game.py
2,363
4.3125
4
#importing the required libraries import random import tkinter as tk #create a window for our game window=tk.Tk() window.title("Rock Paper Scissors") window.geometry("400x300") #now define the global variables that we are going to #use in our program USER_SCORE=0 COMP_SCORE=0 USER_CHOICE="" COMP_CHOICE="" #define the functions to get the users choice to a number def choice_to_number(choice): rps={"rock":0,"paper":1,"scissor":2} return rps[choice] def number_to_choice(number): rps={0:"rock",1:"paper",2:"scissor"} return rps[number] #define function to get the computers choice def random_computer_choice(): return random.choice(['rock','paper','scissor']) #Now we define the most important function def result(human_choice,comp_choice): global USER_SCORE global COMP_SCORE user=choice_to_number(human_choice) comp=choice_to_number(comp_choice) if(user==comp): print("Tie") elif((user-comp)%3==1): print("You Win") USER_SCORE+=1 else: print("Comp Wins") COMP_SCORE+=1 text_area=tk.Text(master=window,height=12,width=30,bg="#ffff99") text_area.grid(column=0,row=4) answer=("Your Choice: {uc} \nComputer's Choice: {cc} \nYour Score: {u} \nComputer Score: {c}".format(uc=USER_CHOICE,cc=COMP_CHOICE,u=USER_SCORE,c=COMP_SCORE)) text_area.insert(tk.END,answer) #now lets define three methods for the 3 different chocies def rock(): global USER_CHOICE global COMP_CHOICE USER_CHOICE='rock' COMP_CHOICE=random_computer_choice() result(USER_CHOICE,COMP_CHOICE) def paper(): global USER_CHOICE global COMP_CHOICE USER_CHOICE='paper' COMP_CHOICE=random_computer_choice() result(USER_CHOICE,COMP_CHOICE) def scissor(): global USER_CHOICE global COMP_CHOICE USER_CHOICE='scissor' COMP_CHOICE=random_computer_choice() result(USER_CHOICE,COMP_CHOICE) #Now lets define 3 buttons so that the user can click them #and play the game button1=tk.Button(text=" Rock ",bg="skyblue",command=rock) button1.grid(column=0,row=1) button2=tk.Button(text=" Paper ",bg="pink",command=paper) button2.grid(column=0,row=2) button3=tk.Button(text=" Scissor",bg="lightgreen",command=scissor) button3.grid(column=0,row=3) #and we finally our favourite line; window.mainloop()
true
95171efb5910f91d9862c370014134e18dffbadc
ucsd-cse8a-w20/ucsd-cse8a-w20.github.io
/lectures/CSE8AW20-01-09-Lec2-Functions/functions.py
351
4.15625
4
# takes two numbers and returns the sum # of their squares def sum_of_squares(x, y): return x * x + y * y test1 = sum_of_squares(4, 5) test2 = sum_of_squares(-2, 3) # NOTE -- try moving test1/test2 above function definition? # takes two strings and produces the sum # of their lengths def sum_of_lengths(s1, s2): return len(s1) + len(s2)
true
a49d236fd70cf2c4c6456a1a36972143b7de6ae7
sttagent/impractical-python-projects
/PigLatin/pig_latin.py
460
4.125
4
def convert_to_pig_latin(word): is_vowel = test_if_vowel(word[0]) if is_vowel: converted_word = word + 'way' else: partitioned_word = word.partition(word[0]) converted_word = partitioned_word[2] + partitioned_word[1] + 'ay' return converted_word def test_if_vowel(letter): vowels = ('a', 'e', 'i', 'u', 'o') if letter in vowels: is_vowel = True else: is_vowel = False return is_vowel
false
ebfa533261b02fe4b7799167b266d177eb1ba818
luismmontielg/project-euler
/euler001.py
737
4.1875
4
print """ Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ------------------------------------------------------------------------------ 1 + 2 + 3 + 4 + ... + N = (N*(N+1)/2) The sequences for any number divisible by n can be written as n*N*(N+1)/2... Divisible by 3: 3 + 6 + 9 + 12 + ... + 999 = 3 * (1 + 2 + 3 + 4 + ... + 333) """ def sum_divisibles(a, b): """ sum of n first multiples of x = x*n*(n+1)/2 n = b/a """ return a * (b/a) * ((b/a) + 1) / 2 print "result:" print sum_divisibles(3, 999) + sum_divisibles(5, 999) - sum_divisibles(15, 999)
true
bcb419aeccdb8d5d2b4187f501dd7b1a23be5f9c
shen-huang/selfteaching-python-camp
/19100104/imjingjingli/d3_exercise_calculator.py
1,538
4.3125
4
# 定义函数 def add(x, y): """ 加法运算 parameter x: 被加数 parameter y: 加数 return x + y: 和 """ return x + y def subtract(x, y): """ 减法运算 parameter x:被减数 parameter y:减数 return x - y:差 """ return x - y def multiply(x, y): """ 乘法运算 parameter x:被乘数 parameter y:乘数 return x * y:积 """ return x * y def divide(x, y): """ 除法运算 parameter x:被除数 parameter y:除数 return x / y:商 """ return x / y # 用户输入 print("选择运算:") print("1、相加") print("2、相减") print("3、相乘") print("4、相除") while True: #如果运算结果正确则无限循环 choice = input("输入你要进行的运算(1/2/3/4):") if choice == '1': num1 = int(input("输入第一个数字: ")) num2 = int(input("输入第二个数字: ")) print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': num1 = int(input("输入第一个数字: ")) num2 = int(input("输入第二个数字: ")) print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': num1 = int(input("输入第一个数字: ")) num2 = int(input("输入第二个数字: ")) print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': num1 = int(input("输入第一个数字: ")) num2 = int(input("输入第二个数字: ")) print(num1,"/",num2,"=", divide(num1,num2)) else: print("非法输入")
false
44e1e5c8fc57a96622c7bc7a0037e985091566eb
shen-huang/selfteaching-python-camp
/19100102/jynbest6066/d3_exercise_calculator.py
668
4.15625
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") calculator = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if calculator == '1': print('result:', add(num1, num2)) elif calculator == '2': print('result:', subtract(num1, num2)) elif calculator == '3': print('result:', multiply(num1, num2)) elif calculator == '4': print ('result:', divide(num1, num2)) else: print("Invalid input")
false
35bcd5fe3a3bd0ad94cba7ac9ed045010c1b820f
shen-huang/selfteaching-python-camp
/19100304/lllp1736/d3_exercise_calculator.py
725
4.15625
4
#简易版本计算器 # 加 def add(x, y): return x + y # 减 def subtract(x, y): return x - y # 乘 def multiply(x, y): return x * y # 除 def divide(x, y) return x / y print("选择对应的运算方式") print("1.加") print("2.减") print("3.乘") print("4.除") choice = input("输入(1/2/3/4):") num1 = int(input("输入第一个数字")) num2 = int(input("输入第一个数字")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice =='2': print(num1, "+", num2, "=", subtract(num1, num2)) elif choice =='3': print(num1, "+", num2, "=", multiply(num1, num2)) elif choice =='4': print(num1, "+", num2, "=", divide(num1, num2)) else: print("错误输入")
false
848266fdc465abc24c86f094f45b2fdc7c825a5a
shen-huang/selfteaching-python-camp
/exercises/1901050117/1001S02E03_calculator.py
365
4.15625
4
operator=input('enter your operator(+、-、*、/): ') number_1=input('enter your first number: ') number_2=input('enter your second number: ') a=int (number_1) b=int (number_2) #addition print("{}+{}={}".format(a,b,a+b)) #subtraction print("{}-{}={}".format(a,b,a-b)) #multiplication print("{}*{}={}".format(a,b,a*b)) #division print("{}/{}={}".format(a,b,a/b))
false
d3663009bc284e80647393c9de19544fc90bec96
shen-huang/selfteaching-python-camp
/19100303/Luchen1471/d3_exercise_calculator.py
671
4.125
4
# Fibonacci series: #a, b = 0, 1 #print('\nThe fibonacci series is:') #while a<100: # print(a, end=" ") # a, b=b, a+b #print('...\n') print('\nHello! I\'d like to help you to do the math homework. Feel free to try me!') x=float(input("Please tell me a float number here:")) #A=input("please tell me what kind of operation you want:") y=float(input("Please tell me another float number here:")) print('\nTa-daaa! The resaults are:') #print('x+y=',round(x+y,2)) #print('x-y=',round(x-y,2)) #print('x*y=',round(x*y,2)) #print('x/y=',round(x/y,2)) li = [x+y,x-y,x*y,x/y] i = 0 for op in ["+", "-", "*", "/"]: print('x{}y'.format(op),'=',li[i] ) i += 1 print('\n')
false
60d6ca3d2a88bd66ab05ed6a179a52c5256a71ec
shen-huang/selfteaching-python-camp
/exercises/1901100258/1001S02E03_calculator.py
480
4.1875
4
operator = input('Please enter an operator (+, -, *, /) : ') first_number = input('Please enter the first number : ') second_number = input('Please enter the second number : ') a = int(first_number) b = int(second_number) if operator == '+': print(a, '+', b, '=', a + b) elif operator == '-': print(a, '-', b, '=', a - b) elif operator == '*': print(a, '*', b, '=', a * b) elif operator == '/': print(a, '/', b, '=', a / b) else: print('Null operator')
true
d7996d9ef1923366651cf33969e97933e7222297
shen-huang/selfteaching-python-camp
/exercises/1901100017/1001S02E03_calculator.py
875
4.15625
4
# calculator # filename 1001S02E03_calculator.py firstchoice = 1 calculatchoice = 0 while firstchoice == 1: print("this is a calculator program 1. use calculator 2. end") firstchoice = int(input("what is your choice ")) if firstchoice == 1: print("I can do 1. plus 2. minus 3. multiply 4. divide") calculatchoice = int(input("which calculation would you like ")) number1 = float(input("please enter the first number ")) number2 = float(input("please enter the second number ")) if calculatchoice == 1: result = number1 + number2 elif calculatchoice == 2: result = number1 - number2 elif calculatchoice == 3: result = number1 * number2 else: result = number1 / number2 print("result is ", result) else: print("goodbye!")
true
040f0149ae74fa525eae37ac866dece09fb1fdd8
shen-huang/selfteaching-python-camp
/19100304/yeerya/d3_exercise_calculator.py
757
4.1875
4
def add(x,y): """相加""" return x+y def subtract(x,y): """相减""" return x-y def multiply(x,y): """相乘""" return x*y def divide(x,y): """相除""" return x/y print("请选择运算:") print("1、相加") print("2、相减") print("3、相乘") print("4、相除") choice=input("请输入你的选择(1/2/3/4):") num1=int(input("请输入第一个数字:")) num2=int(input("请输入第二个数字:")) if choice=='1': print(num1,"+",num2,"=",add(num1,num2)) elif choice=='2': print(num1,"-",num2,"=",subtract(num1,num2)) elif choice=='3': print(num1,"*",num2,"=",multiply(num1,num2)) elif choice=='4': print(num1,"/",num2,"=",divide(num1,num2)) else: print("输入有误、请重新输入")
false
fdaa0f8d2e6dd84e15cd207cd4c11163acb07371
shen-huang/selfteaching-python-camp
/exercises/1901100148/1001S02E03_calculator.py
1,274
4.3125
4
# 这是单行注释 ''' 这是 多行注释 注释的作用只是方便我们理解代码,并不参与执行 ''' """ 这也是 多行注释 """ # 计算器确定三个输入值,分别是运算符、运算符左边的数字和右边的数字 # 把内置函数 input 接收的 输入字符 赋值 给 变量 operator=input('请输入运算符(+、-、*、/):') # input里面的字符串的作用是在等待输入的时候进行提示 first_number=input('请输入第一个数字:') second_number=input('请输入第二个数字:') a=int(first_number) # int(first_number) 在这里的作用是 把 str 类型 的 first_number 转换成 int 类型 b=int(second_number) print('operator:',operator,type(operator)) print('first_number:',first_number,type(first_number),type(a)) print('second_number:',second_number,type(second_number),type(b)) print('测试加法 str 加法:',first_number + second_number) # print('测试加法 str 减去:',first_number - second_number) if operator == '+': print(a,'+',b,'=',a+b) elif operator == '-': print(a,'-',b,'=',a-b) elif operator == '*': print(a,'*',b,'=',a*b) elif operator == '/': print(a,'/',b,'=',a/b) else: print('无效的运算符') # raise ValueError('无效的运算符')
false
d080f97ad8eceef9ba2b6f15771f54c3a2036cf7
shen-huang/selfteaching-python-camp
/exercises/1901010074/1001S02E03_calculator.py
864
4.15625
4
def add(num1,num2): return num1 + num2 def subtract(num1,num2): return num1 - num2 def multiply(num1,num2): return num1 * num2 def divide(num1,num2): return num1 / num2 print("please select operation -\n" \ "1. ADD\n" \ "2. Subtract\n" \ "3. Multiply\n" \ "4. Divide \n" ) # Take input from user select = input("Select operations form 1,2,3,4:") number_1 =int(input("input first number:")) number_2 =int(input("input second number")) if select =="1": print(number_1+ "+" + number_2 + "=",add(number_1,number_2)) elif select == "2": print(number_1 ,"-", number_2,"=",subtract(number_1,number_2)) elif select == "3": print(number_1 + "*"+ number_2+"=",multiply(number_1,number_2)) elif select == "4": print(number_1 + "/"+ number_2+"=",divide(number_1,number_2)) else: print("Invalid input")
false
ad287d0f899615c6bc9d13c813b564133633c76a
shen-huang/selfteaching-python-camp
/19100301/Xuzhengfu/d5_exercise_array.py
917
4.21875
4
# 三、数组操作,进制转换 # 1、…… # 2、将数组 [0,1,2,3,4,5,6,7,8,9] 翻转 numbers = [0,1,2,3,4,5,6,7,8,9] numbers.reverse() # 3、翻转后的数组拼接成字符串 num_str_list = [str(num_str) for num_str in numbers] # 使用list comprehension生成列表 numbers_str = "".join(num_str_list) # Join all items in the list "num_str_list" into the string "numbers_str" # 4、用字符串切片的方式取出第三到第八个字符(包含第三和第八个字符) substring = numbers_str[2:8] # 5、将获得的字符串进行翻转 substring = substring[::-1] # 6、将结果转换为int类型 subint = int(substring) # 7、分别转换成二进制,八进制,十六进制 bin_result = bin(subint) oct_result = oct(subint) hex_result = hex(subint) # 8、最后输出三种进制的结果 print(bin_result, oct_result, hex_result, sep="\n")
false
b12a49beb2e4b3c5bcd812c463bcc9e70282f0e6
shen-huang/selfteaching-python-camp
/exercises/1901100030/1001S02E05_array.py
943
4.25
4
# day5 字符串练习 # 2019年7月9日 # 陈浩 学号 1901100030 #对列表进行翻转 sample_list = [0,1,2,3,4,5,6,7,8,9] #print(sample_list) #<<<<<<< master #======= #reversed_list = sample_list.reverse() #>>>>>>> master sample_list.reverse() reversed_list = sample_list print(reversed_list) #拼接字符串 #<<<<<<< master #join_str="" #for i in reversed_list: # join_str = join_str + str(i) join_str = "".join([str(i) for i in reversed_list]) #======= join_str="" for i in reversed_list: join_str = join_str + str(i) #>>>>>>> master print(join_str) #切片取出3到8字符 sliced_str = join_str[2:8] print(sliced_str) # 翻转字符串 reversed_str = sliced_str[::-1] print(reversed_str) # 格式转换 int_value = int(reversed_str) print("转换为int类型:", int_value) print("转换为二进制:", bin(int_value)) print("转换为八进制:", oct(int_value)) print("转换为十六进制:", hex(int_value))
false
d222aaea0d8a9ede5eb11cbb905686340b2d6a29
shen-huang/selfteaching-python-camp
/exercises/1901080011/1001S02E03_calculator.py
966
4.25
4
def add(x,y): return x+y def subtract(x,y): return x-y def multiply(x,y): return x*y def divide(x,y): return x/y first_num = float(input("Enter first number: ")) second_num = float(input("Enter second number: ")) operator = input("Enter operator: ") if operator=='+': result = add(first_num,second_num) elif operator=='-': result = subtract(first_num,second_num) elif operator=='*': result= multiply(first_num,second_num) elif operator=='/': result = divide(first_num,second_num) else: result = 0 print(result) while True: num = float(input("Enter number again: ")) opt = input("Enter operator again(非+、-、*、/输出结果归零): ") if opt=='+': result = add(result,num) elif opt=='-': result = subtract(result,num) elif opt=='*': result= multiply(result,num) elif opt=='/': result = divide(result,num) else: result = 0 print(result)
true
d769a1c83e5fbdb58f580f374d440da392baa762
shen-huang/selfteaching-python-camp
/exercises/1901080001/1001S02E03_calculator.py
759
4.1875
4
# 流程图:定义函数-输入数值-输入运算操作-输入数值-输出结果 # 定义加法、减法、乘法、除法的运算操作函数 def add( x, y): return x + y def sub( x, y): return x - y def multi( x, y): return x*y def div( x, y): return x/y num1 = input('请输入第一个数字:') opt = input('请选择要进行的运算操作相关数字(1、加 2、减 3、乘 4、除):') num2 = input('请输入第第二个数字:') opt = int(opt) num1 = int(num1) num2 = int(num2) if opt == 1: print(add(num1, num2)) elif opt == 2: print(sub(num1, num2)) elif opt == 3: print(multi(num1, num2)) elif opt == 4: print(div(num1, num2)) else: print('你的输入有误,请重新输入:')
false
0886f4ae059aa95e703646c7bdcb7a19eed5b78a
shen-huang/selfteaching-python-camp
/exercises/1901050061/1001S02E03_calculator.py
2,535
4.375
4
output = 0 num1 = "" operation = "" num2 = "" ''' In python, user input on the command line can be taken by using the command input(). Putting in a string (optional) as a paramter will give the user a prompt after which they can input text. This statement returns a string with the text the user typed, so it needs to be assigneed to a variable. This can be done in python like so, myvar = input("Feed me data! "). Python is not a language with strongly typed variables, which means that you do not have to define a type when you create a variable. The interpreter will automatically assign the variable a type the first time it is instantiated with data. ''' ''' Getting input from the user for a calculation This code will print a prompt asking for a first number to the screen, ask for input, print a prompt asking for an operation to the screen, ask for input, etc. The \n at the end of the strings is an escape character that tells python to add a newline to the end of the prompt. I did this so that the user would start typing on the line below the prompt. ''' num1 = input("Hello, What is your First Number?\n") operation = input("Operation (+, -, *, /)?\n") num2 = input("Your Second Number?\n") ''' In order for us to do math on the numbers that the user typed, we need to convert them to numerical values, as you cannot do math on strings, for obvious reasons. (After all, what is "abc" / "def" anyways?) The method for doing so is called Typecasting. and in Python, you can convert to float (decimal numbers less than 7 digits) by using the float() statement. This can be done for our purposes like so, ''' floatnum1 = float(num1) floatnum2 = float(num2) ''' Performing the math ''' if operation == "+": output=floatnum1+floatnum2 if operation == "-": output=floatnum1-floatnum2 if operation == "*": output=floatnum1*floatnum2 if operation == "/": output=floatnum1/floatnum2 if operation == "+" or operation == "-" or operation == "/" or operation == "*": ''' Using the print() statement, we can print the result out to the screen. In Python, strings can be concatenated by "adding" them together, as if they were numbers. The code for this step looks like this: print("Your Answer: "+str(output)). This code prints the text "Your answer: " concatenated with the output, after it has been typecasted to a string. (You can't concatenate it while it is still formatted as a float) ''' print("Your Answer: "+str(output)) else: print("Your operation is invalid, please try again")
true
8e9a7834b813a54fea009d051dca97d670c8a40b
shen-huang/selfteaching-python-camp
/19100302/7Lou/d3_exercise_calculator.py
447
4.28125
4
#加减乘除计算器 # 思路:分三步输入 计算 输出 #输入 input()函数 #计算 + - * /,提供可选择项 #输出 print()函数 x = input('x:') y = input('y:') z = input('请选择+ or - or * or /:') if z == '+': print(float(x)+float(y)) elif z == '-': print(float(x)-float(y)) elif z == '*': print(float(x)*float(y)) elif z == '/': print(float(x)/float(y)) elif z == '+' or '-' or '*' or '/': print('Error')
false
fb1bd2740282ae93bb5ff150a13267fd344d1040
shen-huang/selfteaching-python-camp
/exercises/1901100137/1001S02E05_array .py
490
4.15625
4
[0,1,2,3,4,5,6,7,8,9] #1 翻转数组 number= [0,1,2,3,4,5,6,7,8,9] number1 = list(reversed(number)) print(number1) #翻转后的数组拼接成字符串 str1= ''.join([str(i) for i in number1]) print(str1) #用字符串切片的方式取出第三到第八个字符 str2 = str1[2:8] print(str2) #字符串翻转 str3 = str2[::-1] print(str3) #转为int型 int1= int(str3) #6 分别转换二进制,八进制,十六进制 print(int1) print(bin(int1)) print(oct(int1)) print(hex(int1))
false
142c0280b62831f4b4611ce2a683f3bc8008bbbd
shen-huang/selfteaching-python-camp
/exercises/1901090039/1001S02E03_calculator.py
830
4.15625
4
#加、减、乘、除计算器 #定义加法 def add(x,y): return x + y #定义减法 def subtract(x,y): return x - y #定义乘法 def multiply(x,y): return x * y #定义除法 def divide(x,y): return x / y #用户输入 print("可进行的运算") print("1,加法") print("2,减法") print("3,乘法") print("4,除法") choice = input("请输入要进行的运算符号(1/2/3/4):") num1 = int(input("请输入第一个数字:")) num2 = int(input("请输入第二个数字:")) #进行运算 if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("error")
false
e3a2a93ae901a793c00bfcb123388dfb011f910a
shen-huang/selfteaching-python-camp
/19100401/shense01/d3_exercise_calculator.py
677
4.125
4
def add(x,y): return x + y def subtract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x / y print("选择运算方式:") print("1、+") print("2、-") print("3、*") print("4、/") num1 = int(input("输入第一个数字:")) choice = input("输入运算器选择(1/2/3/4):") num2 = int(input("输入第二个数字:")) if choice == '1': print(num1,"+",num2,"=",add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=",subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=",multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=",divide(num1,num2)) else: print("非法输入")
false
372c25294fa9dc1ddf2e7445cc76d981cc90a27b
shen-huang/selfteaching-python-camp
/exercises/1901050034/1001S02E01_calculator.py
362
4.1875
4
num1 = float(input('please enter one number:')) num2 = float(input('please enter another number:')) op = input('please enter a operational symbol:') if op == '+': print(num1,'+',num2,'=',num1+num2) if op == '-': print(num1,'-',num2,'=',num1-num2) if op == '*': print(num1,'*',num2,'=',num1*num2) if op == '/': print(num1,'/',num2,'=',num1 / num2)
false
bb0d6aa3d6c274b5783ad1c154724c31f2aaea75
vladkudiurov89/PY111-april
/Tasks/a0_my_stack.py
836
4.34375
4
"""My little Stack""" my_stack = [] """Operation that add element to stack :param elem: element to be pushed :return: Nothing""" def push(elem): global my_stack my_stack.append(elem) return None """Pop element from the top of the stack :return: popped element""" def pop(): global my_stack if len(my_stack) != 0: b = my_stack[-1] del my_stack[-1] return b else: return None """Allow you to see at the element in the stack without popping it :param ind: index of element (count from the top) :return: peeked element""" def peek(ind: int = 0): global my_stack b = ind + 1 return my_stack[-b] """Clear my stack :return: None""" def clear() -> None: global my_stack my_stack.clear() return None if __name__ == '__main__': push(2) push(1) print(my_stack) print(pop()) print(my_stack) print(pop())
true
b2f358cfc90b32d48a3cae4c613763fd066702a7
billpoon12138/python_study
/Advance_Features/Iteration.py
426
4.125
4
from collections import Iterable d = {'a': 1, 'b': 2, 'c': 3} # iterate key in default condition for key in d: print(key) # iterate value for value in d.values(): print(value) # iterate items for k, v in d.items(): print(key, ':', value) # judge an object whether can be iterated isiterable = isinstance('abc', Iterable) print(isiterable) # add the index for i, value in enumerate(['A', 'B', 'C']): print(i, value)
true
ddcbead5ff1a78eaed4e1d81b4cf1adc088c2170
JakNowy/python_learn
/decorators.py
2,109
4.15625
4
# # FUNCTION BASED DECORATORS # def decorator_function(original_function): # def wrapper_function(): # print('Logic before') # result = original_function() # print('Logic after') # return result # return wrapper_function # # @decorator_function # def original_function(): # print('Original function') # # # original_function() # # # # f1 = decorator_function(original_function) # CLASS BASED DECORATORS import functools class DecoratorClass: def __init__(self, decorator_argument): """ Instantiation of decorator_object, like decorator_object = DecoratorClass(arg) :param arg: Argument of decorator. """ self.counter = 0 self.decorator_argument = decorator_argument def __call__(self, original_function): """ Called when the decorator_object gets called, like decorator_closure = decorator_object(original_function). Returns actual decorator_closure ready to be executed. @decorator syntax executes this step automatically. """ # Functools handles naming of wrapped functions (its .__name__ method) @functools.wraps(original_function) def wrapper(*args, **kwargs): # Adds logic before and after original_function print('Logic before') result = original_function(*args, **kwargs) self.counter += 1 print('Logic after') print(f'Decorator_argument = {self.decorator_argument}') return result return wrapper # EXECUTING USING @DECORATOR SYNTAX @DecoratorClass(decorator_argument=5) def original_function2(a, b): print(f'This is original function. It has function arguments a = {a} and b = {b}') original_function2(1, 2) # EXECUTING MANUALLY def original_function1(a, b): print(f'This is original function. It has function arguments a = {a} and b = {b}') # __INIT__ decorator_object = DecoratorClass(decorator_argument=5) # __CALL__ decorator_closure = decorator_object(original_function1) # Closure execution decorator_closure(1, 2)
true
a9920180a5cfcc87b785b384e0163f7cf7f4c5a9
vedmara/ALgorithms_python_lessons_1-8
/lesson_1/lesson_1_Task_2.py
573
4.125
4
#Выполнить логические побитовые операции «И», #«ИЛИ» и др. над числами 5 и 6. # Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. a = 5 print(a, " = ", bin(a)) b = 6 print(b, " = ", bin(b)) print(a, " & ", b, " = ", a&b, "(", bin(a&b), ")") print(a, " | ", b, " = ", a|b, "(", bin(a|b), ")") print(a, " ^ ", b, " = ", a^b, "(", bin(a^b), ")") print(a, " << 2 = ", a<<2, "(", bin(a<<2), ")") print(a, " >> 2 = ", a>>2,"(", bin(a>>2), ")")
false
c842cd6d2a6c01b8b4301fb82e45bd812b8b2b86
gregmoncayo/Python
/Python/arrayList.py
2,099
4.21875
4
lis = [] # array list # Main menu for user display def Menu(): print("A. See the list ") print("B. Add to the list ") print("C. Subtract from the list") print("D. Delete the entire list") print("E. See the size of your list") print("F. Reverse") print("G. Search the list") print("H. Quit") # Switch statement for user option def Switch(option): option = option.upper() switch = { "A": PrintList, "B": Insert, "C": Delete, "D": StartOver, "E": Size, "F": Reverse, "G": Search, } return switch.get(option, "Wrong choice")() # Prints the array def PrintList(): print(lis) # Inserts a certain value at a certain index def Insert(): index = input("Enter the index of the array: ") index = int(index) phrase = input("Enter a word: ") lis.insert(index, phrase) print(lis) # Deletes a certain value at a certain index def Delete(): deletion = input("Enter an index of the array: ") deletion = int(deletion) lis.pop(deletion) print(lis) # Deletes the entire array def StartOver(): del lis[0 : len(lis)] # Prints the size of the array def Size(): print(len(lis)) # Reverses the array def Reverse(): print(list(reversed(lis))) # Searches a certain value in the array def Search(): seek = input("Enter a string to search: ") counter = 0 for x in range(0, answer): if (lis[x] == seek): counter+= 1 print("There is", counter, seek, "in the list ") # main function if __name__ == "__main__": answer = input("Enter a size for your array: ") answer = int(answer) if (answer < 1): print("This is not a value size. Please try again later..") else: i = 0 while (i < answer): sentence = input("Enter a string: ") lis.append(sentence) i+=1 Menu() choice = input("Enter a choice: ") while (choice != 'H' and choice != 'h'): Switch(choice) Menu() choice = input("Enter a choice: ") print("Goodbye")
true
2400616ad90902a303878407bc543b56103e48b4
jgambello2019/projectSet0
/ps0.py
2,877
4.4375
4
# 0. Write a boolean function that takes a non-negative integer as a parameter and returns True if the number is even, False if it is odd. It is common to call functions like this is_even. def is_even(int): '''Returns true if number is even, false if odd''' divisibleByTwo = int % 2 return divisibleByTwo == 0 # 1. Write a function that takes a non-negative integer as a parameter and returns the number of digits in it. def amount_digits(num): '''Tells the amount of digits in a number''' num = str(num) length = len(num) return length # 2. Write a function that takes a non-negative integer as a parameter and returns the sum of its digits. def sum_digits(num): '''Returns the sum of every digit in a number added together''' sum = 0 for digit in str(num): sum += int(digit) return sum # 3. Write a function that takes a non-negative integer as a parameter and returns the sum of all the integers that are less than the given number. def sum_less_ints(numbr): '''Returns the sum of every value in a number lower than itself''' sum = 0 num = numbr - 1 while num != 0: sum += num num -= 1 return sum # 4. Write a function that takes a non-negative integer as a parameter and returns its factorial. def factorial(num): '''Returns the factorial of num which is all its factors multiplied''' product = num if num != 0: while num != 1: product = product * (num - 1) num -= 1 elif num == 0: product = 0 return product # 5. Write a boolean function that takes two positive integers as parameters and returns true if the second number is a factor of the first def is_factor(x, y): '''Returns true if y is a factor of x''' seeIfFactor = x % y return seeIfFactor == 0 # 6. Write a boolean function that takes an integer greater than or equal to 2 as a parameter and returns whether the number is a prime. def is_prime(int): '''Returns true if int is prime''' numbersToTry = range(2,(int)) indicator = 0 for number in numbersToTry: seeIfDivisible = int % number if seeIfDivisible == 0: indicator += 1 return indicator == 0 # 7. Write a boolean function that takes a positive integer as a parameter and returns whether the number is perfect. def is_perfect(int): '''returns true if number is perfect''' numbersBelow = range(1,int) sumFactors = 0 properFactors = [] for number in numbersBelow: if (int % number) == 0: properFactors.append(number) for number in properFactors: sumFactors += number return sumFactors == int # 8. Write a boolean function that takes a positive integer as a parameter and returns true if the sum of the digits of the number divides evenly into the number, false otherwise. def divides_evenly(int): '''returns true if sum of the digits of a number divides evenly into the number itself''' sumOfDigits = sum_digits(int) return (int % sumOfDigits == 0)
true
aa182293c7d48552d5f7454953d3e7d6bb999cad
AHKerrigan/Think-Python
/exercise4_2.py
1,131
4.375
4
import math import turtle def polyline(t, n, length, angle): """Draws n line segments with the given length and angle (in degrees) between them. t is a turtle. """ for i in range(n): t.fd(length) t.lt(angle) def polygon(t, length, n): """Draws an Ngon made up of equal angles of the given length t is a turtle """ angle = (360 / n) polyline(t, n, length, angle) def arc(t, r, angle): """Draws a arc, or piece of a circle, of an angle and given radium """ arc_length = 2 * math.pi * r * angle / 360 n = int(arc_length / 4) + 3 step_length = arc_length / n step_angle = float(angle) / n # making a slight left turn before starting reduces the # error of linear approximation of the arc t.lt(step_angle/2) polyline(t, n, step_length, step_angle) t.rt(step_angle/2) def circle(t, r): arc(t, r, 360) def petal(t, r, angle): for i in range(2): arc(t, r, angle) t.lt(180-angle) def flower(t, r, n, angle): """Draws a flower with n petals, with petal length r, sepended by an angle """ for i in range(n): petal(t, r, angle) t.lt(360.0 / n) bob = turtle.Turtle() flower(bob, 100.0, 7, 100.0)
false
62c63539e4b9b726a3fb5d41ead0ebcb669c8df5
AHKerrigan/Think-Python
/exercise3_2.py
1,435
4.5
4
# A function object is a value you can assign to a variable or pass as an argument. For # example, do_twice is a function that takes a function object as an argument and calls # it twice: # def do_twice(f): # f() # f() #Here’s an example that uses do_twice to call a function named print_spam twice: # def print_spam(): # print('spam') # do_twice(print_spam) # 1. Type this example into a script and test it. # 2. Modify do_twice so that it takes two arguments, a function object and a value, # and calls the function twice, passing the value as an argument. # 3. Copy the definition of print_twice from earlier in this chapter to your script. # 4. Use the modified version of do_twice to call print_twice twice, passing 'spam' # as an argument. # 5. Define a new function called do_four that takes a function object and a value and # calls the function four times, passing the value as a parameter.There should be # only two statements in the body of this function, not four. # Takes a function with a value "value", and runs that function twice using that value def do_twice(f, value): f(value) f(value) # prints some value def print_spam(value): print(value) # Takes an arbitrary parameter (param) and prints it twice def print_twice(param): print(param) print(param) # calls do twice, twice def do_four(f, value): do_twice(f, value) do_twice(f, value) do_twice(print_spam, 'spam') do_four(print_spam, 'spam')
true
65fa427c004588b2ea12bc496314b9a46e1b0f71
AHKerrigan/Think-Python
/exercise9_4.py
934
4.28125
4
""" This is a solution to an exercise from Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ Exercise 9-4: Write a function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list. Can you make a sentence using only the letters acefhlo?” """ def uses_only(word, req_chr): """Takes a word and returns true only if it uses only the letters in req_chr""" for letters in word: flag = False # Goes through each letter in word and looks for it to be at least one of the characters in req_chr # Will return false otherwise for c in req_chr: if c == letters: flag = True if not flag: return False return True print(uses_only('kerrigan', 'keigan')) fin = open("words.txt") for line in fin: if uses_only(line.strip(), 'acefhlo'): print(line.strip())
true
a3dab7ee3a4f4219af5795df3251825ed25e22f4
AHKerrigan/Think-Python
/exercise5_5.py
554
4.28125
4
""" This is a solution to an exercise from Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ Exercise 5-5: This exercise is simply a copy-paste to determine if the reader understands what is being done. It is a fractal of order n. """ import turtle def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) t.rt(2*angle) draw(t, length, n-1) t.lt(angle) t.bk(length*n) bob = turtle.Turtle() draw(bob, 20, 5)
true
31f411dbe5909272f0ddd95da8b43b7718da423c
AHKerrigan/Think-Python
/exercise10_9.py
1,007
4.15625
4
""" This is a solution to an exercise from Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ s Exercise 10-9: Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why? """ def file_list_append(file): """Takes a file, then puts every line in the file into an element of a list, then returns that list""" t = [] fin = open(file) for line in fin: t.append(line) return t def file_list_idiom(file): """Takes a file as input, then uses operators to turn each line into an element of a list""" t = [] fin = open(file) for line in fin: t = t + [line] return t # print(len(file_list_append("words.txt"))) print(len(file_list_idiom("words.txt"))) # The idiom version is slower because the operator creates and entire new list
true
57a8b9a6d6d36e3046373e8e018e4e48c8c6ebe3
ypratham/python-aio
/Games/Rock Paper Scissor/rps.py
2,469
4.1875
4
import random print('ROCK PAPER SCISSORS') print('-' * 20) print('\nInstructions:' '\n1. This game available in only Computer v/s Player mode' '\n2. You play 1 round at a time' '\n3. Use only rock, paper and scissor as input') input('\nPress Enter to continue') while True: choice = str(input('Do you want to start the game now ? [y/n]')) if choice == 'y': moves = ['rock', 'paper', 'scissor'] computer = random.randint(0, 2) while True: user_move = str(input('Enter your choice:')) if user_move not in moves: print("That's not a valid choice. Check your spelling!") # TIE Only if user_move == 'rock' and computer == 0: print('\nIt\'s a TIE !') print('\nBoth you and computer chose Rock as your move') break elif user_move == 'paper' and computer == 1: print('\nIt\'s a TIE !') print('\nBoth you and computer chose Paper as your move') break elif user_move == 'scissor' and computer == 2: print('\nIt\'s a TIE !') print('\nBoth you and computer chose Scissor as your move') break # User Wins Only elif user_move == 'rock' and computer == 2: print('\nYou WON!') print('\nComputer chose Scissors as their move') break elif user_move == 'paper' and computer == 0: print('\nYou WON!') print('\nComputer chose Rock as their move') break elif user_move == 'scissor' and computer == 1: print('\nYou WON!') print('\nComputer chose Paper as their move') break # Computer Wins Only elif user_move == 'rock' and computer == 1: print('\nComputer WON!') print('\nComputer chose Paper as their move') break elif user_move == 'paper' and computer == 2: print('\nComputer WON!') print('\nComputer chose Paper as their move') break elif user_move == 'scissor' and computer == 0: print('\nComputer WON!') print('\nComputer chose Paper as their move') break else: print('Thanks for Playing !') break
true
80503d61dc785101e8ccfdb85a0de5bedf55600d
harerakalex/code-wars-kata
/python/usdcny.py
523
4.15625
4
''' Create a function that converts US dollars (USD) to Chinese Yuan (CNY) . The input is the amount of USD as an integer, and the output should be a string that states the amount of Yuan followed by 'Chinese Yuan' For Example: usdcny(15) => '101.25 Chinese Yuan' usdcny(465) => '3138.75 Chinese Yuan' The conversion rate you should use is 6.75 CNY for every 1 USD. All numbers shold be rounded to 2 decimal places. (e.g. "21.00" NOT "21.0" or "21") ''' def usdcny(usd): return f"{usd * 6.75:.2f} Chinese Yuan"
true
aeb7486fae65a77dc97c2b4151a900dcf8ac4b36
harerakalex/code-wars-kata
/python/fibonacci.py
1,918
4.15625
4
''' Problem Context The Fibonacci sequence is traditionally used to explain tree recursion. def fibonacci(n): if n in [0, 1]: return n return fibonacci(n - 1) + fibonacci(n - 2) This algorithm serves welll its educative purpose but it's tremendously inefficient, not only because of recursion, but because we invoke the fibonacci function twice, and the right branch of recursion (i.e. fibonacci(n-2)) recalculates all the Fibonacci numbers already calculated by the left branch (i.e. fibonacci(n-1)). This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much. You may go for a cup of coffee or go take a nap while you wait for the answer. But if you try it here in Code Wars you will most likely get a code timeout before any answers. For this particular Kata we want to implement the memoization solution. This will be cool because it will let us keep using the tree recursion algorithm while still keeping it sufficiently optimized to get an answer very rapidly. The trick of the memoized version is that we will keep a cache data structure (most likely an associative array) where we will store the Fibonacci numbers as we calculate them. When a Fibonacci number is calculated, we first look it up in the cache, if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number. Refactor the function into a recursive Fibonacci function that using a memoized data structure avoids the deficiencies of tree recursion Can you make it so the memoization cache is private to this function? ''' def fibonacci(n): if n in [0, 1]: return n return (fibonacci(n - 1) + fibonacci(n - 2)) def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper fibonacci = memoize(fibonacci)
true
6b1dc0b9eedc1e8ebf819738c060a6b8ab238eb3
profnssorg/valmorMantelli1
/exer504.py
429
4.1875
4
###Titulo: Exibe números impares ###Função: Este programa exibe todos os números ímpares até o número escolhido pelo usuário ###Autor: Valmor Mantelli Jr. ###Data: 10/12/20148 ###Versão: 0.0.2 # Declaração de variáve x = 1 n = 0 # Atribuição de valor a variavel n = int(input("Digite o número final. O programa exibirá todos os ímpares até ele: ")) # Processamento while x <= n: # Saída print(x) x = x + 2
false
4065723d8f4ab99639325c1789d639fd4cf9b6ab
profnssorg/valmorMantelli1
/exer403.py
724
4.1875
4
###Titulo: Maior valor ###Função: Este programa pergunta tres números e exibe o de maior valor ###Autor: Valmor Mantelli Jr. ###Data: 08/12/20148 ###Versão: 0.0.3 # Declaração de variável a = 0 b = 0 c = 0 maior = 0 menor = 0 # Atribuição de valor a variavel a = int(input("Diga o primeiro número inteiro: ")) b = int(input("Diga o segundo número inteiro: ")) c = int(input("Diga o terceiro número inteiro: ")) #Processamento if a > b and a > c: maior = a if b > a and b > c: maior = b if c > a and c> b: maior = c if a < b and a < c: menor = a if b < a and b < c: menor = b if c < a and c < b: menor = c # Saída print("O maior dos números informados é o %d e o menor é o %d." %(maior, menor))
false
768cf5d7a78e2b362923349ea5ef094f147cb784
profnssorg/valmorMantelli1
/exer606.py
1,494
4.125
4
###Titulo: Organizador de fila ###Função: Este programa organiza entradas e saídas de duas filas ###Autor: Valmor Mantelli Jr. ###Data: 31/12/2018 ###Versão: 0.0.2 ### Declaração de variáve último = 0 fila1 = [] fila2 = [] x = 0 operação = [] ### Atribuição de valor while True: print ("\nExistem %d clientes na fila a e %d clientes na fila 2" % (len (fila1), len (fila2))) print ("Fila 1 atual: ", fila1) print ("Fila 2 atual: ", fila2) print ("Digite F para adicionar um cliente ao final da fila 1 ou G a fila 2,") print ("para realizar o atendimento na fila 1 digite A ou para B fila 2.") print ("Pressione S para sair") operação = input ("Operação (F ou G, A ou B, ou S): ") x = 0 sair = False ### Processamento e saída while x < len (operação): if operação [x] == "A" or operação [x] == "F": fila = fila1 else: fila = fila2 if operação [x] == "A" or operação [x] == "B": if (len(fila)) > 0: atendido = fila.pop(0) print ("Cliente %d atendido" % atendido) else: print ("Fila vazia! Ninguém para atender") elif operação [x] == "F" or operação [x] == "G": último += 1 #Adicionado o ticket do novo cliente fila.append(último) elif operação [x] == "S" or operação [x] == "s": sair = True break else: print ("Operação ínválida! %s na posição %d! Digite Apenas F, A ou S!" % (operação [x], x)) x += 1 if (sair): break
false
a56defabab48718524a7eac281fd4fc28052488c
NotGeobor/Bad-Code
/Password Generator.py
2,307
4.40625
4
# user input word = input("Choose a website: ").lower() # list tracks repeats in string repeats = [] # length variable makes working with 2 different lengths of the "word" string easier length = len(word) # tracks even/odd position in string index with 2 being even and 1 odd odd = 2 # dictionaries used to capitalize numbers and symbols because python doesn't let me do it by default sym = { "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")" } numb = { "!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0" } # finds repeat letters, adds them to the end of string, slices the string, and # adds repeat letter to repeats list to avoid running for the same letter twice and to be used later on for letter in word: if word.count(letter) > 1 and letter not in repeats: word += letter word = word[:word.index(letter)] + word[(word.index(letter) + 1):] repeats.append(letter) # reverses word, adds letters to the end of string, and slices the original letters off for letter in reversed(word): word += letter word = word[length:] # adds number equivalent to the length of the word times the number of repeats to the string word += str(len(repeats) * len(word)) # defines new word variable, still unsure if entirely needed new_word = word # finds length of word, changes it to a string. This leaves us with a number that we can iterate and # compare with the sym dictionary to concatenate the string with the symbols equivalent to it's length for num in str(len(word)): new_word += sym[num] # resets word word = "" # checks if index of string is even or odd using odd variable, if index is odd, capitalizes letter, if letter is number or symbol, uses sym and numb dictionaries for letter in new_word: if odd == 1: if letter in sym: word += sym[letter] elif letter in numb: word += numb[letter] else: word += letter.upper() odd = 2 else: word += letter odd = 1 # prints output with spaces to make it easier to see and copy in the terminal, especially during debugging print("") print(word) print("")
true
4e33aa5b846349604f6aa5b5361fb0c00407c221
nileshnegi/hackerrank-python
/day009/ex55.py
778
4.375
4
""" Company Logo Given a string ```s``` which is the company name in lowercase letters, your task is to find the top three most common characters in the string. Print the three most common characters along with their occurrence count. Sort in descending order of occurrence count. If occurrence count is the same, sort the characters in alphabetical order. """ if __name__ == '__main__': s = input() occur = dict() result = [] for char in s: if occur.get(char) == None: occur[char] = 1 else: occur[char] += 1 occur = dict(sorted(occur.items(), key=lambda item:(-item[1], item[0]))) count = 3 for k, v in occur.items(): print(k, v) count -= 1 if count == 0: break
true
085de4e412b65c6610e8fd079bfe151dd6598725
nileshnegi/hackerrank-python
/day015/ex98.py
699
4.40625
4
""" Map and Lambda Function You have to generate a list of the first `N` fibonacci numbers, `0` being the first number. Then, apply the map function and a lambda expression to cube each fibonacci number and print the list. """ cube = lambda x: x**3 # complete the lambda function def fibonacci(n): # return a list of fibonacci numbers res = list() if n == 1: res.append(0) elif n == 2: res.append(0) res.append(1) elif n > 2: res.append(0) res.append(1) for i in range(2, n): res.append(res[i-1] + res[i-2]) return res if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
true
de64cf80d0e029df3e4c97f366071ce001653fec
nileshnegi/hackerrank-python
/day001/ex5.py
1,178
4.5625
5
""" Lists Consider a list. You can perform the following functions: insert i e: Insert integer ```e``` at position ```i``` print: Print the list remove e: Delete the first occurrence of integer ```e``` append e: Insert integer ```e``` at the end of the list sort: Sort the list pop: Pop the last element from the list reverse: Reverse the list Initialize your list and read in the value of ```n``` followed by lines of ```n``` commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list. """ if __name__ == '__main__': N = int(input()) lst = [] for i in range(N): line = input() cmd = line.split()[0] if cmd == "insert": lst.insert(int(line.split()[1]), int(line.split()[2])) elif cmd == "print": print(lst) elif cmd == "remove": lst.remove(int(line.split()[1])) elif cmd == "append": lst.append(int(line.split()[1])) elif cmd == "sort": lst.sort() elif cmd == "pop": lst.pop() elif cmd == "reverse": lst.reverse()
true
4951d729fe33ec638a78ff43dbf3b0c474ee74ac
nileshnegi/hackerrank-python
/day014/ex89.py
644
4.1875
4
""" Validating Credit Card Numbers A valid credit card has the following characteristics: It must start with `4`, `5` or `6`. It must contain exactly 16 digits `[0-9]`. It may have digits in groups of 4, seperated by a hyphen `-`. It must not use any seperators like ` `, `_`, etc. It must not have `4` or more consecutive repeated digits. """ import re if __name__ == '__main__': regex = re.compile( r"^" r"(?!.*(\d)(-?\1){3})" r"[456]" r"\d{3}" r"(?:-?\d{4}){3}" r"$" ) for _ in range(int(input().strip())): print("Valid" if regex.search(input().strip()) else "Invalid")
true
19649a71c597222f34d4e1192683c9a27c4c586c
nileshnegi/hackerrank-python
/day009/ex59.py
320
4.15625
4
""" Set .add() The first line contains an integer ```N```, the total number of country stamps. The next ```N``` lines contains the name of the country where the stamp is from. """ if __name__ == "__main__": country = set() for _ in range(int(input())): country.add(input()) print(len(country))
true
0e91aad14d9c1287ecdf38786cdad445c4bc36ed
Daniyal56/Python-Projects
/Positive OR Negative Number.py
622
4.5625
5
# Write a Python program to check if a number is positive, negative or zero # Program Console Sample Output 1: # Enter Number: -1 # Negative Number Entered # Program Console Sample Output 2: # Integer: 3 # Positive Number Entered # Program Console Sample Output 3: # Integer: 0 # Zero Entered user_input = int(input("Enter your number to check it's positive OR negative : ")) def function(user_input): if user_input > 0: print(f'Your number {user_input} is Positive Number') elif user_input < 0: print(f'Your number {user_input} Negative Number') else: print(f'You entered {user_input}') function(user_input)
true
d9ea424c5adcd7c2d7ad207f2ad1c254d7ff90ff
Daniyal56/Python-Projects
/Sum of a Number.py
584
4.25
4
## 14. Digits Sum of a Number ### Write a Python program to calculate the sum of the digits in an integer #### Program Console Sample 1: ##### Enter a number: 15 ###### Sum of 1 + 5 is 6 #### Program Console Sample 2: ##### Enter a number: 1234 ###### Sum of 1 + 2 + 3 + 4 is 10 print('=========================================== Digits Sum Of Number =========================================== ') #getting user input user_input = (input('Enter Number : ')) sum_of_number = 0 for i in user_input: sum_of_number += int(i) print(f'Sum Of Number {user_input} is {sum_of_number}')
true
5f52bd1beda25e36c57098ac0187b79688e45457
seed-good/mycode
/netfunc/calculator.py
1,968
4.28125
4
#!/usr/bin/env python3 """Stellantis || Author: vasanti.seed@stellantis.com""" import crayons # function to calculate def calculator(first_operand, second_operand, operator): print('Attempting to calculate --> ' + crayons.blue(first_operand) + " " + crayons.blue(operator) + " " + crayons.blue(second_operand)) if operator == "+": return first_operand + second_operand elif operator == "-": return first_operand - second_operand elif operator == "*": return first_operand * second_operand elif operator == "/": if second_operand != 0: return first_operand / second_operand else: return "ERROR!" elif operator == "**": return first_operand ** second_operand elif operator == "%": return first_operand % second_operand # start our main script def main(): ## get data set print(crayons.red("WELCOME TO THE PYTHON CALCULATOR!", bold=True)) print() while True: op1 = input(crayons.red("Please enter the first operand: ")) try: op1 = float(op1) break except ValueError: print(crayons.red("That's not a number! Try again!", bold-True)) while True: oper = input(crayons.red("Please enter the operator (+, -, *, /, **, %): ")) if oper in ["+", "-", "*", "/", "**", "%"]: break while True: op2 = input(crayons.red("Please enter the second operand: ")) try: op2 = float(op2) if (oper == "/" or oper == "%") and op2 == 0: print(crayons.red("Cannot divide by zero!", bold=True)) else: break except ValueError: print(crayons.red("That is not a number! Try again!", bold= True)) ## run result = calculator(op1, op2, oper) # call function to calc print(f"The result is {result}") # call our main function main()
true
ebaf0f43bc2fbe1238c48669acd256fc949dccaf
ostrbor/prime_numbers
/public_key.py
538
4.125
4
#!/usr/bin/env python #Find two random prime number of same size #and return it's product. from functools import reduce from check import is_prime size = input('Enter size of number: ') min = 10**(size-1) max = 10**size-1 def find_primes(min, max): '''Find two different biggest prime number''' res = [] for i in range(max, min, -1): if is_prime(i): res.append(i) if len(res) == 2: break return res primes = find_primes(min, max) print(primes) product = reduce(lambda x,y: x*y, primes) print(product)
true
9d68d62847e213ca97ba6d8805b0c1ab73afcf7e
Lucky0214/machine_learning
/isin_pd.py
544
4.25
4
# isin() function provides multiple arguments import pandas as pd df = pd.read_csv("testing.csv") print(df) #We are taking same concept which is not better for coder mask1 = df["class"] =="a" #mask is used for finding same type in a perticular column print(df[mask1]) mask2 = df["class"] == "b" mask3 = df["class"] == "c" print(df[ mask1 | mask2 | mask3]) #Above concept in a single line print("*****************Code optimize concept with isin function*************************") mask = df["class"].isin(["a","b","c"]) print(df[mask])
true
e46cbac7f53f918c16c35bdc0121a64e8fd7d0f4
ShreyashSalian/Python_count_vowel
/Program2.py
295
4.34375
4
#Wap to count the number of each vowel in string def count_vowel(string): vowel = "aeiou" c = {}.fromkeys(vowel,0) string = string.lower() for co in string: if co in c: c[co] += 1 return c string = input("Enter The String : ") print(count_vowel(string))
true
2a20357da5c6c782ee190906d8706fdb793dc0b2
Pixelus/MIT-6.0.0.1-problems
/ps1a.py
1,686
4.4375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 7 17:02:11 2018 @author: PixelNew """ ############################################################################### # You decide that you want to start saving to buy a house. You realize you are # going to have to save for several years before you can afford to make the # down payment on a house. Write a program to calculate how many months it will # take you to save up enough money for a down payment. ############################################################################### # Ask the annual salary to the user annual_salary = float(input("Enter your annual salary: ")) # Ask the amount % of user salary to saving each month for the down payment portion_saved = float(input("Enter the percent of your salary to save, as a \ decimal:​ ")) # Monthly savings monthly_savings = (annual_salary / 12) * portion_saved # Ask the cost of the user dream home total_cost = float(input("Enter the cost of your dream home: ")) # Cost needed for a down payment portion_down_payment = total_cost * 0.25 # Start with a current savings of $0 current_savings = 0.0 # Annual return on personal investment r = 0.04 # Remaining months for a down payment months = 0 ############################################################################### # Determine how long it will take you to save enough money to make the down # payment. ############################################################################### while current_savings < portion_down_payment: current_savings += monthly_savings + ((current_savings * r) / 12) months += 1 print("Number of months: " + str(months))
true
e7bed62194217f93e2508a54436dae60e9dd08f6
jsillman/astr-119-hw-1
/functions.py
618
4.46875
4
#this program prints every value of e^(x) for x ranging from 0 to one less than # a given value, or 9 by default import numpy as np import sys def exponent(x): #exponent(x) function: returns e^(x) return np.exp(x) def show_exponent(x): #show_exponent(x) function: prints the result of for i in range(x): # e^(i) for every value of i from 0 to x-1 print(exponent(float(i))) def main(): n = 10 #initialize n if(len(sys.argv)>1): #if there's a command line argument, n = int(sys.argv[1]) # use it for n show_exponent(n) #call show_exponent(n) if __name__ == "__main__": main()
true
f5d5765b913fc91176d15e94d9222d03d276cb02
qiaoy9377/python-base
/第一天练习代码/5.字符串.py
2,616
4.15625
4
#打印变量的数据类型 a = 'hello world' b = 'abcdefg' print(type(a)) print(type(b)) #字符串输入 # name = input('请输入你的名字:') # print(f'您输入的名字为{name}') # print(type(name)) # # password = input('请输入您的密码:') # print('您输入的密码为%s'% password) # print(type(password)) #字符串name=“abcdef”,取到不同下标对应的数据 name = 'abcdefg' print(name[0]) print(name[1]) print(name[2]) #切片,负数代表倒数第几个数 print(name[2:5:1]) print(name[2:5]) print(name[:5]) print(name[1:]) print(name[:]) print(name[::2]) print(name[:-1]) #表示倒数第一个数 print(name[-4:-1]) print(name[::-1]) #查找字符串内容 mystr = "hello world and superctest and chaoge and Python" print(mystr.find('and')) print(mystr.find('and',15,30)) print(mystr.find('ands')) print(mystr.index('and')) print(mystr.index('and',15,30)) #print(mystr.index('ands'))--报错 print(mystr.rfind('and')) print(mystr.rfind('and',15,30)) print(mystr.rfind('ands')) print(mystr.rindex('and')) print(mystr.rindex('and',15,30)) #print(mystr.rindex('ands'))--报错 print(mystr.count('and')) print(mystr.count('and',0,15)) print(mystr.count('ands')) #修改-replace print(mystr.replace('and','he')) print(mystr.replace('and','he',1)) print(mystr.replace('and','he',5)) #split print(mystr.split('and')) print(mystr.split('and',2)) print(mystr.split('and',5)) print(mystr.split(' ')) #join() print('_'.join(mystr)) list1 = ['hello','world','!'] print('-'.join(list1)) t1 = ('a','b','c','d','1','2') print('...'.join(t1)) #capitalize() print(mystr.capitalize()) #title() print(mystr.title()) #lower() mystr1 = mystr.title() print(mystr1) print(mystr1.lower()) #upper() print(mystr.upper()) #删除字符串的空白字符lstrip()、rstrip()、strip() mystr2 = ' hello world he superctest he chaoge he Python ' print(mystr2.rstrip()) print(mystr2.lstrip()) print(mystr2.strip()) #ljust() mystr3='hello' print(mystr3.ljust(10)) print(mystr3.ljust(8,'~')) #rjust() print(mystr3.rjust(10,'.')) print(mystr3.rjust(8)) #center() print(mystr3.center(10)) print(mystr3.center(8,'-')) #判断-startswith() print(mystr.startswith('hello')) print(mystr.startswith('h',5,10)) #endswith() print(mystr.endswith('thon')) print(mystr.endswith('thon',-10,-1)) #isalpha() mystr4 = 'abcd123' print(mystr3.isalpha()) print(mystr4.isalpha()) #isdigit() mystr5 = '12345' print(mystr4.isdigit()) print(mystr5.isdigit()) #isalnum() print(mystr.isalnum()) print(mystr4.isalnum()) #isspace() mystr6 = ' ' print(mystr.isspace()) print(mystr6.isspace())
false
9b02571f769a49486363f882624e8a33a5799bd8
fszatkowski/python-tricks
/2_decorators_and_class_methods/6.py
959
4.34375
4
import abc # ABC (abstract base classes) package provides tools for creating abstract classes and methods in python # Abstract classes must inherit from abc.ABC class # Then @abd.abstractmethod can be defined class BaseClass(abc.ABC): @abc.abstractmethod def greet(self): pass # Abstract class can have non-abstract methods def base_greet(self): print("This is a greeting from the parent") # Now subclass must implement greet class SubClass(BaseClass): def greet(self): self.base_greet() print("Hello") if __name__ == "__main__": # Try to instantiate base class try: base = BaseClass() except Exception as e: print(e) sub = SubClass() sub.greet() # Try inheriting from base class without overriding greet() try: class AnotherSubClass(BaseClass): pass another = AnotherSubClass() except Exception as e: print(e)
true
1c6a8a019de03c58205068b13ea9aa343867ba30
Alasdairlincoln96/210CT
/Week 1/Question 1.py
1,805
4.28125
4
from random import * newarray = [] used = [] def create_array(): '''A function which asks the user to enter numbers into an array, the user can carry on entering numbers as long as they want. All the inputs are checked to make sure they are an integer.''' array = [] done = False print("To finish entering numbers please enter a non integer.")#used to help the user #a while loop to get the user to enter numbers into the array, the input is also validated to make sure its usable while done == False: try: user = int(input("Please enter a number into the array: ")) array.append(user) done = True return array except ValueError: pass array = create_array() print("This is the original array of numbers: ",array) #a for loop that itterates over the array for i in range(len(array)): randin = True while randin == True: rand = randint(0,(len(array)-1))#picks a random number between 0 and the last index in the array (i.e picks a random index from the array) if rand in used:#checks to see if the random index has already been used, if it has then the code will return to the top of the while loop randin = True else:#if the random index hasnt been used before then it is added to the array of used items (to make sure its not used again), the while loop is then exited used.append(rand) randin = False newarray.append(array[rand])#the item in randomly choosen index is then added to a new array #checks to see if the array was actually shuffled and lets the user know the program failed if array == newarray: print("Error: List not shuffled, please try again.") print("This is the shuffled array of numbers",newarray)
true
a90ef4442ea6bb682b1d193310c3ad7b0a670310
Alasdairlincoln96/210CT
/Week 0/Question 1.py
1,255
4.125
4
number1 = False number2 = False number3 = False number4 = False while number1 == False: try: a = int(input("Please enter a number: ")) number1 = True except valueerror: print("Thats not a number. Please enter a whole number: ") number1 = False while number2 == False: try: b = int(input("Please enter a second number: ")) number2 = True except valueerror: print("Thats not a number. Please enter a whole number: ") number2 = False while number3 == False: try: c = int(input("Please enter a third number: ")) number3 = True except valueerror: print("Thats not a number. Please enter a whole number: ") number3 = False while number4 == False: try: d = int(input("Please enter a fourth number: ")) number4 = True except valueerror: print("Thats not a number. Please enter a whole number: ") number4 = False fraction1 = a/b fraction2 = c/d if fraction1 > fraction2: print(fraction1, "is the larger value") elif fraction2 > fraction1: print(fraction2, "is the larger value") elif fraction1 == fraction2: print("the values are the same") else: print("error, please try again")
true
269bd14dc41c21e35ddce507a7a1bb2154c79010
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/primitive types/numbers.py
738
4.375
4
x = 1 y = 1.1 # a + bi # complex numbers, where i is an imaginary number. # we use `j` in python syntax to represent the imaginary number z = 1 + 2j # standard arithmetic math operations print(10 + 3) # addition print(10 - 3) # substraction print(10 * 3) # multiplication print(10 / 3) # division - returns a floating point number print(10 // 3) # returns an integer print(10 % 3) # modulus - returns remainder of the division print(10 ** 3) # exponent - left side to the power of right side # augmented assignment operator x = 10 x = x + 3 # say we want to increment the value of x by 3 x += 3 # shorter syntax with augmented assignment operator # you can use any of the operators above in the augmented assignment operator
true
7fd189d0f76b16e509eabcd8a12786f19641a6fa
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/popular python packages/pynumbers/app.py
2,543
4.4375
4
import numpy as np # use of alias to shorten module import # array = np.array([1, 2, 3]) # print(array) # print(type(array)) # returns `<class 'numpy.ndarray'>` # creating multi-dimensional array # this is a 2D array or a matrix in mathematics # this is a matrix with 2-rows and 3-columns # array = np.array([[1, 2, 3], [4, 5, 6]]) # print(array) # returns a tuple that specifies the number of items in each dimension # print(array.shape) # returns `(2, 3)` # some interesting methods in numpy to create arrays # this creates an array and initializes it with zeros # takes a shape tuple argument # by defaulf the 0s are floating point numbers # array = np.zeros((3, 4)) # pass a second argument to change the data type # array = np.zeros((3, 4), dtype=int) # initialize array with 1s # array = np.ones((3, 4), dtype=int) # fill array with any other number # array = np.full((3, 4), fill_value=5, dtype=int) # create an array with random values # array = np.random.random((3, 4)) # print(array) # we can access individual element using an index # get element at first row and first column # print(array[0, 0]) # returns whether each corresponding element in the multi-dimensional array # is greater than 0.2 # print(array > 0.2) # boolean indexing. use a boolean expression as index # returns all elements greater than 0.2 in a new 1D array # print(array[array > 0.2]) # methods for performing computations on arrays # returns the sum of all items in the array # print(np.sum(array)) # returns a new multi-D array with the floor of each item # print(np.floor(array)) # returns a new multi-D array with the ceiling of each item # print(np.ceil(array)) # returns a new multi-D array with the round of each item # print(np.round(array)) # we can also perform arithmetic operations between arrays and numbers first = np.array([1, 2, 3]) second = np.array([1, 2, 3]) # NumPy arrays supports all alrithmetic operations you're familiar with # returns a new array by adding corresponding elements in both arrays # print(first + second) # returns a new array, and adds 2 to each individual item # print(first + 2) # a real world example, is when we have an array of numbers in inches # and we want to convert it to centimeters # dimensions_inch = np.array([1, 2, 3]) # convert the array to centimeters # dimensions_cm = dimensions_inch * 2.54 # print(dimensions_cm) # this is how it would be done in normal python code dimensions_inch = [1, 2, 3] dimensions_cm = [item * 2.54 for item in dimensions_inch] print(dimensions_cm)
true
33603d4f428fa7eb1e4a44390281a94547a5503f
tobitech/code-labs
/machine learning/complete_python_programming_for_beginners/data structures/map_function.py
408
4.28125
4
items = [ ("Product1", 10), ("Product2", 9), ("Product3", 12) ] # say we want to transform the above list into a list of prices (numbers) # prices = [] # for item in items: # prices.append(item[1]) # print(prices) # returns a map object which is iterable # x = map(lambda item: item[1], items) # convert map object to a list prices = list(map(lambda item: item[1], items)) print(prices)
true