blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b073e30fb0c7b43e61845de6a0cb50ea6fe1d4f0
Benature/Computational-Physics-Course-Code
/chp9/随机数/布朗运动1d.py
1,082
4.25
4
# 参考答案 # random walk,随机行走 import matplotlib.pyplot as plt import random as rd # %matplotlib inline nsteps = 100 # input('number of steps in walk -> ') nwalks = 100 # input('number of random walks -> ') 粒子数 seed = 10 # input('random number seed -> ') rd.seed(seed) steps = range(nsteps) xrms = [0.0] * nsteps # mean squared distance # loop over the number of walks being done for i in range(nwalks): x = [0] * nsteps # position at each step in walk # loop over steps in this walk for n in steps[1:]: if rd.random() < 0.5: x[n] = x[n-1] - 1 else: x[n] = x[n-1] + 1 xrms[n] += (x[n]**2 - xrms[n]) / (i+1) plt.plot(steps, x, 'o-') for n in steps: xrms[n] = xrms[n]**0.5 plt.title('random walk') plt.xlabel('step number') plt.ylabel('x') plt.grid() plt.figure() plt.title('root-mean-squared distance for %d walks' % nwalks) plt.plot(steps, xrms, '.') plt.plot(steps, [n**0.5 for n in steps], '-') plt.xlabel('step number') plt.ylabel('root-mean-squared distance') plt.grid() plt.show()
true
0bb48e09dcbde0d8d604075bf650e9f2c42e9570
jezzicrux/Python-Alumni-Course
/Excercises/inclass9_16.py
508
4.28125
4
#Making a function the adds three number and divdes by 3. (Pretty much average) #This the function to get the average of the three numbers avg = 0 def average(x,y,z): avg=(x+y+z)/3 print(f"The average the three numbers is {avg}.") def getting_numbs(): print ("Please enter your first number") x = int(input(">>")) print ("Please enter your second number") y = int(input(">>")) print ("Please enter your third number") z = int(input(">>")) average(x,y,z) getting_numbs()
true
ef1b85d6df36bc6b251b94edd51c27c019bc63ec
jezzicrux/Python-Alumni-Course
/Excercises/triangle.py
992
4.25
4
def main(): print(f"Welcome to the triangle finder program") print(f"Please enter 3 values for each side.") print(f"Enter in value for side 1") side1 = int(input(">> ")) print(f"Enter in value for side 2") side2 = int(input(">> ")) print(f"Enter in value for side 3") side3 = int(input(">> ")) triangle_check(side1,side2,side3) def triangle_check(a,b,c): if (a+b > c) and (a+c > b) and (b+c > a) and (((a**2) + (b**2)) == (c**2)): print(f"All your sides can make a triangle! ALRIGHT!!!! Get it?") elif (a+b > c) and (a+c > b) and (b+c > a) and (((a**2) + (b**2)) > (c**2)): print(f"Look at your triangle. It's a cutie") elif (a+b > c) and (a+c > b) and (b+c > a) and (((a**2) + (b**2)) < (c**2)): print(f"Your triangle is so obtuse") elif (a+b == c) or (a+c == b) or (c+b == a): print("YOUR TRIANGLE IS OUT OF CONTROL. IT'S A REAL DEGENERATE!!") else: print("You aint got nutin' son!") main()
true
17a546db017b9abc0b1853b1df5137167e6fb795
jezzicrux/Python-Alumni-Course
/Excercises/HW1.py
837
4.34375
4
#a message stating it going to count the number on chickens print("I will now count my chickens:") #number of hens print("Hens", 25 + 30 / 6) #number of roosters print("Roosters", 100 - 25 * 3 % 4) #a message counting the number of eggs print("Now I will count the eggs:") #The math for calculating the number of eggs print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) #A message print("Is it true that 3 + 2 < 5 - 7?") #the answer print(3 + 2 < 5 - 7) #A question and then the answer. Answer is found with a math equation print("What is 3 + 2?", 3 + 2) #A question and then the answer. Answer is found with a math equation print("What is 5 - 7?", 5 - 7) #a message print("Oh, that's why it's False.") # print("How about some more.") print("Is it greater?", 5 > -2) print("Is it greater or equal?", 5 >= -2) print("Is it less or equal?", 5 <= -2)
true
fb8125f73e2825f92d99ac10951cf857e8be7239
jaredmckay17/DataStructuresAlgorithmsPractice
/binary_search.py
1,120
4.125
4
# Non-recrusive implementation def binary_search(input_array, value): first = 0 last = len(input_array) - 1 while first <= last: midpoint = (first + last) // 2 if input_array[midpoint] == value: return midpoint else: if value < input_array[midpoint]: last = midpoint - 1 else: first = midpoint + 1 return -1 test_list = [1,3,9,11,15,19,29] test_val1 = 19 test_val2 = 2 print binary_search(test_list, test_val1) # 5 print binary_search(test_list, test_val2) # -1 # Recursive implementation def binary_search(input_array, value): if len(input_array) == 0: return False else: midpoint = len(input_array) // 2 if input_array[midpoint] == value: return midpoint else: if value < input_array[midpoint]: return binary_search(input_array[:midpoint], value) else: return binary_search(input_array[midpoint + 1:], value) testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42] print(binary_search(testlist, 3)) print(binary_search(testlist, 13))
true
622fcca8ab5f8c6c280f6ec1c75df9ff52f81e07
sumforest/first_python
/test_repr_str_format.py
563
4.15625
4
# 输入一个立方表 for x in range(1,11): print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ') print(repr(x*x*x).rjust(4)) for x in range(1,11): print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x)) # 在:后面跟数字可以保证宽度 table = {'Google':1,'Runoob':2,'Alibaba':3} for k,v in table.items(): print('{0:10}===>{1:10}'.format(k,v)) print('-'*10) print('Google: {0[Google]:d}; Runoob: {0[Runoob]:d}; Alibaba:{0[Alibaba]:d}'.format(table)) print('-'*10) print('Google:{Google:d};Runoob:{Runoob};Alibaba:{Alibaba}'.format(**table))
false
f3f08d4b739c4993a6597060d8e8b66340b4d514
sumforest/first_python
/列表-列表推导式.py
587
4.15625
4
# 将列表中每个数值乘三,获得一个新的列表: vec = [3,6,9] print([x*3 for x in vec]) # 得到一个嵌套列表 print([[x,x*2] for x in vec]) # 对序列里每一个元素逐个调用某方法: freshfruit = [' banana', ' loganberry ', 'passion fruit '] print([fruit.strip() for fruit in freshfruit]) # 使用if做过滤条件 print([x for x in vec if x > 3]) # 循环和其它技巧的演示: vec1 = [1,2,3] vec2 = [2,-3,4] print([x*y for x in vec1 for y in vec2]) # 使用复杂表达式或嵌套函数: print([str(round(355/113,i)) for i in range(1,6)])
false
f791702e716e22da1327780cbc9e272648b5c2b8
justinmyersdata/ProjectEuler
/7_Project_Euler.py
607
4.25
4
def isprime(x): '''Returns True if x is prime and false if x is composite''' if x == 1: return False elif x == 2: return True elif x % 2 == 0: return False else: for y in range(3,int(x**(1/2))+1,2): if x % y == 0: return False return True def prime(n): '''Returns the nth prime number''' count = 0 num = 1 while count < n: num +=1 if isprime(num): count+=1 return(num) prime(10001)
true
ab65d41474186820587e216e5c91617621b599c2
amitshipra/PyExercism
/recursion/examples.py
743
4.28125
4
__author__ = 'agupt15' # Source: http://www.python-course.eu/python3_recursive_functions.php # # # # # ## Example 1 # # Write a recursive Python function that returns the sum of the first n integers. ### def rec_add(num): if num == 1: return 1 return num + rec_add(num - 1) print(rec_add(10)) ### Exmple 1.1: Add numbers in a list using recursion. def add_list(lst, total = 0): return None ### Example 2 # # Write a function which implements the Pascal's triangle: # # 1 # 1 1 # 1 2 1 # 1 3 3 1 # 1 4 6 4 1 # 1 5 10 10 5 1 def pascal_triangle(row_count): return None
true
4350d764af0961abc44c2adb1c54d4d8173dd403
srikanthpragada/pythondemo_21_june_2019
/oop/gen_demo.py
269
4.125
4
# Generator to yield even number from start to end def even_numbers(start, end): if start % 2 != 0: start = start + 1 for n in range(start, end + 1, 2): yield n print(type(even_numbers(10, 20))) for n in even_numbers(11, 21): print(n)
false
5bea9d32a0f174543c3d734002f8e856d6ac6279
gurkiratsandhu/Assignment_Daily
/assignment7 (1).py
1,521
4.15625
4
#(Q.1)- Create a function to calculate the area of a circle by taking radius from user. def area(): pi = 3.14 radius = float(input("enter radius: ")) area = pi*radius**2 print("Area of a circle = ",area) area() #(Q.2)- Write a function “perfect()” that determines if parameter number is a perfect number. #Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. #[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), #sum to the number. E.g., 6 is a perfect number because 6=1+2+3]. def perfect(n): sum=0 for x in range(1,n): if n % x == 0: sum = sum + x if sum == n: print("perfect Number:",n) for i in range(1,1001): #(Q.3)- Print multiplication table of 12 using recursion. def table(): number=int(input("enetr value")) for i in range(1,11): result=number*i print("%d * %d = %d"%(number,i,result)) table() #(Q.4)- Write a function to calculate power of a number raised to other ( a^b ) using recursion. def power(): i = int(input("enter any no.: ")) n = int(input("enter power of : ")) result = i**n print("power of %d: %d"%(i,result)) power() #(Q.5)- Write a function to find factorial of a number but also store the factorials calculated in a dictionary. def factorial(number): if number==1 or number==0: return 1 else: f = number*factorial(number-1) return f call = int(input("enter any no.")) fact=factorial(call) print("factorial of %d: %d"%(call,fact))
true
8263b10b5c958eb40ebc8c67a4aafecf5b18a6f8
rhysJD/CC1404_Practicals
/Prac 2/exceptions_demo.py
785
4.21875
4
""" CP1404 - Practical 2 Rhys Donaldson """ try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) while denominator == 0: denominator = int(input("Denominator cannot be zero. PLease enter a new number: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.") #Q1: ValueError occurs when the input is not an integer. Putting in symbols, letter, or decimals will get this number #Q2: This occurs when the denominator is zero and the program attempts to divide by it. Fixed by checking that it doesnt contain a zero, and asking for a new input if it does.
true
685f5b4ead65493c2689d479df91bbc9af93aa0c
kiwi-33/Programming_1_practicals
/p12-13/p12p3(+pseudo).py
639
4.28125
4
'''define function for getting approx square root prompt for input and convert to float check if greater than 0 call function with (input, self selected tolerance) else print message''' def sq(number, epsilon): root = 0.0 step = epsilon**2 while abs(number-root**2) >= epsilon and root <= number: root += step if abs(number-root**2) < epsilon: print('Approx. square root of ', number, 'is', root) else: print('Failed to find the square root of ',number) number = float(input('Enter a floating point number: ')) if number >= 0: sq(number, .01) else: ('An appropriate error message')
true
ddb2f13ed4d056934a51cdc65a58aa3c7eabe411
kiwi-33/Programming_1_practicals
/p14-15/p15p3.py
568
4.1875
4
'''define the function prompt for input enter while loop: enter for loop, limit = input: print statement that shows progression towards the base case and calls function prompt for input''' def series(x): if x == 0: return 13 elif x == 1: return 8 else: return((series(x-2)) + ((13)*(series(x-1)))) number = int(input("Enter a number: ")) while number >= 0: for i in range(0, number): print("Term number", i, "in series of length", number, "is:", series(i)) number = int(input("Enter a number: "))
true
68390cc2272a00e24b578960ba52c76c1a3265e4
Kadus90/CS50
/pset6/mario/less/mario.py
899
4.21875
4
from cs50 import get_int def main(): # Get an integer between 1 - 8 height = get_positive_int("Height: ") # Print bricks print_bricks(height) def get_positive_int(prompt): # Use get_int to get an integer from the user n = get_int(prompt) # While not in the proper range while n < 1 or n > 8: n = get_int(prompt) return n def print_bricks(height): # Initialize spaces to height spaces = height for i in range(height): # Set spaces to the current row spaces -= 1 for j in range(spaces): # Print the spaces while omitting the new line print(" ", end="") # Set the bricks bricks = height - spaces for k in range(bricks): # Print the bricks print("#", end="") # Create a new line print("") if __name__ == "__main__": main()
true
ccb9824ec5d7ffeeb123b86914383d174eb63e03
alcoccoque/Homeworks
/hw5/ylwrbxsn-python_online_task_5_exercise_2/task_5_ex_2.py
692
4.5625
5
""" Task05_2 Create function arithm_progression_product, which outputs the product of multiplying elements of arithmetic progression sequence. The function requires 3 parameters: 1. initial element of progression - a1 2. progression step - t 3. number of elements in arithmetic progression sequence - n Example, For a1 = 5, t = 3, n = 4 multiplication equals to 5*8*11*14 = 6160 Note: The output of your program should contain only the multiplication product Usage of loops is obligatory """ from math import prod def arithm_progression_product(a1, t, n): res = [] tmp = a1 for i in range(n): res.append(tmp) tmp += t return prod(res)
true
a0716844aecf22b76731ae339ea52037ba170bb9
alcoccoque/Homeworks
/hw10/ylwrbxsn-python_online_task_10_exercise_3/task_10_ex_3.py
2,102
4.375
4
""" File `data/students.csv` stores information about students in CSV format. This file contains the student’s names, age and average mark. 1. Implement a function get_top_performers which receives file path and returns names of top performer students. Example: def get_top_performers(file_path, number_of_top_students=5): pass print(get_top_performers("students.csv")) Result: ['Teresa Jones', 'Richard Snider', 'Jessica Dubose', 'Heather Garcia', 'Joseph Head'] 2. Implement a function write_students_age_desc which receives the file path with students info and writes CSV student information to the new file in descending order of age. Example: def write_students_age_desc(file_path, output_file): pass Content of the resulting file: student name,age,average mark Verdell Crawford,30,8.86 Brenda Silva,30,7.53 ... Lindsey Cummings,18,6.88 Raymond Soileau,18,7.27 """ import csv from operator import itemgetter def get_top_performers(file_path: str, number_of_top_students: int = 5) -> list: with open(file_path, newline='') as file: csv_data = list(csv.reader(file, quoting = csv.QUOTE_ALL)) csv_data = csv_data[1:] csv_data = [[i[0], int(i[1]), float(i[2])] for i in csv_data] csv_data = sorted(csv_data, key=itemgetter(2), reverse=True) return [x[0] for x in csv_data[:number_of_top_students] if x] def write_students_age_desc(file_path: str, output_file: str) -> None: with open(file_path, newline='') as file: csv_data = list(csv.reader(file, quoting=csv.QUOTE_ALL)) info = csv_data[0] csv_data = csv_data[1:] csv_data = [[i[0], int(i[1]), float(i[2])] for i in csv_data] csv_data = sorted(csv_data, key=itemgetter(1), reverse=True) with open(f'{output_file}', 'w', newline='') as wfile: writer = csv.writer(wfile, delimiter=',') writer.writerow(info) for row in csv_data: if row: writer.writerow(row) else: continue # print(get_top_performers('students.csv', 3)) # write_students_age_desc('students.csv', 'out.csv')
true
28c998e30f41f350345d22934294b93fda8f3dc2
alcoccoque/Homeworks
/hw9/ylwrbxsn-python_online_task_9_exercise_4/task_9_ex_4.py
2,094
4.28125
4
""" Implement a bunch of functions which receive a changeable number of strings and return next parameters: 1) characters that appear in all strings 2) characters that appear in at least one string 3) characters that appear at least in two strings Note: raise ValueError if there are less than two strings 4) characters of alphabet, that were not used in any string Note: use `string.ascii_lowercase` for list of alphabet letters Note: raise TypeError in case of wrong data type Examples, ```python test_strings = ["hello", "world", "python", ] print(chars_in_all(*test_strings)) >>> {'o'} print(chars_in_one(*test_strings)) >>> {'d', 'e', 'h', 'l', 'n', 'o', 'p', 'r', 't', 'w', 'y'} print(chars_in_two(*test_strings)) >>> {'h', 'l', 'o'} print(not_used_chars(*test_strings)) >>> {'q', 'k', 'g', 'f', 'j', 'u', 'a', 'c', 'x', 'm', 'v', 's', 'b', 'z', 'i'} """ import string def chars_in_all(*strings): if len(strings) >= 2: chars_inall = set() uniquechars = set(''.join(strings)) for i in uniquechars: if all(i if i in x else False for x in strings): chars_inall.add(i) return chars_inall raise ValueError def chars_in_one(*strings): return set(''.join(strings)) def chars_in_two(*strings): if len(strings) >= 2: chars_inall = set() uniquechars = set(''.join(strings)) for i in uniquechars: if len([i for x in strings if i in x]) >= 2: chars_inall.add(i) return chars_inall raise ValueError def not_used_chars(*strings): strings = set(''.join([x.lower() for x in strings if x.isalpha()])) list_of_str = set() for i in string.ascii_lowercase: if i not in strings: list_of_str.add(i) else: continue return list_of_str # # print(chars_in_all('asd', 'asas','asd')) # print(chars_in_one('asd', 'asdasdd','asdddd')) # print(chars_in_two('asd', 'asas','bbbbbb')) # print(not_used_chars('asd', 'asas','bbbbbb')) # print()
true
d5b3eb35448994bbe027230cf715f633e3bbef90
alcoccoque/Homeworks
/hw4/ylwrbxsn-python_online_task_4_exercise_8/task_4_ex_8.py
638
4.1875
4
""" Task 04-Task 1.8 Implement a function which takes a list of elements and returns a list of tuples containing pairs of this elements. Pairs should be formed as in the example. If there is only one element in the list return `None` instead. Using zip() is prohibited. Examples: >>> get_pairs([1, 2, 3, 8, 9]) [(1, 2), (2, 3), (3, 8), (8, 9)] >>> get_pairs(['need', 'to', 'sleep', 'more']) [('need', 'to'), ('to', 'sleep'), ('sleep', 'more')] >>> get_pairs([1]) None """ def get_pairs(lst: list) -> list: if len(lst) > 1: return [(lst[i], lst[i + 1]) for i in range(len(lst) - 1)] return None
true
0039bfc1dae3f74a8116973fade7541d37435561
mandypepe/py_data
/spark_querin_dataset.py
1,071
4.1875
4
# First we need to import the following Row class from pyspark.sql import SQLContext, Row # Create a RDD peopleAge, # when this is done the RDD will # be partitioned into three partitions peopleAge = sc.textFile("examples/src/main/resources/people.txt") # Since name and age are separated by a comma let's split them parts = peopleAge.map(lambda l: l.split(",")) # Every line in the file will represent a row # with 2 columns name and age. # After this line will have a table called people people = parts.map(lambda p: Row(name=p[0], age=int(p[1]))) # Using the RDD create a DataFrame schemaPeople = sqlContext.createDataFrame(people) # In order to do sql query on a dataframe, # you need to register it as a table schemaPeople.registerTempTable("people") # Finally we are ready to use the DataFrame. # Let's query the adults that are aged between 21 and 50 adults = sqlContext.sql("SELECT name FROM people \ WHERE age >= 21 AND age <= 50") # loop through names and ages adults = adults.map(lambda p: "Name: " + p.name) for Adult in adults.collect(): print Adult
true
2a51577b5291d2667e285d799a1cb47d0dec5c88
lunawarrior/python_book
/Exercises/6/1_turn_clockwise.py
721
4.28125
4
''' This is the first exercise in chapter 6: The four compass points can be abbreviated by single-letter strings as “N”, “E”, “S”, and “W”. Write a function turn_clockwise that takes one of these four compass points as its parameter, and returns the next compass point in the clockwise direction. Here are some tests that should pass: ''' from test import test # Define your turn_clockiwse function here # Here are the tests test(turn_clockwise("N") == "E") test(turn_clockwise("W") == "N") test(turn_clockwise("E") == "S") ''' When you have those working, other values should return None. Uncomment the below tests ''' # test(turn_clockwise(42) == None) # test(turn_clockwise("rubbish") == None)
true
9f682db0dcc89ab6381271f077388845f204f8ed
Kvazar78/Skillbox
/8_algoritm_for/task_83_3.py
1,004
4.1875
4
# Саша просыпается когда угодно, но в 23 часа уже точно идёт спать. # Питается Саша следующим образом: каждые 3 часа он выпивает литр воды и # съедает N калорий. Пить и есть он, кстати, начинает сразу как только # проснётся. Напишите программу, которая считает сколько он выпьет литров # воды и сколько калорий он съест перед тем как пойдёт спать. wake_up = int(input('Во сколько проснулся Саша? ')) wather = 0 totalCalories = 0 for hour in range(wake_up, 23, 3): wather += 1 calories = int(input('Сколько калорий употребил? ')) totalCalories += calories print(f'Саша выпил {wather} литров воды') print(f'Саша скушал {totalCalories} калорий')
false
b391144829bc43326c3a7be3eef5c7b6ad9e4166
Kvazar78/Skillbox
/float2/dz/task_9.py
1,087
4.4375
4
# Степень числа # # Дано вещественное положительное число a и целоe число n. # # Вычислите a в степени n, не используя циклы, возведение в степень через ** и функцию math.pow() # (да, такая тоже есть). Решение оформите в виде функции power(a, n). def power(a, n): if n < (-1): a *= a n +=1 power(a, n) elif n > 1: a *= a n -= 1 power(a, n) else: print('\nРезультат возведения "а" в степень:', end=' ') if n < 0: print(1 / a) else: print(a) a = float(input('Введите вещественное положительное число "a": ')) n = int(input('Введите степень: ')) if a > 0 and n != 0: power(a, n) else: print('По условию "а" должно быть положительным! И cтепень не должна быть равна 0!')
false
d77058dc12856ad93390c6485de970a21e76160c
Kvazar78/Skillbox
/15_list1/task_153_2.py
1,497
4.1875
4
# Соседи # # Дана строка S и номер позиции символа в строке. Напишите программу, которая выводит соседей этого символа и сообщение # о количестве таких же символов среди этих соседей: их нет, есть ровно один или есть два таких же. # # Пример 1: # # Введите строку: abbc # Номер символа: 3 # # Символ слева: b # Символ справа: c # # Есть ровно один такой же символ. # # Пример 2: # # Введите строку: abсd # Номер символа: 3 # # Символ слева: b # Символ справа: d # # Таких же символов нет. string = input('Введите строку: ') num_symbol = int(input('Номер символа: ')) find_nei = '' string_list = list(string) print(f'\nСимвол слева: {string_list[num_symbol - 2]}') print(f'Символ справа: {string_list[num_symbol]}') for sym in range(num_symbol - 2, num_symbol + 1): find_nei += string_list[sym] if find_nei.count(string_list[num_symbol - 1]) == 3: print('\nЕсть еще два таких же символа.') elif find_nei.count(string_list[num_symbol - 1]) == 2: print('\nЕсть ровно один такой же символ.') else: print('\nТаких же символов нет.')
false
bc799c08a481763510aaa17ef54168892738ff1c
Kvazar78/Skillbox
/18_format_f-strings/task_182_1.py
963
4.21875
4
# Заказ # # После того, как человек сделал заказ в интернет-магазине, ему на почту приходит оповещение # с его именем и номером заказа. # # Напишите программу, которая получает на вход имя и код заказа, а затем выводит на экран # соответствующее сообщение. Для решения используйте строковый метод format. # # Пример: # # Имя: Иван # Номер заказа: 10948 # # Здравствуйте, Иван! Ваш номер заказа: 10948. Приятного дня! name = input('Имя: ') order_number = int(input('Номер заказа: ')) string = 'Здравствуйте, {name}! Ваш номер заказа: {order}. Приятного дня!'.format(name=name, order=order_number) print(string)
false
8972ce6fcf663435611ff17ecf65bbd40c79a6c3
Kvazar78/Skillbox
/24_classes/dz/task_3.py
2,501
4.125
4
# Окружность # # На координатной плоскости рисуются окружности, у каждой окружности следующие параметры: координаты X и Y центра окружности и значение R ― это радиус окружности. По умолчанию центр находится в (0, 0), а радиус равен 1. # # Реализуйте класс «Окружность», который инициализируется по этим параметрам. Круг также может: # # Находить и возвращать свою площадь. # Находить и возвращать свой периметр. # Увеличиваться в K раз. # Определять, пересекается ли он с другой окружностью. from math import pi, sqrt class Circle: def __init__(self, x=0, y=0, r=1): self.x = x self.y = y self.r = r def _area(self): return pi * self.r ** 2 def area_info(self): return f'Площадь круга равна: {round(self._area(), 2)}' def _perimeter(self): return 2 * pi * self.r def perimeter_info(self): return f'Периметр круга равен: {round(self._perimeter(), 2)}' def increase(self, k=1): area_k = self._area() * k r_k = sqrt(self._area() * 2 / pi) print(f'Площадь круга была {round(self._area(), 2)}, увеличившись в {k} раз станет - {round(area_k, 2)}\n \ Внимание: изменился радиус {round(r_k, 2)}') self.r = r_k def crossing(self): croos_flag = False d = sqrt(abs(cir1.x - cir2.x) ** 2 + abs(cir1.y - cir2.y) ** 2) if d <= cir1.r + cir2.r: croos_flag = True return croos_flag circle_list = [] for i in range(1, 3): x = int(input(f'Введите Х координату {i} окружности: ')) y = int(input(f'Введите Y координату {i} окружности: ')) r = int(input(f'Введите радиус {i} окружности: ')) circle_list.append(Circle(x, y, r)) cir1, cir2 = circle_list print(cir1.perimeter_info()) print(cir2.area_info()) if cir1.crossing(): print('Окружности пересекаются') else: print('Окружности не пересекаются')
false
5cd6b42215512fd27cc989d662e58057a02ee112
Kvazar78/Skillbox
/float2/dz/task_2.py
1,419
4.125
4
# Генеалогическое древо # # Сэм создаёт генеалогические деревья разных семей. Ему постоянно приходится рассчитывать количество # места, занимаемое именами родителей на экране. # # Пользователь вводит имена и фамилии двух родителей. Создайте функцию get_parent_names_total_length # для Сэма, которая возвращает количество символов в именах матери и отца суммарно, пробелы между # именем и фамилией тоже учитываем. # # Пример: # # ФИ отца: Иван Петров # ФИ матери: Алена Петрова # # Символов в ФИ отца: 11 # Символов в ФИ матери: 13 # # Сумма символов: 24 def count_symbol(name): count = 0 for i in name: count += 1 return count father_name = input('ФИ отца: ') mother_name = input('ФИ матери: ') countSym_fatherName = count_symbol(father_name) countSym_motherName = count_symbol(mother_name) print(f'\nСимволов в ФИ отца: {countSym_fatherName}') print(f'Символов в ФИ матери: {countSym_motherName}') print(f'\nСумма символов: {countSym_fatherName + countSym_motherName}')
false
daf822d911b62894b775b26a322be393f83163f8
Kvazar78/Skillbox
/9_for_strings/task_93_2.py
870
4.4375
4
# Ваня экспериментирует с различного рода компьютерными вирусами, # которые портят жизнь людям. На просторах Интернета он нашёл код довольно # необычного вируса, который “поворачивает” весь текст в документе и # повторяет каждый символ 3 раза. # # Пользователь вводит текст. Напишите программу, которая выводит каждый # символ текста в отдельной строке и три раза. # # Пример: # # Введите текст: Привет! # ППП # ррр # иии # ввв # еее # ттт # !!! word = input('Введите текст: ') for symbol in word: print(symbol * 3)
false
2ade3194e71fa9dc2ae37377c7aba4f69c98e050
Kvazar78/Skillbox
/6.3_while_break/dz/task_1.py
720
4.21875
4
# Любителю математики Паше снова стало мало распечатанных табличек, # включая последнюю со степенями двойки. Теперь он хочет взять третью # степень чисел от 1 до абсолютно любого! # Напишите программу, которая возводит в третью степень каждое число # от 1 до N и выводит результат на экран. num = int(input('По какое число считать? ')) num_start = 1 while num_start <= num: print(f'{num_start} в третьей степени - {num_start ** 3}') num_start += 1
false
8ca442198d42b54b5aa4ee8538f72201d50fc491
anasazi/Swarm-AI---Zombies
/vector.py
2,572
4.25
4
#Alice Forehand #Robert Pienta #Eric Reed from math import acos, sqrt, pi, atan2 class Vector: """A simple 2d vector >>> v1 = Vector(1,0) >>> v2 = Vector(0,1) >>> print(v1.add(v2)) (1, 1) >>> print(v1 + v2) (1, 1) >>> print(v1.subtract(v2)) (1, -1) >>> print(v1 - v2) (1, -1) >>> print(v1 / 2) (0.5, 0.0) >>> print(v1 * 3) (3, 0) >>> v1.magnitude() 1.0 >>> v2.magnitude() 1.0 >>> v1.dotProduct(v2) 0 >>> v2.dotProduct(v1) 0 >>> v1.dotProduct(v1) 1 >>> v2.dotProduct(v2) 1 >>> print(v1) (1, 0) >>> v1.angleBetween(v2)*180/pi 90.0 >>> print(v1.projection(v2)) (0.0, 0.0) >>> print(v1.truncate(.5)) (0.5, 0.0) >>> v3 = Vector(1,1) >>> print(v3.truncate(1)) (0.707106781187, 0.707106781187) """ def __init__(self, xi, yi): self.x = xi self.y = yi def __str__(self): return "({0}, {1})".format(self.x, self.y) def add(self, v1): return Vector(self.x+v1.x, self.y+v1.y) def __add__(self, v1): return Vector(self.x+v1.x, self.y+v1.y) def subtract(self, v1): return Vector(self.x-v1.x, self.y-v1.y) def __sub__(self, v1): return Vector(self.x-v1.x, self.y-v1.y) def __truediv__(self, scalar): return Vector(self.x/scalar, self.y/scalar) def __mul__(self, scalar): return Vector(self.x*scalar, self.y*scalar) def scalarMult(self, scalar): return Vector(self.x*scalar, self.y*scalar) def magnitude(self): return sqrt(self.x*self.x + self.y*self.y) def magnitudeSansRoot(self): return self.x*self.x + self.y*self.y def dotProduct(self, v1): return self.x*v1.x + self.y*v1.y def angleBetween(self, v1): t = self.magnitude()*v1.magnitude() if(not t == 0): return acos(self.dotProduct(v1)/(self.magnitude()*v1.magnitude())) return 0 def angleBetweenAtan(self, v1): return atan2(self.y, self.x) - atan2(v1.y, v1.x) def projection(self, v1): return v1.scalarMult(self.dotProduct(v1)/v1.magnitudeSansRoot()) def truncate(self, scalar): mag = self.magnitude() if(mag > scalar): return Vector(self.x/mag*scalar, self.y/mag*scalar) return Vector(self.x, self.y) def vec2tuple(self): return (self.x, self.y) def normal(self): return Vector(-1 * self.y, self.x) if __name__ == "__main__": import doctest doctest.testmod()
false
b735e871863e7f2fe735293b21f01ea0158bb9d5
quydau35/quydau35.github.io
/ds/chunk_6/python_modules.py
2,618
4.53125
5
""" # Python Modules\n What is a Module?\n Consider a module to be the same as a code library.\n A file containing a set of functions you want to include in your application.\n # Create a Module\n To create a module just save the code you want in a file with the file extension ```.py```:\n ``` # Save this code in a file named mymodule.py def greeting(name): print("Hello, " + name) ``` # Use a Module\n Now we can use the module we just created, by using the ```import``` statement:\n ``` # Import the module named mymodule, and call the greeting function: import mymodule mymodule.greeting("Jonathan") ``` Note: When using a function from a module, use the syntax: ```module_name.function_name```.\n # Variables in Module\n The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):\n ``` # Save this code in the file mymodule.py person1 = { "name": "John", "age": 36, "country": "Norway" } ``` ``` # Import the module named mymodule, and access the person1 dictionary: import mymodule a = mymodule.person1["age"] print(a) ``` # Naming a Module\n You can name the module file whatever you like, but it must have the file extension ```.py```\n # Re-naming a Module\n You can create an ```alias``` when you import a module, by using the ```as``` keyword:\n ``` # Create an alias for mymodule called mx: import mymodule as mx a = mx.person1["age"] print(a) ``` # Built-in Modules\n There are several built-in modules in Python, which you can import whenever you like.\n ``` # Import and use the platform module: import platform x = platform.system() print(x) ``` # Using the ```dir()``` Function\n There is a built-in function to list all the function names (or variable names) in a module. The ```dir()``` function:\n ``` # List all the defined names belonging to the platform module: import platform x = dir(platform) print(x) ``` Note: The ```dir()``` function can be used on all modules, also the ones you create yourself.\n # Import From Module\n You can choose to import only parts from a module, by using the from keyword.\n ``` # The module named mymodule has one function and one dictionary: def greeting(name): print("Hello, " + name) person1 = { "name": "John", "age": 36, "country": "Norway" } ``` ``` # Import only the person1 dictionary from the module: from mymodule import person1 print (person1["age"]) ``` Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: ```person1["age"]```, not ```mymodule.person1["age"]```\n """
true
fa096dffbef3c9578b693c3b2c07014a53b94ec6
sandycamilo/SPD1.4
/Complexity_Analysis/merge_lists.py
1,027
4.125
4
# Merge two sorted linked lists and return it as a new list. # The new list should be made by splicing together the nodes of the first two lists. # Input: 1->2->4, 1->3->4 #Create a new linked list: # Output: 1->1->2->3->4->4 # O(1) class Solution(object): def mergeTwoLists(self, l1, l2): head = ListNode(0) ptr = head #reference to the head while True: if l1 is None and l2 is None: break #nothing to merge elif l1 is None: ptr.next = l2 break elif l2 is None: ptr.next = l1 else: smallerVal = 0 if l1.val < l2.va: smallerVal = l1.val l1 = l1.next else: smallerVal = l2.val l2 = l2.next newNode = ListNode(smallerVal) ptr.next = newNode ptr = prt.next return head.next
true
62cf7ad9407f66a4a189ae9d8232c10ca64a0043
capkum/python-calculator
/example/step01.py
850
4.34375
4
''' example 변수안의 식만을 계산 ''' def calculator(str): number = [] operation = [] for x in str.replace(' ', ''): if x.isdigit(): number.append(x) else: operation.append(x) nmbr_len = len(number) x = int(number[nmbr_len - 2]) y = int(number[nmbr_len - 1]) return formula(operation[0])(x, y) def formula(opr): calcu = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y, } return calcu[opr] if __name__ == '__main__': example = [ '1+1', '3-1', '4- 1', '5 +1', '5 * 2', '8/ 2', ] for e in example: result = calculator(e) print('calculation result : {} = {}({})'.format(e, int(result), result))
false
2acf6153ffee5b46504954ea22204254ff1c5ca9
matamkiran/python2020
/functions/function_multiplication.py
298
4.25
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 31 11:26:26 2021 @author: Divya """ def func1(n,l): for i in l: print(n ," * ", i,"=",n*i) number=int(input("Enter the number you wish to display multiplication of table :")) b=[1,2,3,4,5,6,7,8,9,10] func1(number,b)
false
e85c5ae1101d7e3e25ccd570231e3e04e5e32d74
JLtheking/cpy5python
/practical03/q1_display_reverse.py
899
4.3125
4
# Filename: q1_display_reverse.py # Author: Justin Leow # Created: 19/2/2013 # Modified: 22/2/2013 # Description: Displays an integer in reverse order ##Input a positive integer: 5627631 ##1367265 ##Input a positive integer: nope ##Input is not an integer. Utilizing default value of 6593 ##3956 ##Input a positive integer: quit def newString(inputString): tempInput = input(inputString) if(tempInput=="quit"): quit() try: int(tempInput) except: print("Input is not an integer. Utilizing default value of 6593") return 6593 tempInput = int(tempInput) if(tempInput < 0): print("Input is not positive. Utilizing default value of 6593") return 6593 else: return tempInput # main while(True): #get user input myNumber = str(newString("Input a positive integer: ")) print (int(myNumber[::-1]))
true
bf920db934db1952d9c741ce8e8335a47dae2d0f
JLtheking/cpy5python
/08_OOP/bankaccount.py
2,339
4.3125
4
#bankaccount.py class Account(): '''Bank account class''' def __init__(self,account_no,balance): '''constructor method''' #double underscore makes it a hidden private attribute self.__account_no = account_no self.__balance = balance def get_account_no(self): '''accessor method to retrieve account no''' return self.__account_no def get_balance(self): return self.__balance def deposit(self,amount): '''modifier/mutator method to update balance''' self.__balance += amount print("") def withdraw(self,amount): self.__balance -= amount print("") #no public method to change account number, for safety because usually you do not change account number after creation def display(self): '''helper/support method to show account info''' print("Account No:",self.__account_no) print("Balance:",self.__balance) class Savings_Account(Account): def __init__(self,account_no,balance,interest): super().__init__(account_no,balance) self.__interest = interest def withdraw(self,amount): if amount > self.get_balance(): print("Your account does not have sufficient funds") else: super().withdraw(amount) def calc_interest(self): self.deposit(self.get_balance() * self.__interest) def display(self): print("Account type: Savings Account") super().display() print("") class Current_Account(Account): def __init__(self,account_no,balance,overdraft_limit): super().__init__(account_no,balance) self.__overdraft_limit = overdraft_limit def withdraw(self,amount): if (self.get_balance() - amount) < (self.__overdraft_limit * -1): print("The amount you have intended to withdraw, ",amount,"has exceeded the overdraft limit for your account, ",self.__overdraft_limit,".") else: super().withdraw(amount) def display(self): print("Account type: Current Account") super().display() print("Overdraft limit:",self.__overdraft_limit) print("") #main acct1 = Savings_Account("S01",5000,.1) acct1.display() acct1.calc_interest() acct1.display() acct1.calc_interest() acct1.display() acct1.withdraw(3000) acct1.display() acct1.withdraw(3000) acct1.display() print("") acct2 = Current_Account("C01",5000,3000) acct2.display() acct2.withdraw(3000) acct2.display() acct2.withdraw(3000) acct2.display() acct2.withdraw(3000) acct2.display()
true
73b2fa58628caf0682ba2fbcca4d44c25662c460
JLtheking/cpy5python
/practical01/q1_fahrenheit_to_celsius.py
634
4.25
4
# Filename: q1_fahrenheit_to_celsius.py # Author: Justin Leow # Created: 22/1/2013 # Modified: 22/1/2013 # Description: Program which converts an input of temperature in farenheit to an # output in celcius # main while(True): #get user input farenheit fInput = input(["Input temperature in farenheit, or 'quit' to quit"]) if(fInput=="quit"): quit() try: float(fInput) except: print("please input a number") else: fInput=float(fInput) #calculate celcius cOutput=(5/9)*(fInput-32) #display result print("{0:.2f}".format(cOutput)+"\n")
true
1e53c2e3e7052d86c164fa4b58c85b266338f01f
KathMoreno/prog-101
/Python/clases/arrays.py
845
4.1875
4
# Declare array my_array = ["Luna de miel en familia", "Escuadrón suicida", "Maléfica"] # Print a value from the array # print(my_array[1]) # Print all the array # print(my_array) # Add item # my_array.append("Nuestro video prohibido") # print(my_array) # Remove item # my_array.remove("Nuestro video prohibido") # print(my_array) pelicula_1 = "Luna de miel en familia" pelicula_2 = "Escuadrón suicida" pelicula_3 = "Maléfica" pelicula_4 = "Terminator Genesys" pelicula_5 = "Star Treck: Sin límites" pelicula_6 = "Capitán Phillips" pelicula_7 = "La quinta ola" pelicula_8 = "El arte de robar" pelicula_9 = "The martian" pelicula_10 = "Sospechosos" # This breaks DRY print(pelicula_1) print(pelicula_2) print(pelicula_3) print(pelicula_4) print(pelicula_5) print(pelicula_6) print(pelicula_7) print(pelicula_8) print(pelicula_9) print(pelicula_10)
false
bbcd58c87ea0fbc8479ac182e434715e079b37de
NaguBianchi/Workspace
/Integrando_conocimientos/Integracion.py
1,834
4.3125
4
""" Una librería de la ciudad de Carlos Paz requiere de un programa que permita cargar los montos de todas las ventas realizadas en el mes. Para ello el programa debe permitir guardar ese valor en una lista. Se debe generar un menú que permita realizar las siguientes operaciones: Agregar el monto de una venta. Mostrar todos los datos en la lista. Mostrar la venta más baja. Mostrar la ganancia total (Suma de todas las ventas). Calcular el promedio de Ventas. Cada opción debe llamar a una función que se encargue de hacer el calculo correspondiente recibiendo la lista por parametro y retornando el valor correspondiente. """ from Integrando_conocimientos import Funciones_para_venta def menu(): lista_ventas = [] opcion = Funciones_para_venta.opcion_venta() while opcion != 0: if opcion == 1: venta = float(input("Ingrese el monto de la venta: ")) lista_ventas.append(venta) elif opcion == 2: Funciones_para_venta.imprimir_lista(lista = lista_ventas) # print(lista_ventas) #Metodo sin funcion elif opcion ==3: r = Funciones_para_venta.venta_minima(lista = lista_ventas) print(f"La venta minima es: {r}") # print(f"La menor venta es: {min(lista_ventas)}") #Metodo sin funcion elif opcion == 4: r = Funciones_para_venta.venta_total(lista = lista_ventas) print(f"El monto de las ventas totales es: {r}") # print(f"El monto de las ventas totales es: {sum(lista_ventas)}") #Metodo sin funcion elif opcion == 5: r = Funciones_para_venta.promedio_ventas(lista = lista_ventas) print(f"El promedio de las ventas es: {r}") else: print("Opcion incorrecta!") opcion = Funciones_para_venta.opcion_venta() menu()
false
cd4121bd09406dad559630f0d16a91eba83fd4fe
NaguBianchi/Workspace
/Estructuras/Clase2_Funciones.py
1,303
4.25
4
""" Parametros o Argumentos Los Parametros son posicionales y requeridos Para que los parametros no sean obligatorios se define un parametro por default Ej:def user_info(nombre, edad, ciudad = "Cordoba"): En pocas palabras, son valores que se reciben en una funcion a traves de los parentesis """ # def user_info(nombre, edad, ciudad): # print(f"{nombre} tiene {edad} anios y vive en {ciudad}") # user_info(nombre="Nagu", edad=23, ciudad="Villa Carlos Paz") # Podemos especificar los parametros con la variable para evitar errores de posicion """ Funciones con retorno Son funciones que retornan un valor para ser usado en otra funcion """ def suma(): a = int(input('Ingrese un numero: ')) b = int(input('Ingrese otro numero: ')) sum = a + b return sum # s = suma() # print('El resultado es : ' + str(s)) # retorno # No se puede retornar un print de pantalla # Tampoco se puede retornar mas de 1 vez a no ser que tengas un condicional def que_temperatura_es(): return '30 grados' temp = que_temperatura_es() print(f'La temperatura es: {temp}') # Se puede llamar a una funcion dentro de otra funcion y que ambas tengan retorno # otro ej def que_temperatura_es_en_celcius(f): c = (5 / 9) * (f - 32) return c g = que_temperatura_es_en_celcius(f = 32) print(g)
false
af47a62770895f3239b6a0505b1cce9509a903ad
mmutiso/digital-factory
/darts.py
773
4.28125
4
import math def square(val): return math.pow(val,2) def score(x, y): ''' Give a score given X and Y co-ordinates Rules X range -10,10 Y range -10, 10 The problem is finding the radius of the circle created by a given point x,y then compare if the point is inside the circle using pythagoras theorem where a^2 + b^2 = c^2 ''' if (square(x) + square(y)) <= square(1): return 10 elif ((square(x) + square(y)) <= square(5)) and ((square(x) + square(y)) > square(1)): return 5 elif ((square(x) + square(y)) <= square(10)) and ((square(x) + square(y)) > square(5)): return 1 else: return 0 if __name__ == "__main__": result = score(0,10) print(result) assert result == 1
true
d239595956f2ebdd76d628be8aae6892ba43e352
Andeleisha/dicts-restaurant-ratings
/ratings.py
1,534
4.15625
4
"""Restaurant rating lister.""" # put your code here def build_dict_restaurants(filename, dictionary): """Takes a file and creates a dictionary of restaurants as keys and ratings as values""" with open(filename) as restaurant_ratings: for line in restaurant_ratings: line = line.strip() line = line.split(":") dictionary[line[0]] = line[1] return dictionary def print_restuarant_ratings(dictionary): """Given a dictionary it alphebatizes the keys""" alpha_list = sorted(dictionary.keys()) for restaurant in alpha_list: print("{} is rated at {}".format(restaurant, dictionary[restaurant])) def add_rating(dictionary): """add new entry into dictionary""" new_restaurant_name = input("What's your new restaurant? ") new_restaurant_score = input("What rating would you give it? ") dictionary[new_restaurant_name] = dictionary.get(new_restaurant_name, new_restaurant_score) return dictionary #print("Thank you for your rating!") # dict_restaurants = {} def ratings_loop(fname): dict_restaurants = {} dict_restaurants = build_dict_restaurants(fname, dict_restaurants) print_restuarant_ratings(build_dict_restaurants(fname, dict_restaurants)) add_rating(dict_restaurants) print("Here is the new list of restaurant ratings.") print_restuarant_ratings(dict_restaurants) ratings_loop('scores.txt') # dict[upper_version] = [rating, "string_user_input"] # dict[upper][0] == rating # dict[upper][1] == input # sort(dict) => keys in actual sorted order # dict[key][1] => printed version
true
f12370d769339351a1e01eb6189c6e45914fbd67
sukritishah15/DS-Algo-Point
/Python/armstrong_number.py
585
4.1875
4
n = int(input()) l = len(str(n)) s = 0 temp = n while temp > 0: s += (temp%10) ** l temp //= 10 if n == s: print("Armstrong number") else: print("Not an armstrong number") ''' Check whether a number entered by the user is Armstrong or not. A positive integer of n digits is called an Armstrong Number (of order n) if: abcd.. = a^n + b^n + c^n + d^n + ... Sample Input: n = 153 Sample Output: Armstrong number Explanation: 153 is an armstrong number because, 153= 1x1x1 + 5x5x5 + 3x3x3 i.e. 1^3+5^3+3^3 = 153. Time complexity : O(log N) Space complexity: O(1) '''
true
ec34d801bf68c970a600d37ae6cc5a6e04fee1f6
sukritishah15/DS-Algo-Point
/Python/majority_element.py
733
4.375
4
# Python problem to find majority element in an array. def majorityElement(nums, n): nums.sort() for i in range(0, n): if(i+int(n/2)) < n and nums[i] == nums[i+int(n/2)]: return nums[i] return None n = int(input("Enter the total number of elements\n")) print('Enter a list of '+str(n) + ' number in a single line') arr = list(map(int, input().split())) result = majorityElement(arr, n) if (result == None): print("No majority element") else: print("Majority element is", result) ''' Time complexity ==> O(nlogn) Space complexity=> O(1) I/O --> Enter the total number of elements 10 Enter a list of 10 number in a single line 1 1 3 1 2 1 1 6 5 1 O/P --> Majority element is 1 '''
true
c1d8ba9a81d785d6a77de20d075150f371825ba7
sukritishah15/DS-Algo-Point
/Python/automorphic.py
423
4.125
4
# Automorphic Number: The last digits of thr square of the number is equal to the digit itself n=int(input("Enter the number: ")) sq= n**2 l=len(str(n)) ld=sq%pow(10,l) if (ld==n): print("Automorphic Number") else: print("Not a automorphic number") """ I/O Enter the number: 25 Automorphic Number Enter the number: 12 Not a automorphic number Time complexity- O(1) Space Complexity- O(1) """
true
ccfe5912c428bbaf377448c3b4961ce2d3c4e838
sukritishah15/DS-Algo-Point
/Python/inordder.py
608
4.28125
4
class Node: def __init__(self,key): self.left = None self.right = None self.val = key def printInorder(root): if root: printInorder(root.left) print(root.val), printInorder(root.right) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print "\nInorder traversal of binary tree is" printInorder(root) ''' Time Complexity - O(N) Space Complexity - O(N) Input - Taken in the Code . Output -Inorder traversal of binary tree is 4 2 5 1 3 '''
true
00d927ab9488e3d8954720d71ee8272394f99739
sukritishah15/DS-Algo-Point
/Python/harmonic.py
372
4.3125
4
# Sum of harmonic series def sumHarmonic(n): i = 1 sum = 0.0 for i in range(1, n+1): sum = sum + 1/i; return sum; n = int(input("First term :")) print("Sum of the Harmonic Series :", sumHarmonic(n)) """" Example: First term : 6 Sum of the Harmonic Series : 2.4499999999999997 ......... Time Complexity :- O(logn) Space Complexity :- O(n) """
true
aabf2577bd44425c702d6a670ba21dcef79c4aa0
dboldt7/PRG105
/Banana revised.py
1,207
4.21875
4
"""" Banana Bread Recipe: 2 cups of flour 1 teaspoon of baking soda 0.25 teaspoons of salt 0.5 cups of butter 0.75 cups of brown sugar 2 eggs 2.33 bananas Recipe produces 12 servings of bread Write a program that asks the user how many servings they want Program displays the ingredients needed to make the desired amount """ Servings = 12 Flour = 2 bakingSoda = 1 salt = 0.25 butter = 0.5 sugar = 0.75 egg = 2 banana = 2.33 desiredServings = int(input("How many servings do you want? ")) percentChange = (desiredServings - Servings) / Servings if percentChange == 0: percentChange = 1 elif percentChange > 0: percentChange = 1 + percentChange else: percentChange = percentChange * -1 print("") print("Ingredients Needed:\n") print((Flour * percentChange), " cups of flour") print(format(bakingSoda * percentChange, ".1f"), "teaspoons of baking soda") print(format(salt * percentChange, ".1f"), " teaspoons of salt") print(format(butter * percentChange, ".1f"), " cups of butter") print(format(sugar * percentChange, ".1f"), " cups of sugar") print(format(egg * percentChange, ".1f"), " eggs") print(format(banana * percentChange, ".1f"), " bananas")
true
4d58fd2658087cccd782b2b14f05ed2e5cd138fc
dboldt7/PRG105
/lesson 5.2 logic.py
988
4.25
4
number = int(input("Enter a whole number between 20 and 100 ")) def divide_two(num): if num % 2 == 0: print(num, "is divisible by 2") else: print(num, "is not divisible by 2") def divide_three(num): if num % 3 == 0: print(num, "is divisible by 3") else: print(num, "is not divisible by 3") def divide_five(num): if num % 5 == 0: print(num, "is divisible by 5") else: print(num, "is not divisible by 5") def main_func(): final_num = check_function(number) divide_two(final_num) divide_three(final_num) divide_five(final_num) def check_function(placeholder): local_number = placeholder if 20 < local_number < 100: return local_number else: while local_number > 100 or local_number < 20: local_number = int(input("Try again, enter a whole number between 20 and 100 ")) return local_number main_func()
false
c3920afa242227c20a26747c5903249ca2fb2687
AliMazhar110/Python-Projects
/Guess-a-number/main.py
1,575
4.1875
4
#Number Guessing Game Objectives: from art import logo import random from os import system # Include an ASCII art logo. # Allow the player to submit a guess for a number between 1 and 100. # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. # If they got the answer correct, show the actual answer to the player. # Track the number of turns remaining. # If they run out of turns, provide feedback to the player. # Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode). while 1==1: system('cls') print(logo) number = random.randint(1,100) print("\nGuess a number between 1 - 100"); level = input("\nSelect a level 'EASY' or 'HARD' = ").lower() if level == "easy": attempts = 10 else: attempts = 5 finish = False print(f"\nYou have {attempts} attempts.") while not finish: if attempts==0: print("\nNo Attempts Left. You Lost.") print(f"The number was {number}") finish = True continue guess = int(input("\nGuess a number = ")) if guess == number: print(f"\nCorrect. You got it. Number was {number}") finish = True elif guess > number: print("Too high.") elif guess < number: print("Too low") attempts-=1 print(f"attempts Left: {attempts}") again = input("\nDo you want to play again(yes/no)? = ") if(again!="yes"): break else: continue
true
29e98b11111eb495b5c71f6e308abcb03881273c
dilciabarrios/Curso-Python
/5_Tipos_datos_avanzados/al_turron1.py
1,478
4.125
4
#Tenemos una lista con nombres de ciudades ciudadesDeEspaña = ['Granada','Cordoba','Santiago de Compostela','Paris','Malagá', 'Barcelona'] otrasCiudades = ['Toledo','Sevilla','Cadiz','Berlin','Alicante'] #Tareas # 1- Quitar de la listas las ciudades que no pertezcan a España (Berlin y Paris) # 2- Unir ambas listas en una unica # 3- Añadir Madrid, la capital, en la primera posicion de la lista, porque no esta # 4- Añadir otras ciudades a tu eleccion (Por Ejemplo: Mallorca, Santander y Burgos) # 5- Imprimir la siguiente frase por pantalla # >> Mi lista de ciudades tiene {numero de ciudades aquí} ciudades: [Contenido de la lista] # 1-ELIMINANDO CIUDADES del ciudadesDeEspaña [3] print('Eliminando Ciudad de Paris \n',ciudadesDeEspaña) del otrasCiudades [3] print('Eliminando Ciudad de Berlin \n',otrasCiudades) # 2- UNIR AMBAS LISTAS ciudadesDeEspaña.extend(otrasCiudades) print('Uniendo ambas listas el resultado es:') print (ciudadesDeEspaña) # 3- AÑADIR MADRID EN LA PRIMERA POSICION ciudadesDeEspaña[0]= 'Madrid' print('El resultando añandiendo Madrid es:\n',ciudadesDeEspaña) # 4- AÑADIR OTRAS CIUDADES nuevaLista = ['Mallorca', 'Santander', 'Burgos'] ciudadesDeEspaña.extend(nuevaLista) print('Añandiendo otras ciudades:',ciudadesDeEspaña) # 5-AÑADIENDO INFORMACION DE LA LISTA numeroDeElementos =len(ciudadesDeEspaña) print ('>> Mi lista de ciudades tiene %d ciudades:\n>> Las Ciudades Son:\n %s' %(numeroDeElementos,ciudadesDeEspaña))
false
f3dccd370b40a781ab0854040305fa7415609131
dilciabarrios/Curso-Python
/9_Funciones/al_turron.py
1,698
4.34375
4
#Objetivo: dividir las diferentes operaciones en funciones: #Ademas, añadir: #Una comprobacion que nos diga si el numero par o impar #Una comprobacion que nos diga si el numero es primo o no def ComprobarSiEsPar (numero): if (numero % 2 == 0): return True else: return False def ComprobarMultiplos (numero): multiplos = [] for num in range (1,6): numresultado = num*numero multiplos.append(numresultado) print ('- Los multiplos son:', multiplos) return multiplos def ComprobarCuadrado (numero): cuadrado = numero**2 print ('- Su número al cuadrado es:', cuadrado) def ComprobarCubo (numero): cubo = numero**3 print ('- Su número al cubo es:', cubo) def ComprobarMultiplicado (numero): multiplicado = numero*100 print ('- Su número multiplicado por 100 es:', multiplicado) def ComprobarPrimo (numero): if (numero % 1 == 0 and numero % numero == 0 and numero % 2 != 0 and numero % 3 != 0 and numero % 5 != 0 and numero % 7 != 0): print('- El número', numero, 'es primo') elif (numero == 2 and numero == 3 and numero == 5 and numero ==7): print('- El número', numero, 'es primo') else: print ('- El número', numero, 'no es primo') miNum = input ('Introduce un número:') miNum = int (miNum) resultado = ComprobarSiEsPar(miNum) resultado1 = ComprobarPrimo(miNum) if (resultado): print('- El número', miNum, 'es par ') else: print('- El número', miNum, 'es impar ') miMultiplos = ComprobarMultiplos(miNum) alCuadrado = ComprobarCuadrado(miNum) alCubo = ComprobarCubo (miNum) multiplicado = ComprobarMultiplicado(miNum) primos = ComprobarPrimo (miNum)
false
1147112c2a786e7e1c20436914cbe043db9b97dc
dilciabarrios/Curso-Python
/12_Debug/al_turron.py
986
4.40625
4
print('Bienvenido al sistema de almacenamiento de usuarios.') usuarios = ['Juan','Marta','Miguel','Elisa','Claudia','Jorge','Ana','Pedro'] while(True): print('''--- ¿Qué operación deseas realizar? 1 - Ver una lista de usuarios 2 - Añadir un usuario 3 - Eliminar un usuario X - Salir del programa''') opcionElegida = input('Introduce la opción: ') print('---') if(opcionElegida == '1'): print('Lista de usuarios') for usuario in usuarios: print(usuario) elif(opcionElegida == '2'): nuevoUsuario = input('Introduce el nombre del nuevo usuario: ') usuarios.append(nuevoUsuario) print(nuevoUsuario, 'añadido') elif(opcionElegida == '3'): usuarioAEliminar = input('¿Qué usuario quieres eliminar?:') usuarios.remove(usuarioAEliminar) print(usuarioAEliminar, 'eliminado') elif(opcionElegida == 'X'): break else: print('Entrada inválida.')
false
357c290a2c2ab8f2ce0e8da3552084d3f4218518
leofoch/PY
/ManejoDeCadenas.py
494
4.15625
4
#documentacion en: http://pyspanishdoc.sourceforge.net/lib/module-string.html #nombreUsuario=input("intro nombre: ") #print("El nombre es: ", nombreUsuario.upper()) #print("El nombre es: ", nombreUsuario.capitalize()) edad=input("intro Edad: ") while(edad.isdigit()==False): print("No es numerico") edad=input("intro Edad: ") if(int(edad)<18): #ojo--> todo lo que introduce desde pantalla es considerado un texto. por eso se usa "int" print("ok") else: print("NO OK")
false
db509bc5c514d48ea0dfcfd2b0445bd8879e87a3
PacktPublishing/-Python-By-Example
/Section 1/Section1/Video2_Nesting_Python_dicts_2_vehicles.py
784
4.15625
4
''' Created on Mar 30, 2018 @author: Burkhard A. Meier ''' from pprint import pprint cars = {} car_1 = {'make': 'BMW', 'speed': 'fast'} car_2 = {'make': 'Mercedes', 'speed': 'good'} car_3 = {'make': 'Porsche', 'speed': 'very fast'} cars['car 1'] = car_1 cars['car 2'] = car_2 cars['car 3'] = car_3 # 3 levels of nesting vehicles = {'cars': cars, 'planes': None, 'trains': None} # create dict with key-value pairs pprint(vehicles) print() print(vehicles['cars']) # access nested dict via its key print(vehicles['planes']) print(vehicles['trains']) print() vehicles_cars = vehicles['cars'] # assign nested dict to new variable pprint(vehicles_cars) print() print(type(vehicles_cars)) # variable type is dictionary
false
233d0067b828c7d7a12c6fd0d7c8e5f2f3d5476a
Elyseum/python-crash-course
/ch9/car.py
1,512
4.25
4
""" Modifying class state """ class Car(): """ Simple car """ def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ Formatting a descriptive name """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """ print mileage """ print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ Set odometer to given mileage, don't allow roll back! """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """ Add given amount to odometer """ if miles >= 0: self.odometer_reading += miles else: print("You can't roll back an odometer!") MY_NEW_CAR = Car('audi', 'a4', 2016) print(MY_NEW_CAR.get_descriptive_name()) MY_NEW_CAR.read_odometer() MY_NEW_CAR.odometer_reading = 23 MY_NEW_CAR.read_odometer() MY_NEW_CAR.update_odometer(46) MY_NEW_CAR.read_odometer() MY_NEW_CAR.update_odometer(23) MY_USED_CAR = Car('subaru', 'outback', 2013) print(MY_USED_CAR.get_descriptive_name()) MY_USED_CAR.update_odometer(23500) MY_USED_CAR.read_odometer() MY_USED_CAR.increment_odometer(100) MY_USED_CAR.read_odometer()
true
92eaf41e7093c52216487e96553cb00fb0b17cc5
Elyseum/python-crash-course
/ch8/formatted_name.py
788
4.25
4
""" Return values """ def get_formatted_name(first_name, last_name): """ Returns a full name, neatly formatted""" full_name = first_name + ' ' + last_name return full_name.title() MUSICIAN = get_formatted_name('jimi', 'hendrix') print(MUSICIAN) def get_formatted_name_2(first_name, last_name, middle_name=''): """ Optional middle name """ if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() MUSICIAN = get_formatted_name_2('jimi', 'hendrix') print(MUSICIAN) MUSICIAN = get_formatted_name_2('john', 'hooker', 'lee') print(MUSICIAN) MUSICIAN = get_formatted_name_2(first_name='john', middle_name='lee', last_name='hooker') print(MUSICIAN)
false
f21caae41042f33a4a60ea9ebcc8211b85d62bd2
jormao/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
939
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This module have a function that prints My name is <first name> <last name> prototype: def say_my_name(first_name, last_name=""): """ def say_my_name(first_name, last_name=""): """ function that prints My name is <first name> <last name> first_name and last_name must be strings otherwise, raise a TypeError exception with the message first_name must be a string or last_name must be a string Do not allowed to import any module Args: first name: first parameter lasta name: second parameter Raises: TypeError: first_name must be a string TypeError: last_name must be a string """ if type(first_name) is not str: raise TypeError('first_name must be a string') if type(last_name) is not str: raise TypeError('last_name must be a string') print("My name is {} {}".format(first_name, last_name))
true
48af3a3a7920e8b0fc67cca325cc3d1305db77d1
PureWater100/DATA-690-WANG
/ass_2/ass2.py
1,413
4.21875
4
# python file for assignment 2 # code from the jupyter notebook user_inputs = [] MAX_TRY = 11 for i in range(1, MAX_TRY): while True: try: user_input = input("Please enter an integer:") in_input = int(user_input) break except: print("Please retry (only integer accepted)") user_inputs.append(user_input) print(f"You have entered integer #{i}:", user_input) ints = [int(item) for item in user_inputs] #cast each element into an integer print("Overall, you have entered:", ints) #display looks cleaner after casting ints.sort(reverse = True) print("The minimum is:", ints[9]) print("The maximum is:", ints[0]) the_max = ints[0] the_min = ints[9] print("The range is:", the_max - the_min) # Python program to find sum of elements in list sum = 0 # Iterate each element in list # and add them in variale sum for ele in range(0, len(ints)): sum += ints[ele] mean = sum / 10 print("The mean is:", mean) sum_diff = 0 for ele in range(0, len(ints)): sum_diff += (ints[ele] - mean) ** 2 var = sum_diff / 9 # Format variance to display only 2 decimals variance = "The variance is: {:.2f}" print(variance.format(var)) # Get standard deviation by raising variance to .5 power stan_dev = var ** .5 # Format standard deviation to 2 decimals stand_dev = "The standard deviation is: {:.2f}" print(stand_dev.format(stan_dev))
true
5c3e03c9ec8a0c41e68d542f959098169adf612f
selvendiranj-zz/python-tutorial
/hello-world/exceptions.py
2,018
4.3125
4
""" Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them Exception Handling Assertions """ def KelvinToFahrenheit(Temperature): assert (Temperature >= 0), "Colder than absolute zero!" return ((Temperature - 273) * 1.8) + 32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78)) # print KelvinToFahrenheit(-5) # Handling an exception try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.close() # finally block try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data" try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print "Going to close the file" fh.close() except IOError: print "Error: can\'t find file or read data" # Argument of an Exception # Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbers\n", Argument # Call above function here. temp_convert("xyz") # Raising an Exceptions. def functionName(level): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception try: # Business Logic here... print("Business Logic here...") except "Invalid level!": # Exception handling here... print("Exception handling here...") else: # Rest of the code here... print("Rest of the code here...") # User - Defined Exceptions class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg try: raise Networkerror("Bad hostname") except Networkerror, e: print e.args
true
b1cff2e2be5fc5b3c99833102c7382dbe6efe8af
Loser-001/p_008
/chap6/demo14.py
564
4.15625
4
#位 置:南京邮电大学 #程 序 员:邱礼翔 #开发时间:2020/10/29 19:20 a=20 b=100 #两个整数类对象的相加操作 c=a+b d=a.__add__(b) print(c) print(d) class Student: def __init__(self,name): self.name=name def __add__(self, other): return self.name+other.name def __len__(self): return len(self.name) stu1=Student('张三') stu2=Student('李四') s=stu1+stu2 print(s) print('------------------------------------------') lst=[11,22,33,44] print(len(stu1)) print(lst.__len__()) print(stu1.__len__())
false
fc2a1870e98be5abae3b215fc719125eae7ccedf
Loser-001/p_008
/chap4/demo5.py
624
4.1875
4
#位 置:南京邮电大学 #程 序 员:邱礼翔 #开发时间:2020/10/25 16:09 ''' for item in 'python': print(item) for i in range(10): pass print(i) for _ in range(5): print('人生苦短,我用python') sum=0 for j in range(1,101): if j%2==0: sum=sum+j print(sum) ''' a=135 print(int(a/100)) print(int(a/10%10)) print(a%10) '''输出a100到999之间的水仙花数''' s=0 for i in range(100,1000): a=int(i/100) #百位 b=int(i/10%10) #十位 c=int(i%10) #个位 if i==a**3+b**3+c**3: print(i) s=1 if s==0: print('当中没有水仙花数')
false
c16a4d2cb51863a144f5a9e33c46467620b8abd9
LogSigma/unipy
/docstring.py
916
4.5
4
def func(*args, **kwargs): """ Summary This function splits an Iterable into the given size of multiple chunks. The items of An iterable should be the same type. Parameters ---------- iterable: Iterable An Iterable to split. how: {'equal', 'remaining'} The method to split. 'equal' is to split chunks with the approximate length within the given size. 'remaining' is to split chunks with the given size, and the remains are bound as the last chunk. size: int The number of chunks. Returns ------- list A list of chunks. See Also -------- Examples -------- >>> up.splitter(list(range(10)), how='equal', size=3) [(0, 1, 2, 3), (4, 5, 6), (7, 8, 9)] >>> up.splitter(list(range(10)), how='remaining', size=3) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)] """ pass
true
9d07ce046e2c46a928da07c2d6578f7e91d1df9b
kristinamb15/cracking-the-coding-interview
/1_ArraysStrings/1.4.py
1,286
4.15625
4
# 1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. # The palindrome does not need to be limited to just dictionary words. # You can ignore casing and non-letter characters. import unittest # Solution 1 # O(N) def palindrome_perm(mystring): mystring = mystring.lower() char_dict = {char:0 for char in mystring if char.isalpha()} for char in mystring: if char.isalpha(): char_dict[char] += 1 evens = 0 odds = 0 for key in char_dict: if char_dict[key] % 2 == 0: evens += 1 else: odds += 1 result = (odds == 1 or odds == 0) return result # Testing class Tests(unittest.TestCase): def test_with_space_true(self): self.assertTrue(palindrome_perm('taco cat')) def test_with_space_false(self): self.assertFalse(palindrome_perm('I am not a palindrome')) def test_no_space_true(self): self.assertTrue(palindrome_perm('racecar')) def test_no_space_false(self): self.assertFalse(palindrome_perm('nope')) def test_with_punc_true(self): self.assertTrue(palindrome_perm('Was it a cat I saw?')) if __name__ == '__main__': unittest.main()
true
eaac82b9fe0a9bb5eff99d38a3d75cfa23e3cdc6
jorgepdsML/Threads_Projects_Python
/threading_sub_class_example2/threading_sub_class_python.py
1,093
4.21875
4
""" uso del modulo threading mediante la definición de una sub_clase la herencia viene de la clase base Thread """ import threading import time class BThread(threading.Thread): #atributo de clase Nthread=0 #overriding el método __init__() def __init__(self,name="braintels"): #invocar al método __init__() del ancestro threading.Thread.__init__(self) #agregar un atributo name self.name=name #atributo de clase paara saber el numero de hilos creados self.__class__.Nthread+=1 def run(self): #método run representa al hilo que se desea ejecutar print("====HILO N°1 ==== INICIO") #==========colocar codigo aqui======= print("MI NOMBRE ES:",self.name) #================================ print("===HILO N°1 === FIN") #crear un hilo h1=BThread("jorge_miranda") #iniciar la actividad del hilo h1.start() #este método invoca al método run () #esperar hasta que el hilo termine su ejecución h1.join() print("===HILOS CREADOS SON:",BThread.Nthread)
false
616067b46918e0940fcf1805d8e3ae12ab0bbf2f
ShehabAhmedSayem/Rosalind-Chapterwise
/Chapter 1/ba1a.py
691
4.15625
4
# Problem Name: Compute the Number of Times a Pattern Appears in a Text def read_input_from_file(file_name): with open(file_name, 'r') as file: string = file.readline().strip() pattern = file.readline().strip() return string, pattern def occurrence(string, pattern): """ string: input string pattern: pattern to search """ count = 0 l = len(string) p = len(pattern) for start in range(l-p+1): if(string[start:start+p] == pattern): count += 1 return count if __name__ == "__main__": string, pattern = read_input_from_file("in.txt") print(occurrence(string, pattern))
true
f8b875595f336a2d7ad29db2b2f6051f5340f82d
Cmartis/pythonsrc
/examples/automate/ch05_01.py
555
4.28125
4
birthdays = {'rachel':'26th Sept 2006', 'ryan':'9th Jan 2003', 'chris':'28th Jan 1973', 'medha':'8th Sep 1973', 'rita':'14th July 1940'} while True: print('enter a name: (blank to quit]') name = input() if name == '': break if name in birthdays: print(birthdays[name] + ' is the birthday of ' + name) else: print(' i do not have the birthday for ' + name) print('what is their birthday') bday = input() birthdays[name] = bday print('birthdays database updated')
false
864401be5d0d0ba69503da811f67cebe37edbaa4
Mustafa-Filiz/HackerRank--Edabit--CodeWars
/Codewars_12_ROT13.py
1,234
4.65625
5
# ROT13 """ ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation". Please note that using encode is considered cheating. """ def rot13(message): import string cipher = "" for i in message: if i in string.ascii_uppercase: if string.ascii_uppercase.index(i) < 13: cipher += string.ascii_uppercase[string.ascii_uppercase.index(i) + 13] else: cipher += string.ascii_uppercase[string.ascii_uppercase.index(i) - 13] elif i in string.ascii_lowercase: if string.ascii_lowercase.index(i) < 13: cipher += string.ascii_lowercase[string.ascii_lowercase.index(i) + 13] else: cipher += string.ascii_lowercase[string.ascii_lowercase.index(i) - 13] else: cipher += i return cipher
true
d8ad0945acb41da09f474325b940b6b289bd91ad
newemailjdm/intro_python
/121515/conditional.py
337
4.21875
4
first_name = input("What's your first name") name_length = len(first_name) if name_length > 10: print("That's a long name!") elif name_length > 3: print("Nice, that's a name of medium length.") elif name_length == 3: print("That's a short name.") else: print("Are you sure those aren't your initials?")
true
83a1611d3673951ca106228ea3b28e55c97a85b1
AnkurPokhrel8/LinkedList
/LinkedList.py
2,012
4.28125
4
# -*- coding: utf-8 -*- """ @author: Ankur Pokhrel """ class Node: # Node class def __init__(self, data): self.data = data self.next = None class LinkedList: # Linkedlist class def __init__(self): self.head = None def addNode(self, data): if not self.head: # if linked list is empty, set first element as head self.head = Node(data) else: top = self.head # if not, add element at last of linked list while top.next: top = top.next top.next = Node(data) def deleteNodefromFirst(self): print(self.head.data, " is deleted") self.head = self.head.next # set second element as head of linkedlist, hence deleting first element def deleteNodefromLast(self): top = self.head while top.next.next: top = top.next print(top.next.data, " is deleted") top.next = None # set next value of second last element as None, hence deleting last element def showAll(self): top = self.head if self.head: top = self.head while top.next: # Iterating through the linkedlist printing all elements print(top.data) top = top.next else: print(top.data) else: print("The Linked List is empty") ll = LinkedList() ll.addNode(25) ll.addNode(36) ll.addNode(5) ll.addNode(15) ll.addNode(250) ll.addNode(360) ll.addNode(50) ll.addNode(100) ll.showAll() ll.deleteNodefromFirst() ll.deleteNodefromLast() ll.showAll() ''' Output: 25 36 5 15 250 360 50 100 25 is deleted 100 is deleted 36 5 15 250 360 50 '''
true
6243bfacd386b76e0bf1fb38183e40bba96c48d9
jmason86/python_convenience_functions
/lat_lon_to_position_angle.py
982
4.1875
4
import numpy as np def lat_lon_to_position_angle(latitude, longitude): """Function to translate heliocentric coordinates (latitude, longitude) into position angle Written by Alysha Reinard and James Paul Mason. Inputs: longitude [float]: The east/west coordinate latitude [float]: The north/south coordinate Optional Inputs: None Outputs: position_angle [float]: The converted position angle measured in degrees from solar north, counter clockwise Optional Outputs: None Example: position_angle = lat_lon_to_position_angle(35, -40) """ x = longitude * 1.0 y = latitude * 1.0 if y != 0: pa = np.arctan(-np.sin(x) / np.tan(y)) else: pa = 3.1415926 / 2. # limit of arctan(infinity) pa = pa * 180.0 / 3.1415926 if y < 0: pa += 180 if x == 90 and y == 0: pa += 180 if pa < 0: pa += 360 if x == 0 and y == 0: pa = -1 return pa
true
7a9c22cdc58108bf175cc08bcd9a63b069caec0c
hadesLiu/python100d
/day08-面向对象编程基础/circle.py
1,412
4.3125
4
# -*- coding: utf-8 -*- # @Author : hiro, # @Mail : hiroliu@yeah.net # @FileName: circle.py # @Time : 2019/6/3 7:27 PM """ 练习 修一个游泳池 半径(以米为单位)在程序运行时输入 游泳池外修一条3米宽的过道 过道的外侧修一圈围墙 已知过道的造价为25元每平米 围墙的造价为32.5元每米 输出围墙和过道的总造价分别是多少钱(精确到小数点后2位) Version: 0.1 Author: 骆昊 Date: 2018-03-08 """ from math import pi class Circle(object): def __init__(self, radius): """ 初始化方法 :param radius: 半径 """ self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, radius): self._radius = radius if radius > 0 else 0 @property def perimeter(self): """ 周长 :return: 2 * pi * radius """ return 2 * pi * self._radius @property def area(self): """ 面积 :return: """ return pi * self._radius * self._radius def main(): radius = float(input('请输入泳池的半径:')) small = Circle(radius) big = Circle(radius + 3) print('围墙的造价为:%.2f' % (big.perimeter * 32.5)) print('过道的造价为:%.2f' % ((big.area - small.area) * 25)) if __name__ == '__main__': main()
false
94418a9660befad407049a9b6b6c3e3708c3e394
LogicPenguins/BeginnerPython
/Udemy Course/HW Funcs & Methods/exer3.py
444
4.375
4
# Write a Python function that accepts a string and calculates the number of upper case # and lowercase letters. def case_info(string): num_upper = 0 num_lower = 0 for char in string: if char.islower(): num_lower += 1 elif char.isupper(): num_upper += 1 print(f'Upper Case Chars: {num_upper}\nLower Case Chars: {num_lower}') case_info('Hello Mr. Rogers, how are you this fine Tuesday?')
true
d79574835a4f1924c0d5fc4160cb3e31788aba42
madhuri-bh/DSC-assignmentsML-AI
/Python1.py
572
4.25
4
movieEntered = input("Enter a movie") thriller=["Dark","Mindhunter","Parasite","Inception","Insidious","Interstellar","Prison Break","MoneyHeist","War","Jack Ryan"] comedy=["Friends","3 Idiots","Brooklyn 99","How I Met Your Mother","Rick And Morty","The Big Bang Theory","TheOffice","Space Force"] movieEntered = movieEntered.lower() thriller = map(str.lower,thriller) comedy = map(str.lower,comedy) if movieEntered in thriller: print("It is a thriller") elif movieEntered in comedy: print("It is a comedy") else: print("It's neither thriller nor comedy")
true
2e045de83fd7aa18e3e13758215025950768c1d8
sushtend/100-days-of-ml-code
/code/basic python in depth/11 logical operator.py
202
4.15625
4
name = "Abdul Kalam" if not name: print("1st name is empty") name = "" if not name: print("2nd name is empty") # Chaining comparison operator age = 25 if 18 <= age <= 25: print("Eligible")
false
6c8326308e4df9e5a607376b8ccf1c68a1ba6478
sushtend/100-days-of-ml-code
/code/basic python/13.5 guessing game.py
361
4.1875
4
Guess_count=1 guess=9 print("+++++ This program lets you guess the secret number +++++") while Guess_count<=3: num = int(input("Gues the number: ")) if guess==num: print("Correct") #exit() break Guess_count+=1 # Else for while loop evaluates after completion of all loops without brteak else : print("Sorry you failed")
true
a957102ba9b196c13b102ecdf02e81ed94796a8b
sushtend/100-days-of-ml-code
/code/basic python in depth/21 sets.py
1,367
4.5
4
# https://realpython.com/python-sets/ # numbers = [1, 2, 3, 4] first = set(numbers) second = {1, 5} print(first | second) # Uniion print(first & second) # Intersection print(first - second) # Differece print(first ^ second) # semantic difference. Items in either a or b but not both # ---------------------------------------- print("+++++++++++++Strings++++++++++++++") x = set(["foo", "bar", "baz", "foo", "qux"]) print(x) x = set(("foo", "bar", "baz", "foo", "qux")) print(x) x = {"foo", "bar", "baz", "foo", "qux"} print(x) # Strings are also iterable, so a string can be passed to set() as well. s = "quux" print(list(s)) print(set(s)) # A set can be empty. However, recall that Python interprets empty curly braces ({}) as an empty dictionary, so the only way to define an empty set is with the set() function. # An empty set is falsy in Boolean context y: set = set() print(bool(y)) print(len(x)) print("----------------") x1 = {"foo", "bar", "baz"} x2 = {"baz", "qux", "quux"} print(x1.union(x2)) print(x1.intersection(x2)) print(x1.difference(x2)) print(x1.symmetric_difference(x2)) # Determines whether or not two sets have any elements in common. print(x1.isdisjoint(x2)) # Determine whether one set is a subset of the other. print(x1.issubset(x2)) # Modify a set by union. x1.update(["corge", "garply"]) x1.add("corge") x1.remove("baz")
true
635a67a18e9542866a68fc362ecc2941069da6e1
jinm808/Python_Crash_Course
/chapter_4_working_w_lists/pracs.py
1,661
4.5625
5
''' 4-1: Pizzas Think of at least three kinds of your favorite pizza. Store these pizza names in a list, and then use a for loop to print the name of each pizza. Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza. For each pizza you should have one line of output containing a simple statement like I like pepperoni pizza. Add a line at the end of your program, outside the for loop, that states how much you like pizza. The output should consist of three or more lines about the kinds of pizza you like and then an additional sentence, such as I really love pizza! ''' favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie'] # Print the names of all the pizzas. for pizza in favorite_pizzas: print(pizza) print("\n") # Print a sentence about each pizza. for pizza in favorite_pizzas: print("I really love " + pizza + " pizza!") print("\nI really love pizza!") ''' 4-3: Counting to Twenty Use a for loop to print the numbers from 1 to 20, inclusive. ''' numbers = list(range(1, 21)) for number in numbers: print(number) ''' 4-5: Summing a Million Make a list of the numbers from one to one million, and then use min() and max() to make sure your list actually starts at one and ends at one million. Also, use the sum() function to see how quickly Python can add a million numbers. ''' numbers = list(range(1, 1000001)) print(min(numbers)) print(max(numbers)) print(sum(numbers)) ''' 4-7: Threes Make a list of the multiples of 3 from 3 to 0. Use a for loop to print the numbers in your list. ''' threes = list(range(3, 31, 3)) for number in threes: print(number)
true
cab02298ed5b609d152d734f11416bf9442792f8
jinm808/Python_Crash_Course
/chapter_8_functions/user_album.py
712
4.21875
4
def make_album(artist_name, album_title, tracks = 0): """Build a dictionary describing a music album.""" album_dict = { 'artist' : artist_name.title(), 'album' : album_title.title() } if tracks: album_dict['tracks'] = tracks return album_dict print("Enter 'q' at any time to stop.") while True: title = input('\nWhat album are you thinking of? ').lower() if title == 'q': break artist = input('Who\'s the artist? ').lower() if artist == 'q': break tracks = input('Enter number of tracks if you know them: ') if artist == 'q': break album = make_album(artist, title, tracks) print(album) print("\nThanks for responding!")
true
2fc1a9a57b5e8713e1fd8b231289656d1838e32c
wandingz/daily-coding-problem
/daily_coding_problem61.py
1,695
4.28125
4
''' This problem was asked by Google. Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. Do this faster than the naive method of repeated multiplication. For example, pow(2, 10) should return 1024. ''' class Solution: def powNaive(self, a, b): # naive method of repeated multiplication result = 1 for _ in range(b): result *= a return result def powNaive2(self, a, b): # naive method of repeated multiplication if not b: return 1 return a * self.powNaive2(a, b-1) def powSquaring(self, a, b): # exponentiation by squaring if b == 1: return a elif b % 2 == 1: return a * self.powSquaring(a, b-1) else: p = self.powSquaring(a, b/2) return p*p def powSquaring2(self, a, b): # exponentiation by squaring result = 1 while True: if b % 2 == 1: result *= a b -= 1 if b == 0: break b /= 2 a *= a return result def powBinary(self, a, b): # left-to-right binary exponentiation def _traversal(n): bits = [] while n: bits.append(n % 2) if n % 2 == 1: n -= 1 n /= 2 return bits result = 1 for x in reversed(_traversal(b)): result *= result if x == 1: result *= a return result a, b = 2, 5 a, b = 3, 4 Solution().powBinary(a, b)
true
5503d10bbcf8a15a7e6e4d4e1becb769f87839d1
glemvik/Knowit_julekalender2017
/Luke11.py
2,087
4.375
4
# -*- coding: utf-8 -*- from time import time from math import sqrt def mirptall(primes): """ Returns all positive 'mirptall' smaller than 'number', where 'mirptall' are primes which are also primes when the digits are reversed without being palindromes. """ # INITIALIZE primes = set(primes) mirptall = [] # WORK THROUGH SET OF PRIMES while primes: prime = primes.pop() reverse_prime = int(str(prime)[::-1]) # IF NOT PALINDROME AND REVERSE OF PRIME IS PRIME if prime != reverse_prime and reverse_prime in primes: # ADD BOTH 'MIRPTALL' AND REMOVE FROM SET OF PRIMES mirptall.append(prime) mirptall.append(reverse_prime) primes.remove(reverse_prime) return mirptall def primes(number): """ Returns an array of all primes smaller than 'number'. """ # INITIALIZE primes = [2] # WORK THROUGH LIST for number in range(3, number): index = 0 is_prime = True # CHECK DIVISIBILITY BY PRIME NUMBERS while index < len(primes) and primes[index] < sqrt(number) + 1: # DIVISIBLE BY OTHER PRIME -> NOT PRIME if number % primes[index] == 0: is_prime = False break index += 1 # IF NOT DIVISIBLE BY OTHER PRIMES -> APPEND TO PRIMES if is_prime: primes.append(number) return primes #-----------------------------------------------------------------------------# #---------------------------------- M A I N ----------------------------------# #-----------------------------------------------------------------------------# start_time = time() number = 1000 # FIND PRIMES BELOW 'number' primes = primes(number) # FIND 'MIRPTALL' AMONG PRIMES mirptall = mirptall(primes) print('Result:', len(mirptall)) print('Time:', time() - start_time)
true
db545519dc14cf85b7b0a0b7c146974958756205
pipa0979/barbell-squats
/Singly Linked List/Insertion/LL-Insertion-end.py
1,746
4.28125
4
# Purpose - to add node to the end of the list. class Node(object): def __init__(self, val): self.data = val self.next = None class LinkedList(object): # Head, Tail in a new LL will point to None def __init__(self): self.head = None self.tail = None def isEmpty(self): if self.head==None: return True else: return False def status(self): if self.isEmpty(): print "Empty!! No Status!" return else: print "Head --> {}".format(self.head.data) print "Tail --> {}".format(self.tail.data) # Print the LL def traverse(self): node = self.head if node == None: print "Empty Linked List" else: while node.next != None: print "{} -->".format(node.data), node = node.next print "{} --> |".format(node.data) # Adding the new node to the end of the list. # the head pointer will stay constant # the tail pointer will move to the new node. def addEnd(self, val): new_node = Node(val) if self.head == None: self.head = new_node self.tail = new_node self.head.next = None return True else: self.tail.next = new_node # ask why self.tail = new_node new_node.next = None return True LL = LinkedList() LL.status() LL.traverse() for each in xrange(6): if LL.addEnd(each): print "{} added at the end!".format(each) else: print "{} not added :(".format(each) LL.status() LL.traverse()
true
8d90eb725e1b93cafb1f814f531052d52f7db673
emcguirk/atbs
/Chapter 7/strongPass.py
573
4.1875
4
import re import pyperclip # Regexes for each requirement: hasLower = re.compile(r'[a-z]') hasUpper = re.compile(r'[A-Z]') hasNumber = re.compile(r'[0-9]') def isStrong(pwd): assert type(pwd) == str lower = hasLower.findall(pwd) upper = hasUpper.findall(pwd) number = hasNumber.findall(pwd) if len(lower) < 1 or len(upper) < 1 or len(number) < 1: print('Password is not strong enough. Make sure to include all required characters') if len(pwd) < 8: print('Password is not strong enough. Please enter at least 8 characters') else: print('Password is strong')
true
159c7cf258c708281d9f1cc17d48e9f871f0ece8
jakubwosko/Algorithms
/number_of_bits.py
792
4.1875
4
########################################################## # Several ways to count bits in Python 3.6 # JW 2018 ########################################################## # classic bit shift def number_of_bits1(n): x = 0 while n > 0: x += n & 1 n >>= 1 return x # bin.count method def number_of_bits2(n): x = bin(n).count("1") return x # divide by 2 method def number_of_bits3(n): x = 0 while n > 0: if (n%2 > 0): x = x + 1 n = n//2 return x #for 8 bit number n def number_of_bits4(n): x = 0 for p in range(8): x += (n>>p) & 1 return x # test for 100 (bin: ‭0110 0100‬) print (number_of_bits1(100)) print (number_of_bits2(100)) print (number_of_bits3(100)) print (number_of_bits4(100))
false
f242ca44b241f49b69bd857d106747af2bcf5e2c
mattdrake/pdxcodeguild
/python/fizz_buzz.py
757
4.1875
4
__author__ = 'drake' #reques input from user for any number question = input("Enter a number. ") #created variable for incrementing input from user num = -1 #create loop to count from zero to user input number while question > num: #incrementing by one num += 1 #test if number is a multiple of both 3 and 4 not including zero if num % 3 ==0 and num % 4 == 0 and num != 0: print('\033[1;32mfizzbuzz\033[1;m') #test if number is a multiple of 3 not including zero elif num % 3 == 0 and num != 0: print('\033[1;31mfizz\033[1;m') #test if number is a multiple of 4 not including zero elif num % 4 == 0 and num != 0: print('\033[1;34mbuzz\033[1;m') #otherwise print number incremented else: print(num)
true
742e5d7916310d6be17299e6d47c40c901498635
kebron88/essential_libraries_assignment
/question11.py
941
4.21875
4
import numpy as np import pandas as pd #Do not import any other libraries """ Suppose you have created a regression model to predict some quantity. Write a function that takes 2 numpy arrays that both have the same length, y and y_pred. The function should return the loss between the predicted and the actual values where the losss function is defined here to be loss = 1/N * Sum from i=1 to N (y[i] - y_pred[i])**2 (See sklearn part 1 video for explanation of this loss function) Where N is the number of datapoints. For example if y = array([0.5,1,2,4,8]) and y_pred = array([1,2,3,4,5]), then f(y, y_pred) should return 2.25 """ y = np.array([4,11.5,6,3,8]) y_pred = np.array([7.1,12,5,6.5,5]) def f(y,y_pred): N=len(y) return np.sum((y-y_pred)**2)/N print(f(y,y_pred)) ###########END CODE############### if __name__=='__main__': ######CREATE TEST CASES HERE###### pass ##################################
true
45b12f398d04c8e709bc201c172a499eeae9c852
ttund21/LearningPython
/PythonBrasilExercicios/EstruturaSequencial/Respostas/11_Questao.py
474
4.21875
4
# 11. Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: # A. o produto do dobro do primeiro com metade do segundo . # B. a soma do triplo do primeiro com o terceiro. # C. o terceiro elevado ao cubo. num = [] for i in range(3): inpNum = int(input(f'Escreva o {i + 1}º número: ')) num.append(inpNum) print(f'Letra A: {(2 * num[0]) + (num[1] / 2)}') print(f'Letra B: {(3 * num[0]) + num[2]}') print(f'Letra C: {num[2] ** 3}')
false
c5e14dd3bb3bd198c4d732330af9032436e6e1e8
ttund21/LearningPython
/PythonBrasilExercicios/EstruturaDeDecisao/Respostas/2_Questao.py
203
4.15625
4
# 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. valor = int(input('Escreva uma valor: ')) if valor < 0: print('Negativo') else: print('Positivo')
false
a89b7beb4621c92bb11042bc38315ec76cf2f519
ttund21/LearningPython
/PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/11_Questao.py
248
4.125
4
# 11. Altere o programa anterior para mostrar no final a soma dos números. num1 = int(input('Número 1: ')) num2 = int(input('Número 2: ')) soma = 0 for i in range(num1 + 1, num2): soma += i print(i, end=' ') print(f'\nSoma: {soma}')
false
bf80df161b39f16e53a395e5ac177afca976a262
Mujju-palaan/Python
/loopswithlist39.py
201
4.15625
4
numbers = [1,2,3,4,5,6,7,8,9,10] for i in range(0,len (numbers)): print(numbers[i]) for i in range(0,len (numbers),2): print(numbers[i]) for i in range(0,len (numbers),3): print(numbers[i])
false
69ba98a8c14e62037d3016662fc7d6e571187c67
LukeG-dev/CIS-2348
/homework1/3.18.py
888
4.21875
4
# Luke Gilin import math wall_H = float(input("Enter wall height (feet):\n")) wall_W = float(input("Enter wall width (feet):\n")) wall_A = wall_H * wall_W # Calculate wall area print("Wall area:", '{:.0f}'.format(wall_A), "square feet") paintNeeded = wall_A / 350 # Calculate Paint needed for wall print("Paint needed:", '{:.2f}'.format(paintNeeded), "gallons") cansNeeded = math.ceil(paintNeeded) # Rounds up the paint gallons needed to the nearest integer print("Cans needed:", cansNeeded, "can(s)\n") paintColor = input("Choose a color to paint the wall:\n") paintColors = {'red': 35, 'blue': 25, 'green': 23} # create dic of paint colors and prices colorPrice = paintColors[paintColor] * cansNeeded # multiply number of cans by the price of that color print('Cost of purchasing {color} paint: ${price}'.format(color=paintColor, price=colorPrice))
true
5226c99becd7721dcced90cd85b26526fa8880c8
ashish-dalal-bitspilani/python_recipes
/python_cookbook/edition_one/Chapter_One/recipe_two.py
597
4.625
5
# Chapter 1 # Section 1.2 # Swapping values without using a temporary variable # Python's automatic tuple packing (happens on the right side) # and unpacking are used to achieve swap readily a,b,c = 1,2,3 print("pre swap values") print('a : {}, b : {}, c : {}'.format(a,b,c)) a,b,c = b,c,a print("post swap values") print('a : {}, b : {}, c : {}'.format(a,b,c)) # Tuple packing, done using commas, on the right hand side and # sequence (tuple) unpacking, done by placing several comma-separated # targets on the lefthand side of a statement, are both useful, simple # and general mechanisms
true
43ab394f43b06ace4fffb0b09c18d01c04c0b962
CruzAmbrocio/python-factorial
/application.py
1,161
4.28125
4
"""This program calculates a Fibonacci number""" import os def fib(number): """Generates a Fibonacci number.""" if number == 0: return 0 if number == 1: return 1 total = fib(number-1) + fib(number-2) return total def typenum(): """Function that allows the user to enter a number.""" while True: try: num = int(raw_input(" >*Enter a number: ")) print "" print "Fibonacci in position", str(num), ":" print fib(num) new() break except ValueError: print " Please enter a valid number!" def new(): """It allows entering a new number.""" question = raw_input("Do you want to type another number? y/n ") questlow = question.lower() if questlow == "y" or questlow == "yes": typenum() elif questlow == "n" or questlow == "not": os.system("exit") else: print "Type 'y' or 'n'" new() print "" print " ----> *Fibonacci number* <----" print "" print "/*Enter a number, and the fibonacci number in the given position is displayed." print "" typenum()
true
95c11512136c758f51ae686b4ac904be82f361ee
Lcarera/Trabajo-Practico-1
/ej4y5.py
1,202
4.3125
4
"""El programa da 3 opciones. Dependiendo de la opcion elegida pide la temperatura y la devuelva convertida, o devuelve una tabla de conversion.""" def conversorC(f): """Convierte grados Celsius a Fahrenheit.""" Celsius= (f-32)*5/9 return "{0:.2f}".format(Celsius) def conversorF(c): """Convierte grados Fahrenheit a Celsius.""" Fahrenheit= (9/5) * c + 32 return "{0:.2f}".format(Fahrenheit) #"{0:.2f}".format sirve para mostrar solo los dos primeros numeros despues de la coma. def tablaConversion(): f = 0 while f <= 120: """Imprime una tabla de conversion entre grados Fahrenheit y Celsius.""" print(f"{f} °F son {conversorC(f)} °C.") f = f + 10 conversion=(input(""" 1. Convertir Fahrenheit a Celsius. 2. Convertir Celsius a Fahrenheit. 3. Tabla de conversion. """)) if conversion == "1" : temp=float(input("Ingrese la temperatura a convertir: ")) print(f"{temp}°F son {conversorC(temp)}°C.") elif conversion == "2" : temp=float(input("Ingrese la temperatura a convertir: ")) print(f"{temp}°C son {conversorF(temp)}°F.") elif conversion == "3" : tablaConversion() else: print("Ingrese un valor valido.")
false
29322f2c5a750b532c5faccb5549d29841bd5b14
miku/khwarizmi
/sorting/median.py
645
4.21875
4
#!/usr/bin/env python # coding: utf-8 """ Swap the median element with the middle element. Create two smaller problems, solve these. Subproblems: Find the median of an unsorted list efficiently. """ def sort(A): medianSort(A, 0, len(A)) def medianSort(A, left, right): if left > right: # find median A[me] in A[left:right] mid = math.floor((right + left) / 2) A[mid], A[me] = A[me], A[mid] for i in range(mid): if A[i] > A[mid]: # find A[k] <= A[mid], where k > mid A[i], A[k] = A[k], A[i] medianSort(A, left, mid) medianSort(A, mid, right)
true
1771618b573a48c8f0c19fbce9d50bf705fd481e
joedo29/Self-Taught-Python
/NestedStatementsAndScope.py
1,367
4.46875
4
# Author Joe Do # Nested Statement and Scope in Python ''' It is important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is stored in a *name-space*. Variable names also have a *scope*, the scope determines the visibility of that variable name to other parts of your code. ''' # Example: x = 25 def printer(): x = 50 return x print(x) # print 25 print(printer()) # print 50 #Enclosing function locals. # This occurs when we have a function inside a function (nested functions) name = 'This is a global name' def greet(): # Enclosing function name = 'Sammy' def hello(): print ('Hello ' + name) hello() greet() # #Local Variables When you declare variables inside a function definition, # they are not related in any way to other variables with the same names used outside the function x = 50 def func(x): print ('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is still', x) # Global statement is used to declare that y if global var y = 50 def func(): global y print('This function is now using the global y!') print('Because of global y is: ', y) y = 2 print('Ran func(), changed global y to', y) print('Before calling func(), y is: ', y) print(func()) print('Value of y (outside of func()) is: ', y)
true
072ad3929e779ef840bc40875ff1eccaf7e55c1a
joedo29/Self-Taught-Python
/Files.py
1,452
4.65625
5
# Joe Do # Python uses file objects to interact with external files on your computer. # These file objects can be any sort of file you have on your computer, # whether it be an audio file, a text file, emails, Excel documents, etc. # Note: You will probably need to install certain libraries or modules to interact with those various file types, # but they are easily available. # Python has a built-in open function that allows us to open and play with basic file types. # We're going to use some iPython magic to create a text file! # Open the phonebook.txt file my_file = open('phonebook.txt') # Read a file using read() function # after you read, the cursor is now at the end of the file # meaning you can't read the file again unless you seek print(my_file.read()) # Seek to the start of file (index 0) so you can read the file again my_file.seek(0) print(my_file.read()) # readlines() returns a list of the lines in the file # readlines() avoid having to reset cursor every time my_file.seek(0) print() print('The first line of the file is {p}'.format(p=my_file.readline())) # ITERATING THROUGH A FILE for line in open('phonebook.txt'): print(line) # WRITING TO A FILE # By default, using the open() function will only allow us to read the file, # we need to pass the argument 'w' to write over the file. For example: my_file = open('phonebook.txt', 'w+') # now write to my_file my_file.write('JOE DO 123456') print(my_file.read())
true
516defd5b62da3eb06cacfaddbd7e33b48c267f8
shilpa5g/Python-Program-
/python_coding_practice/leap_year.py
290
4.3125
4
# program to check a year is leap year or not year = int(input("enter a year: ")) if(year % 400 == 0): print(year,"is a leap year.") elif(year % 100 == 0): print(year,"is not a leap year.") elif(year % 4 == 0): print(year,"is a leap year.") else: print(year,"is not a leap year.")
false
0230151c53ea3f13baa6b353e2c9108452b1edff
shilpa5g/Python-Program-
/python_coding_practice/sum_of_series.py
276
4.25
4
# program to find Sum of natural numbers up to given range terms = int(input("Enter the last term of the series: ")) if terms < 0: print("please enter a positive number.") else: sum = 0 for i in range(1, terms+1): sum +=i print('sum of series = ',sum)
true
55084a7529445303cf7dc531022ee39ab52613d2
shilpa5g/Python-Program-
/python_coding_practice/palindrome.py
246
4.5625
5
# Program to check if a string is palindrome or not string = str(input("enter a string: ")) rev_str = reversed(string) if list(string) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.")
true