blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
37f0162910ed4541fbad07ba16b71d71b406449f
BeniyamL/alx-higher_level_programming
/0x03-python-data_structures/2-replace_in_list.py
384
4.3125
4
#!/usr/bin/python3 def replace_in_list(my_list, idx, element): """ replace_in_list - replace an element of a list @my_list: the given list @idx: the given index @element: element to be replaced @Return : the replaced element """ if idx < 0 or idx >= len(my_list): return my_list else: my_list[idx] = element return my_list
true
a7ce1f8eca0bed05c35f6cbaa0671ec1febea9df
BeniyamL/alx-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
311
4.40625
4
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): """function to sort a dictionary Arguments: a_dictionary: the given dictionary Returns: nothing """ sorted_dict = sorted(a_dictionary.items()) for k, v in sorted_dict: print("{0}: {1}".format(k, v))
true
0497d2f931697ad17a338967d629b2c430ece31b
BeniyamL/alx-higher_level_programming
/0x0B-python-input_output/100-append_after.py
660
4.28125
4
#!/usr/bin/python3 """ function defintion for append_after """ def append_after(filename="", search_string="", new_string=""): """ function to write a text after search string Arguments: filename: the name of the file search_string: the text to be searched new_string: the string to be appended Returns: nothing """ result_string = "" with open(filename) as file: for line in file: result_string += line if search_string in line: result_string += new_string with open(filename, mode="w", encoding="utf-8") as file: file.write(result_string)
true
ee769eb6ad867b1e9b7cb2462c2b48ac2abaf5b8
BeniyamL/alx-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
485
4.46875
4
#!/usr/bin/python3 """ print_square function """ def print_square(size): """ function to print a square of a given size Arguments: size: the size of the square Returns: nothing """ if type(size) is not int: raise TypeError("size must be an integer") if type(size) is int and size < 0: raise ValueError("size must be >= 0") for i in range(size): for j in range(size): print("#", end="") print()
true
2d55b3451ad2d1d344cb614b0b8ab8eb085fb125
JanhaviMhatre01/pythonprojects
/flipcoin.py
618
4.375
4
''' /********************************************************************************** * Purpose: Flip Coin and print percentage of Heads and Tails * logic : take user input for how many times user want to flip coin and generate head or * tail randomly and then calculate percentage for head and tail * * @author : Janhavi Mhatre * @python version 3.7 * @platform : PyCharm * @since 21-12-2018 * ***********************************************************************************/ ''' from utilities import utility n = int(input("number of times to flip coin: ")) # number of times user want to flip coin utility.flips(n)
true
65d88e7d92ca1e0ddde0bef59759663520c591fe
TAndrievskiy/Test_python
/hw4/longest_word.py
1,233
4.21875
4
""" 1. Вводится строка 2. Программа считает количество слов в введенной строке и выводит на экран. 2. Программа определяет самое длинное слово и его длину и выводит на экран. ___________________________________________________________________________ Например: ### Hello,world! I am learning python. ### Слов в введенной строке: 6 Самое длинное слово: "learning" (8 символов) """ string = input("Введіть текст:") + " " string = ( string.replace(",", "") .replace(".", " ") .replace("!", " ") .replace("-", "") .replace("?", " ") ) words = string.split() length = len(string) count = 0 _max_ = 0 begin = 0 print("Кількість слів:", len(words)) for i in range(length): if string[i] != " ": count += 1 else: if count > _max_: _max_ = count begin = i - count count = 0 print("Найдовше слово:", string[begin:begin+_max_])
false
38003895f46c8d64b626005812e6a18b649d233b
TAndrievskiy/Test_python
/hw5/practice_1.py
1,704
4.25
4
""" Программу принимает на ввод строку string и число n. Выводит на экран строку с смещенными символами на число n. Весь код можно написать в одной функции main, но рекомендуется разбить код на несколько функций, например: - main - функция для получения не пустой строки. - функция для получения сдвига (целое число). - функция, которая делает сдвиг строки. Пример: Введите строку: python hello world Введите сдвиг: 5 Результат: n hello worldpytho Введите строку: python hello world Введите сдвиг: -2 Результат: ldpython hello wor * используйте индексы, срезы и возможно циклы """ def main(): text = get_text() shift = get_shift_num() shift_perform(text, shift) def get_text(): text = input("Type the text:") if len(text) == 0: print("Incorrect value!") return get_text() else: return text def get_shift_num(): try: shift = int(input("Enter shift:")) return shift except ValueError: print("Incorrect value!") return get_shift_num() def shift_perform(text, shift): shift_text = "" for i in range(len(text)): shift_text = text[shift:] + text[:shift] print(f"Result: {shift_text}") return shift_text if __name__ == "__main__": main()
false
fc8f5cda197bf5b0209f2c18b3089d3dc7d08be9
elenabarreto/includeTec
/Situacion-S3.py
474
4.125
4
# -*- coding: utf-8 -*- print "___________________" print "-*- EJERCICIO 3 -*-" print "___________________" print " " print " " print " " print "_______________________________________________________________________________" print " " presion = input("Ingrese valor de presión: ") volumen = input("Ingrese valor de volúmen: ") temperatura = input("Ingrese valor de temperatura: ") masa = (presion * volumen) / (0.37 * (temperatura + 460)) print("La masa es: ", masa)
false
825238465b41ec4ac2979816c1ef236cc759048a
AvinashMishra1997/projects-for-all
/Dictionary.py
841
4.15625
4
from PyDictionary import PyDictionary dictionary = PyDictionary() print ('choose if u want the antonym or synonym or meaning or translations of a word') d=raw_input ("Enter 'a' for antonym 's' for synonym 'm' for meanings and 't' for translations : ") if d=='m': word=raw_input('Enter the word you want the meaning for: ') print (dictionary.meaning(word)) elif d=='s': word = raw_input('Enter the word you want the synonym for: ') print (dictionary.synonym(word)) elif d=='a': word = raw_input('Enter the word you want the antonym for: ') print (dictionary.antonym(word)) elif d=='t': word = raw_input('Enter the word you want the translation for: ') language = raw_input('enter the language code as per google: ') print (dictionary.translate(word , language)) else: print ('INPUT ERROR')
false
a4eddae42b365b5884a465424f2a6ca1203f358f
iliankostadinov/hackerrank-python
/write-a-function.py
537
4.15625
4
#!/usr/bin/python def is_leap(year): leap = False if year % 400 == 0: leap = True elif year % 100 == 0: leap = False elif year % 4 == 0: leap = True return leap if __name__ == '__main__': year = int(raw_input()) if year < 1900: print "You should enter year between 1900 and 10 on power 5" year = int(raw_input()) elif year > 10**5: print "You should enter year between 1900 and 10 on power 5" year = int(raw_input()) print is_leap(year)
false
8cb108ab7d77ee8f7d7e44b68b2d0b0fdd77849b
rodrigo-meyer/python_exercises
/odd_numbers_selection.py
340
4.3125
4
# A program that calculates the sum between all the odd numbers # that are multiples of 3 and that are in the range of 1 to 500. # Variables. adding = 0 counter = 0 for c in range(1, 501, 2): if c % 3 == 0: counter = counter + 1 adding = adding + c print('The total sum of {} values is {}'.format(counter, adding))
true
b04b13fffc01f746d2e6795682fe9d993702b865
sunilkum84/golang-practice-2
/revisiting_ctci/chapter3/MultiStack_3_1.py
1,314
4.25
4
""" use one array to implement three stacks. i.e. array := []Stack{3} have functions to call the array position and perform the stacks command on the given position """ from stack import Stack class MultiStack(): def __init__(self): self.__stack_list = [Stack(), Stack(), Stack()] self.__pos_err = 'MultiStack has three positions avaliable!' + \ ' index: 0 -> 2.' def Push(self, dat, pos): """ take the given data and add it to the proper stack """ if pos > 2 : raise IndexError(self.__pos_err) self.__stack_list[pos].Push(dat) def Pop(self, pos): if pos > 2 : raise IndexError(self.__pos_err) return self.__stack_list[pos].Pop() def Peek(self, pos): if pos > 2 : raise IndexError(self.__pos_err) return self.__stack_list[pos].Peek() def __repr__(self): outstring = '' for i, x in enumerate(self.__stack_list): dat = f'{i}:\t{x}\n' outstring += dat return outstring if __name__ == '__main__': test = MultiStack() test.Push(1,0) test.Push(2,0) test.Push(3,0) test.Push(4,0) test.Push(5,1) test.Push(6,1) test.Push(7,1) test.Push(8,1) test.Push(9,2) test.Push(10,2) test.Push(11,2) test.Push(12,2) print(test) print('Popped vals:') print(test.Pop(0)) print(test.Pop(1)) print(test.Pop(2)) print('\n') print(test)
false
34c3bec34c7d4c18596381f3ac1c7164a183091f
gulnarap1/Python_Task
/Task3_allincluded.py
2,822
4.1875
4
#Question 1 # Create a list of the 10 elements of four different types of Data Types like int, string, #complex, and float. c=[2, 6, 2+4j, 3.67, "Dear Client", 9, 7.9, "Hey!", 4-3j, 10] print(c) #Question 2 #Create a list of size 5 and execute the slicing structure my_list=[10, 20, ["It is me!"], 40, 50] #Slicing S1=my_list[:3] print(S1) S2=my_list[1:] print(S2) S3=my_list[::2] print(S3) S4=my_list[2][0] print(S4) S5=my_list[2][0][1] print(S5) #Question 3 list = list(range(1,21)) # use argument-unpacking operator i.e. * sum_items = 0 multiplication = 1 for i in list: sum_items = sum_items + i multiplication = multiplication * i print ("Sum of all items is: ", sum_items) print ("Multiplication of all items is: ", multiplication) # Question 4: Find the largest and smallest number from a given list. x=[3,2,7,4,5,10,1,8,9] print(max(x)) print(min(x)) #Question 5: Create a new list that contains the specified numbers after removing # the even numbers from a predefined list. my_list=list(range(1,91)) for i in my_list: if i%2==0: my_list.remove(i) print(my_list) # Question 6: Create a list of first and last 5 elements where the values # are square of numbers between 1 and 30 (both included). initial_list=range(1,31) x=[] for i in initial_list: x=i**2 print(x) #Slicing - I couldnt do the slicing part but tried beneath code which didnt work out a= list(([x[:4], x[-4:]])) print(a) # Question 7: Write a program to replace the last element in a list with another list. # Sample data: [[1,3,5,7,9,10],[2,4,6,8]] # Expected output: [1,3,5,7,9,2,4,6,8] sample_list=[[1,3,5,7,9,10],[2,4,6,8]] begin= sample_list[0][:5] end= sample_list[1][:] a=sample_list[0][:]+sample_list[1][:] print(a) a.remove(10) print(a) #Question 8: Create a new dictionary by concatenating the following two dictionaries: #a={1:10,2:20} #b={3:30,4:40} #Expected Result: {1:10,2:20,3:30,4:40} a={1:10,2:20} b={3:30,4:40} concatenate={} for i in (a,b): concatenate.update(i) print(concatenate) #Question 8: Create a dictionary that contains a number (between 1 and n) in the form(x,x*x). #Expected Output: {1:1,2:4,3:9,4:16,5:25} n=int(input("Input a number ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d) #Question 9: Create a dictionary that contains a number (between 1 and n) in the form(x,x*x). #Expected Output: {1:1,2:4,3:9,4:16,5:25} n=int(input("Input a number ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d) #Question 10: Write a program which accepts a sequence of comma-separated numbers from the console and generate # a list and a tuple which contains every number. Suppose the following input is supplied to the program: #34,67,55,33,12,98 ln = str(input()) li = ln.split(',') tup = tuple(li) li = list(li) print(tup) print(li)
true
46f0f7ed004db78260c547f99a3371bb64ce6b08
MemeMasterJeff/CP1-programs
/9-8-payroll-21.py
2,572
4.125
4
#William Wang & Sophia Hayes #9-8-21 #calculates payroll for each employee after a week #defins the employee class try: class employee: def __init__(self, name, pay): self.name = name self.pay = pay #inputted/calculated values self.rate = float(input(f'How many hours did {self.name} work?\n>')) self.gross = self.pay * self.rate self.social = 0.07 * self.gross self.tax = 0.15 * self.gross #calculates net pay self.net = self.gross - (self.tax + self.social) #defines objects employee1 = employee("Everett Dombrowski", float(8.35)) employee2 = employee('Anagha Nittalia', float(15.50)) employee3 = employee('Luke Olsen', float(13.25)) employee4 = employee('Emily Lubek', float(13.50)) #defines lists people = [employee1.name, employee2.name, employee3.name, employee4.name] payRate = [employee1.pay, employee2.pay, employee3.pay, employee4.pay] hours = [employee1.rate, employee2.rate, employee3.rate, employee4.rate] grossPay = [employee1.gross, employee2.gross, employee3.gross, employee4.gross] socialSecurity = [employee1.social, employee2.social, employee3.social, employee4.social] federalTax = [employee1.tax, employee2.tax, employee3.tax, employee4.tax] netPay = [employee1.net, employee2.net, employee3.net, employee4.net] #used a for loop that iterates through multiple lists to print 4 different sets of information for a, b, c, d, e, f, g in zip(people, payRate, hours, grossPay, socialSecurity, federalTax, netPay): print("{:<15}{:>15}".format("Name:", a)) print("{:<12}{:>15}".format("Pay Rate:", b)) print("{:<12}{:>15}".format("Hours worked", c)) print("{:<12}{:>15}\n".format("Gross pay:", f'${d}')) print("{:<20}".format("Deductions")) print("{:<19}{:<18}".format("\t\tSocial Security:", f'${round(e, 2)}')) print("{:<19}{:<18}\n".format("\t\tFederal Tax:", f'${round(f,2)}')) print("{:<25}{:<18}".format("Net Pay:", f'${round(g,2)}')) print("{:<40}\n".format("----------------------------------")) print(f"Miller Co.\n440 W.Aurora Avenue\nNaperville, IL.60565\n\n") print('{:<40}{:>20}'.format(f"Pay to the Order of: {a}", f'${round(f,2)}\n')) print('{:>80}'.format("----------------------------------")) print('{:>80}\n\n'.format('Mr. Miller, the Boss')) input('press enter key to exit') except: print('program errored out, please check your inputs.')
true
b7c53f9f71b18e7b850c9d6327507cd6590a43e3
gomezquinteroD/GWC2019
/Python/survey.py
557
4.1875
4
#create a dictionary answers = {} # Create a list of survey questions and a list of related keys that will be used when storing survey results. survey = [ "What is your name?", "How old are you?", "What is your hometown?", "What is your date of birth? (DD/MM/YYYY)"] keys = ["name", "age", "hometown", "DOB"] # Iterate over the list of survey questions and take in user responses. i = 0 #index for question in survey: response = input(survey[i] +": ") answers[keys[i]] = response i += 1 #increase index by 1 print(answers)
true
4e808368dcb9f4e791aca828f31a17b47c6947dc
macrespo42/Bootcamp_42AI
/day00/ex03/count.py
1,009
4.375
4
import sys import string def text_analyzer(text=None): """ This functions count numbers of upper/lower letters, punctuation spaces and letters in a string """ upper_letters = 0 lower_letters = 0 punctuation = 0 spaces = 0 text_len = 0 if (text == None): print("What is the text ton analyze ?") text = sys.stdin.readline() spaces -= 1 text_len = len(text) - 1 else: text_len = len(text) for char in text: if (char.isupper()): upper_letters += 1 if (char.islower()): lower_letters += 1 if char in (string.punctuation): punctuation += 1 if char.isspace(): spaces += 1 print("The text contains {} characters:".format(text_len)) print("- {} upper letters".format(upper_letters)) print("- {} lower letters".format(lower_letters)) print("- {} punctuation marks".format(punctuation)) print("- {} spaces".format(spaces))
true
26d14c6b1786baf307400f126ca9c81f183d0aa3
AndrewBatty/Selections
/Selection_development_exercise_2.py
368
4.125
4
# Andrew Batty # Selection exercise: # Development Exercise 2: # 06/102014 temperature = int(input("Please enter the temperature of water in a container in degrees centigrade: ")) if temperature <= 0: print("The water is frozen.") elif temperature >=100: print("The water is boiling.") else: print("The water is neither boiling or frozen.")
true
c224d08507b99b58f1deee67a61a110567c28169
whp5924/Python
/fig09_03.py
860
4.21875
4
# # 基类 派生类 import math class Point: def __init__(self,xValue=0,yValue=0): self.x=xValue self.y=yValue class Circle(Point): def __init__(self,x=0,y=0,radiusValue=0): Point.__init__(self,x,y) self.radius=float(radiusValue) def area(self): return math.pi * self.radius ** 2 print(Point.__bases__) print(Circle.__bases__) print("类Point是类Circle的子类",issubclass(Point,Circle)) print("类Circle是类Point的子类",issubclass(Circle,Point)) b1=Point(10,30) a1=Circle(12,34,2.7) print("对象a1是类Point的一个对象:",isinstance(a1,Point)) print("对象a1是类Circle的一个对象:",isinstance(a1,Circle)) print("对象b1是类Point的一个对象:",isinstance(b1,Point)) print("对象b1是类Circle的一个对象:",isinstance(b1,Circle)) print("圆的面积是:",round(a1.area(),2))
false
3b4608f02475a5cb37397511b3fa5bad4c4007e2
earth25559/Swift-Dynamic-Test
/Number_3.py
530
4.1875
4
test_array = [-2, -3, 4, -6, 1, 2, 1, 10, 3, 5, 6, 4] def get_index(max_val): for index, value in enumerate(test_array): if(value == max_val): return index def find_index_in_array(arr): max_value = arr[0] for value in arr: if value > max_value: max_value = value index = get_index(max_value) print('The greatest value in the array is', max_value) print('The index of the greatest value in the array is', index) return index find_index_in_array(test_array)
true
e4ad61b609bed028b402265b224db05ceef7e2de
itaditya/Python
/Maths/toPostfixConv.py
937
4.125
4
from stack import Stack def prec(operator): if(operator == '^'): return 3 elif(operator == '*' or operator == '/'): return 2 elif(operator == '+' or operator == '-'): return 1 else: return -1 # print("Not a valid operator") def postfixConv(): s = Stack() expression = list(raw_input()) i = 0 postfixExp = "" l = len(expression) while(i < l): if(prec(expression[i]) != -1): # means we get operations if(prec(s.peek()) < prec(expression[i])): # simple situation s.push(expression[i]) else: postfixExp += s.pop() s.push(expression[i]) else: # means we get operands postfixExp += expression[i] i += 1 while(prec(s.peek()) != -1): postfixExp += s.pop() print postfixExp postfixConv() # a + b + c
true
56e9ead65e1b1eea967b3f3a2f54634db55a61b0
Yu-python/python3-algorithms
/5. LeetCode/104.maximum-depth-of-binary-tree/3.py
1,764
4.1875
4
""" 方法三: 广度优先搜索(BFS) https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefb4e/ 解题思路: 首先我们引入一个队列,这是把递归程序改写成迭代程序的常用方法。 1. 队列中只存放「某一层的所有节点」 2. 先记录这一层的节点数 size (队列中元素个数) 3. 迭代 size 次,每次出队一个元素,获取它的左右子节点再入队 4. 迭代完 size 次后,队列中就是下一层的所有节点。将最终结果 ans 值加 1 5. 重复步骤 1 - 4。二叉树的最大深度即为 ans 时间复杂度:O(n),其中 n 为二叉树节点的个数。每个节点只会被遍历一次。 空间复杂度:取决于队列中存储的最大元素个数,其在最坏情况下会达到 O(n)。 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 que = [root] # 创建队列,第一层的所有节点先进入队列 ans = 0 while que: # 如果队列不为空,说明还没有遍历完整棵树 size = len(que) # 每一层的节点个数 for i in range(size): cur = que.pop(0) # 依次将「当前层的所有节点」出队,由 size 正确计算出应该出队多少个节点 if cur.left: que.append(cur.left) # 左子节点入队 if cur.right: que.append(cur.right) # 右子节点入队 ans += 1 # 层数加 1,因为 ans 初始值为 0 return ans
false
275fe7b79c7c091237ce170cb043b4983a1fc1b2
SweLinHtun15/GitFinalTest
/Sets&Dictionaries.py
1,520
4.1875
4
#Sets #include a data type for sets #Curly braces on the set() function can be used create sets. basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) #Demonstrates set operations on unique letters from two words a = set('abracadabra') b = set('alacazm') a # unique letter in a a - b # letter in a but not in b a | b # letters in a or b or both a & b # letters in both a and b a ^ b # letters in a or b but not both a = {x for x in 'abracadabra' if x not in 'abc'} a fruits = {"apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"} print("cherry" in fruits) fruits.add("cucumber") fruits fruits.update("grape", "water melon") fruits fruits.remove("banana") fruits fruits.discard("kiwi") fruits >>>Dictionaries #Dictionaries #Another useful data type bulit into python is the dictionary tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 tel del tel['sape'] tel['irv'] = 4127 tel list(tel) sorted(tel) dict([('sape', 4098,),('guido', 4139), ('irv', 3123)]) dict(sape=4139, guido=4127, jack=4098) {x: x**2 for x in (2,4,6)} {x: x**3 for x in (1,2,3,4,5)} #when looping through dictionaries knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k,v) for i, v in enumerate(['tic','toc','toe']): print(i,v) questions = ['name', 'quest', 'favourite color'] answers = ['lancelot', 'the holy graill', 'blue'] for q, a in zip(questions, answers): ... print('What is your{0}? It is {1}.'.format(q,a))
true
38f1a362e3adc4f816c57980606498d5ab1b56b3
tylors1/Leetcode
/Problems/longestSubarray.py
681
4.125
4
# subarray sum - find the longest subarray sequence # that adds up to a target # FOLLOW UPS: # 1. How would we modify this if we're looking for min subarray sequence? # 2. How would we modify this if we're looking for min subarray sequence equal to OR greater than target? def longestSubarray(nums, k): curr = 0 l = r = 0 res = 0 while r < len(nums): while r < len(nums) and curr < k: curr += nums[r] r += 1 while l < r and curr > k: curr -= nums[l] l += 1 if curr == k: res = max(res, r-l) curr -= nums[l] l += 1 return res k = 10 # nums = [1,1,1,1,1,1,1,1,1,1,5,5] nums = [1,1,1,1,1,5] print longestSubarray(nums, 10)
false
885d43c1619d5ddd8166a60492eb74f026778c5f
Candy-Robot/python
/python编程从入门到实践课后习题/第七章、用户输入与循环/while.py
1,683
4.15625
4
""" prompt = "\nwhat Pizza ingredients do you want: " prompt += "\n(Enter 'quit' when you are finished) " while True: order = input(prompt) if order == 'quit': break print("we will add this "+order+" for you") prompt = "\nwhat Pizza ingredients do you want: " prompt += "\n(Enter 'quit' when you are finished) " massage = '' while massage != 'quit': massage = input(prompt) if massage != 'quit': print("we will add this "+massage+" for you") prompt = "\nhow old are you,tell me: " flag = True while flag: age = input(prompt) age = int(age) if age <= 3: price = 0 elif age <= 12: price = 10 elif age > 12: price = 15 print("your ticket price is "+str(price)) sandwich_orders = ['pastrami','tuna','pastrami','turkey' ,'pig','pastrami','salad'] finished_sandwiches = [] while sandwich_orders: sandwich = sandwich_orders.pop() finished_sandwiches.append(sandwich) print("I made your "+sandwich+" sandwich") print(finished_sandwiches) print(sandwich_orders) print("-------------------------------") print('pastrami is sold out') while 'pastrami' in finished_sandwiches: finished_sandwiches.remove('pastrami') print(finished_sandwiches) """ dream_place = {} massage = "If you could visit one place in the world,where would you go?\n" active = True while active: name = input("what's your name: ") place = input(massage) dream_place[name] = place print("did you finished?") flag = input("YES/NO\n") if flag == 'YES': active = False for name,place in dream_place.items(): print(name+" want to go to "+place) print(dream_place)
true
07df07e0d977f286a3cb28c187f5a4adbbd2fd12
samyhkim/algorithms
/56 - merge intervals.py
977
4.25
4
''' sort by start times first if one interval's end is less than other interval's start --> no overlap [1, 3]: ___ [6, 9]: _____ if one interval's end is greater than other interval's started --> overlap [1, 3]: ___ [2, 6]: _____ ''' def merge(intervals): merged = [] intervals.sort(key=lambda i: i[0]) # sort by start times for interval in intervals: # add to merged if the list of merged intervals is empty # or if the curr interval does not overlap with the prev if not merged or merged[-1][1] < interval[0]: merged.append(interval) # otherwise, there is overlap: prev end > curr start # merge the greater between curr's end and prev's end # ex: [1, 3] and [2, 6] or [1, 5] and [2, 4] else: merged[-1][1] = max(merged[-1][1], interval[1]) return merged input = [[1, 3], [2, 6], [8, 10], [15, 18]] output = [[1, 6], [8, 10], [15, 18]] print(merge(input) == output)
true
79ca667df5a747c3926ca8806022df645789d6d5
abisha22/S1-A-Abisha-Accamma-vinod
/Programming Lab/27-01-21/prgm4.py
437
4.25
4
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> def word_count(str): counts=dict() words=str.split() for word in words: if word in counts: counts[word]+=1 else: counts[word]=1 return counts >>> print(word_count('Think before you do')) {'Think': 1, 'before': 1, 'you': 1, 'do': 1} >>>
true
a00231b5aaa06630c3237083ca1650384ce7d71b
FJLRivera86/Python
/Dictionary.py
1,118
4.53125
5
#DICTIONARY {}: Data structure Like Tuple or List #It's possible save elements,list or tuples in a dictionary firstDictionary = {"Germany":"Berlin", "France":"Paris", "England":"London", "Spain":"Madrid"} #To print a value, It's necessary say its KEY print(firstDictionary) print(firstDictionary["England"]) #ADD element firstDictionary["México"]="León" print(firstDictionary) #MODIFY element value firstDictionary["México"]="Ciudad de México" print(firstDictionary) #DELETE element del firstDictionary["France"] print(firstDictionary) secondDictionary = {"Team":"Chicago Bulls", 1:"23", 23:"Michael Jordan"} print(secondDictionary) #TUPLE for use as KEY and asign VALUES in a DICTIONARY languageTuple = ["México", "France", "Brazil", "Italy"] languageDictionary = {languageTuple[0]:"Spanish", languageTuple[1]:"French", languageTuple[2]:"Portuguese", languageTuple[3]:"Italian"} print(languageDictionary) print(languageDictionary["Brazil"]) # alumnDictionary = {1:"Aguirre", 2:"Biurcos", 3:"Cazares", 4:"Durazo", "Group":{"year":["1st F", "2nd F", "3th F"]}} print(alumnDictionary["Group"]) print[alumnDictionary.keys()]
true
2d042a110b5642719a60a1d5aedc4528bb40cb86
momentum-cohort-2019-05/w2d1-house-hunting-redkatyusha
/house_hunting.py
754
4.1875
4
portion_down_payment = .25 current_savings = 0 r = .04 months = 0 annual_salary_as_str = input("Enter your annual salary: ") portion_saved_as_str = input( "Enter the percent of your salary to save, as a decimal: ") total_cost_as_str = input("Enter the cost of your dream home: ") annual_salary = int(annual_salary_as_str) portion_saved = float(portion_saved_as_str) total_cost = int(total_cost_as_str) down_payment = total_cost / portion_down_payment if annual_salary > 0: monthly_savings = (annual_salary / 12) * portion_saved else: print("You have no income, buddy.") while current_savings < down_payment: months += 1 current_savings += monthly_savings + (current_savings * (r / 12)) print("Number of months:", str(months))
true
f2ce62028c31efdc396f3209e1c30681daa87c17
pmxad8/cla_python_2020-21
/test_files/test_1.py
769
4.21875
4
################### code to plot some Gaussians #################################### #### import libraries #### import math import numpy as np #import numerical library import matplotlib.pyplot as plt #allow plotting n = 101 # number of points xx = np.linspace(-10,10,n) #vector of linearly spaced points s = 0.5,1,1.5,2,5 # vector of sigma values g = np.zeros(n) # making vector of n zeros ## reoding stupid python syntax. This syntax is clunky and I hate it... PI = math.pi EXP = np.exp SQRT= math.sqrt ## loop over all sigma values for sig in s: #this is apparently how loops work in python? g = 1/(sig*SQRT(2*PI)) * EXP(-xx**2/(2*sig**2)) # formula of Gaussian curve plt.plot(xx,g,linestyle = '--') # update python plot plt.show() # actually show the figure
true
b708990ef5d70f151ca468a13784f9b6c49745db
san33eryang/learnpy
/sorted.py
896
4.21875
4
# -*- coding: utf-8 -* # 排序数字,或按照绝对值排序 print(sorted([-2,-6,-99,9,8])) print(sorted([-2,-6,-99,9,8],key = abs)) #排序字母,按照大小写或忽略大小写排序 print(sorted(['bob','about','Zoo','Credit','credit'])) print(sorted(['bob','about','Zoo','Credit','credit'],key=str.lower)) print(sorted(['bob','about','Zoo','Credit','credit'],key=str.lower,reverse=True)) # 练习1 按照字母对list排序 # 方法1 L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_name(t): new_list=sorted(t,key=lambda x:x[0]) return new_list print(by_name(L)) #方法2 def by_name1(t): return t[0] print(sorted(L,key=by_name1)) # 练习2 ,按照分数排序 # 方法1 def by_score(t): new_list=sorted(t,key=lambda x:x[1]) return new_list print(by_score(L)) # 方法2 def by_score1(t): return t[1] print(sorted(L,key=by_score1))
false
7deff2841c1b9164ff335a4b1cb11c3266482a00
SuryaDhole/tsf_grip21
/main.py
2,683
4.125
4
# Author: Surya Dhole # Technical TASK 1: Prediction using Supervised ML (Level - Beginner) # Task Description: in this task, we will predict the percentage of marks that a student # is expected to score based upon the number of hours # they studied. This is a simple linear regression task as it involves just two variables. # Importing required libraries import pandas as pd import numpy as np from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # Importing and Reading the dataset from remote link data = pd.read_csv('http://bit.ly/w-data') print(data) print("data imported successfully!") # Plotting the distribution of score data.plot(x='Hours', y='Scores', style='o') plt.title('Hours vs Percentage') plt.xlabel('Hours Studied') plt.ylabel('Percentage Scored') plt.show() # dividing the data into "attributes" (inputs) and "labels" (outputs) x = data.iloc[:, :-1].values y = data.iloc[:, 1].values x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0) # Training the model reg = LinearRegression() reg.fit(x_train.reshape(-1, 1), y_train) print("Trained!!") # Plotting the regression line line = reg.coef_ * x + reg.intercept_ # Plotting for the test data plt.scatter(x, y) plt.plot(x, line, color='Black') plt.show() # Testing data - In Hours print(x_test) # Predicting the scores y_predict = reg.predict(x_test) # Comparing Actual vs Predicted data = pd.DataFrame({'Actual': y_test, 'Predicted': y_predict}) print(data) # Estimating the Training Data and Test Data Score print("Training score:", reg.score(x_train, y_train)) print("Testing score:", reg.score(x_test, y_test)) # Plotting the line graph to depict the difference between actual and predicted value. data.plot(kind='line', figsize=(8, 5)) plt.grid(which='major', linewidth='0.5', color='black') plt.grid(which='major', linewidth='0.5', color='black') plt.show() # Testing the model. hours = 8.5 test_data = np.array([hours]) test_data = test_data.reshape(-1, 1) own_predict = reg.predict(test_data) print("Hours = {}".format(hours)) print("Predicted Score = {}".format(own_predict[0])) # Checking the efficiency of model # This is the final step to evaluate the performance of an algorithm. # This step is particularly important to compare how well different algorithms # perform on a given dataset print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_predict)) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict)) print('Root mean squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict)))
true
eeb9ffe5b8ebe9beb9eda161b15b61ccea90ba9a
RezaZandi/Bank-App-Python
/old_code/switch_satements.py
758
4.15625
4
""" def main(): print("hi") main_console = ("\nSelect an option to begin:") main_console += ("\nEnter 0 to Create a new account") main_console += ('\nEnter 1 to Deposit') main_console += ('\nEnter 2 to Withdraw') main_console += ('\n What would you like to do?: ') while True: user_option = int(input(main_console)) """ def action_1(): print("action1") def action_2(): print("action2") def action_3(): print("i'm happy with option 3") def unknown_action(): print("unknown") main_console = ("choose a number ") number_choice = int(input("choose a number: ")) switcher = { 1: action_1, 2: action_2, 3: action_3 } switcher.get(number_choice,unknown_action)()
true
382fbdd4d1b95633025b9f2951ddaa904a1727f1
AdaniKamal/PythonDay
/Day2/Tuple.py
2,762
4.53125
5
#Tuple #1 #Create a Tuple # Set the tuples weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") weekend = "Saturday", "Sunday" # Print the tuples print('-------------------------EX1---------------------------------') print(weekdays) print(weekend) #2 #Single Item Tuples a = ("Cat") b = ("Cat",) print('-------------------------EX2---------------------------------') print(type(a)) print(type(b)) #3 #Tuple containing a List # Set the tuple t = ("Banana", ['Milk', 'Choc', 'Strawberry']) print('-------------------------EX3---------------------------------') # Print the tuple print(t) #4 #Access the Values in a Tuple # Set the tuple weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") print('-------------------------EX4---------------------------------') # Print the second element of the tuple print(weekdays[1]) #range weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") print(weekdays[1:4]) #5 #Access a List Item within a Tuple t = (101, 202, ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]) print('-------------------------EX5---------------------------------') print(t[2][1]) #6 #Update a Tuple # Set and print the initial tuple weekend = ("Saturday", "Sunday") print('-------------------------EX6---------------------------------') print(weekend) # Reassign and print weekend = ("Sat", "Sun") print(weekend) #7 #Update a List Item within a Tuple # Assign the tuple t = (101, 202, ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]) print('-------------------------EX7---------------------------------') print(t) # Update the third list item t[2][2] = "Humpday" print(t) #8 #Concatenate Tuples (Combine) #Can also use a tuple as the basis for another tuple. #For example, can concatenate a tuple with another one to create a new a tuple that contains values from both tuples. # Set two tuples weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") weekend = ("Saturday", "Sunday") # Set a third tuple to the value of the previous two alldays = weekdays + weekend print('-------------------------EX8---------------------------------') # Print them all print(weekdays) print(weekend) print(alldays) #9 #Delete a Tuple t = (1,2,3) del t #10 #Named Tuples #Need to import modules # Import the 'namedtuple' function from the 'collections' module from collections import namedtuple # Set the tuple individual = namedtuple("Individual", "name age height") user = individual(name="R3in3", age=20, height=160) print('-------------------------EX10---------------------------------') # Print the tuple print(user) # Print each item in the tuple print(user.name) print(user.age) print(user.height) print('-------------------------THANK YOU---------------------------------')
true
8d96260c69e129db0e133a1d23042af4eea88c40
gongnanxiong235/fullstack
/day10/lesson_set.py
990
4.15625
4
# author:gongnanxiong # date:2018/11/22 ''' set的两大用途: 1.去重,把列表转换成set之后自动去重 2.关系式 set的key都是可哈希的,也就是key不能是列表和字典 set是可变的,非可哈希的,所以set也不能作为dict的key set是无顺序的,所以不能像list一样通过下标找到元素,只能通过遍历和iter的方式 set是无顺序的,所以set.pop()是随机删除一个值 ''' set_a=set([1,2,3]) set_b=set([1,2,3]) print(set_a==set_b) set_b.add(4) print(set_a<set_b) set_a.update([4,5,6]) print(set_a) print(set_a>set_b) # set_a.remove('hello')# 如果remove的key不存在会报错 # 差级 print(set_a.difference(set_b)) print(set_a-set_b) # 反向差级 set_b.add(7) print(set_a.symmetric_difference(set_b)) print(set_a^set_b) # 取并集 print(set_a.union(set_b)) print(set_a|set_b) print("---------") print(set_a) print(set_b) print(set_a-set_b) # 取交集 print(set_a.intersection(set_b)) print(set_a & set_b)
false
9ab16b835f79e48d35d6ceed5b216e73cc9a090b
RobsonDaniel/Treinamento-python3
/aula6_atividade.py
1,235
4.21875
4
''' Exercício: Escreva uma função que recebe um objeto de coleção e retorna o valor do maior número dentro dessa coleção. Faça outra função que retorna o menor número dessa coleção. ''' # def maior_numero(lista_numero): # return max(lista_numero) # # def menor_numero(lista_numero): # return min(lista_numero) def maior_numero(lista_numero): # [55,5,93,0] # 55>0 #55 # 55>93 #93 # 93>5 #93 numeros = lista_numero maior = numeros[0] contador = len(numeros)-1 #3 while contador > 0: if maior > numeros[contador]: maior = maior else: maior = numeros[contador] contador -= 1 return maior def menor_numero(lista_numero): # [55,5,93,0] # 55<5 #5 # 5<93 #5 # 5<0 #0 numeros = lista_numero menor = numeros[0] contador = len(numeros)-1 #3 while contador > 0: if menor < numeros[contador]: menor = menor else: menor = numeros[contador] contador -= 1 return menor numeros = [55,5,93,0] print(f"O maior número da lista {numeros} é {maior_numero(numeros)}") print(f"O menor número da lista {numeros} é {menor_numero(numeros)}")
false
9ffe03358e681158af1452776150deb8057eaa29
violetscribbles/Learn-Python-3-the-Hard-Way-Personal-Exercises
/Exercises 1 - 10/ex9.py
791
4.28125
4
# Here's some new strange stuff, remember type it exactly. # Defines 'days' variable as a string days = "Mon Tue Wed Thu Fri Sat Sun" # Defines 'months' variable as a string. Each month is preceded by \n, which # is an escape character that tells python to create a new line before the # text. months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # Prints a string and then variable 'days' print("Here are the days: ", days) # Prints a string and then variable 'months' print("Here are the months: ", months) # Prints a multi-line string using """, which achieves the same effect as # /n but is more readable. print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """)
true
361d9db0d848b177a18fb734d04451616ef06a2a
Rolodophone/various-python-programs
/Completed/String manipulation programming challenges 2.py
689
4.15625
4
while True: string = input("\n\nEnter a string") option = input("Would you like to:\nFind the [N]umber of characters in " "the string\n[R]everse the string\nConvert the string " "to [U]ppercase\nConvert the string to [L]owercase\n") if option == "n": print(len(string)) elif option == "r": print(string[::-1]) elif option == "u": print(string.upper()) elif option == "l": print(string.lower()) option = input("Would you like to input [A]nother string or [L]eave?") if option == "l": exit() elif option == "a": continue else: break
false
974f629117846daae4de8b0e22b1d68407763078
study-material-stuff/Study
/Study/Python/Assignments/Assignment 8/Assignment8_5.py
570
4.28125
4
#5.Design python application which contains two threads named as thread1 and thread2. #Thread1 display 1 to 50 on screen and thread2 display 50 to 1 in reverse order on #screen. After execution of thread1 gets completed then schedule thread2. import threading; def DispNumbers(): for no in range(1,51): print(no); def DispReverseNumbers(): for no in range(50,0,-1): print(no); thread1 = threading.Thread(target = DispNumbers ); thread2 = threading.Thread(target = DispReverseNumbers); thread1.start(); thread1.join(); thread2.start();
true
2fb056ddefd2368f9947f213e92627b9e09071e1
study-material-stuff/Study
/Study/Python/Assignments/Assignment 4/Assignment4_1.py
238
4.28125
4
#1.Write a program which contains one lambda function which accepts one parameter and return #power of two. powerof2 = lambda num : num * num; num = int(input("Enter the number :")); print("power of the number is ",powerof2(num));
true
d023f2fe5bfb44a3ca32176ad557542eeaf0883b
Devil-Rick/Advance-Task-6
/Inner and Outer.py
506
4.1875
4
""" Task You are given two arrays: A and B . Your task is to compute their inner and outer product. Input Format The first line contains the space separated elements of array A . The second line contains the space separated elements of array B . Output Format First, print the inner product. Second, print the outer product. Sample Input """ import numpy as np A, B = [np.array([input().split()], int) for _ in range(2)] print(np.inner(A, B)[0][0], np.outer(A, B), sep="\n")
true
c1108c9ae69f08de277b80fbba0d450c245fe081
mygoal-javadeveloper/Dataquest.io
/Machine Learning Introduction/Calculus For Machine Learning/Finding Extreme Points-159.py
565
4.15625
4
## 3. Differentiation ## import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5,6,110) y = -2 * x + 3 plt.plot(x,y) plt.show() ## 6. Power Rule ## slope_one = 5 * (2 ** 4) print(slope_one) slope_two = 9 * (0 ** 8) print(slope_two) ## 7. Linearity Of Differentiation ## slope_three = 5 * (1 ** 4) - 1 print(slope_three) slope_four = 3 * (2 ** 2) - 2 * (2 ** 1) print(slope_four) ## 8. Practicing Finding Extreme Values ## rel_min = [] rel_max = [] derivative = 3 * (x ** 2) - 2 * (x) critical_points = [0, 2/3] rel_min = [2/3] rel_max = [0]
false
e9ff6b17552a2cc278d5817ce0ced6ef730cc144
ilakya-selvarajan/Python-programming
/mystuff/4prog2.py
353
4.21875
4
#a program that queries the user for number, and proceeds to output whether the number is an even or an odd number. number=1 while number!=0: number = input("Enter a number or a zero to quit:") if number%2==0 and number!=0: print "That's an even number" continue if number%2==1: print "That's an odd number" if number==0: print "bye"
true
876eb77d4a81863b5d478f37827c0298a4270cf2
ilakya-selvarajan/Python-programming
/mystuff/7prog6.py
440
4.125
4
#A function which gets as an argument a list of number tuples, and sorts the list into increasing order. def sortList(tupleList): for i in range( 0,len(tupleList) ): for j in range(i+1, len(tupleList) ): if tupleList[j][0]*tupleList[j][1]<tupleList[i][0]*tupleList[i][1]: temp=tupleList[j] tupleList[j]=tupleList[i] tupleList[i]=temp myList = [(2, 3.0), (3, 1.0), (4, 2.5), (1, 1.0)] sortList(myList) print myList
true
eee40d974a515868c2db25c959e1cfa303002d00
ilakya-selvarajan/Python-programming
/mystuff/8prog4.py
433
4.21875
4
# A function to find min, max and average value from __future__ import division def minMaxAvg(dict): sum=0 myTuple=() myValues= dict.values() #extracting the values for values in myValues: sum+=values avg=sum/len(myValues) #Calculating the average myTuple=(min(myValues),max(myValues),avg) #Returning the min, max, and avg return myTuple d = {"a":0, "b":-1, "c":3, "d":6, "e":11, "f":8} print minMaxAvg(d)
true
2600172fbc0223edb28af3000ea79adc68a81210
luisauribe/Python-languaje
/listas.py
1,310
4.15625
4
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 mi_lista = [17, 39, "Laura", True] print(mi_lista) # Asigna un valor nuevo al indive 1 mi_lista[1] = 7 print(mi_lista[:]) # Accede al indice 1 e imprime desde el 1 hasta el 3 omitiendo el 3 print(mi_lista[1:3]) # Imprime la lista completa print(mi_lista[:]) # Agrega un nuevo elemento al final de la lista mi_lista.append("Maria") print(mi_lista[:]) # Empieza a contar desde el final de la lista print(mi_lista[-2]) # Accede al indice e imprime los dos últimos elementos hastael final de la lista print(mi_lista[2:]) # Añade un elemento en el indice deseado mi_lista.insert(3,50.87) print(mi_lista[:]) # Toma una lista como argumento y agrega todos los elementos lista_2 = ["Numeros", 5, 87.32] mi_lista.extend(lista_2) print(mi_lista[:]) # Muestra el indice en el que se encuentra un element print(mi_lista.index("Maria")) # Revisa si hay dicho elemento en la lista print("Laura" in mi_lista) # Elimina elementos de la lista mi_lista.remove(True) print(mi_lista[:]) # Elimina el ultimo elemento de la lista mi_lista.pop() print(mi_lista[:]) # Suma listas lista_3 = [1, 2, 3, 'a', 'b', 'c'] print(mi_lista + lista_3) # Multiplica una lista print(mi_lista * 3)
false
12a89096fd6ad6bab15da2f113bd6d6067292380
luisauribe/Python-languaje
/ejercio_1.py
335
4.15625
4
num_1 = int(input("Introduce un numero: ")) num_2 = int(input("Introduce otro numero: ")) def devuelve_max(num_1, num_2): if num_1 > num_2: print("El número más alto es: ", num_1) elif num_1 < num_2: print("El número mas alto es: ", num_2) else: print("Son iguales") devuelve_max(num_1, num_2)
false
68b01adeba8e433530175f0c39a80c5c336d1ce3
thinboy92/HitmanFoo
/main.py
2,562
4.21875
4
### Animal is-a object (yes, sort of confusing) look at the extra credit class animal(object): def __init__(self, type): self.type = type def fly(self): print "This %s can fly" %(self.type) ## Dog is-a animal class Dog(animal): def __init__(self, name): # class Doh has-a __init__ that accepts self and name parameters ## Dog has-a name self.name = name ## cat is-a animal class Cat(animal): def __init__(self, name): ## class Cat has-a __init__ that accepts self and name parameters self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## class Person has-a __init__ that accepts self and name parameters self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): super(Employee, self).__init__(name) ## this ## gives access to the name attribute ## of Employee's parent object i.e. Person. ## apparently useful in the case of multiple inheritance. ## Employee has-a salary self.name = name self.salary = salary print "%s's salary is %d" % (self.name,self.salary) def write(self,name,salary): print "This is invoked by using function in a class. %s's salary is %d" % (name,salary) ## Fish is-a object class Fish(object): def __init__(self,steam): self.steam = steam() def fry(): print "Whether to steam or fry %s" %(self.steam) ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## Satan is-a Cat satan = Cat("Satan") ## Mary is-a Person mary = Person("Mary") ## From mary, take the attribute pet and set it to variable satan. mary.pet = satan # Now, mary's pet is-a cat object named satan ## frank is-a Employee with parameters Frank and 120000 frank = Employee("Frank", 120000) frank.write("Frank", 120000) ## from frank, take the pet attribute and set it to rover. frank.pet = rover # frank's pet is-a dog object named rover ## set flipper to an instance of class Fish # flipper is-a fish #flipper = Fish(steam) ##afeez, When I run it in python or Terminal this is what I get: ##Traceback (most recent call last): ## File "ex42.py", line 85, in <module> ## flipper = Fish() ##TypeError: __init__() takes exactly 2 arguments (1 given) ## setting crouse to an instance of class Salmon # course is-a salmon and salmon is-a fish #crouse = Salmon() ## set harry to an instance of class Halibut # harry is-a halibut and halibut is-a fish #harry = Halibut()
true
03bc0cf52a337355dc9d829995465da3778f8531
bulsaraharshil/MyPyPractice_W3
/class.py
1,071
4.40625
4
class MyClass: x = 5 print(MyClass) #Create an object named p1, and print the value of x class MyClass: x=5 p1=MyClass() print(p1.x) #Create a class named Person, use the __init__() function to assign values for name and age class Person: def __init__(self,name,age): self.name = name self.age = age p1 = Person("John",36) print(p1.name) print(p1.age) #Insert a function that prints a greeting, and execute it on the p1 object class Person: def __init__(self,name,age): self.name = name self.age = age def myfunc(self): print("Hello my name is "+ self.name) p1 = Person("John",36) p1.myfunc() #Use the words mysillyobject and abc instead of self class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() #Set the age of p1 to 40 p1.age = 40 print(p1.age) #Delete the age property from the p1 object del p1.age print(p1.age) #Delete object p1 del p1 print(p1)
true
1f468a2055ef8548a517fb5333f574737a2da217
bulsaraharshil/MyPyPractice_W3
/lambda.py
768
4.5
4
#lambda arguments : expression #A lambda function that adds 10 to the number passed in as an argument, and print the result x = lambda x:x+5 print(x(5)) #A lambda function that multiplies argument a with argument b and print the result x = lambda a,b:a*b print(x(5,6)) #A lambda function that sums argument a, b, and c and print the result x = lambda a,b,c:a+b+c print(x(5,6,7)) #Use that function definition to make a function that always doubles the number you send in def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) #use the same function definition to make both functions, in the same program def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) print(mytripler(12))
true
e42b70c7d1d2a3284808ef118eedfb1a1a90d63e
BI4HUU/WEB
/py.py
2,703
4.28125
4
print("Показать ето в консоль") name = 8 # переменная input("1") # Предлагает ввести даные # Преобразовать тип даных int(name) # В число str(name) # В строку float(name) # В число с точкой del name # Удалить переменную name += 80 # Условные операции ten = 10 if ten == 1: print("ok1") elif ten == 10: print("ok10") else: print("ok--") # Цыклы i = 0 while i < 10: print(i) i += 1 for j in "hello": print(j) continue # прпустить ету итерацию break # выйти с цыкла else: # выполнится если break был но сработал print(0) # Списки (Массивы) aray = [1, "a", True] aray2 = [2] aray.append("append")# добавля в конец масива aray.extend(aray2)# добавля в конец масива масив aray.insert(2, aray2)# добавля в 2 место масива масив aray.remove("a") # Удалить "a" с масива aray.pop(2) # Удалить 2 елемент с масива aray.index("append") # вернет индекс значения "append" aray.sort() # сортирует с меньшего к большему значению aray.clear() # Очищает список (Массивы) aray[2:4:1]#Обрезать с 1 елмент до 4 с шагом 1 # Кортежи korteg = (1, "a", True) #Словари (асоциативный масив) slovar + {'klyuch' : 'znachenia', 'klyuch2' : 'znachenia2'} slovar['klyuch2'] = 'znachenia3' #Функции def nameFun(e): return e (lambda e: print(e))(8) # Исключения (ошибки) try: 5/0 except ZeroDivisionError: False else: True finally: 100% # робота с файламы filename = open('test.py', 'rt' encoding='utf-8') print(filename.read()) filename.write("NewText") filename.close #Модули import math, os from myModule import fun1 import myModule as mm # myModule.py # ООП class nameClass: name = "Nastya" age = 18 def __init__(self, name): self .name = name # def set(self, name): # self .name = name class nameClass2(nameClass): course = 2 class2 = nameClass("Vika") # class2.set("Vika") print(class2.age) print(class2.name) #Декоратори def decorator (func): def wrapper (): print("Код ДО") func() print("Код ПОСЛЕ") return wrapper @decorator # def s (): print("Код") # s = decorator(s) s()
false
8fdbe01a6176568addcfe99fa3eafbf386c740f0
dindamazeda/intro-to-python
/lesson3/homework/3.third_task.py
1,606
4.40625
4
# TREĆI ZADATAK # Dat je niz imenica u nasumičnom redosledu. # Napisati program koji će da grupiše imenice u novu listu na osnovu početnog slova tj. da ih poređa po redosledu # Međutim ima jedan uslov - prve imenice u novoj listi moraju da počinju sa slovom 'm', a nakon toga treba da ide po alfabetu # Videti primer ispod # ## primer ### # imenice = ['patka', 'kvaka', 'staka', 'barka', 'marka', 'koka', 'ljorka', 'abrakadabra', 'mantra', 'karma', 'deka', 'seka', 'mleka'] # program: ['mantra', 'marka', 'mleka', 'abrakadabra', 'barka', 'deka', 'karma', 'koka', 'kvaka', 'ljorka', 'patka', 'seka', 'staka' ] # # Third Task # a list of words in random is given. # Write a program that group the words into a new list based on the initial letter. to sort them in order # However, there is one condition - the first nouns in the new list must start with the letter 'm', and after that it should go in alphabetical order # See example below # Example # nouns = ['patka', 'kvaka', 'staka', 'barka', 'marka', 'koka', 'ljorka', 'abrakadabra', 'mantra', 'karma', 'deka', 'seka', 'mleka'] # program: ['mantra', 'marka', 'mleka', 'abrakadabra', 'barka', 'deka', 'karma', 'koka', 'kvaka', 'ljorka', 'patka', 'seka', 'staka' ] words = ['patka', 'kvaka', 'staka', 'barka', 'marka', 'koka', 'ljorka', 'mantra', 'karma', 'deka', 'seka', 'mleka'] sorted_words = sorted(words) m_words =[] no_m_words = [] for x in sorted_words: if x[0][0]=='m': m_words.append(x) else: no_m_words.append(x) final_words = [] final_words.extend(m_words) final_words.extend(no_m_words) print(final_words)
false
06dc005308c02f4950075b21aa04fec50a073fc7
dindamazeda/intro-to-python
/lesson3/homework/6.sixth_task.py
1,038
4.15625
4
# ŠESTI ZADATAK # # Napisati program koji će da uzme dve liste i od njih napravi dictionary gde će elementi prve liste biti ključevi, a elementi druge liste vrednosti # ### primer ### # # voce = ['banane', 'kivi', 'limun', 'lubenica', 'grejpfrut', 'jabuke', 'ananas'] # # cene = [127.5, 119.8, 220.3, 84.4, 255.8, 65.3, 182] # program: {'banane': 127.5, 'kivi': 119.8 itd. } # # Sixth Task # Write a program that will take two lists and make a dictionary out of them where the elements of the first list will be the keys and the elements of the second list the values # Example # # fruit = ['bananas', 'kiwi', 'lemon', 'watermelon', 'grapefruit', 'apples', 'pineapple'] # # prices = [127.5, 119.8, 220.3, 84.4, 255.8, 65.3, 182] # program: {'bananas': 127.5, 'kiwis': 119.8, etc.} fruit = ['bananas', 'kiwi', 'lemon', 'watermelon', 'grapefruit', 'apples', 'pineapple'] prices = [127.5, 119.8, 220.3, 84.4, 255.8, 65.3, 182] dictionary_fruit = {} for x in range(len(fruit)): dictionary_fruit[fruit[x]] = prices[x] print(dictionary_fruit)
false
0c1e3c615df5d832a4f875b51a8ec27a25dddfa8
dindamazeda/intro-to-python
/lesson4/homework/5. frequency-in-paragraph.py
2,916
4.25
4
# PETI ZADATAK # Napisaćemo program koji utvrđuje frekventnost slova u srpskom jeziku nad datim tekstom # Potrebno je ispisati rečnik sa slovom i procenat (udeo) tog slova u odnosu na ukupan broj slova # npr. ako je dat tekst -> patka je slatka, program treba da zna sledeće: # u tekstu ima 13 slova (razmaci se ne računaju kao slovo!) dok se slovo 'a' ponavlja 4 puta # To znači da u rečniku treba da stoji a: 30.76 jer je toliki udeo (procenat) slova a u odnosu na ukupan broj slova # Pažnja! - promenljiva koja je data ispod je i dalje string i ponaša se isto kao i svaki string bez obzira što je na više linija to je i dalje jedan string! # U Pythonu su dozvoljeni stringovi na više linija (ako je tekst dugačak kao ovaj naš sada npr.) samo se umesto apostrofa ili navodnika stave 3 apostrofa ili 3 navodnika # FIFTH TASK # We will write a program that determines the frequency of letters in the Serbian language over a given text # It is necessary to print a dictionary with the letter and the percentage (share) of that letter in relation to the total number of letters #e.g. if the given text -> patka je slatka, the program should know the following: # there are 13 letters in the text (spaces do not count as a letter!) while the letter 'a' is repeated 4 times # This means that the dictionary should say a: 30.76 because that is the proportion of letters and in relation to the total number of letters # Attention! - the variable given below is still a string and behaves the same as any string no matter that it is on multiple lines it is still a single string! # In Python, multi-line strings are allowed (if the text is as long as ours now, for example) only 3 apostrophes or 3 quotation marks are placed instead of apostrophes or quotation marks tekst = """Prestižno priznanje Man Buker u fokus najpre stavlja uži izbor koji je u septembru prošle godine imao šest knjiga. Nagradu je, među autorima koji su pažnju posvetili osobenom istraživanju engleskog jezika, temama istraživanja bola, društvene i rodne nepravde, kao i ugrožene prirode, prvi put osvojila autorka iz Severne Irske Ana Berns za roman Mlekadžija. Ona je osvetlila problem zlostavljanja jedne mlade devojke. Zašto se bavimo brojevima kada je u stvaralaštvu, u bilo kojoj umetničkoj oblasti, kvalitet najvažniji? Upravo zbog toga što je i književno stvaranje oblast slobode u kojoj ne bi trebalo da vlada industrijalizacija kreacije, odnosno osrednjost u štancovanju.""" #tekst = 'Dinda , . Mazeda' text = tekst.replace(' ','') text = text.replace(',','') text = text.replace('.','') text = text.replace('?','') text = text.replace('\n','') list_text = list(text.lower()) dictionary_letter = {} for x in list_text: dictionary_letter.setdefault(x,0) if x in dictionary_letter: dictionary_letter[x] +=1 dictionary_letter [x] = round(dictionary_letter [x]/len(list_text)*100,3) print (dictionary_letter)
false
36b2d60352a9e55abb53d30f25e98319383dadc0
dindamazeda/intro-to-python
/lesson3/exercise/7.element-non-grata.py
542
4.28125
4
# We have a list of sweets. Write a program that will ask the user which is his least favourite sweet and then remove that sweet from the list ### example ### # sweets = ['jafa', 'bananica', 'rum-kasato', 'plazma', 'mars', 'bananica'] # program: Which one is your least favourite? # korisnik: bananica # program: ['jafa','rum-kasato', 'plazma', 'mars'] sweets = ['jafa', 'bananica', 'rum-kasato', 'plazma', 'mars', 'bananica'] print(sweets) input_sweet = input('Which one is your least favpurite? ') sweets.remove(input_sweet) print(sweets)
true
05cb1521168d0320f080cd8c25137ea9ef6e91b9
dindamazeda/intro-to-python
/lesson2/exercises/3.number-guessing.py
821
4.1875
4
# Create list of numbers from 0 to 10 but with a random order (import random - see random module and usage) # Go through the list and on every iteration as a user to guess a number between 0 and 10 # At end the program needs to print how many times the user had correct and incorrect guesses # random_numbers = [5, 1, 3, 9, 7, 2, 4, 6, 8] # program: Guess a number between 0 and 10. # (If we look at the above list the current number is 5) user: 8 # program: That is not a correct number. Try to guess a new number between 0 and 10. # (If we look at the above list the next number is 1) user: 1 # program: Bravo! That is the correct number. Try to guess a new one. # The program continues until the end of the list... # program: Congratulations. You've guessed the correct number 3 times and 7 times you were not correct.
true
227d3c1780cca1ea0979d759c9a383fcdafb2314
dindamazeda/intro-to-python
/lesson1/exercises/6.more-loops_dm.py
612
4.3125
4
# write a loop that will sum up all numbers from 1 to 100 and print out the result ### example ### # expected result -> 5050 sum = 0 for numbers in range(1, 101): sum = sum + numbers print(sum) # with the help of for loop triple each number from this list and print out the result numbers = [5, 25, 66, 3, 100, 34] for number in numbers: triple = number * 3 print(triple) # with the help of for loop and range() function print out all odd numbers from 1 to 100 ### example ### # program: 1, 3, 5, 7 etc. for numbers in range(1, 101): if numbers % 2 == 0: continue print(numbers)
true
bb941f4da9976abb554a43fe2d348ec956587cf1
micalon1/small_tasks
/part5.py
760
4.125
4
shape = input("Enter a shape: ") s = "square" r = "rectangle" c = "circle" if shape == s: l = int(input("What is the length of the square? ")) print("The area of the square is {}.". format(l**2)) elif shape == r: h = int(input("What is the height of the rectangle? ")) w = int(input("What is the width of the rectangle? ")) print("The area of the rectangle is {}.". format(h*w)) elif shape == c: r = int(input("What is the radius of the circle? ")) q = input("Enter 'c' for circumference or 'a' for area: ") if q == "c": print("The circumference is {}.". format(6*r)) elif q == "a": print("The area is {}.". format(3*r**2)) else: print("Invalid choice.") else: print("Invalid shape.")
true
7bd385f1465918ac1c73311062647516a0d8ce74
ritesh2k/python_basics
/fibonacci.py
328
4.3125
4
def fibonacci(num): if num==0: return 0 elif num==1: return 1 else: return fibonacci(num-1)+fibonacci(num-2) #using recursion to generate the fibonacci series num=int(input('How many fibonacci numbers do you want? \n')) print('Fibonacci numbers are :\n') for i in range(num): print(fibonacci(i) , end=' ') print()
true
7c3e9c6db39509af1c38818f60a5b9c9697697c4
ritesh2k/python_basics
/sentence_capitalization.py
429
4.3125
4
def capitalization(str): str=str.strip() cap='' for i in range(len(str)): if i==0 or str[i-1]==' ':cap=cap+str[i].upper() #checking for the space and the first char of the sentence else: cap=cap+str[i] #capitalizing the character after space #cap =[words[0].upper()+words[1:]] print ('The result is:\n{}'.format(cap)) str=input('Enter the sentence and each word will be capitalized:\n') capitalization(str)
true
7a6c27963f8e1adcba4b636cd29fdf598acdde0b
YeasirArafatRatul/Python
/reverse_string_stack.py
492
4.125
4
def reverse_stack(string): stack = [] #empty #make the stack fulled by pushing the characters of the string for char in string: stack.append(char) reverse = '' while len(stack) > 0: last = stack.pop() #here the pop function take the last character first thats why #we have to put it as the right operand reverse = reverse + last return reverse string = input("Give Input:") result = reverse_stack(string) print(result)
true
817a383769b024049a81ad3e76be36231099462d
YeasirArafatRatul/Python
/reverse_string_functions.py
340
4.625
5
def reverse_string(string): reverse = "" #empty for character in string: """ when we concate two strings the right string just join in the left string's end. """ reverse = character + reverse return reverse string = input("Enter a string:") result = reverse_string(string) print(result)
true
2c5b1e85b26ea93a1f6636758db8889b28b7798a
tnotstar/tnotbox
/Python/Learn/LPTHW/ex06_dr01.py
822
4.5
4
# assign 10 to types_of_people types_of_people = 10 # make a string substituting the value of types_of_people x = f"There are {types_of_people} types of people." # assign some text to some variables binary = "binary" do_not = "don't" # make a string substituting last variable's values y = f"Those who know {binary} and those who {do_not}." # printing string variables print(x) print(y) # printing formatting string values print(f"I said: {x}") print(f"I also said: '{y}'") # assigning some values to some variables hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" # printing a formatted string print(joke_evaluation.format(hilarious)) # again, assigning some text to some vars w = "This is the left side of..." e = "a string with a right side." # printing a concatenation expression print(w + e)
true
d854d2f8e29e061f085af15ac1da61b4cf9a6283
wendotdot/my-first-blog
/tutorial.py
280
4.21875
4
if 5 > 2 : print("5 is greater than 2") else : print("5 is not greater than 2") name = "Wendy" def hi(name): #print("Hi There") #print("How are you?") if name == "Ola": print("Hi Ola!") elif name == "Sonja": print("Hi Sonja!") else: print("Hi Anonymous") hi(name)
false
833d91dfe8f65ce41b7dfa9b4ae15632a03e6170
undefinedmaniac/AlexProjects
/Basic Python Concepts/if statements and loops.py
1,580
4.40625
4
# If statements are used to make decisions based on a conditional statement # for example, the value in a variable could be used variable1 = True variable2 = False if variable1: print("True") # else if statements can be added to check for additional conditions if variable1: print("Variable 1 is True") elif variable2: print("Variable 2 is True") # else statements can be added as a sort of "default" for when none of the other # conditions are met if variable1: print("Variable 1 is True") elif variable2: print("Variable 2 is True") else: print("Variable 1 and Variable 2 are both False") # Remember that only one of the available branches in an if statement is executed # Also remember OR and AND operators if variable1 or variable2: print("Variable 1 or Variable 2 is True (or possibly both)") if variable1 and variable2: print("Variable 1 and Variable 2 are both True") # Now fixed count loops # Count to 10 and print 0 - 9 # i is the index for each loop for i in range(10): print(i) # Python allows easy looping through lists as well list1 = ["Hello", "There", "Alex"] for i in list1: print(i) # While loops repeat steps until a condition is false # Count to 10 and print 0 - 9 count = 0 while count != 10: print(count) count += 1 # This is commonly used as an infinite loop while True: # "break" leaves a loop early break # "continue" skips the rest of the code in a loop and moves to the next iteration # Print 0 - 9 but skip 5 for i in range(10): if i == 5: continue print(i)
true
971247c94cba717a85b4d900b0f93ae2bb6338a1
radek-coder/simple_calculator
/run_it.py
636
4.21875
4
from addition import addition from multiplication import multiplication from division import division from subtraction import subtraction num_1 = int(input("Please insert your first number: ")) num_2 = int(input("Please insert your second number: ")) operation = input("Please insert your operation ") if operation == "x" or operation == "X" or operation == "*": print(multiplication(num_1, num_2)) elif operation == "+": print(addition(num_1, num_2)) elif operation == "-": print(subtraction(num_1, num_2)) elif operation == "/": print(division(num_1, num_2)) else: print("You are trying to break my calculator")
true
f88b699c69329d90c31d9b9d18ca19bb7f671090
Arl-cloud/Python-basics
/basics5.py
2,327
4.28125
4
#For loops: How and Why monday_temperatures = [9.1, 8.8, 7.6] print(round(monday_temperatures[0])) #print rounded number with index 0 #in 1st iteration, variable temp = 9.1, in the 2nd iteration 8.8 for temp in monday_temperatures: print(round(temp)) #executed command for all items in an array print("Done") for letter in "hello": print(letter.title()) #array can also be a string #For loop (with if condition) that prints out only numbers in colors over 50 colors = [11, 34, 98, 43, 45, 54, 54] for foo in colors: if foo > 50: print(foo) #prints out only if number in colors is type integer for boo in colors: if isinstance(boo, int): #use isinstance to check for type print(boo) #Loops for dictionaries student_grades = {"Marry": 9.9, "Sim": 6.5, "John": 7.4} for grades in student_grades.items(): #iterates over ITEMS (= key + value) print(grades) #keys(names) and values are printed out in a tupel for grades2 in student_grades.keys(): #iterates over keys print(grades2) for grades3 in student_grades.values(): #iterates over values print(grades3) #Combining dictionary loop and string formatting phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"} for key, value in phone_numbers.items(): print("{}: {}".format(key, value)) #replace "+" with "00" in phone numbers phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"} for value in phone_numbers.values(): print(value.replace("+", "00")) #a for loop runs until a container is exhausted for i in [1, 2, 3]: print(i) #a while loop runs as long as its condition is TRUE a = 3 #while a > 0: will run endlessly, as this condition is always true # print(1) #execution of this loop ends when user types in "pypy" as username username = "" #variable username is an empty string while username != "pypy": #!= means is different than #in the first iteration, variable username is an empty string-thus different than "pypy" and one gets the print #in the second iteration, the variable username is what is entered by user username = input("Enter username: ") #while loops with break and continue while True: #is always true name = input("Enter name: ") if name == "pypy": #if variable name is "pypy" break #stops loop else: continue
true
ae35bfc0d8c5057a7d70cf79a272a353a0f15cf4
pwgraham91/Python-Exercises
/shortest_word.py
918
4.34375
4
""" Given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types. """ def find_short_first_attempt(string): shortest_word_length = None for word in string.split(' '): len_word = len(word) if shortest_word_length is None or len_word < shortest_word_length: shortest_word_length = len_word return shortest_word_length def find_short(string): return min(len(word) for word in string.split(' ')) assert find_short("bitcoin take over the world maybe who knows perhaps") == 3 assert find_short("turns out random test cases are easier than writing out basic ones") == 3 assert find_short("lets talk about javascript the best language") == 3 assert find_short("i want to travel the world writing code one day") == 1 assert find_short("Lets all go on holiday somewhere very cold") == 2
true
dc9a10c8f8f1cd1c46f78c475ed1ca57cc381ee1
pwgraham91/Python-Exercises
/process_binary.py
494
4.15625
4
""" Given an array of one's and zero's convert the equivalent binary value to an integer. Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1 """ def binary_array_to_number(array): output = '' for i in array: output += str(i) return int(output, 2) assert binary_array_to_number([0, 0, 0, 1]) == 1 assert binary_array_to_number([0, 0, 1, 0]) == 2 assert binary_array_to_number([1, 1, 1, 1]) == 15 assert binary_array_to_number([0, 1, 1, 0]) == 6
true
9b8ee1df25e986a9ad3abd9134abda3f6d3970f5
pwgraham91/Python-Exercises
/sock_merchant.py
990
4.71875
5
""" John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . Function Description Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. Input: 9 10 20 20 10 10 30 50 10 20 Output: 3 """ def get_num_match_socks(socks): unmatched_socks = {} num_matched_socks = 0 for i in socks: if unmatched_socks.get(i): del unmatched_socks[i] num_matched_socks += 1 else: unmatched_socks[i] = 1 return num_matched_socks assert get_num_match_socks([10, 20, 20, 10, 10, 30, 50, 10, 20]) == 3
true
7c9c234858d6903b255c291661ae61787f7c8a4f
victorcwyu/python-playground
/learn-python/functions.py
1,273
4.375
4
# divide code into useful blocks # allows us to order code, make it more readable, reuse it and save time # a key way to define interfaces to share code # defined using the block keyword "def", followed by the function name as the block name def my_function(): print("Yolo") # may receive arguments (variables passed from the caller to the function) def my_function_args(name, greeting): print("Yolo %s %s!" % (name, greeting)) my_function_args("Jolo", "Dolo") # may also return a value to the caller def sum_nums(a, b): return a + b print(sum_nums(2, 4)) # use an existing function, while adding own to create a program # Modify this function to return a list of strings as defined above def list_benefits(): return ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"] # Modify this function to concatenate to each benefit - " is a benefit of functions!" def build_sentence(benefit): # return benefit + " is a benefit of functions!" return "%s is a benefit of functions!" % benefit def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print(build_sentence(benefit)) name_the_benefits_of_functions()
true
f515c806b5240f92a077dd7ded268eaa19e8edd2
victorcwyu/python-playground
/python-crash-course/string-replacement.py
512
4.125
4
# exercise: use Python's string replace method to fix this string up and print the new version out to the console journey = """Just a small tone girl Leaving in a lonely whirl She took the midnight tray going anywhere Just a seedy boy Bored and raised in South Detroit or something He took the midnight tray going anywhere""" # solution 1 properLyrics = journey.replace("tone", "town").replace("whirl", "world").replace("tray", "train").replace("seedy", "city").replace(" or something", "") print(properLyrics)
true
84bd0d4db2706319680706e1cd0621ed313fa034
Utkarshkakadey/Assignment-solutions
/Assignment 1.py
1,053
4.40625
4
# solution 1 # Python program to find largest # number in a list # list of numbers list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # printing the last element print("Largest element is:", list1[-1]) #solution 2 a=[] c=[] n1=int(input("Enter number of elements:")) for i in range(1,n1+1): b=int(input("Enter element:")) a.append(b) n2=int(input("Enter number of elements:")) for i in range(1,n2+1): d=int(input("Enter element:")) c.append(d) new=a+c new.sort() print("Sorted list is:",new) #solution 3 # Python program to find second largest # number in a list # list of numbers list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # printing the second last element print("Second largest element is:", ) #solution 4 # Python3 program to swap first # and last element of a list # Swap function def swapList(newList): newList[0], newList[-1] = newList[-1], newList[0] return newList # Driver code newList = [12, 35, 9, 56, 24] print(swapList(newList))
true
36ca26358ff16d783d4b7bc0b24e2768879ef9b4
NadezhdaBzhilyanskaya/PythonProjects
/Quadratic/src/Bzhilyanskaya_Nadja_Qudratic.py
2,751
4.125
4
import math class Qudratic: def __init__(self, a,b,c): """Creates a qudratic using the formula: ax^2+bx+c=0""" self.a = a self.b = b self.c = c self.d = (b**2)-(4*a*c) def __str__(self): a = str(self.a) + "x^2 + " + str(self.b) + "x + " + str(self.c) return a; def displayFormula(self): """Prints out the formula of the qudratic""" print (self) def getDiscriminant(self): """Finds and returns the discriminant: b^2-4ac""" return self.d def getNumberOfRoots(self): """Determines how many roots the qudratic has using the discriminant""" if self.d > 0: return 2 elif self.d < 0: return 0 else: return 1 def isRealRoot(self): """Determines if root/roots are real or imaginary""" if self.d < 0: return False else: return True def getRoot1(self) : """Gets first root: If 2 real roots exists finds and returns the root in which the radical is subtracted. If 1 real root exists finds and returns that 1 root. If no real roots exist returns None""" a = self.a b = self.b num = self.getNumberOfRoots() if num == 0 : return None elif num == 0 : answer= ((-1)*b) /(2*a) else : answer = ((-1)*b + math.sqrt(self.d))/(2*a) return answer def getRoot2(self) : """Gets second root: If 2 real roots exists finds and returns the root in which the radical is added. If 1 real root exists returns None. If no real roots exist returns None""" a = self.a b = self.b num = self.getNumberOfRoots() if num < 2 : return None else : answer = ((-1)*b - math.sqrt(self.d))/(2*a) return answer if __name__ == "__main__": print("Welcome to the qudratic formula Program") print(" Formula: ax^2+bx+c=0") print("\n") aIN=int(input("Value for a: ")) bIN=int(input("Value for b: ")) cIN=int(input("Value for c: ")) print("\n") qud1= Qudratic(aIN,bIN,cIN) print(qud1) d = qud1.getDiscriminant() num = qud1.getNumberOfRoots() print("\n") print("Discrimanent: ",d) print("\n") print("# of Roots: ",num) print("\n") print("Is root real: ",qud1.isRealRoot()) print("\n") print("Root 1: ",qud1.getRoot1()) print("\n") print("Root 2: ",qud1.getRoot2())
true
68202e160654a74f879656915b632679e51ccb89
lmaywy/Examples
/Examples/Examples.PythonApplication/listDemo.py
1,041
4.25
4
lst=[1,2,3,4,5,6,7] # 1.access element by index in order print 'access element by index in order'; print lst[0]; print 'traverse element by index in order ' for x in lst: print x; # 2.access element by index in inverse order print 'access element by index in inverse order' print lst[-1]; length=len(lst); i=length-1; print 'traverse element by index in inverse order' while i>=0: print lst[i]; i=i-1; # 3.add element lst.append(8); lst.insert(0,0); print lst; # 4.remove an element lst.remove(3); lst.pop(-1); print lst; # 5.replace an element from list lst[-1]=5; print lst; # 6.sort list lst.sort(); print lst; # 7.reverse list lst.append(3) print lst; lst.reverse(); print lst; # 8.count given an value in the list times=lst.count(5); print times; # 9.extend list with given list/tuple lst.extend([10,11]) print lst; # 10. generate list using while,also call sum to calculate total value L = []; x=1; while x<=100: L.append(x*x); x=x+1; print sum(L)
true
1f4619da7153fa21df1f9bb5b8b647bc566c41c5
Piero942/calculadora
/t03alfaro/ejercicio3.py
331
4.34375
4
#Algoritmo para hallar la resta de 3 numeros numero1,numero2,numero3,resta=0.0,0.0,0.0,0.0 #asignacion de valores numero1,numero2,numero3=35.9,25.5,7.4 #calculo resta=numero1-numero2-numero3 #mostrar valores print("la numero1 es",numero1) print("la numero2 es",numero2) print("la numero3 es",numero3) print("la resta es",resta)
false
62d8c229f14671d1ffacfcd65a667a1bce570b9b
aguynamedryan/challenge_solutions
/set1/prob4.py
2,219
4.28125
4
# -*- coding: utf-8 -*- """ Question: Complete the function getEqualSumSubstring, which takes a single argument. The single argument is a string s, which contains only non-zero digits. 
This function should print the length of longest contiguous substring of s, such that the length of the substring is2*N digits and the sum of the leftmost N digits is equal to the sum of the rightmost N digits.If there is no such string, your function should print 0. Sample Test Cases: 

Input #00:
123231

Output #00:
6

Explanation:
1 + 2 + 3 = 2 + 3 + 1. 
The length of the longest substring = 6 where the sum of 1st half = 2nd half Input #01:
986561517416921217551395112859219257312

Output #01:
36 """ """ Solution """ def firstHalfOfString(s): return s[0:len(s) / 2] def secondHalfOfString(s): return s[len(s) / 2:len(s)] def sumString(string): someSum = 0 for num in string: someSum += int(num) return someSum def isEqualSumSubstring(string): if (len(string) % 2 == 1): return 0 if (sumString(firstHalfOfString(string)) == sumString(secondHalfOfString(string))): return 1 return 0 def getEqualSumSubstring(string): from collections import deque # The queue will store all the strings we need to check # We start by checking the entire string queue = deque([string]) while len(queue) != 0: s = queue.popleft(); # The first string that matches our criteria is, # by design, the longest so we're done. # Return the length! if (isEqualSumSubstring(s)): return len(s) # If the current string isn't our winner we'll add # to the queue two new substrings of the current string # We trim a character off either end of the current string # and feed it into the queue # # In this way, the queue will get filled # with all possible substrings of the initial string # until either a string matches our criteria, # or the string becomes the empty string, meaning # there is no match if (len(s) - 1 > 0): queue.append(s[0:len(s) - 1]) queue.append(s[1:len(s)]) return 0 if __name__ == "__main__": print getEqualSumSubstring('986561517416921217551395112859219257312')
true
3cf5096bbe84a7fc9fca40f3b076252d06e0d9bb
Kimuksung/bigdata
/python/carclass.py
727
4.15625
4
''' 동적 멤버 변수 생성 - 필요한 경우 특정 함수에서 멤버 변수 생성 self : class의 멤버를 호출 하는 역할 self.member / self.method() ''' class Car: door = cc = 0 name = None # null #생성자 : 객체 + 초기화 def __init__(self , door , cc , name): self.door = door self.cc= cc self.name = name def info(self): self.kind = "" if self.cc>=3000: self.kind = "대형" else: self.kind="소형" self.display() def display(self): print( self.name , self.cc,self.door) tmp1 = Car(2,4000,'uk') print(tmp1.info()) #print(tmp1.kind) tmp2 = Car(4,3000,'GRAMDer') print(tmp2.info())
false
26b44398c5ffb32c22b98bd8a145cca3e7540185
usddddd/CompSci
/myfunc.py
1,236
4.25
4
def is_divisible_by_2_or_5(n): """ >>> is_divisible_by_2_or_5(8) True >>> is_divisible_by_2_or_5(7) False >>> is_divisible_by_2_or_5(5) True >>> is_divisible_by_2_or_5(9) False """ return n % 2 == 0 or n % 5 == 0 def compare(a,b): """ >>> compare(5, 4) 1 >>> compare(7, 7) 0 >>> compare(2, 3) -1 >>> compare(42, 1) 1 """ if a > b: return 1 if b > a: return -1 else: return 0 def hypotenuse(a,b): """ >>> hypotenuse(3, 4) 5.0 >>> hypotenuse(12, 5) 13.0 >>> hypotenuse(7, 24) 25.0 >>> hypotenuse(9, 12) 15.0 """ c = (a**2 + b**2)**0.5 return c def slope(x1,y1,x2,y2): """ >>> slope(5,3,4,2) 1.0 >>> slope(1,2,3,2) 0.0 >>> slope(1,2,3,3) 0.5 >>> slope(2,4,1,2) 2.0 """ dx = x2 - x1 dy = y2 - y1 return float(dy)/dx def intercept(x1,y1,x2,y2): """ >>> intercept(1,6,3,12) 3.0 >>> intercept(6,1,1,6) 7.0 >>> intercept(4,6,12,8) 5.0 """ yint = y1 - (slope(x1,y1,x2,y2)*x1) return yint if __name__ == '__main__': import doctest doctest.testmod()
false
3cb212414eb444e17899f469d89d8a2421f39517
usddddd/CompSci
/numberlists.py
2,385
4.125
4
def only_evens(numbers): """ >>> only_evens([1, 3, 4, 5, 6, 7, 8]) [4, 6, 8] >>> only_evens([2, 4, 6, 8, 10, 11, 0]) [2, 4, 6, 8, 10, 0] >>> only_evens([1, 3, 5, 7, 9, 11]) [] >>> only_evens([4, 0, -1, 2, 6, 7, -4]) [4, 0, 2, 6, -4] >>> nums = [1, 2, 3, 4] >>> only_evens(nums) [2, 4] >>> nums [1, 2, 3, 4] """ new_list = [] for i in range(len(numbers)): if numbers[i]%2 == 0: new_list += [numbers[i]] return new_list def only_odds(numbers): """ >>> only_odds([1, 3, 4, 6, 7, 8]) [1, 3, 7] >>> only_odds([2, 4, 6, 8, 10, 11, 0]) [11] >>> only_odds([1, 3, 5, 7, 9, 11]) [1, 3, 5, 7, 9, 11] >>> only_odds([4, 0, -1, 2, 6, 7, -4]) [-1, 7] >>> nums = [1, 2, 3, 4] >>> only_odds(nums) [1, 3] >>> nums [1, 2, 3, 4] """ new_list = [] for i in range(len(numbers)): if numbers[i]%2 != 0: new_list += [numbers[i]] return new_list def multiples_of(num, numlist): """ >>> multiples_of(3, [1,4,6,9,13]) [6, 9] >>> multiples_of(2, [1, 2, 4, 5, 6, 7, 8, 9, 10]) [2, 4, 6, 8, 10] >>> nums = [10, 20, 30, 40, 50, 51] >>> multiples_of(10, nums) [10, 20, 30, 40, 50] >>> nums [10, 20, 30, 40, 50, 51] """ new_list = [] for i in range(len(numlist)): if numlist[i] % num == 0: new_list += [numlist[i]] return new_list def replace(s, old, new): """ >>> replace('Mississippi', 'i', 'I') 'MIssIssIppI' >>> s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!' >>> replace(s, 'om', 'am') 'I love spam! Spam is my favorite food. Spam, spam, spam, yum!' >>> replace(s, 'o', 'a') 'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!' >>> s = 'My name is Adam and I am the goddamn man!' >>> replace(s,'dam', 'tommmm') 'My name is Atommmm and I am the godtommmmn man!' """ import string j = 0 new_list = [] while j < (len(s)): if s[j:(j + len(old))] == old: new_list += [new] j += len(old) else: new_list += s[j] j += 1 new_list = string.join(new_list, '') return new_list if __name__ == '__main__': import doctest doctest.testmod()
false
e443a8469abd8dd648d3919ba5122505f9ae0ee7
ozturkaslii/GuessNumber
/Py_GuessNumber/Py_GuessNumber/Py_GuessNumber.py
1,214
4.25
4
low = 0; high =100; isGuessed = False print('Please think of a number between 0 and 100!'); #loop till guess is true. while not isGuessed: #Checking your answer with Bisection Search Algorithm. It allows you to divide the search space in half at each step. ans = (low + high)/2; print('Is your secret number '+ str(ans) +'?'); #explanation allows to user to write her/his own input explanation = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. "); #c represents correct answer. isGuessed will be true and game over. if(explanation == 'c'): isGuessed = True #h is used for that computer's guess is higher than user's secret answer. this means high should be limited by guess. elif(explanation == 'h'): high = ans #c is used for that computer's guess is lower than user's secret answer. this means low should be limited by guess. elif(explanation == 'l'): low = ans #this condition allows us to limit user's input by h, l, or c. else: print("Sorry, I did not understand your input.") print('Game over. Your secret number was: ' + str(ans))
true
6bb5fe7da5b77c12e4f6f37cd852a5b74478ab3d
wrenoud/aoc2020
/lib/__init__.py
628
4.125
4
class Coord(object): def __init__(self, x: int, y: int): self.x = x self.y = y def __add__(self, other): return Coord(self.x + other.x, self.y + other.y) def __sub__(self, other): return Coord(self.x - other.x, self.y - other.y) def __len__(self) -> int: """returns manhattan distance from origin""" return abs(self.x) + abs(self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y)) def __repr__(self) -> str: return "({},{})".format(self.x, self.y)
false
3b72cf3f9878c6a37ba0274f31df18f4f3a5ad69
khusheimeda/Big-Data
/Assignment1 - Map Reduce/reducer.py
789
4.125
4
#!/usr/bin/python3 import sys # current_word will be used to keep track of either recognized or unrecognized tuples current_word = None # current_count will contain the number of tuples of word = current_word seen till now current_count = 0 word = None for line in sys.stdin: line = line.strip() word,count = line.split("\t") count = int(count) # If the seen word is equal to the one we're counting, update count if (current_word == word): current_count += count else: if current_word: print(current_count) # This is a new word, so initialise current_word and current_count variables current_count = count current_word = word if current_word == word: print(current_count)
true
9ce6d36ed817b6029a056e3dbd9e6581a00853e5
KirthanaRamesh/MyPythonPrograms
/decimal_To_Binary.py
1,577
4.53125
5
# Function for separating the integer and fraction part from the input decimal number. def separation_of_integer_and_fraction(): global decimal_number, decimal_integer, decimal_fraction decimal_integer = int(decimal_number) decimal_fraction = decimal_integer - decimal_number # Function to convert integer part to binary. def integral_to_binary_calculation(): global decimal_number, decimal_integer, decimal_fraction global binary_integral while decimal_integer >= 1: remainder = decimal_integer % 2 decimal_integer = decimal_integer // 2 binary_integral.append(remainder) binary_integral.reverse() # Function to convert fraction part to binary def fraction_to_binary_conversion(): global decimal_fraction, temp1, temp2 global binary_fraction i = 0 temp1 = decimal_fraction * 2 while i < precision : temp2 = int(temp1) temp1 = temp2 - temp1 #temp1 = temp1 - temp2 #temp1 = temp1 - int(temp1) binary_fraction.append(abs(temp2)) temp1 = temp1 * 2 i = i + 1 # Getting input from the user print("\nConversion of decimal number N into equivalent binary number up-to K precision after decimal point. ") decimal_number = float(input("\nEnter decimal number, N: ")) precision = int(input("Enter K: ")) binary_integral = [] binary_fraction = ["."] separation_of_integer_and_fraction() integral_to_binary_calculation() fraction_to_binary_conversion() print("The equivalent binary number is ", *binary_integral, *binary_fraction, sep = "")
true
409e2fc12f0a27a26d2b84e830e79694509c5063
Sigtamx/EDD-HOFJ
/Practica2u1.py
671
4.25
4
""" Desplegar y calcular factorial de un numero dado por el usuario con recursividad """ m=1 def factorialRecursivo(n): global m if(n>1): m*=n n-=1 factorialRecursivo(n) else: print(m) print("Fin") print("Ingrese el numero para usar factorial:") n = input() factorialRecursivo(n) """ Desplegar y calcular factorial de un numero dado por el usuario con iteraciones """ def factorialIterativo(n): m=n for i in range(n-1): m*=(n-1) n-=1 print(m) print("Fin") print("Ingrese el numero para usar factorial:") n = input() factorialIterativo(n)
false
6b8bf1fd5506f086a1367c35f416315b8cc8b8bb
jeffder/legends
/main/utils/misc.py
621
4.3125
4
# Miscellaneous utilities from itertools import zip_longest def chunks(values, size=2, fill=None): """ Split a list of values into chunks of equal size. For example chunks([1, 2, 3, 4]) returns [(1, 2), (3, 4)]. The default size is 2. :param values: the iterable to be split into chunks :param size: the size of the chunks. Must be an integer. :param fill: fill missing values in with fill value """ if not isinstance(size, int): raise TypeError('Size must be an integer') if size <= 0: size = 2 return zip_longest(*(iter(values),) * size, fillvalue=fill)
true
0649d4edfd70e8836a98437b1860c7f7709adaae
mihaivalentistoica/Algorithms_Data_Structures
/01-recursion/example-01.py
319
4.34375
4
def factorial(n): """Factorial of a number is the product of multiplication of all integers from 1 to that number. Factorial of 0 equals 1. e.g. 6! = 1 * 2 * 3 * 4 * 5 * 6 """ print(f"Calculating {n}!") if n == 0: return 1 return n * factorial(n - 1) print(f"6! = {factorial(6)}")
true
187269a9d58a66513d8bdda626b909f8c62ef928
mosesokemwa/bank-code
/darts.py
1,113
4.375
4
OUTER_CIRCLE_RADIUS = 10 MIDDLE_CIRCLE_RADIUS = 5 INNER_CIRCLE_RADIUS = 1 CENTRE = (0, 0) def score(x: float, y: float): """Returns the points earned given location (x, y) by finding the distance to the centre defined at (0, 0). Parameters ---------- x : float, The cartesian x-coordinate on the target y : float, The cartesian y-coordinate on the target """ try: x = abs(float(x)) y = abs(float(y)) except ValueError: print('ValueError: The function score only accepts floats as inputs') return distance_to_centre = ( (x - CENTRE[0])**2 + (y - CENTRE[1])**2 ) ** (0.5) if distance_to_centre > OUTER_CIRCLE_RADIUS: return 0 elif MIDDLE_CIRCLE_RADIUS < distance_to_centre <= OUTER_CIRCLE_RADIUS: return 1 elif INNER_CIRCLE_RADIUS < distance_to_centre <= MIDDLE_CIRCLE_RADIUS: return 5 elif 0 <= distance_to_centre <= INNER_CIRCLE_RADIUS: return 10 if __name__ == '__main__': x, y = input('score ').split(',') s = score(x, y) print(f'Player earns: {s} points')
true
e52d775f79831414f58c5ceeef965f1306b27293
OsamaOracle/python
/Class/Players V1.0 .py
1,294
4.3125
4
''' In the third exercise we make one final adjustment to the class by adding initialization data and a docstring. First add a docstring "Player-class: stores data on team colors and points.". After this, add an initializing method __init__ to the class, and make it prompt the user for a new player color with the message"What color do I get?: ". Edit the main function to first create two player objects from the class, player1 and player2. After this, make the program call player1's method "goal" twice and player2's goal once. After this, call both objects with the method "tellscore". If everything went correctly, the program should print something like this: ''' class Player: teamcolor = "Blue" points = 0 def __init__(self): self.teamcolor = input("What color do I get?: ") def tellscore(self): print ("I am", self.teamcolor,",", " we have ", self.points, " Points!") def goal(self): self.points += 1 def printscore(self): print("The", self.teamcolor, "contender has", self.__points, "points!") def fucntion_main(): player1 = Player () player2 = Player () player1.goal() player1.goal() player2.goal() player1.tellscore() player2.tellscore() if __name__ == '__main__': fucntion_main()
true
cb159d75464cd184798a3069e8779a0ec65b9472
jbmarcos/Python-Curso-em-video-Mundo-1-2-3-
/ex037 # bin oct hex fatiamento str if elif else .py
594
4.125
4
# bin oct hex fatiamento str if elif else num = int(input(' Digite um númeto inteiro: ')) print('''Escolha a base de conversção que deseja: [ 1 ] para Binário [ 2 ] para Octal [ 3 ] para Hexadecimal''') opção = int(input(' Sua opção: ')) if opção == 1: print(' {} convertido para Binário é {} '.format(num, bin(num) [2:])) elif opção == 2: print(' {} convertido para Octal é {}'.format(opção, oct(num) [2:])) elif opção == 3: print(' {} convertido para Hexadecimal é {}'.format(opção, hex(num) [2:])) else: print(' Opção inválida. Tente novamente.')
false
87c6013053de3c1b0cdddff68e64ea6b76e5040f
lihaoranharry/INFO-W18
/week 2/Unit 2/sq.py
316
4.25
4
x = int(input("Enter an integer: ")) ans = 0 while ans ** 2 <= x: if ans **2 != x: print(ans, "is not the square root of" ,x) ans = ans + 1 else: print("the square root is ", ans) break if ans **2 == x: print("we found the answer") else: print("no answer discovered")
true
055abc0aa8a0fe307d3b1dda6ec697c908e61e44
RelayAstro/Python
/ejercicio29.py
962
4.5625
5
#The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in this function to return True if the passed string is a palindrome, False if not. def is_palindrome(input_string): # Replacing spaces with nothing single_word = input_string.replace(" ", "") # Converting the word to lower case single_word = single_word.lower() # Checking the first element with the last elements and so on for i in range(len(single_word)): if single_word[i] != single_word[len(single_word) - 1 - i]: return False return True print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True
true
5c84f84a9e1816751630c17bb1acb9b3301459a3
dbrooks83/PythonBasics
/Grades.py
711
4.5
4
#Write a program to prompt for a score between 0.0 and 1.0. #If the score is out of range, print an error. If the score is between #0.0 and 1.0, print a grade using the following table: #Score Grade #>= 0.9 A #>= 0.8 B #>= 0.7 C #>= 0.6 D #< 0.6 F #If the user enters a value out of range, print a suitable error message #and exit. For the test, enter a score of 0.85. grades = raw_input("Enter your score:") try: grade = float(grades) except: grade = -1 if grade>1.0: print 'Enter your score as a decimal' elif grade>=.9: print 'A' elif grade>=.8: print 'B' elif grade>=.7: print 'C' elif grade>=.6: print 'D' elif grade<.6: print 'F' elif grade==-1: print 'Not a number'
true
91fa15b2c4ae7d49ff66f69e13a921aed349f63e
TranshumanSoft/Repeat-a-word
/repeataword.py
205
4.1875
4
word = str(input("What word do you want to repeat?")) times = int(input(f"How many times do you want to repeat '{word}'?")) counter = 0 while counter < times: counter = counter + 1 print(word)
true
8c855c41046f03888b12b957cfb66ac866144ca7
fandres70/Python1
/functiondefaults.py
575
4.34375
4
# Learning how Python deals with default values of # function parameters def f(a, L=[]): '''This function appends new values to the list''' L.append(a) return L # not specifying a list input print(f(1)) print(f(2)) print(f(3)) # specifying a list input print(f(1, [])) print(f(2, [])) print(f(3, [])) def g(a, L=None): if L is None: L = [] L.append(a) return(L) # not specifying a list input print(g(1)) print(g(2)) print(g(3)) # specifying a list input print(g(1, [])) print(g(2, [])) print(g(3, []))
true
39b12a36d1c809b5b64250ac4543c95d26f5912b
fandres70/Python1
/factorial.py
426
4.34375
4
#!/usr/bin/env python # Returns the factorial of the argument "number" def factorial(number): if number <= 1: #base case return 1 else: return number*factorial(number-1) # product = 1 # for i in range(number): # product = product * (i+1) # return product user_input = int(raw_input("Enter a non-negative integer: ")) factorial_result = factorial(user_input) print factorial_result
true
a4034f4c5a30994a6b8568eb369a8a4df8610c46
Saskia-vB/eng-57-pyodbc
/error_file.py
1,338
4.5
4
# Reading a text file # f = open ('text_file.txt', 'r') # # print(f.name) # # f.close() # to use a text within a block of code without worrying about closing it: # read and print out contents of txt file # with open('text_file.txt', 'r') as f: # f_contents = f.read() # print(f_contents) # reading a txt file and print each line using a loop # with open('text_file.txt', 'r') as f: # for line in f: # print(line, end='') # I can write to a file # if the file does exist it will override it so if you want to write to an existing file you write with a for appending # with open('test_file.txt', 'w') as f: # f.write('Test') # append # with open('text_file.txt', 'a') as f: # f.write('it worked again!') # write on a new line # with open('text_file.txt', 'a') as f: # f.write('this time on a new line!\n') # created a function that can open any txt file and print out each line # def read_text(text_file): # with open(text_file, 'r') as f: # for line in f: # print(line, end = '') # # print(read_text('test_file.txt')) # create a function that writes a new line in a file # user_input = str(input("Enter your new line: ")) # def new_line(user_input): # with open('test_file.txt', 'a') as f: # f.write("'" + user_input + "'" + '\n') # # print(new_line(user_input))
true
5f62cb78547b5a4152223c2a9c55789768d87b21
bhumphris/Chapter-Practice-Tuples
/Chapter Practice Tuples.py
2,234
4.46875
4
# 12.1 # Create a tuple filled with 5 numbers assign it to the variable n n = (3,5,15,6,12) # the ( ) are optional # Create a tuple named tup using the tuple function tup = tuple() # Create a tuple named first and pass it your first name first = tuple("Ben") # print the first letter of the first tuple by using an index print first[0] print "\n" # print the last two letters of the first tuple by using the slice operator (remember last letters means use # a negative number) print first[-2:] print "\n" # 12.2 # Given the following code, swap the variables then print the variables var1 = tuple("Good") var2 = tuple("Afternoon") var1, var2 = var2, var1 print var1, var2 print "\n" # Split the following into month, day, year, then print the month, day and year date = 'Jan 15 2016' month, day, year = date.split() print month print day print year print "\n" # 12.3 # pass the function divmod two values and store the result in the var answer, print answer answer = divmod(19,2) print answer print "\n" # 12.4 # create a tuple t4 that has the values 7 and 5 in it, then use the scatter parameter to pass # t4 into divmod and print the results t4 = (7,5) print divmod(*t4) print "\n" # 12.5 # zip together your first and last names and store in the variable zipped # print the result zipped = zip("Ben", "Humphris") print zipped print "\n" # 12.6 # Store a list of tuples in pairs for six months and their order (name the var months): [('Jan', 1), ('Feb', 2), etc months = [("Jan", 1), ("Feb", 2), ("March", 3), ("April", 4), ("May", 5), ("June", 6)] print months print "\n" # create a dictionary from months, name the dictionary month_dict then print it month_dict = dict(months) print month_dict print "\n" # 12.7 # From your book: def sort_by_length(words): t = [] for word in words: t.append((len(word), word)) t.sort(reverse=True) res = [] for length, word in t: res.append(word) return res # Create a list of words named my_words that includes at least 5 words and test the code above # Print your result my_words = ("ashamed", "wonderful", "Spectacular", "Hyper", "Democracy") print sort_by_length(my_words)
true
03ef1ea5a2c991e7a597f40b06aac37890dde380
knobay/jempython
/exercise08/h01.py
593
4.1875
4
"""Uniit 8 H01, week2""" # Gets an input from the user works # out if it is an Armstrong number def armstrong_check(): "Works out if the user has entered an Armstrong number" userinput = input("Enter a 3 digit number") evaluation = int(userinput[0])**3 + int(userinput[1])**3 + int(userinput[2])**3 if len(userinput) > 3: result = 'invalid input' elif int(userinput) == evaluation: result = 'that was an armstrong number' else: result = 'that was not an armstrong number' print(result) return # call the funciton armstrong_check()
true
688fa627915adf73bf41bc04d0636d41fb0d349d
knobay/jempython
/exercise08/e03.py
581
4.125
4
"""Uniit 8 E03, week2""" # Gets an input from the user works # out if it contains a voul PI = [3.14, 2] def voul_or_not(): "Works out if the user has entered a voul or consonant" userinput = input("Enter a letter") if (userinput == 'a' or userinput == 'e' or userinput == 'i' or userinput == 'o' or userinput == 'u'): result = 'that was a voul' elif len(userinput) > 1 or userinput.isdigit(): result = 'invalid input' else: result = 'that was a consonant' print(result) return # call the funciton voul_or_not()
true
2d766aea3921242f98860cc272bbfda43fb38efe
knobay/jempython
/exercise08/e02.py
720
4.28125
4
import math # print("\n--------------------------------------------------------------") print("------------------------ E02 -------------------------") x = True while x: numStr = input("Please enter a whole number:- ") if numStr.isdigit(): num = int(numStr) break elif numStr.replace("-","").isdigit(): num = int(numStr) break else: print("Sorry, it had to be a positive or negative integer, please try again") if num > 0: print("The number you entered was:- {} and it is greater than zero.".format(num)) elif num < 0: print("The number you entered was:- {} and it is less than zero.".format(num)) else: print("The number you entered was zero")
true