blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4cc251643d5402e0efcf329d49cae419353e212a
AntnvSergey/EpamPython2019
/13-design-patterns/hw/4-chain_of_responsibility/chain_of_responsibility.py
2,995
4.34375
4
""" С помощью паттерна "Цепочка обязанностей" составьте список покупок для выпечки блинов. Необходимо осмотреть холодильник и поочередно проверить, есть ли у нас необходимые ингридиенты: 2 яйца 300 грамм муки 0.5 л молока 100 грамм сахара 10 мл подсолнечного масла 120 грамм сливочного масла В итоге мы должны получить список недостающих ингридиентов. """ class BaseHandler: def __init__(self): self.next = None def set_next(self, handler): self.next = handler return self.next class Fridge: def __init__(self, eggs=0, flour=0, milk=0.0, sugar=0, sunflower_oil=0, butter=0): self.eggs = eggs self.flour = flour self.milk = milk self.sugar = sugar self.sunflower_oil = sunflower_oil self.butter = butter class EggsHandler(BaseHandler): def handle(self, fridge: Fridge): if fridge.eggs < 2: print(f'Need {2-fridge.eggs} eggs') if self.next: self.next.handle(fridge) class FlourHandler(BaseHandler): def handle(self, fridge: Fridge): if fridge.flour < 300: print(f'Need {300-fridge.flour} gram of flour') if self.next: self.next.handle(fridge) class MilkHandler(BaseHandler): def handle(self, fridge: Fridge): if fridge.milk < 0.5: print(f'Need {0.5-fridge.milk} liter of milk') if self.next: self.next.handle(fridge) class SugarHandler(BaseHandler): def handle(self, fridge: Fridge): if fridge.sugar < 100: print(f'Need {100-fridge.sugar} gram of sugar') if self.next: self.next.handle(fridge) class SunflowerOilHandler(BaseHandler): def handle(self, fridge: Fridge): if fridge.sunflower_oil < 10: print(f'Need {10-fridge.sunflower_oil} milliliter of ' f'sunflower oil') if self.next: self.next.handle(fridge) class ButterHandler(BaseHandler): def handle(self, fridge: Fridge): if fridge.butter < 120: print(f'Need {120-fridge.butter} gram of butter') if self.next: self.next(fridge) fridge = Fridge() another_fridge = Fridge(eggs=3, butter=200, milk=0.3) eggs_handler = EggsHandler() flour_handler = FlourHandler() milk_handler = MilkHandler() sugar_handler = SugarHandler() sunflower_handler = SunflowerOilHandler() butter_handler = ButterHandler() eggs_handler.set_next(flour_handler).set_next(milk_handler) milk_handler.set_next(sugar_handler).set_next(sunflower_handler) sunflower_handler.set_next(butter_handler) eggs_handler.handle(fridge) print(30*'-') eggs_handler.handle(another_fridge)
false
18ef3a0b8d402ad9d8d8990d4e659716b1ef9e2f
deepakgit2/Python-Basic-and-Advance-Programs
/polynomial_multiplication_using_cauchy_prod.py
639
4.1875
4
# This function multiply two polynomials using cauchy product formula # Input : a polynomial can be represent by a list where elements # of list are the coefficients of polynomial # Output : This program return multiplication of two polynomails in list form # a = 1 + 2x can be wriiten as following a = [1, 2, 3] # b = 1 + x can be wriiten as following b = [1, 1] def p_multi(a,b): m = len(a) n = len(b) k = m+n-1 b += [0]*k a += [0]*k m_l = [] for i in range(k): s = 0 for j in range(i+1): s += a[j]*b[i-j] m_l += [s] return m_l print(p_multi(a,b))
true
27729bbd7bd225d94e31b088294d9eb1a4334f8d
Shressaajan/AssignmentsCA2020Soln
/FunctionsTask/T5Q11.py
425
4.1875
4
# 11. Write a program which can map() and filter() to make a list whose elements are square of even number in # [1,2,3,4,5,6,7,8,9,10] # Hints: Use map() to generate a list. # Use filter() to filter elements of a list # Use lambda to define anonymous functions sqr_list = list(range(1, 11)) even_x = list(filter(lambda i: i % 2 == 0, sqr_list)) sqr_x = list(map(lambda x: x * x, even_x)) print(sqr_x)
true
d0fa5db62fd6550b002462d65aa9ccda064500eb
Shressaajan/AssignmentsCA2020Soln
/FunctionsTask/T5Q4.py
293
4.40625
4
# 4. Write a program that accepts a hyphen-separated sequence of words as input and prints the words in a # hyphen-separated sequence after sorting them alphabetically. def sorted_output(x): y = x.split('-') return print('-'.join(sorted(y))) sorted_output("a-z-s-x-d-c-f-v-g-b-h-n")
true
a5fb5007a15661cffee7e630118336a2ec14b11f
Shressaajan/AssignmentsCA2020Soln
/DataStructureTask/T4Q6.py
259
4.15625
4
# 6. Write a program in Python to iterate through the list of numbers in the range of 1,100 and print the number # which is divisible by 3 and a multiple of 2. x = [] for i in list(range(1100)): if i % 3 == 0 and i % 2 == 0: x.append(i) print(x)
true
aedcdfa645bf5411601773c9cd4606de4d88e3fd
Shressaajan/AssignmentsCA2020Soln
/FunctionsTask/T5Q8.py
273
4.28125
4
# 8. Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20. def sqr_tuple(): x = list(range(1,21)) y = [] for i in x: i *= i y.append(i) z = tuple(y) return z print(sqrt_tuple())
true
b083122b51b9cf91469312cb9cd4adc4f559c985
Shressaajan/AssignmentsCA2020Soln
/DataStructureTask/T4Q8.py
238
4.40625
4
# 8. Write a program in Python to iterate through the string “hello my name is abcde” and print the string which # has even length of word. x = 'Hello my name is abcde' for i in x.split(' '): if len(i) % 2 == 0: print(i)
true
8d9109e2ab0b4f15c17b47fa202cc9420003d130
gxmls/Python_Leetcode
/28.py
1,188
4.125
4
''' 实现 strStr() 函数。 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。 说明: 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。 示例 1: 输入:haystack = "hello", needle = "ll" 输出:2 示例 2: 输入:haystack = "aaaaa", needle = "bba" 输出:-1 示例 3: 输入:haystack = "", needle = "" 输出:0 提示: 0 <= haystack.length, needle.length <= 5 * 104 haystack 和 needle 仅由小写英文字符组成 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-strstr 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle!='': return haystack.find(needle) else: return 0
false
8d5f5109d6f35772e5b4f564d34c2a6a0262c983
sudarshan-suresh/python
/core/CalculateGrossPay.py
276
4.3125
4
#!/usr/bin/python # Problem Statement:- # user will input number of hours and rate the program has to calculate wage. input1 = input("Enter Number of hours: ") hours = int(input1) input2 = input("Enter the rate perhour: ") rate = float(input2) wage = rate * hours print(wage)
true
e8bd0e48bc136bb3fc5af6c340c0d76aa4e7c2ef
muhdibee/holberton-School-higher_level_programming
/0x0B-python-input_output/3-write_file.py
535
4.125
4
#!/usr/bin/python3 def write_file(filename="", text=""): """Write string to file Args: filename (str): string of path to file text (str): string to write to file Returns: number of characters written """ chars_written = 0 with open(filename, 'w', encoding='utf-8') as f: chars_written += f.write(text) return chars_written if __name__ == '__main__': nb_characters = write_file( "my_first_file.txt", "Holberton School is so cool!\n") print(nb_characters)
true
abb48f87c3e2e1592bbd9a91ee142a05305bf162
muhdibee/holberton-School-higher_level_programming
/0x07-python-test_driven_development/tests/6-max_integer_test.py
1,210
4.25
4
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest #max_integer = __import__('6-max_integer').max_integer def max_integer(list=[]): """Function to find and return the max integer in a list of integers If the list is empty, the function returns None """ if len(list) == 0: return None result = list[0] i = 1 while i < len(list): if list[i] > result: result = list[i] i += 1 return result class TestMaxInteger(unittest.TestCase): def test_simple_complete_list(self): self.assertEqual(max_integer([1, 2, 3, 4]), 4) self.assertEqual(max_integer([5, 2, 0, -1]), 5) self.assertEqual(max_integer([5, 5, 5]), 5) def test_simple_empty_none_list(self): self.assertEqual(max_integer([]), None) self.assertRaises(TypeError, max_integer, None) def test_string_comparison(self): self.assertRaises(TypeError, max_integer, [1, 2, 3, "Hol"]) self.assertRaises(TypeError, max_integer, ["H", 1, 2, 3]) def test_integer_comparison_none(self): self.assertRaises(TypeError, max_integer, [1, None, 2]) if __name__ == '__main__': unittest.main()
true
184d8c046ba1e9f415737544602e7f5369aa3c66
aldo2811/cz1003_project
/module/check.py
1,845
4.375
4
def user_input_index(min_index, max_index): """Asks user for input and checks if it matches a number in the specified range. Args: min_index (int): Minimum number of user input. max_index (int): Maximum number of user input. Returns: int: An integer that the user inputs if it satisfies the condition. Otherwise it returns itself, keeps on asking the user for input until the condition is satisfied """ user_input = input() # range is inclusive, between min_index and max_index if user_input.isdigit() and min_index <= int(user_input) <= max_index: return int(user_input) else: print("Error! Invalid input!") return user_input_index(min_index, max_index) def user_input_float(): """Asks user for input and checks whether it is a float. Returns: float: User input if it is a positive float number. Otherwise it returns itself, keeps on asking the user for input until condition is satisfied. """ user_input = input() try: user_input = float(user_input) # in this project, only positive float values are needed, # that's why negative float values are considered invalid if user_input < 0: print("Error! Invalid input!") return user_input_float() else: return user_input except: print("Error! Invalid input!") return user_input_float() def non_empty_input(): """Checks whether user input is empty or not. (For string) Returns: string (str): The input entered by the user. Returns itself and keeps on asking for input if input is empty. """ string = input() if not string or string.isspace(): print("Invalid input!") return non_empty_input() return string
true
a49d33bb74d81fb96198b1353be7a9c06a2eeb7a
RatnamDubey/DataStructures
/LeetCode/7. Reverse Integer.py
1,314
4.125
4
""" 7. Reverse Integer Easy Add to List Share Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -ç Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ integers = [] mul = 1 pow = 10 ** ((len(str(x))-1)) if (len(str(x))) == 0: return(0) if (len(str(x))) == 1: return(x) elif x * (-1) > 0: mul = -1 x = x * -1 for values in range(len(str(x))): val = x%10 integers.append(val) x = int(x/10) strings = [str(integer) for integer in integers] a_string = "".join(strings) an_integer = int(a_string) if an_integer > 2147483647: return(0) else: an_integer = an_integer * mul return(an_integer) c = Solution() print(c.reverse(-1))
true
a301e55ed8c88d1cb3a54af1e6e45b581dd00dc5
jbailey430/The-Tech-Academy-Python-Projects
/POLYMORPHISM.py
1,028
4.1875
4
#Parent Class User class User: name = "Steve" email = "Steve@gmail.com" password = "12345678" def getLogin(self): entry_name =("Enter your name: ") entry_email = input("Enter your email: ") entry_password = input("Enter your password: ") if (entry_email == self.email and entry_password == self.password): print("Welcome back, {}!".format(entry_name)) else: print("The password or email is incorrect.") #Child Class Employee class Employee(User): base_pay = 12.00 department = "General" pin_number = 3091 def getLogin(self): entry_name =("Enter your name: ") entry_email = input("Enter your email: ") entry_pin = input("Enter your pin: ") if (entry_email == self.email and entry_pin == self.pin): print("Welcome back, {}!".format(entry_name)) else: print("The pin or email is incorrect.") #not sure if I need the if __name__ == "__main__:" here or not? customer = User() customer.getLogin() manager = Employee() manager.getLogin()
true
2431c4b7da841c2fbce9387e4b4a633eb1316eaa
42madrid/remote-challs
/chall04/vde-dios.py
1,971
4.28125
4
#!/usr/bin/env python3 import sys import re def error(e , i): file_name = "stdin" if i == 0 else sys.argv[i] if (e == 1): print("%s: %s: Bad format" %(sys.argv[0], file_name)) elif (e == 2): print("%s: %s: Can't read file" %(sys.argv[0], file_name)) elif (e == 3): print("%s: %s: Not enough space in the given shelves" %(sys.argv[0], file_name)) # Check format plus sort shelves def shelf_parse(shelves): l = shelves.replace("\n", "").split(" ") l.sort(key=len, reverse=True) for c in l: if not c.isdigit(): return None return (l) # Check book format and add books def book_parse(books): b = re.search('^\d+', books) if re.search('^\d+\s\w+', books) is None: return None return int(b.group()) # Calculate number of shelves: placing books on shells until completed def calc_number(shelves, books, i): n_shelves = 0 capacity = 0 for c in shelves: capacity += int(c) n_shelves += 1 if capacity >= books: break if capacity < books: error(3, i) else: print(n_shelves) # Get number of shelves, prior parsing info def number_of_shelves(f, i): books = 0 shelves = shelf_parse(f.readline()) for x in f: if shelves is None or book_parse(x) is None: return(error(1, i)) books += book_parse(x) f.close() if books == 0: error(1, i) else: calc_number(shelves, books, i) def main(): l = len(sys.argv) if (l > 1): for i in range(1, l): try: print("%s:\n" % sys.argv[i] if l > 2 else "", end = "") f = open(sys.argv[i], "r") number_of_shelves(f, i) except: error(2, i) print("\n" if i < l - 1 else "", end="") else: f = sys.stdin number_of_shelves(f, 0) if __name__ == "__main__": main()
true
dd869008cb29eb27f7e2840ce0cc014c326091e3
TheArchit/equiduct-test
/exercise2.py
582
4.34375
4
#!/usr/local/bin/python -S from sys import argv """ Write a function that takes a list of integers (as arguments) and returns a response with the average (mean), total/sum of integers, the maximum and minimum values. Print the average to two decimal places. To make this a little more straightforward assume that input values are always integers. """ def maxminavg(nums): sumall = sum(nums) avg = round(float(sumall) / len(nums), 2) return avg, sumall, max(nums), min(nums) def main(): print maxminavg(map(int, argv[1:])) if __name__ == '__main__': main()
true
3367d1e03ca47c3aeea059a3b760a8b4d39ab5b6
petervalberg/Python3-math-projects
/Binomialtest.py
2,061
4.375
4
""" Binomial Distribution Calculator. --------------------------------- n is the number of times the experiment is performed. p is the probability of success in decimal. k is the target number of successes. """ from math import factorial combinations = 0 def binomial_coefficient(n, k): globals()['combinations'] = (factorial(n)) / (factorial(k) * factorial(n-k)) def equal_to(p, n, k): binomial_coefficient(n, k) result = combinations * (p**k) * (1-p) ** (n-k) print(f"P(X={k}) = {round(result, decimals)}") def greater(p, n, k): result = 0 for i in range(k+1, n+1): binomial_coefficient(n, i) result += combinations * (p**i) * (1-p) ** (n-i) print("P(X" + u'\u003E' + f"{k}) = {round(result, decimals)}") def greater_equal(p, n, k): result = 0 for i in range(k, n+1): binomial_coefficient(n, i) result += combinations * (p**i) * (1-p) ** (n-i) print("P(X" + u'\u2265' + f"{k}) = {round(result, decimals)}") def less(p, n, k): result = 0 for i in range(k-1, -1, -1): binomial_coefficient(n, i) result += combinations * (p**i) * (1-p) ** (n-i) print("P(X" + u'\u003C' + f"{k}) = {round(result, decimals)}") def less_equal(p, n, k): result = 0 for i in range(k, -1, -1): binomial_coefficient(n, i) result += combinations * (p**i) * (1-p) ** (n-i) print("P(X" + u'\u2264' + f"{k}) = {round(result, decimals)}") print('---------------------------------------------------------------') print('The program will compute Binomial and Cumulative Probabilities.') print('---------------------------------------------------------------\n') n = int(input('Number of times the experiment is performed: ')) k = int(input('Number of successes: ')) p = float(input('Probability of success (in decimal): ')) decimals = int(input('How may decimals in results: ')) print('') equal_to(p, n, k) less(p, n, k) less_equal(p, n, k) greater(p, n, k) greater_equal(p, n, k)
true
ba2a94081ff03d9e2718a9345ccfb6f2f7a703d7
novdulawan/python-function
/function_stdoutput.py
390
4.15625
4
#!/usr/bin/env python #Author: Novelyn G. Dulawan #Date: March 16, 2016 #Purpose: Python Script for displaying output in three ways def MyFunc(name, age): print "Hi! My name is ", name + "and my age is", age print "Hi! My name is %s and my age is %d" %(name, age) print "Hi! My name is {} and my age is {}".format(name,age) print MyFunc("Mary", 19)
true
eb3c96a2dc281331533d6f20f75c6a7e8f4a6ad4
SaidRem/just_for_fun
/ints_come_in_all_sizes.py
361
4.125
4
# Integers in Python cab be as big as the bytes in a machine's # memory. There is no limits in size as there is: # 2^31 - 1 or 2^63 - 1 # Input # integers a, b, c, d are given on four separate lines. # Output # Print the result of a^b + c^d a = int(input()) b = int(input()) c = int(input()) d = int(input()) result = a**b + c**d print(result)
true
b478fd8893a353ee3ec536d5083d6faf8fafc372
LGonzales930/My-Project
/FinalProjectPart2/FinalProjectinput.py
1,476
4.15625
4
# Lorenzo Gonzales # ID: 1934789 # Final Project part 2 # The Following program outputs information about an Electronics stores inventory import csv # The Dictionary ID is created to connect the other values together as a key, Everything else acts as a value # Everything is connected using ID = {} with open("ManufacturerList.csv", "r") as Info_1: # Information is read and accessed from the manufacture csv file Info_reader_1 = csv.reader(Info_1) for row in Info_reader_1: ID[row[0]] = {'Manufacture': row[1], 'Type': row[2]} with open("PriceList.csv", "r") as Info_2: # Information is read and accessed from the Price list csv file Info_reader_2 = csv.reader(Info_2) for row in Info_reader_2: ID[row[0]] = {'Price': row[1]} with open("ServiceDatesList.csv", "r") as Info_3: # Information is read and accessed from Service Dates List csv file Info_reader_3 = csv.reader(Info_3) for row in Info_reader_3: ID[row[0]] = {'Date': row[1]} print("Greetings User") # Program greets user and prompts for information print("Please enter a Manufacture name and Item type to proceed:") Selection = input() if 'Manufacture' and 'Type' in ID: print("Your item is:", ID['Manufacture': row[1]]['Type': row[2]]['Price': row[1][['Date']: row[1]]]) elif Selection == "q": print("Have a Nice Day") # program ends when user inputs q for quit else: print("No such item in Inventory") # Program displays message if item type and manufacture is not in data
true
d6e0f39b05b2fc88e1d6b55943d81f4a9ac031b5
MarkisDev/python-fun
/Competitive Programming/fibonacci.py
733
4.28125
4
""" Fibonacci Series This script prints Fibonacci series for n value of numbers using variable swap to implement recursion. @author : MarkisDev @copyright : https://markis.dev @source : https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ """ number = int(input('Enter the maximum numbers to be displayed: ')) # Initializing our swapping variables and list a = 0 c = 0 b = 1 seriesList = [0] # Loop to find the sum of the previous number, append to list and swap the variables to implement recursion for i in range(1 , number): c = a + b seriesList.append(c) # Variable swapping a = b b = c # Printing the output print("The sequence is as follows: ") print(seriesList)
true
92216f65be78b9d4951c2a2e8d9be9333da312a1
Grizz5678/Apprendre-Python
/Pythagore.py
1,529
4.15625
4
import turtle import time from math import * tortue1 = turtle.Turtle() tortue1.color("green") tortue1.shape("turtle") tortue1.pensize(6) for i in range(4): tortue1.showturtle() time.sleep(.5) tortue1.hideturtle() time.sleep(.5) tortue1.showturtle() a = input("Quelle est la longueur du premier côté du triangle que tu veux tracer avec ta tortue?: ") print("D'accord! J'enregistre donc la première variable pour la formule d'égalité de Pythagore ... a = " + str(a)) print("Et je fais avancer ta tortue de " + str(a) + " hectopixels!") time.sleep(3) tortue1.forward(int(a)*100) for i in range(4): tortue1.showturtle() time.sleep(.5) tortue1.hideturtle() time.sleep(.5) tortue1.showturtle() tortue1.left(90) b = input("Quelle est la longueur du deuxième côté du triangle que tu veux tracer avec ta tortue?: ") print("D'accord! J'enregistre donc la deuxième variable pour la formule d'égalité de Pythagore ... b = " + str(b)) print("Et je fais avancer ta tortue de " + str(b) + " hectopixels!") time.sleep(3) tortue1.forward(int(b)*100) for i in range(4): tortue1.showturtle() time.sleep(.5) tortue1.hideturtle() time.sleep(.5) tortue1.showturtle() tortue1.goto(0,0) time.sleep(3) print("Maintenant laisse moi calculer la longueur de l'hypothénuse de ce triangle rectangle!") for i in range(10): print(".") time.sleep(.5) c = sqrt(int(a)**2 + int(b)**2) print("La longueur de l'hypoténuse est..." + str(c))
false
ec2e930df7110bcb1ea94d80d6ace008e8e8447b
onlyrobot/DiscreteMathematicsProgram
/code/greatest_common_factor.py
391
4.15625
4
# greatest common factor a = int(input('input a non-negative number: ')) b = int(input('input another no-negative number: ')) if a < b: a, b = b, a if b == 0: print('the greatest common factor is ', a) if a == 0: print('no greatest common factor') else: r = a % b while r != 0: a, b = b, r r = a % b print('the greatest common factor is ', b)
false
bd484643860671de6ee0259cf719d67c10fc4efd
sakurashima/my-python-exercises-100
/programming-exercises/34-打印字典从1到20.py
493
4.1875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @文件 :34.py @说明 :Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. @时间 :2020/09/02 16:03:17 @作者 :martin-ghs @版本 :1.0 ''' def print_dict(): my_dict = dict() for i in range(1, 21): my_dict[i] = i**2 print(my_dict) def main(): print_dict() if __name__ == "__main__": main()
true
136df51b61bfd054a757839411aae2c8db8c1b49
sakurashima/my-python-exercises-100
/programming-exercises/58-59-re在放送一遍成功过.py
800
4.4375
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @文件 :58.py @说明 :Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. @时间 :2020/09/06 10:43:25 @作者 :martin-ghs @版本 :1.0 ''' import re def main(): email = input( "Enter the email addresses: \n(format like this: username@companyname.com)\n") pattern = "(\w+)@(\w+).com" ret = re.search(pattern, email) if ret: username = ret.group(1) companyname = ret.group(2) print("username:{}\ncompanyname:{}".format(username, companyname)) else: print("未提取到信息") if __name__ == "__main__": main()
true
c5c9391a9220edf57014300e0c71292377f1cab7
sakurashima/my-python-exercises-100
/programming-exercises/21-坐标轴自己选取数据结构.py
1,311
4.53125
5
""" Question A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 ¡­ The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program: UP 5 DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 """ import math def main(): position = {"x": 0, "y": 0} while True: my_str = input() if not my_str: break my_str = my_str.split(" ") direction = my_str[0] # 方向 distance = int(my_str[1]) # 距离 if direction == "UP": position["y"] += distance elif direction == "DOWN": position["y"] -= distance elif direction == "RIGHT": position["x"] += distance elif direction == "LEFT": position["x"] -= distance ret = int(position["x"])**2 + int(position["y"])**2 ret = math.sqrt(ret) print(round(ret)) if __name__ == "__main__": main()
true
bf8e6248c0d6df71d96446e0e6fa2e0f1c699720
sakurashima/my-python-exercises-100
/programming-exercises/91.py
495
4.125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @文件 :91.py @说明 :By using list comprehension, please write a program to print the list after removing the 0th, 4th,5th numbers in [12,24,35,70,88,120,155]. @时间 :2020/09/11 16:34:42 @作者 :martin-ghs @版本 :1.0 ''' def main(): li = [12, 24, 35, 70, 88, 120, 155] li = list(enumerate(li)) li = [x for (i, x) in li if i not in [0, 4, 5]] print(li) if __name__ == '__main__': main()
true
476ac61e9f8b8a4b5f20b2ddaaf9c36818e094af
sakurashima/my-python-exercises-100
/programming-exercises/02-求n!.py
524
4.15625
4
# Question: Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 def main(): given_num = input("enter the num: ") sum = 1 if(given_num == "0"): print("sum=0") else: for i in range(1, int(given_num)+1): sum *= i print("sum = {}".format(sum)) if __name__ == "__main__": main()
true
8c4b74f17278c12cb587509679b1c1f7fec6548a
sakurashima/my-python-exercises-100
/programming-exercises/40-还是列表索引.py
600
4.3125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @文件 :40.py @说明 :Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. @时间 :2020/09/02 16:22:15 @作者 :martin-ghs @版本 :1.0 ''' def generate_list_from1To20(): num_list = list() for i in range(1, 21): num_list.append(i**2) print(num_list[5:]) def main(): generate_list_from1To20() if __name__ == "__main__": main()
true
68dd0bda0d33c5ac3ce00bf9c7d5eab867627220
deepabalan/python-practice-book
/2_working_with_data/38.py
269
4.34375
4
# Write a function invertdict to interchange keys and values in a # dictionary. For simplicity, assume that all values are unique. def invertdict(d): res = {} for i, v in d.items(): res[v] = i return res print invertdict({'x': 1, 'y': 2, 'z': 3})
true
1138dd8c34c4dbb343e3089ba6caf3a28c1c213b
deepabalan/python-practice-book
/2_working_with_data/6.py
396
4.5
4
# Write a function reverse to reverse a list. Can you do this without # using list slicing? # reverse([1, 2, 3, 4]) gives [4, 3, 2, 1] # reverse(reverse([1, 2, 3, 4])) gives [1, 2, 3, 4] def reverse_list(l): rev = [] i = len(l) - 1 while i >= 0: rev.append(l[i]) i -= 1 return rev print reverse_list([1, 2, 3, 4]) print reverse_list(reverse_list([1, 2, 3, 4]))
true
2cb6675cf76f8de1f9d3545b206c4441b843203c
njuliacsouza/_udemy_Python
/secao_13/2_leitura_arquivos.py
1,106
4.28125
4
""" Leitura de Arquivos Para ler o conteúdo de um arquivo em Python, usamos a função integrada open(). open() -> Na forma mais simples de utilização, nós passamos apenas um parâmetro de entrada, que neste caso é o nome do arquivo a ser lido. Essa função retorna um _io_TextIOWrapper e é com ele que travalhamos então. https://docs.python.org/3/library/functions.html#open # OBS: Por padrão, a função open() abre o arquivo para leitura. Este arquivo deve existir, ou então teremos o erro FileNotFoundError <_io.TextIOWrapper name='texto.txt' mode='r' encoding='cp1252'> mode: 'r' -> Modo de leitura (read) """ # Exemplo arquivo = open('texto.txt', encoding="utf-8") # print(arquivo) # print(type(arquivo)) # Para ler o conteúdo de um arquivo após sua abertura, # devemos utilizar a função read() print(arquivo.read()) # OBS: O Python utiliza um recurso para trabalhar com arquivos # chamado cursor. Esse cursos funciona como o cursos quando # estamos escrevendo. print(arquivo.read()) # ele não vai imprimir nada # OBS: a função read() lê todo o conteúdo do arquivo
false
5709fd8aa94eeb63606d9d1e3d9ee21e7d606e3f
njuliacsouza/_udemy_Python
/secao_10/zip.py
1,103
4.34375
4
""" Zip zip() -> Cria um interavel (zp object) que agrega elemento de cada um dos iteraveis de entrada. # Exemplo lista1 = [1, 2, 3, 10] lista2 = [4, 5, 6] zip1 = zip(lista1, lista2) # cria tuplas com os elementos, o valor 10 será ignorado print(zip1) print(type(zip1)) print(list(zip1)) # pode ser set, tupla e dict também, só pode ser chamado uma vez # retorna: [(1, 4), (2, 5), (3, 6)] zip1 = zip(lista1, lista2) print(dict(zip1)) # aqui a primeira lista vira a chave e a segundo o valor # Utilizando elementos diferentes tupla = 1, 2, 3, 4, 5 lista = [6, 7, 8, 9, 10] dicionario = {'a': 11, 'b': 12, 'c': 13, 'd': 14, 'e': 15} zp = zip(tupla, lista, dicionario.values()) print(list(zp)) # Lista de tuplas dados = [(0, 1), (2, 3), (4,5)] print(list(zip(*dados))) """ # Exemplos mais complexos prova1 = [80, 91, 78] prova2 = [98, 89, 53] alunos = ['maria', 'pedro', 'carla'] final = {dado[0]: max(dado[1], dado[2]) for dado in zip(alunos, prova1, prova2)} print(final) # Podemos usar o map() final = zip(alunos, map(lambda nota: max(nota), zip(prova1, prova2))) print(dict(final))
false
b216f080be17474d02d8e5ccf461cd24c7b31710
njuliacsouza/_udemy_Python
/secao_12/modulo_random.py
1,437
4.125
4
""" Módulo Random e o que são módulos? - Em Python, módulos nada mais são do que outros arquivos Python. Módulo Random -> Possui várias funções para geração de números pseudo-aleatório. # OBS: Existem duas formas de se utilizar um módulo ou função deste # Forma 1 - importando todo o módulo import random # Ao realizar o import de todo o módulo, todas as funções, atributos, classes # e propriedades que estão dentro do módulo ficarão em memória. print(random.random()) # random() -> Gera um semi-aleatorio entre 0 e 1 # Forma 2 - importando função específica (forma recomendada) from random import random print(random()) # funciona da mesma forma # uniform -> Gerar um número pseudo-aleatório entre os valores estabelecidos from random import uniform for i in range(10): print(uniform(3, 7)) # 7 não é incluido # randint() -> Gera valores pseudo-aleatório entre os valores estabelecidos from random import randint # Gerador de apostas for i in range(6): print(randint(1, 6), end=', ') # inclui 1 e 6, com repetição # choice() -> Mostra um valor aleatório entre um iterável from random import choice jogadas = ['pedra', 'papel', 'tesoura'] print(choice(jogadas)) """ # shuffle() -> Tem a função de embaralhar dados from random import shuffle cartas = ['K', 'Q', 'J', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10'] print(cartas) shuffle(cartas) print(cartas)
false
6ef1c3547acf3b758f8854ad6d978afd92ec8e48
njuliacsouza/_udemy_Python
/secao_10/any_all.py
832
4.28125
4
""" Any e All All: retorna True se todos os elementos do iteravel são verdadeiros ou se o iteravel está vazio # Exemplo all() print(all([0, 1, 2, 3, 4])) # Todos são True? Não, o zero é falso print(all([1, 2, 3, 4])) # True print(all([])) # True OBS: não apenas listas, mas sets, tuplas também. nomes = ['Carla', 'Carolina', 'Celio', 'Carlos', 'Cristina'] print(all([nome[0] == 'C' for nome in nomes])) # True Any: Retorna True se qualquer elemento de iterável for verdadeiro, se o iterável estiver vaio, retorn Falso """ # Exemplo any() print(any([0, 1, 2, 3, 4])) # Pelo menos um é verdadeiro, assim: True print(any([0, False, {}, ()])) # False, tudo é falso print(any([])) # False nomes = ['Carla', 'Carolina', 'Celio', 'Carlos', 'Cristina', 'Ana'] print(any([nome[0] == 'C' for nome in nomes])) # True
false
414430518b37f4ec2ad0e62ec7d63c3953bf6315
njuliacsouza/_udemy_Python
/secao_13/5_escrever_em_arquivos.py
1,382
4.71875
5
""" Escrevendo em arquivos Vamos utilizar outro modo de abertura da função open(), antes utilizamvamos o modo 'r', que era somente para leitura, não podendo realizar escrita nele. Agora, podemos utilizar o modo para escrita, não podendo lê-lo. # Modo de leitura with open('novo.txt', 'w', encoding='utf-8') as arquivo: arquivo.write('Este é um novo arquivo \n') arquivo.write('Escrever dados em arquivo é muito fácil \n') arquivo.write('Podemos colocar várias linhas') # aqui foi criado um novo arquivo chamado 'novo' com o texto especificado # se fosse colocado em um arquivo antigo, seria sobre-escrito, perdendo o que se tinha with open('novo.txt', encoding='utf-8') as arquivo: print(arquivo.read()) # Truques de str with open('patodavida.txt', 'w', encoding='utf-8') as arquivo: arquivo.write('Textinho pro amor da minha vida, acho que ela nunca vai encontrar, mas está aqui. \n') arquivo.write('TE AMO ' * 1000) with open('patodavida.txt', encoding='utf-8') as arquivo: print(arquivo.read()) """ with open('fruta.txt', 'w', encoding='utf=8') as arquivo: while True: fruta = input('Informe uma fruta ou digite sair: ') if fruta != 'sair': arquivo.write("- " + fruta.capitalize() + '\n') else: break with open('fruta.txt', encoding='utf-8') as arquivo: print(arquivo.read())
false
1d11cc72412b349f9fa4cba5db5f5b7ae209e3f1
njuliacsouza/_udemy_Python
/secao_19/2_manipulando_data_hora.py
1,322
4.34375
4
""" Manipulando Data e Hora Python tem um módulo buit-in (integrado) para se trabalhar com data e hora chamado datetime import datetime # print(dir(datetime)) print(datetime.MAXYEAR) print(datetime.MINYEAR) # Dentro da classe datetime print(datetime.datetime.now()) # 2021-07-30 20:08:48.108489 print(repr(datetime.datetime.now())) # representação # método replace() para fazer ajustes inicio = datetime.datetime.now() print(inicio) #alterando inicio = inicio.replace(hour=16, minute=0, second=0, microsecond=0) print(inicio) # declarando evento = datetime.datetime(2021, 1, 23, 17, 0, 0, 0) print(type(evento)) print(evento) # exemplo data_nascimento = input('Informe sua data de nascimento (dd/mm/yyyy): ') data_nascimento = data_nascimento.split('/') hora_nascimento = input('Informe que horas vc nasceu (hh:mm): ') hora_nascimento = hora_nascimento.split(':') nascimento = datetime.datetime(int(data_nascimento[2]), int(data_nascimento[1]), int(data_nascimento[0]), int(hora_nascimento[0]), int(hora_nascimento[1])) print(nascimento) # 1998-01-09 22:04:00 """ import datetime # Acessando elementos evento = datetime.datetime(2021, 1, 23, 17, 4, 13, 1) print(evento.year) print(evento.month) print(evento.day) print(evento.hour) print(evento.minute) print(evento.second) print(evento.microsecond)
false
770782703584c23ed76a71ece31eaf997c6f0427
carlhinderer/python-algorithms
/classic_cs_problems/code/ch01/fibonacci.py
1,449
4.15625
4
# Different approaches for generating Fibonacci numbers # # First attempt just shows what happens if you forget a base case # # Naive attempt with base case def fib2(n): if n < 2: return n return fib2(n-1) + fib2(n-2) # Use memoization MEMO = {0: 0, 1: 1} def fib3(n): if n not in MEMO: MEMO[n] = fib3(n-1) + fib3(n-2) return MEMO[n] # Use automatic memoization from functools import lru_cache @lru_cache(maxsize=None) def fib4(n): if n < 2: return n return fib4(n-2) + fib4(n-1) # A simple iterative approach is the most performant def fib5(n): if n == 0: return n last = 0 next = 1 for _ in range(1, n): last, next = next, last + next return next # Use a generator to generate a sequence up to a given value def fib6(n): yield 0 if n > 0: yield 1 last = 0 next = 1 for _ in range(1, n): last, next = next, last + next yield next if __name__ == '__main__': assert fib2(0) == 0 assert fib2(1) == 1 assert fib2(9) == 34 assert fib3(0) == 0 assert fib3(1) == 1 assert fib3(9) == 34 assert fib3(50) == 12586269025 assert fib4(0) == 0 assert fib4(1) == 1 assert fib4(9) == 34 assert fib4(50) == 12586269025 assert fib5(0) == 0 assert fib5(1) == 1 assert fib5(9) == 34 assert fib5(50) == 12586269025 # Use the generator for i in fib6(50): print(i)
true
674ee54534ab25221bd886eef60b512aa9edf7d4
msaldeveloper/python
/pythonKodemia/clase3_listas.py
2,034
4.40625
4
##listas en python(arreglos) miPrimerLista =[1,3.1416,"hola mundo"] ### x=[1,2]#se crea la variable x que contiene una lista con valores 1,2 y=x x[0]=0 print(y) ##append miListaUno=[ 1, 2, 3] miListaDos=[ 1, 3] miListaUno.append(miListaDos) ##añade el arreglo de miListDos a un espacio nuevo del arreglo miListaUno #resultado miListaUno=[1,2,3,1,3] ##extend miListaUno=[ 1, 2, 3] miListaDos=[ 1, 3] miListaUno.extend(miListaDos)##añade el arreglo de miArregloDos extendiendo el Nuevo Arreglo miListaUno con sus valores como si fueran de el miListaUno+miListaDos##hace lo mismo que extend pero no sobreescribe ninguna lista solo crea una nueva lista que se puede guardar ##remove miListaUno.remove(2)##elimina el primer 2 que encuentra miListaUno.remove([1,3]) ##pop miListaUno.pop(2)##remueve el elemento del espacio del arreglo 2 y te muestra cual es el elemento ##index miListaUno=[1,2,3] miListDos=[1,3] miListaUno.append(miListaDos) miListaUno.index(3)##hace una consulta y regresa el espacio donde se encuentra el primer elemento 3 miListaUno.index([1,3])##regresa la locacion del arreglo [1,3] ##count miListaUno.count(3)##cuenta cuantos 3 hay en la lista ##reverse miListaUno[::-1]##lee la lista de izquierda a derecha miListaUno.reverse()##cambia el orden de la lista de izquierda a derecha y lo sobreescribe miListaUno[::-1].reverse()##lee el arreglo y lo devuelve al reves luego el .reverse lo cambia el orden de la lista de izquierda a derecha y lo sobreescribe ##insert miListaUno.insert(2,"texto")##inserta el string "texto " en el subindice 2 ##sort miListaUno.sort() ##ordena de mayor a menor o alfabeticamente si son strings (no puedes comprar listas, tienen que ser los datos del mismo tipo en la lista)(no debe de hacer listas dentro de listas) ##[::] miListaUno[-1:-2:-1]##ultimo elemento de la lista mi miListaUno.count(100)#cuenta cuantas veces esta el 100 ###crear mi documentacion #gato para comentarios python no lo lee """ puede usar strings para documentar pero el codigo si se lee """
false
961f9d2658e2fbf0e1642457c0b552117d72fefc
saurabh0307meher/Python-Programs
/basic programs/3nos.py
232
4.15625
4
#largest of two numbers a=int(input("Enter 1st nos")) b=int(input("Enter 2nd nos")) c=int(input("Enter 3rd nos")) if (a>b and a>c): print(a,"is greatest") elif (b>c): print(b,"is greatest") else: print(c,"is greatest")
true
8b660b989bb61fd07afd32bf8b18253e705c3fa4
ruchikpatel/abbdemo
/sort/insertion/reverseOrder_IS.py
679
4.46875
4
''' Author: Ruchik Patel Date: 09/16/2017 File: randromNumbers_IS.py Description: Insertion sort algorithm that sorts reverse orderintegers. ''' import sys #import system library/package n = int(sys.argv[1]) #System argument # For reverse: nums = list(range(n, 0, -1)) print("Unsorted array: \n ", nums)#Prints unsorted integers first #Insertion sort function def insertion_sort(nums): for j in range(1,len(nums)): key = nums[j] i = j - 1 while i >= 0 and nums[i] > key: nums[i + 1] = nums[i] i -= 1 nums[i + 1] = key print("\n\n\n") insertion_sort(nums) #Calling the insertion sort function print("Sorted array: \n", nums) #Prints sorted integers first
true
5c42eb4b6ae9288a1675c24a6491bbf82941714d
ruchikpatel/abbdemo
/sort/selectionSort/selectionSort_reverse.py
718
4.34375
4
''' Author: Ruchik Patel Date: 09/16/2017 File: selectionSort_reverse.py Description: Selection sort algorithm that sorts reverse orderintegers. ''' import sys #import system library/package n = int(sys.argv[1]) #System argument # For reverse: nums = list(range(n, 0, -1)) print("Unsorted array: \n ", nums)#Prints unsorted integers first def selectionSort(nums): for i in range(0,len(nums)-1): min = i for j in range(i+1,len(nums)): if nums[j] < nums[min]: min = j nums[min],nums[i] = nums[i],nums[min] print("\n\n\n") selectionSort(nums) #Calling the insertion sort function print("Sorted array: \n", nums) #Prints sorted integers first
true
0941cffce853d5953f81e0d19afd1cc4ea21e435
greyreality/python_tasks
/Codility/StrSymmetryPoint_my.py
1,530
4.3125
4
# Write a function: def solution(S) # that, given a string S, returns the index (counting from 0) of a character such that the part of the string to the left of that character # is a reversal of the part of the string to its right. The function should return −1 if no such index exists. # Note: reversing an empty string (i.e. a string whose length is zero) gives an empty string. # For example, given a string: "racecar" # the function should return 3, because the substring to the left of the character "e" at index 3 is "rac", and the one to the right is "car". # Given a string:"x" # the function should return 0, because both substrings are empty. # Assume that: # the length of S is within the range [0..2,000,000]. # Complexity: # expected worst-case time complexity is O(length(S)); # expected worst-case space complexity is O(1) (not counting the storage required for input arguments). # Detected time complexity:O(length(S)) # correctness 100% def solution(S): sLen = len(S) # Symmetry point is possible, when and only when the string's length is odd. if sLen % 2 == 0: return -1 # With a odd-length string, the only possible symmetry point is the middle point. mid = sLen // 2 begin = 0 end = sLen - 1 # The middle point of an odd-length string is symmetr point, only when the string is symmetry. while begin < mid: if S[begin] != S[end]: return -1 begin += 1 end -= 1 return mid s = 'racecar' print(solution(s))
true
b1729397c045e0a3b0bd4486e74cf1374a29b880
greyreality/python_tasks
/Other_tasks/triangle_validity.py
613
4.46875
4
# Python3 program to check if three # sides form a triangle or not # У треугольника сумма любых двух сторон должна быть больше третьей. def checkValidity(a, b, c): if (a + b <= c) or (a + c <= b) or (b + c <= a): return False else: return True # Operator Meaning Example # and True if both the operands are true x and y # or True if either/ИЛИ of the operands is true x or y # not True if operand is false (complements the operand) not x a = 3 b = 4 c = 5 if checkValidity(a, b, c): print("Valid") else: print("Invalid")
true
d5808e4eadd351292439c619cd5b73a1d35ede29
Ankur-v-2004/Python-ch-6-data-structures
/prog_q1.py
597
4.28125
4
#Inserting element in a queue Queue = [] rear = 0 def Insertion_Queue(Queue, rear): ch = 'Y' while ch == 'y' or ch=='Y': element = input("Enter the element to be added to the Queue :") rear = rear + 1 #rear is incremented by 1 and then insertion takes place Queue.append(element) # adding element into list Queue print("Do you want to add more elements....<y/n> :") ch = input() if ch =='n' or ch =='N': break print("Contents of the queue are :",Queue) Insertion_Queue(Queue, rear)
true
e6c9c2f68f9d968db92000de5c820ac809fc533a
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH06/EX6.46.py
862
4.21875
4
# 6.46 (Turtle: connect all points in a hexagon) Write a program that displays a hexagon # with all the points connected, as shown in Figure 6.12b. import math import turtle # Draw a line from (x1, y1) to (x2, y2) def drawLine(x1, y1, x2, y2): turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) def drawPolygon(x=0, y=0, radius=50, numberOfSides=3): angle = 2 * math.pi / numberOfSides # Connect points for the polygon for i in range(numberOfSides + 1): for j in range(numberOfSides + 1): drawLine(x + radius * math.cos(i * angle), y - radius * math.sin(i * angle), x + radius * math.cos(j * angle), y - radius * math.sin(j * angle)) turtle.speed(0) # Fastest drawPolygon(0, 0, 50, 6) turtle.hideturtle() turtle.done()
false
a2c893a42650af0f31d847df25921cf0c11e7545
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH03/EX3.15.py
784
4.4375
4
# (Turtle: paint a smiley face) Write a program that paints a smiley face, as shown in # Figure 3.6a. import turtle turtle.circle(100) # face # smile turtle.penup() turtle.left(90) turtle.forward(30) turtle.right(60) turtle.pendown() turtle.forward(80) turtle.backward(80) turtle.left(120) turtle.forward(80) turtle.backward(80) # nose turtle.penup() turtle.setheading(90) turtle.forward(110) turtle.pendown() turtle.right(145) turtle.forward(80) turtle.backward(80) turtle.right(70) turtle.forward(80) turtle.backward(80) # right eye turtle.penup() turtle.setheading(0) turtle.forward(40) turtle.setheading(90) turtle.forward(20) turtle.pendown() turtle.dot(35) # left eye turtle.penup() turtle.setheading(180) turtle.forward(80) turtle.pendown() turtle.dot(35) turtle.done()
false
218ea769330f80223324f5dda2c9749953d34b26
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH06/EX6.26.py
483
4.25
4
# 6.26 (Mersenne prime) A prime number is called a Mersenne prime if it can be written # in the form for some positive integer p. Write a program that finds all # Mersenne primes with and displays the output as follows: # p 2^p - 1 # 2 3 # 3 7 # 5 31 # ... from CH6Module import MyFunctions print("P", " ", "2^p - 1") for p in range(2, 31 + 1): i = 2 ** p - 1 # Display each number in five positions if MyFunctions.isPrime(i): print(str(p) + "\t\t" + str(i))
true
6f40c592f87d09d6a2d046b25fabd3e80395a695
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH11/EX11.38.py
1,372
4.59375
5
# 11.38 (Turtle: draw a polygon/polyline) Write the following functions that draw a # polygon/polyline to connect all points in the list. Each element in the list is a list of # two coordinates. # # Draw a polyline to connect all the points in the list # def drawPolyline(points): # # Draw a polygon to connect all the points in the list and # # close the polygon by connecting the first point with the last point # def drawPolygon(points): # # Fill a polygon by connecting all the points in the list # def fillPolygon(points): import turtle # Draw a polyline to connect all the points in the list def drawPolyline(points): for i in range(len(points) - 1): drawLine(points[i], points[i + 1]) # Draw a polygon to connect all the points in the list and # close the polygon by connecting the first point with the last point def drawPolygon(points): drawPolyline(points) drawLine(points[len(points) - 1], points[0]) # Close the polygon # Fill a polygon by connecting all the points in the list def fillPolygon(points): turtle.begin_fill() drawPolygon(points) turtle.end_fill() # Draw a line from (x1, y1) to (x2, y2) def drawLine(x1, y1, x2, y2): turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) points = input("Enter points: ").split() points = [eval(p) for p in points] drawPolygon(points)
true
9e08660316315554e6272d205261e69d86626036
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH10/EX10.28.py
1,735
4.34375
4
# 10.28 (Partition of a list) Write the following function that partitions the list using the # first element, called a pivot: # def partition(lst): # After the partition, the elements in the list are rearranged so that all the elements # before the pivot are less than or equal to the pivot and the element after # the pivot are greater than the pivot. The function also returns the index where # the pivot is located in the new list. For example, suppose the list is [5, 2, 9, 3, # 6, 8]. After the partition, the list becomes [3, 2, 5, 9, 6, 8]. Implement the # function in a way that takes len(lst) comparisons. Write a test program # that prompts the user to enter a list and displays the list after the partition. def main(): s = input("Enter a list: ") items = s.split() # Extracts items from the string list = [eval(x) for x in items] # Convert items to numbers partition(list) print("After the partition, the list is ", end="") for e in list: print(e, end=" ") def partition(list): pivot = list[0] # Choose the first element as the pivot low = 1 # Index for forward search high = len(list) - 1 # Index for backward search while high > low: # Search forward from left while low <= high and list[low] <= pivot: low += 1 # Search backward from right while low <= high and list[high] > pivot: high -= 1 # Swap two elements in the list if high > low: list[high], list[low] = list[low], list[high] while high > 1 and list[high] >= pivot: high -= 1 # Swap pivot with list[high] if pivot > list[high]: list[0] = list[high] list[high] = pivot main()
true
45f193d1594484a857709fae36c7d96fd39a9a4c
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH04/EX4.11.py
1,227
4.40625
4
# (Find the number of days in a month) Write a program that prompts the user to # enter the month and year and displays the number of days in the month. For example, # if the user entered month 2 and year 2000, the program should display that # February 2000 has 29 days. If the user entered month 3 and year 2005, the program # should display that March 2005 has 31 days. month, year = eval(input("Enter month and year: ")) days = 0 isLeapYear = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) if month == 1: month = "January" days = 31 elif month == 2: month = "February" if isLeapYear: days = 29 else: days = 28 elif month == 3: month = "March" days = 31 elif month == 4: month = "April" days = 30 elif month == 5: month = "May" days = 31 elif month == 6: month = "June" days = 30 elif month == 7: month = "July" days = 31 elif month == 8: month = "Augustus" days = 30 elif month == 9: month = "September" days = 31 elif month == 10: month = "October" days = 30 elif month == 11: month = "November" days = 31 elif month == 12: month = "December" days = 30 print(month, year, "has", days, "days")
true
60621aebebf46e1bab7bdf1bf90f28e68e9d18b7
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH06/EX6.12.py
545
4.53125
5
# 6.12 (Display characters) Write a function that prints characters using the following # header: # def printChars(ch1, ch2, numberPerLine): # This function prints the characters between ch1 and ch2 with the specified # numbers per line. Write a test program that prints ten characters per line from 1 # to Z. def printChars(ch1, ch2, numberPerLine): count = 1 for i in range(ord(ch1), ord(ch2)+1): print(chr(i), end=" ") if count % numberPerLine == 0: print() count += 1 printChars("1", "z", 10)
true
0d4bfdb03fa72aad73ca5a0f74298eb85078720b
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH11/EX11.4.py
832
4.1875
4
# 11.4 (Compute the weekly hours for each employee) Suppose the weekly hours for all # employees are stored in a table. Each row records an employee’s seven-day work # hours with seven columns. For example, the following table stores the work hours # for eight employees. Write a program that displays employees and their total hours # in decreasing order of the total hours. workHours = [ [2, 4, 3, 4, 5, 8, 8], [7, 3, 4, 3, 3, 4, 4], [3, 3, 4, 3, 3, 2, 2], [9, 3, 4, 7, 3, 4, 1], [3, 5, 4, 3, 6, 3, 8], [3, 4, 4, 6, 3, 4, 4], [3, 7, 4, 8, 3, 8, 4], [6, 3, 5, 9, 2, 7, 9]] matrix = [] for row in range(len(workHours)): totHours = sum(workHours[row]) matrix.append([totHours, "Employee " + str(row)]) matrix.sort(reverse=True) for i in matrix: print(i[1]+"'s total hours =", i[0])
true
7e1bb35e01e8e7fbf698a954f8627d381029cb24
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH05/EX5.19.py
465
4.21875
4
# 5.19 (Display a pyramid) Write a program that prompts the user to enter an integer # from 1 to 15 and displays a pyramid, as shown in the following sample run: n = int(input("Enter number of lines: ")) x = n * 2 for i in range(1, n + 1): s = n + x sp = str(s) + "s" print(format(" ", sp), end='') for j in range(i, 0, -1): print(j, end=' ') for j in range(2, i + 1): print(j, end=' ') print(format(" ", sp)) x -= 3
true
3f49290f5bdfe6b67bdabef777e17c8051905f1b
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH08/EX8.5.py
855
4.34375
4
# 8.5 (Occurrences of a specified string) Write a function that counts the occurrences of a # specified non-overlapping string s2 in another string s1 using the following header: # def count(s1, s2): # For example, count("system error, syntax error", "error") returns # 2. Write a test program that prompts the user to enter two strings and displays the # number of occurrences of the second string in the first string. def count(s1, s2): counter = 0 s1 = s1 + ' ' while len(s1) > 0: s = s1[0: s1.index(' ')] s = s[0:len(s2)] if s == s2: counter += 1 s1 = s1[s1.index(' ')+1: len(s1)] return counter def main(): str1 = input("Enter first string: ") str2 = input("Enter second string: ") c = count(str1, str2) print("String", str2, "is occurred", c, "times in", str1) main()
true
5f3c2905fc6851de987bad08f1a0ff2c9d0ec4c5
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH13/EX13.9.py
582
4.40625
4
# 13.9 (Decrypt files) Suppose a file is encrypted using the scheme in Exercise 13.8. # Write a program to decode an encrypted file. Your program should prompt the # user to enter an input filename and an output filename and should save the unencrypted # version of the input file to the output file. infile = input("Enter input filename: ") outfile = input("Enter output filename: ") source = open(infile, 'r') destination = open(outfile, 'w') res = '' data = source.read() for i in range(len(data)): res += chr(ord(data[i]) - 5) destination.write(res) destination.close()
true
11d4ed6ac8734971cdf7cf91f29e57747b72df47
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH05/EX5.44.py
323
4.25
4
# 5.44 (Decimal to binary) Write a program that prompts the user to enter a decimal integer # and displays its corresponding binary value. d = int(input("Enter an integer: ")) bin = "" value = d while value != 0: bin = str(value % 2) + bin value = value // 2 print("The binary representation of", d, "is", bin)
true
40dba80ab9881ee0d5f18a1ef881c6202c707b20
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH08/EX8.8.py
654
4.34375
4
# 8.8 (Binary to decimal) Write a function that parses a binary number as a string into a # decimal integer. Use the function header: # def binaryToDecimal(binaryString): # For example, binary string 10001 is 17 # So, binaryToDecimal("10001") returns 17. # Write a test program that prompts the user to enter a binary string and displays the # corresponding decimal integer value. def binaryToDecimal(binaryString): bin = binaryString[::-1] dec = 0 for i in range(len(bin)): dec = dec + int(bin[i]) * 2 ** i return dec def main(): bin = input("Enter binary string: ") dec = binaryToDecimal(bin) print(dec) main()
true
dac980495e1d018450893bb6247da7049abe78db
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH07/EX7.1.py
1,244
4.875
5
# 7.1 (The Rectangle class) Following the example of the Circle class in Section # 7.2, design a class named Rectangle to represent a rectangle. The class # contains: # ■ Two data fields named width and height. # ■ A constructor that creates a rectangle with the specified width and height. # The default values are 1 and 2 for the width and height, respectively. # ■ A method named getArea() that returns the area of this rectangle. # ■ A method named getPerimeter() that returns the perimeter. # Draw the UML diagram for the class, and then implement the class. Write a test # program that creates two Rectangle objects—one with width 4 and height 40 # and the other with width 3.5 and height 35.7. Display the width, height, area, # and perimeter of each rectangle in this order. from CH7.Rectangle import Rectangle rect1 = Rectangle(4, 40) rect2 = Rectangle(3.5, 35.7) area1 = rect1.getArea() area2 = rect2.getArea() per1 = rect1.getPerimeter() per2 = rect2.getPerimeter() print("Rectangle1:\n\tWidth =", rect1.width, "\n\tHeight =", rect1.height, "\n\tArea =", area1, "\n\tPerimeter =", per1) print("Rectangle2:\n\tWidth =", rect2.width, "\n\tHeight =", rect2.height, "\n\tArea =", area2, "\n\tPerimeter =", per2)
true
0a9788e3aca817a8e3c9bfdd55cc60dddfa710ba
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH05/EX5.43.py
341
4.125
4
# 5.43 (Math: combinations) Write a program that displays all possible combinations for # picking two numbers from integers 1 to 7. Also display the total number of combinations. count = 0 for i in range(1, 8): for j in range(i+1, 8): print(i, " ", j) count += 1 print("The total number of all combinations is", count)
true
c27897d3dd75790a1778be71ae337c7483f29183
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH15/EX15.11.py
512
4.40625
4
# 15.11 (Print the characters in a string reversely) Rewrite Exercise 15.9 using a helper # function to pass the substring for the high index to the function. The helper # function header is: # def reverseDisplayHelper(s, high): def reverseDisplay(value): reverseDisplayHelper(value, len(value) - 1) def reverseDisplayHelper(s, high): if high < 0: print() else: print(s[high], end='') reverseDisplayHelper(s, high - 1) val = input("Enter a string: ") reverseDisplay(val)
true
e9ce060de5debd11b74c64e81cbcdb2149776bea
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH15/EX15.34.py
1,848
4.40625
4
# 15.34 (Turtle: Hilbert curve) Rewrite the Hilbert curve in Exercise 15.33 using Turtle, # as shown in Figure 15.20. Your program should prompt the user to enter the # order and display the corresponding fractal for the order. import turtle def upperU(order): if order > 0: leftU(order - 1) turtle.setheading(270) turtle.forward(length) upperU(order - 1) turtle.setheading(0) turtle.forward(length) upperU(order - 1) turtle.setheading(90) turtle.forward(length) rightU(order - 1) def leftU(order): if order > 0: upperU(order - 1) turtle.setheading(0) turtle.forward(length) leftU(order - 1) turtle.setheading(270) turtle.forward(length) leftU(order - 1) turtle.setheading(180) turtle.forward(length) downU(order - 1) def rightU(order): if order > 0: downU(order - 1) turtle.setheading(180) turtle.forward(length) rightU(order - 1) turtle.setheading(90) turtle.forward(length) rightU(order - 1) turtle.setheading(0) turtle.forward(length) upperU(order - 1) def downU(order): if order > 0: rightU(order - 1) turtle.setheading(90) turtle.forward(length) downU(order - 1) turtle.setheading(180) turtle.forward(length) downU(order - 1) turtle.setheading(270) turtle.forward(length) leftU(order - 1) order = eval(input("Enter an order: ")) SIZE = 400 length = 400 for i in range(order): length = length / 2 # Get the right length for the order # Get the start point x = -SIZE / 2 + length / 2 y = SIZE / 2 - length / 2 turtle.penup() turtle.goto(x, y) turtle.pendown() upperU(order) turtle.done()
true
a97533ceba4eff0dfc8f651a353d21c931c380e4
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH03/EX3.5.py
632
4.15625
4
# (Geometry: area of a regular polygon) A regular polygon is an n-sided polygon in # which all sides are of the same length and all angles have the same degree (i.e., the # polygon is both equilateral and equiangular). The formula for computing the area # of a regular polygon is # Here, s is the length of a side. Write a program that prompts the user to enter the # number of sides and their length of a regular polygon and displays its area. import math n = int(input("Enter the number of sides: ")) s = eval(input("Enter the side: ")) area = (n * s ** 2) / (4 * math.tan(math.pi / n)) print("The area of the polygon is", area)
true
050e743c103dbe2f59ddb3451709031d30ca5b1f
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH13/EX13.2.py
554
4.21875
4
# 13.2 (Count characters, words, and lines in a file) Write a program that will count the # number of characters, words, and lines in a file. Words are separated by a whitespace # character. Your program should prompt the user to enter a filename. filename = input("Enter a filename: ").strip() file = open(filename, 'r') lines = 0 words = 0 chars = 0 for line in file: lines += 1 words += len(line.split()) for c in line: if c != ' ': chars += 1 print(chars, "characters") print(words, "words") print(lines, "Lines")
true
ccea56d0aaed3b2e976259cc6decbd3516bde27c
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH15/EX15.01.py
493
4.3125
4
# 15.1 (Sum the digits in an integer using recursion) Write a recursive function that computes # the sum of the digits in an integer. Use the following function header: # def sumDigits(n): # For example, sumDigits(234) returns Write a test program # that prompts the user to enter an integer and displays its sum. def sumDigits(n): if n == 0: return n return (n % 10 + sumDigits(n//10)) n = eval(input("Enter a digit: ")) print("The sum of the digits is:", sumDigits(n))
true
7ad21495c9581d74dc9b9f02930fbfe7dd7c3f12
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH06/EX6.7.py
1,140
4.3125
4
# 6.7 (Financial application: compute the future investment value) Write a function that # computes a future investment value at a given interest rate for a specified number of # years. The future investment is determined using the formula in Exercise 2.19. # Use the following function header: # def futureInvestmentValue( # investmentAmount, monthlyInterestRate, years): # For example, futureInvestmentValue(10000, 0.05/12, 5) returns # 12833.59. # Write a test program that prompts the user to enter the investment amount and the # annual interest rate in percent and prints a table that displays the future value for # the years from 1 to 30. def futureInvestmentValue(investmentAmount, monthlyInterestRate, years): print("Years Future years") for i in range(1, years + 1): futureValue = investmentAmount * ((1 + monthlyInterestRate) ** (12 * i)) print(i, "\t\t\t", format(futureValue, ".2f")) def main(): investmentAmount = eval(input("The amount invested : ")) interestRate = eval(input("Annual interest rate : ")) futureInvestmentValue(investmentAmount, interestRate / 1200, 30) main()
true
cfa8e99d7f24ebcbb5c4237e74f1f475ba1e5704
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH06/EX6.38.py
557
4.3125
4
# 6.38 (Turtle: draw a line) Write the following function that draws a line from point # (x1, y1) to (x2, y2) with color (default to black) and line size (default to 1). # def drawLine(x1, y1, x2, y2, color = "black", size = 1): import turtle def drawLine(x1, y1, x2, y2, color="black", size=1): turtle.color(color) turtle.pensize(size) turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) def main(): drawLine(10, 20, 70, 90, "blue", 5) drawLine(40, 20, -70, 50, "yellow", 8) turtle.done() main()
true
02b3e59d523a56be6ae7df5c11687f7a168db030
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH10/EX10.5.py
540
4.28125
4
# 10.5 (Print distinct numbers) Write a program that reads in numbers separated by a # space in one line and displays distinct numbers (i.e., if a number appears multiple # times, it is displayed only once). (Hint: Read all the numbers and store # them in list1. Create a new list list2. Add a number in list1 to list2. # If the number is already in the list, ignore it.) n = input("Enter ten numbers: ") l1 = [int(x) for x in n.split()] l2 = [] for x in l1: if x not in l2: l2.append(x) print("The distinct numbers are:",l2)
true
808f4c21115654ed8553ba1e529b933b1e258b79
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH03/EX3.11.py
344
4.25
4
# (Reverse number) Write a program that prompts the user to enter a four-digit integer # and displays the number in reverse order. num = eval(input("Enter an integer: ")) n1 = num % 10 num = num // 10 n2 = num % 10 num = num // 10 n3 = num % 10 num = num // 10 n4 = num print(n1, end='') print(n2, end='') print(n3, end='') print(n4, end='')
true
9ef95ef743118f21adfb7b048d4744122da08dc5
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH05/EX5.40.py
429
4.15625
4
# 5.40 (Simulation: heads or tails) Write a program that simulates flipping a coin one # million times and displays the number of heads and tails. import random print("Simulating flipping a coin 1000000 times") head = 0 tail = 0 print("Wait....") for i in range(0, 1000000): if random.randint(0, 1) == 0: head += 1 else: tail += 1 print("The number of heads:", head, "and the number of tails:", tail)
true
a6da77075a5d612fdd68de486f11f3bb5c7cee12
jameszhan/leetcode
/algorithms/095-unique-binary-search-trees-ii.py
1,417
4.125
4
""" 不同的二叉搜索树 II 给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。 示例: 输入:3 输出: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3   提示: 0 <= n <= 8 """ # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def generate_trees(n: int) -> List[TreeNode]: def do_generate_trees(start, end): if start > end: return [None] ans = [] for i in range(start, end + 1): left_trees = do_generate_trees(start, i - 1) right_trees = do_generate_trees(i + 1, end) for l in left_trees: for r in right_trees: tree = TreeNode(i + 1) tree.left = l tree.right = r ans.append(tree) return ans if n == 0: return [] else: return do_generate_trees(0, n - 1) if __name__ == '__main__': print(generate_trees(3))
false
07bd7f173af81adfc21fb4cc4bf67e2220ce7236
jameszhan/leetcode
/algorithms/035-search-insert-position.py
1,277
4.1875
4
""" 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 示例 3: 输入: [1,3,5,6], 7 输出: 4 示例 4: 输入: [1,3,5,6], 0 输出: 0 """ def search_insert(nums, target) -> int: nums_len = len(nums) if nums_len < 1: return 0 left, right = 0, nums_len - 1 if nums[-1] < target: return nums_len elif nums[0] > target: return 0 else: while left < right: mid = left + (right - left) // 2 if target > nums[mid]: left = mid + 1 elif target < nums[mid]: right = mid - 1 else: return mid return left if nums[left] >= target else left + 1 if __name__ == '__main__': print(search_insert([1], 1)) # 1 print(search_insert([1, 3], 2)) # 1 print(search_insert([1, 3, 5, 6], 5)) # 2 print(search_insert([1, 3, 5, 6], 2)) # 1 print(search_insert([1, 3, 5, 6], 7)) # 4 print(search_insert([1, 3, 5, 6], 0)) # 0
false
159c18a4adce4d20d774ab866e3198b710b00376
jcontreras12/Moduel-6
/factorial.py
336
4.3125
4
# problem 6 use a for statement to calculate the factorial of a users input value import math x = int(input("Enter a number:")) number = 1 for i in range(1, x+1): number = number * i print("Factorial of {} using for Loop {}".format(x, number)) print(" Factorial of {} using inbuilt function: {}".format(x, math.factorial(x)))
true
5e84a356985f8bc40ccb7758b6ea9acc233626fa
kutay/workshop-intro
/python-sqlite3/main.py
1,339
4.3125
4
import sqlite3 from sqlite3 import Error # https://www.sqlitetutorial.net/sqlite-python/ def create_connection(db_file): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def select_all_messages(conn): """ Query all rows in the messages table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT * FROM messages") rows = cur.fetchall() for row in rows: print(row) def select_messages_by_user(conn, user_id): """ Query messages by user_id :param conn: the Connection object :param user_id: :return: """ cur = conn.cursor() cur.execute("SELECT * FROM messages WHERE user_id=?", (user_id,)) rows = cur.fetchall() for row in rows: print(row) def main(): database = r"sqlite.db" conn = create_connection(database) with conn: print("1. Query messages by user:") select_messages_by_user(conn, 1) print("2. Query all messages") select_all_messages(conn) print("3. Post a message") # FIXME main()
true
3fd5c20428b51725c133e7702fed0de0412d05b1
inaram/workshops
/python3/fitnessChallenge.py
899
4.21875
4
def fitnessChallenge(): challengeLength = int(input("How many days do you want your fitness challenge to last? ")) totalMinutes = 0 totalDays = 0 for day in range(1, challengeLength + 1): answer = input("Have you exercised today? (y/n): ") if answer == "y" or answer == "yes" or answer == "Y" or answer == "Yes" or answer == "YES": totalDays += 1 print("Great job!") addMinutes = int(input("For how many minutes? ")) totalMinutes = totalMinutes + addMinutes print("Keep up the good work!") if totalMinutes != 0 or totalDays != 0: print("Congratulations! You have exercised for %d day(s) out of your %d-day challenge" % (totalDays, challengeLength)) print("Total number of minutes:", totalMinutes) def main(): fitnessChallenge() if __name__ == "__main__": main()
true
a6e07131d153747bbeeb90472617f2fe6322aef9
grahamrichard/COMP-123-fall-16
/PycharmProjects/Oct03/whileloops.py
2,820
4.46875
4
""" ================================================== File: whileloops.py Author: Susan Fox Date: Spring 2013 This file contains examples of while and for loops for the Iteration activity. """ # ==================================================== # Simple while loop examples # loop 1 def printEveryFifth(x): """One input x: must be an integer >= 0 Prints every 5th value from x down to zero""" while x >= 0: # x is the loop variable print(x) x = x - 5 # when indentation stops, while loop is over print("Done!") # end of printEveryFifth print("------------------------------") print("Sample calls to printEveryFifth:") print("printEveryFifth(10) does:") printEveryFifth(10) print("printEveryFifth(4) does:") printEveryFifth(4) # printEveryOther counts down from the input number by 2, for positive numbers only # printEveryFifth does the same but by 5 def squareUserNums(): # Initialize loop variable userInp = input("Enter the next number (negative to quit): ") userNum = int(userInp) while userNum >= 0: print(userNum, "squared is", userNum ** 2) userInp = input("Enter the next number (negative to quit): ") userNum = int(userInp) #squareUserNums() # with first 2 lines commented out the f'n doesn't work because the loop variables haven't been initialized # with the two lines in the loop commented out it repeats forever because there's no change in the loop condition def sum3s(topNum): currVal = 0 # loop variable total = 0 # accumulator variable while currVal <= topNum: print(currVal, "\t", total) total = total + currVal currVal = currVal + 3 return total # sum3s sums multiples of three up to the user input value sum3s(20) def adduserNums(): """adds numbers entered by the user until a negative is encountered.""" userNum = 0 accum = 0 while userNum >= 0: userInp = input("enter a number (negative to quit): ") userNum = int(userInp) accum = accum + userNum print(accum) return accum adduserNums() def cappedTotal(numList): """Takes in a list of numbers and adds the numbers up. If it gets to a result that is more than 100, then the loop stops and it returns 100""" total = 0 for val in numList: total = total + val if total > 100: total = 100 break # end if statement # end for loop return total def squareUserNumsTwo(): """edited copy of squareUserNums using if and a break to shorten it.""" while True: userInp = input("Enter the next number (negative to quit): ") userNum = int(userInp) if userNum < 0: break print(userNum, "squared is", userNum ** 2) squareUserNumsTwo()
true
0b141796ccdf60dd04b46e419ee0254db7e79d18
grahamrichard/COMP-123-fall-16
/PycharmProjects/FINAL/Q1.py
2,130
4.65625
5
# In this question you are provided a function to determine # if a string is a palindrome. This function is recursive # you have several tasks # 1. Using comments, label each line of code as either # part of a base case or a recursive case. If there are # more than one base case or recursive case number the # cases (I.E. base case 1) # 2. For each case, explain the case. For base cases, # please explain what the case is (under what conditions # the case gets ran) and why the base case is correct # (the conditions under which the base case is ran, why # is it correct to return what it does). # For recursive cases explain in what way the recursive # call moves closer to a base case. def palindrome(aString): """This function takes a string and returns True if the string is a palindrome. (A palindrome is any string that is the same forwards and backwards) examples: 'a', 'abba', 'qwe r ewq'""" if len(aString) <= 1: # base case 1: if the string is 1 character or less it must be a palindrome return True elif aString[0] != aString[-1]: # base case 2: if the first and last letters of the string are not the same, the string cannot be a palindrome. return False else: return palindrome(aString[1:len(aString)-1]) # recursive case: if the first and last letters of the string are the same, proceed to test the second and second to last letters with the same criteria print(palindrome("")) # True len < 1, it must be a palindrome print(palindrome("abba")) # True first and last letters are the same; 2nd and 2nd to last letters are the same in the recursion print(palindrome("apa")) # True first and last letters are the same; in the recursive call, the remaining string is 1 char long print(palindrome("!")) # True len = 1, it must be a palindrome print(palindrome("ape")) # False first and last letters are not the same print(palindrome("as")) # False first and last letters are not the same print(palindrome("aaaapeaaa")) # False outer letters on the third recursion are not the same
true
94262de064f2348068e6650a9e69c1b227d4bf93
grahamrichard/COMP-123-fall-16
/PycharmProjects/Oct10/InClass.py
1,685
4.28125
4
import turtle wind = turtle.Screen() turt1 = turtle.Turtle() turt1.up() turt1.goto(100,100) turt1.down() turt2 = turtle.Turtle() turt2.up() turt2.goto(-100, -100) turt2.down() turt3 = turt1 # gives us another name to refer to turt1/creates an Alias # this line of code creates a new turtle that is a 'copy' of a previous turtle. turt4 = turt2.clone() # creates a totally new turtle at the same position as turt2. for i in range(4): turt1.forward(100) # turt1/3 goes forward turt3.left(90) # turt1/3 turns left turt2.backward(100) # turt 2 moves turt4.right(90) # turt 4 turns w/out moving wind.exitonclick() def addN(z, n): z.insert(0,str(n)) x=[] # x = [] y=x # y = [] x.insert(0, "apple") # x = ["apple"] z=y+["pies"] # z = ["apple", "pies"] addN(y, 10) # x, y = [10, "apple"] z.append("sound good") # ["apple", "pies", "sound good"] z[0] = "lemon" # ["lemon", "pies", "sound good"] w=z[:] # w = ["lemon", "pies", "sound good"] print (x) # ["10", "apples] print (y) # ["10", "apples] print (z) # ["lemon", "pies", "sound good"] print (w) # ["lemon", "pies", "sound good"] print(x == y) # True print(x is y) # True print(w == z) # True print(w is z) # False def doubleList(inList): outlist = [elem * 2 for elem in inList] return outlist def doubleListInPlace(inList): for elem in range(len(inList)): inList[elem] = elem * 2 testList = [1, 2, 5] print(doubleList(testList)) print(doubleListInPlace(testList)) print(testList)
false
cbbe95857a99d7b349eff3d726b944f5dbf48a20
grahamrichard/COMP-123-fall-16
/PycharmProjects/FINAL/Q2.py
589
4.4375
4
# This question has you write a function named greater. # The Greater function takes a dictionary whose keys are # numbers and whose values are numbers. The function # returns a list of all keys that are larger than their # values. The original dictionary should not be modified. # See the included example for more information. def greater(someDict): greaters = [] for (k, v) in someDict.items(): if k > v: greaters.append(k) return greaters aDict = {1:2, 2:1, 306:306, 4:1, 51:61, 17:3} print(greater(aDict)) #should print (order may change) # [2,4,17]
true
cfcac0732131c1af470b48fee911605cd4b45d07
cabudies/Python-Batch-3-July-2018
/5-July.py
539
4.28125
4
# use input() function to take input from user # use int() function to convert string to int number = int(input('Enter the number of rows for star pattern: ')) for i in range(0, number): for j in range(0, i): print("*", end=" ") print() # use def to create a function def printUserDetails(): print("hello") a = 10 return a name = input("Hello enter your name: ") age = int(input("Enter your age: ")) # calling a function using it's name. number = printUserDetails() print(number)
true
f5d5c595241d3b20830f30c314114a2e00cb7379
Grinch101/data_structure
/algorithms/sorting_algorithms/merge_sort.py
2,196
4.1875
4
# merge sort: # The divide-and-conquer paradigm involves three steps at each level of the recursion: # Divide the problem into a number of subproblems that are smaller instances of the # same problem. # Conquer the subproblems by solving them recursively. If the subproblem sizes are # small enough, however, just solve the subproblems in a straightforward manner. # Combine the solutions to the subproblems into the solution for the original problem. # The merge sort algorithm closely follows the divide-and-conquer paradigm. Intuitively, # it operates as follows. # Divide: Divide the n-element sequence to be sorted into two subsequences of n=2 # elements each. # Conquer: Sort the two subsequences recursively using merge sort. # Combine: Merge the two sorted subsequences to produce the sorted answer. # The recursion “bottoms out” when the sequence to be sorted has length 1, in which # case there is no work to be done, since every sequence of length 1 is already in # sorted order. # The key operation of the merge sort algorithm is the merging of two sorted # sequences in the “combine” step. # The recursion tree has lg n C 1 levels, each costing cn, # for a total cost of cn.lg n C 1/ D cn lg n C cn. Ignoring the low-order term and # the constant c gives the desired result of ‚.n lg n/. def merge_sort( arr): if len(arr) >= 2: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) i = j = idx = 0 while True: if left[i] <= right[j]: arr[idx] = left[i] idx += 1 i += 1 if i == len(left): break else: arr[idx] = right[j] idx += 1 j += 1 if j == len(right): break # put extra item(s) in arr while i < len(left): arr[idx] = left[i] idx += 1 i += 1 while j < len(right): arr[idx] = right[j] idx += 1 j += 1 return arr # test: mg = merge_sort([9, 6, 4, 2, 0, 3, 1, 7, 8]) print(mg)
true
86d2fb4f5f5739055fb0dfbffa1250b7d0ea6840
roctubre/compmath
/serie6/6_3_lists.py
2,262
4.1875
4
from itertools import permutations # a) def has_duplicates(n): """ Check if the given list has unique elements Uses the property of sets: If converted into a set it is guaranteed to have unique elements. -> Compare number of elements to determine if the list contains duplicates """ if type(n) is not list: raise TypeError("Given input is not a list") if len(n) != len(set(n)): return True return False # b) def first_duplicate(n): """ Returns the first duplicate element in a list. Returns False if there are no duplicates. Iterates through the list and keeps track of all seen elements. If an element was already seen, it will return the first seen duplicate. """ if has_duplicates(n): unique = set() for x in n: if x in unique: return x else: unique.add(x) return False # c) def remove_duplicates(n): """ Removes duplicates in a given list (referenced list) Returns a list of all duplicates. """ seen = [] duplicates = [] # determine duplicates for x in n: if x in seen: duplicates.append(x) else: seen.append(x) # modify list in-place by assiining to its slice n[:] = seen; # return duplicates return duplicates # d) def permutation(n): """ Prints out all permutations of a list. Uses itertools.permutations() which is an in-build function """ for x in permutations(n): print(x) if __name__ == "__main__": # a) Test duplicates print("Test a)") mylist1 = ["hello", 1, 2, "world"] mylist2 = ["hello", 1, 2, "world", "hello"] print(has_duplicates(mylist1)) # false print(has_duplicates(mylist2)) # true # b) Test duplicates print("Test b)") mylist3 = ["hello", 1, 2, "world", "world", 2] print(first_duplicate(mylist3)) # 2 # c) Test remove duplicates print("Test c)") print(mylist3) # ['hello', 1, 2, 'world', 'world', 2] print(remove_duplicates(mylist3)) # ['world', 2] print(mylist3) # ['hello', 1, 2, 'world'] # d) Test list permutation mylist4 = [1,2,3,4] permutation(mylist4)
true
c441f91a6bf19db24c245518efaebc4306217d64
WomenWhoCode/WWCodePune
/Python/running_with_python/exercise.py
1,164
4.15625
4
""" 1). Create function without/ with none/default arguments. 2). Try passing args and kwargs 3). Call a lambda function inside a function. 4). Try r,r+,w,w+,a modes with file handling 5). Import modules from different and same directories 6). Create a class and try using __init__ method 7). Try calling a function within a class 8). Try calling a function with/without arguments and changing the properties of that instance as well as class variable. 9).Try using static and class methods for changing the values of that instance as well as class variable. 10). Try changing the hash of an instance, variable 11). Try importing multiple classes in a class 12). Create a class that inherits from 2 base classes and define a function with same name in both the base classes and try to see the method from which class is called 13). Try using super in child classes in python 2,3 14). Try calling a classmethod, staticmethod of base class from derived class 15). Try calling a classmethod, staticmethod of base class from classmethod of derived class 16). Try creating a diamond problem and see the method resolution order of the derived class """
true
987052f4c5e9bf33254a569ecf1a14b7b1fc814f
beatwad/algorithm
/find_max_subarray_recursive.py
1,541
4.125
4
import math def find_max_sublist(_list, low, high): """ Recursively find max sublist of list. Difficulty is O(n*lg(n)) """ if low == high: return low, high, _list[low] else: mid = divmod(low + high, 2)[0] left_low, left_high, left_sum = find_max_sublist(_list, low, mid) right_low, right_high, right_sum = find_max_sublist(_list, mid+1, high) cross_low, cross_high, cross_sum = find_max_crossing_sublist(_list, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_low, cross_high, cross_sum def find_max_crossing_sublist(_list, low, mid, high): """ Find max sublist which is contained by list and crosses it's middle """ max_left = 0 max_right = 0 left_sum = -math.inf _sum = 0 for index in range(mid, low-1, -1): _sum += _list[index] if _sum > left_sum: left_sum = _sum max_left = index right_sum = -math.inf _sum = 0 for index in range(mid+1, high+1): _sum += _list[index] if _sum > right_sum: right_sum = _sum max_right = index return max_left, max_right, left_sum+right_sum if __name__ == '__main__': _list = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7] print(find_max_sublist(_list, 0, len(_list)-1))
true
e58ba82afdc2622c981e0211369580ba6dbc6549
devjinius/algorithm
/Hackerrank/Left_Rotation.py
941
4.1875
4
''' HackerRank Left Rotation 문제 https://www.hackerrank.com/challenges/array-left-rotation/problem 문제 A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. 입력 The first line contains two space-separated integers denoting the respective values of n(the number of integers) and d(the number of left rotations you must perform). The second line contains n space-separated integers describing the respective elements of the array's initial state. 반환값 - 출력 Print a single line of n space-separated integers denoting the final state of the array after performing d left rotations.''' nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) for _ in range(d): a.append(a.pop(0)) print(" ".join(map(str, a)))
true
4742a4c9509853579379e3dfd120c48786e4b659
jalongod/LeetCode
/69.py
933
4.21875
4
''' 69. x 的平方根 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842...,   由于返回类型是整数,小数部分将被舍去。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sqrtx 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def mySqrt(self, x: int) -> int: left, right = 0, x // 2 + 1 while left < right: mid = (left + right + 1) >> 1 square = mid * mid if square > x: right = mid - 1 else: left = mid return left sol = Solution() max = sol.mySqrt(7) print(max)
false
56875cbaf2634b7524737c4d8e063a631811d4ce
MichelPinho/exerc-cios
/Par_ou_Impar.py
277
4.125
4
# CRIE UM PROGRAMA QUE RECEBE UM NÚMERO, E DIGA SE ELE É PAR OU ÍMPAR num = int(input('Informe o número que deseje saber se é par ou ímpar: ')) if num % 2 == 0: print('O número {} é par'.format(num)) else: print('O número {} é ímprar'.format(num))
false
fe5c51d3953c808574151cb872901c2cc00d3850
MichelPinho/exerc-cios
/Desafio_75_AnáliseDados_Tuplas.py
858
4.125
4
# Desenvolva um programa que leia 4 números pelo teclado, e guarde-os em uma tupla, no final disso, mostre : # Quantas vezes apareceu o número 9 ? # Em que posição foi digitado o primeiro número 3 ? # Quais são os números pares ? n = (int(input('Digite um número: ')), int(input('Digite o segundo número: ')), int(input('Digite o terceiro número: ')), int(input('Digite o último número: '))) print(f'Você digitou os valores: {n}') # contando quantas vezes aparece o número 9: print(f'\n O número 9 apareceu {n.count(9)} vezes') # em que posição foi digitado o número 3: if 3 in n: print(f'\n O número 3 foi digitado na {n.index(3)} posição') else: print(' O número 3 não foi digitado') # verificando se algum número digitado é par : for n in n: if n % 2 == 0: print(f'Os valores pares digitados foram: {n}')
false
02cbcf7ee03758c630aa0ffccf4943cd23591960
NathanSouza27/Python
/ING/005 - Predecessor and successor.py
231
4.125
4
#Make a program that reads an integer and shows your successor and predecessor on the screen. n = int(input('Type it a value:')) a = n - 1 s = n + 1 print('The predecessor de {} is {} and successor is {}'.format(n, a, s))
true
0ccadc8754ff399cbb3f4e544e68fd33ed2dbc04
NathanSouza27/Python
/ING/010 - Currency converter.py
294
4.15625
4
#Create a program that reads how much money a person has in their wallet and shows how many dollars they can buy. # Consider 1U$ = R$ 3,27. mon = float(input('How much money do you have in your wallet? U$ ')) con = mon * 3.27 print('With U$ {} you can buy R$ {:.2f}'.format(mon, con))
true
8f7ccc28ea13ded236db2056040a22bf6fa5209f
audy018/tech-cookbook
/python/python-package-example/module_package/techcookbook/caseconvert.py
299
4.34375
4
""" module to convert the strings to either lowercase or uppercase """ def to_lowercase(given_strings): """"convert given strings to lower case""" return given_strings.lower() def to_uppercase(given_strings): """"convert given strings to upper case""" return given_strings.upper()
true
0169985953a5b02442e7169e2068ebf8b1e0ec44
pehuverma/Python-code.py
/function.py
2,232
4.125
4
'''function -> hum is fucntion k through code ko again nd again use kr skte h apne program m function jo h vo code ko divide kr dete h taki code ko easy to understand kr ske programmer function are basically 2 tpyes: 1. User defined : means user apne according function ko built krta h def functionname(): 2. Built in function : ye already defined hote h i: if(),ii: for(), iii: print()''' def function(): print("\nHello function") #in this line of code the program run but it doesn't show the output #because we have to call the function to pront the or show the output function() ''' function can be declare 4 types: a. Function with arguments & with return value b. Function without arguments & without return value c. Function with arguments & without return value d. Function without arguments & with return value ''' #2nd behaviour of function # function with argument end with return value def studentattendence(name, rolllno): #print("student name and its rollno:") return True #means if the value is vaild then it represent the boolena value # after defining the function we need to call the function by its name if(studentattendence('pihu','22')) == True: print("\nYes pihu is present and her rollno is 21 : ") else: print("You got a wrong onformation") # 3rd funtion with argument but without retrun value def singleuser(name): print("Hello",name, "How was your day today:") singleuser("pihu") #4th no argument but retrun value def otheruser(): return False # call function if otheruser()== True: print("Yes other user can use the public authantication") elif otheruser()== False: print("At this moment sever is down") else: print("No one can access the information") # funtion with unexpected number arguments # we the stu as a tuple form def studentcheckfunction(*stu): #print('\nGood morning',stu[0],'',stu[1],'',stu[2],'',stu[3]) #print(type(stu)) if 'pihu' in stu: print("Yes she is in class") studentcheckfunction("pihu",'Himani','kashi','monika') #dictionary used with double star(**) we use in key () def keyfunction(**user): print("hii",user) print(type(user)) keyfunction(user='pihu')
false
aaed8f499f38230ddbfad6373945a2146898cf58
tinali0923/orie5270-ml2549
/hw2/optimize.py
1,121
4.15625
4
import numpy as np from scipy import optimize def Rosenbrock(x): """ This is the function for Rosenbrock with n=3 :param x: a list representing the input vector [x1,x2,x3] :return: a number which is the Rosenbrock value """ return 100 * (x[2] - x[1] ** 2) ** 2 + (1 - x[1]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2 def gradient(x): """ This is the calculate the gradident of Rosenbrock when n=3 :param x: a list representing the input vector [x1,x2,x3] :return: a list representing the gradient vector, which has length of 3 """ return np.array([-400 * x[0] * x[1] + 400 * x[0] ** 3 - 2 * (1 - x[0]), -400 * x[1] * x[2] + 400 * x[1] ** 3 - 2 * (1 - x[1]) + 200 * (x[1] - x[0] ** 2), 200 * (x[2] - x[1] ** 2)]) if __name__ == "__main__": x1 = [222, 4, 1] x2 = [-4, 5, 99] x3 = [66, 91, 20000] x4 = [34, 1, -5] x5 = [2, -5, 2] x = [x1, x2, x3, x4, x5] res = [] for x0 in x: res.append(optimize.minimize(Rosenbrock, x0, method='BFGS', jac=gradient).fun) print(min(res))
true
b8f77afc83bca627d39c2e2373f89a0568e09fd7
PeterMurphy98/comp_sci
/sem_1/programming_1/prac9/p17p1.py
500
4.3125
4
# Define a function to return a list of all the factors of a number x. def divisor(x): """Finds the divisors of a.""" # Initialise the list of divisors with 1 and x divisors = (1,x) # Check if i divides x, from i = 1 up to i = x/2. # If it does, add i to the divisors list. for i in range(2, int(x/2) +1): if x % i == 0: divisors += (i,) # Return the list of divisors. return divisors n = int(input("Enter a positive integer: ")) print(divisor(n))
true
7f267e86ab6e1a5132f8a794bc4e1b8a9501a9dd
PeterMurphy98/comp_sci
/sem_1/programming_1/prac10/p19p1.py
463
4.125
4
def new_base(x, b): """Takes a number, x, in base 10 and converts to base b.""" # Initialise the new number as a string new = '' # While the division result is not equal to 0 while x != 0: # add the remainder to the string remainder = x % b new += str(remainder) x = x // 2 # Reverse the string return new[::-1] n1 = int(input("Enter number: ")) n2 = int(input("Enter base: ")) print(new_base(n1,n2))
true
4c3d05ee24ea643e24813638c1c5592db7776d95
PeterMurphy98/comp_sci
/sem_1/programming_1/test2/exam-q1.py
675
4.375
4
def isPal(text): # Initialise new string new = "" # Add all letters, numbers and spaces from input string to new string for i in range (len(text)): if text[i].isalnum() or text[i] == " ": new += text[i] # Check if new string is the same when reversed if new == new[::-1]: print(text, "is a palindrome.") else: print(text, "is not a palindrome.") # Prompt user for string text = input("Enter a string (empty string to exit): ") # While string is non-empty while text != "": # Check if it is a palindrome isPal(text) text = input("Enter a string (empty string to exit): ") print("Finished!")
true
365a0eef3630dd6ae3e85e1527154ef3b154af26
coder91x/Linked_Lists
/linked_list_swap.py
1,410
4.125
4
class Node(object): def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def swap(self, x, y): if x == y: return prevX = None currX = self.head while currX != None and currX.data != x: prevX = currX currX = currX.next prevY = None currY = self.head while currY != None and currY.data != y: prevY = currY currY = currY.next if currX is None or currY is None: return if prevX is not None: prevX.next = currY else: self.head = currY if prevY is not None: prevY.next = currX else: self.head = currX temp = currX.next currX.next = currY.next currY.next = temp def print_list(self): temp =self.head while temp is not None: print(temp.data) temp = temp.next if __name__ == '__main__': list = LinkedList() list.push(8) list.push(9) list.push(12) list.push(45) list.swap(45,12) list.print_list()
true
be81b120372bcdf5fe1428bbd767d8cc40ae225a
titouanfreville/-3AIT-_Labs_Correction
/TP_NOTE/Python/tri.py
2,440
4.25
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # LIST FUNCTIONS ---------------------------------------------------------------------- # FUNCTION ON LISTS WITHOUT DELETE Lsp Likes # @car # @PARAM list # @RETURN first element def car (l): return l[0] # @cdr # @PARAM list # @RETURN list without head def cdr (l): return l[1:] # @last # @PARAM list # @RETURN value of the last element in list def last (l): return l[-1] # @butlast # @PARAM list # @RETURN list without last element def butlast (l): return l[:-1] # ------------------------------------------------------------------------------------- # Probleme Python ###################################################################################### # Question 2.2 ltest=[2,1,6,5,3,4] ltest1s=[7,3,1] ltest2s=[5,4,2] ltest1i=[1,3,7] ltest2i=[2,4,5] # Split # @param list # @return (l1,l2) tel que l1+L2 = list && 0 < size (l1) - size (l2) < 2 def split (l): if l==[]: return ([],[],) elif cdr (l)==[]: return ([car (l)],[]) else: dl = split (cdr (cdr (l))) return ([car (l)]+dl[0],[car (cdr (l))]+dl[1]) # print split (ltest) sup = lambda a , b: a > b inf = lambda a , b: a < b # Fusion # @param l1, l2 toutes deux triées, f_comp la fonction de comparaison à utiliser # @return l triées comportants les éléments de l1 && l2 def fusion (l1,l2,f_comp): if (l1 == []): return l2 elif (l2 == []): return l1 elif f_comp (car (l1), car (l2)): return ([car (l1)]+fusion (cdr (l1),l2,f_comp)) else: return ([car (l2)]+fusion (l1,cdr (l2),f_comp)) # print fusion (ltest1s,ltest2s,sup) # print fusion (ltest1i,ltest2i,inf) # Tri # @param l, f_comp # @return l triée selon f_comp def tri (l,f_comp): if (l == []): return l elif (cdr (l) == []): return l else: dl = split (l) return fusion (tri (dl[0],f_comp), tri (dl[1],f_comp), f_comp) # print tri (ltest,sup) # print tri (ltest,inf) # tri_croiss # @param List # @return Liste trié dans l'ordre croissant def tri_croiss(l): return tri(l,inf) # tri_decroiss # @param List # @return Liste trié dans l'ordre décroissant def tri_decroiss(l): return tri(l,sup) def main(): lmonaie=[1,2,3,4,5,6,7,8,9,10,20,50] print "Liste trier en ordre croissant" l1= tri(lmonaie, inf) print l1 print "Liste trier en ordre décroissant" l2= tri(lmonaie, sup) print l2 print "Liste renvoyer comme tuple (lCroissant, lDécroissant,)" return (l1,l2,)
false
a0f0acdef772a13a5c7c3666b9e3c0755a1de519
kevna/python-exercises
/src/sorting/stupid_sort.py
956
4.28125
4
from sorting.sorter import Sorter, SortList class StupidSort(Sorter): # pylint: disable=too-few-public-methods """Implementation of stupid sort, also known as gnome sort. If the current pair are out of order swap them and move back one otherwise step forward. """ def sort(self, items: SortList, cutoff: int = None): items = items[:] tel = 0 i = 0 while i < len(items) - 1: if items[i + 1] < items[i]: if tel == 0: tel = i items[i + 1], items[i] = items[i], items[i + 1] if i > 0: i -= 1 elif tel > 0: # Once we've shuffled an item back into place this jumps forward # to where we found the out-of order pair (we already checked in between) i = tel - 1 tel = 0 else: i += 1 return items
true
178c20e7b4a535c3ab70fe6b851dfd90587938cc
KelvienLee/Python-learnning
/chapter_5/creat_str.py
2,124
4.53125
5
# 单引号创建字符串 # name = 'hello' # hobby = "creating" # # zen = ''' # 给注释赋值,适合长文字的输出。 # 这是很长的一段注释 # this is a long paragraph. # 这里面的格式 会被保留。 # ''' # print(name, hobby) # print(zen) # 转义字符的使用 # 这是一种错误的 is 使用方法,单引号会被识别为字符串标识符 # print('kelvien's hobby is creating things.') # 正确的 is 使用方法是使用转义符号 \ 反斜杠 ,另外, 注意反斜杠放在前面的。解释器总是从上到下按先后顺序读取数据。 # print('kelvien\'s hobby is creating things.') # 但是,转义符号不利于代码的阅读 # 所以,正确的使用方法应该是单引号和双引号互相 ’包裹‘ # print("kelvien's hobby is creating things.") # print('so, what is "creating things"?') # 索引和步长的使用 # motto = 'so, what is "creating things"?' # love_sentence = '积善之家,必有余庆。' # print(motto[5]) # 通过索引取得某一个具体的值 # print(love_sentence[5:9]) # 切片同range()函数一样不包含右值 # print(love_sentence[-5:-1]) # print(love_sentence[5:]) # print(love_sentence[-5:]) # print(love_sentence[1:10:2]) # 可设置步长 # 索引越界会报错 # print(love_sentence[11]) # IndexError: string index out of range # 切片越界会自动处理 # print('1', love_sentence[0:11]) # print('2', love_sentence[0:110]) # print('3', love_sentence[11:110]) # 返回空字符串 # print('4', love_sentence[-110:10]) # print('5', love_sentence[5:2]) # 返回空字符串 # print('6', love_sentence[-1:-10]) # 返回空字符串 # print('7', love_sentence) # mutable 可变的 # immutable 不可变的 # 字符串是不可变类型 word = 'python' print(word[0]) # word[0] = 'j' # print(word) # TypeError: 'str' object does not support item assignment # 正确的改变字符串的方法是生成新的字符串变量 new_we_need = 'j' + word[1:] print(new_we_need)
false