blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
31f01f01b4e5abec5c6bb6e42ec704047b78d42e
DLaMott/Calculator
/com/Hi/__init__.py
826
4.125
4
def main(): print('Hello and welcome to my simple calculator.') print('This is will display different numerical data as a test.') value = float(input("Please enter a number: ")) value2 = float(input("Please enter a second number: ")) print('These are your two numbers added together: ', (float(value)) + (float(value2))) print('These are your two numbers subtracted: ', (float(value) - (float(value2)))) print('These are your two numbers multiplied: ', (float(value) * (float(value2)))) print('These are your two numbers divided: ', (float(value)) / (float(value2))) restart = input("Do you want to restart? [y/n] >") if restart== 'y': main() else: print('Thank you, Goodbye.') exit main()
true
acf4f9abb3deab9bf3752aae70ac76537f66b92f
GunterBravo/Python_Institute
/2_1_4_10_Lab_Operadores.py
914
4.125
4
''' Escenario Observa el código en el editor: lee un valor flotante, lo coloca en una variable llamada x, e imprime el valor de la variable llamada y. Tu tarea es completar el código para evaluar la siguiente expresión: 3x3 - 2x2 + 3x - 1 El resultado debe ser asignado a y. Recuerda que la notación algebraica clásica muy seguido omite el operador de multiplicación, aquí se debe de incluir de manera explicita. Nota como se cambia el tipo de dato para asegurarnos de que x es del tipo flotante. Mantén tu código limpio y legible, y pruébalo utilizando los datos que han sido proporcionados. No te desanimes por no lograrlo en el primer intento. Se persistente y curioso.''' print("Se resuelve la expresión algebraica") print("3x-exp3 - 2x-exp2 + 3x - 1") print("El resultado se va asignar a y") x = float(input("Ingresa un valor para x: ")) y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1 print("y = ", y)
false
e48382f4282df95b1f268af7648eec1c885cef18
viticlick/PythonProjectEuler
/archive1.py
331
4.3125
4
#!/usr/bin/python """If we list all the natural numbers below 10 that are multiples of 3 or 5 \ we get 3, 5, 6 and 9. The sumof these multiples is 23.\ \ Find the sum of all the multiples of 3 or 5 below 1000.""" values = [ x for x in range(1,1001) if x % 3 == 0 or x % 5 == 0] total = sum(values) print "The result is", total
true
487cc4e6bcbe699a56e2c448cd2d0ad969b75579
TYakovchenko/GB_Less3
/less3_HW3.py
1,196
4.25
4
##3. Реализовать функцию my_func(), # которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. #Первый вариант def my_func(arg1, arg2, arg3): if arg1 >= arg3 and arg2 >= arg3: return arg1 + arg2 elif arg1 > arg2 and arg1 < arg3: return arg1 + arg3 else: return arg2 + arg3 print("Первый вариант реализации:") arg1 = int(input("Первое значение: ")) arg2 = int(input("Второе значение: ")) arg3 = int(input("Третье значение: ")) print(my_func(arg1, arg2, arg3)) ##Второй вариант def my_func2(arg4, arg5, arg6): range_1 = [arg4, arg5, arg6] total = [] max_1 = max(range_1) total.append(max_1) range_1.remove(max_1) max_2 = max(range_1) total.append(max_2) print(sum(total)) print("Второй вариант реализации:") my_func2(arg4 = int(input("Первое значение: ")), arg5 = int(input("Второе значение: ")),arg6 = int(input("Третье значение: ")))
false
a11e6981301bbdc6a6f55ac7853598ad3b61ede9
BenjaminFu1/Python-Prep
/square area calculator.py
205
4.1875
4
length=float(input("Give me the lenth of your rectangle")) width=float(input("Give me the width of your rectangle")) area=(length) * (width) print("{0:.1f} is the area of your rectangle".format(area))
true
3f620cb320f89f4e0f19bd2d09a30a9b9402b98f
tu-nguyen/linkedinlearning
/Master Python for Data Science/Python Essential Training 1/Chap11/hello.py
453
4.15625
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ # print('Hello, World.'.swapcase()) # print('Hello, World. {}'.format(42 * 7)) # print(""" # Hello, # World. # {} # """.format(42 * 7)) # s = 'Hello, World. {}' # print(s.format(42 * 7)) # class MyString(str): # def __str__(self): # return self[::-1] # s = MyString('Hello, World.') # print(s) x = 42 # y = 73 print(f"The number is {x:.3f}") # .format(x))
false
866c36768b1363d7cd4adef7212458a470e6b0fd
kayshale/ShoppingListApp
/main.py
1,196
4.1875
4
#Kayshale Ortiz #IS437 Group Assignment 1: Shopping List App menuOption = None mylist = [] maxLengthList = 6 menuText = ''' 1.) Add Item 2.) Print List 3.) Remove item by number 4.) Save List to file 5.) Load List from file 6.) Exit ''' while menuOption != '6': print(menuText) menuOption = input('Enter Selection\n') print(menuOption) if menuOption == '1': #print('Add Item') item = '' while item == '': item = input("Enter your new item: ") mylist.append(item) #temp = input('Enter Item\n') #mylist.append(temp) print(mylist) elif menuOption == '2': #print(mylist) n = 1 for item in mylist: print (str(n) + ".)" + item) n+=1 #print(mylist) elif menuOption == '3': req = None while req == None: req = input('Enter item number to delete\n') index = None try: index = int(req) - 1 except: print('Invalid Selection') if index >= 0 and index <= 5: del(mylist[index]) else: print('Your selection was not recognized')
true
b0b67fba426642ef56a1cfa5d5e6a65a0286dacb
Rhysoshea/daily_coding_challenges
/other/sort_the_odd.py
612
4.3125
4
''' You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] ''' def sort_array(source_array): odds = [x for x in source_array if x%2!=0] return [x if x%2==0 else odds.pop() for x in source_array ] assert sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] assert sort_array([5, 3, 1, 8, 0]) == [1, 32, 5, 8, 0] assert sort_array([]) ==[] # sort_array([5, 3, 2, 8, 1, 4])
true
6a02c3fe5111ddf6690e5a060a543164b2db0563
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily25.py
1,686
4.5
4
""" Implement regular expression matching with the following special characters: . (period) which matches any single character * (asterisk) which matches zero or more of the preceding element That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression. For example, given the regular expression "ra." and the string "ray", your function should return true. The same regular expression on the string "raymond" should return false. Given the regular expression ".*at" and the string "chat", your function should return true. The same regular expression on the string "chats" should return false. """ def solution(input, regex): regex_alpha = ''.join([x for x in regex if x.isalpha()]) if not regex_alpha in input: return False regex_split = regex.split(regex_alpha) input_split = input.split(regex_alpha) # print (regex_split) # print (input_split) for i, j in zip(regex_split, input_split): if not len(i) == len(j): if '*' in i: if '.' in i: return False continue return False return True def test(input, regex, ans): assert (solution(input, regex) == ans) str1 = "ray" regex1 = "ra." str2 = "raymond" regex2 = ".*at" str3 = "chat" str4 = "chats" str5 = "at" regex3 = ".at" regex4 = "*at." print (solution(str4, regex2)) test(str1, regex1, True) test(str2, regex1, False) test(str3, regex2, True) test(str4, regex2, False) test(str5, regex2, False) test(str5, regex3, False) test(str4, regex4, True) test(str3, regex3, False) test(str3, regex4, False)
true
be3a184aecc35085a7d69bc447eeaf99d5c2320b
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily44.py
1,329
4.1875
4
# We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. # Given an array, count the number of inversions it has. Do this faster than O(N^2) time. # You may assume each element in the array is distinct. # For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. def mergeSort(left, right): counter = 0 newArr = [] while left and right: if right[0] < left[0]: newArr.append(right[0]) del right[0] counter += len(left) else: newArr.append(left[0]) del left[0] newArr.extend(left) newArr.extend(right) return newArr, counter def solution (arr, counter): if len(arr)==1: return arr,0 n = len(arr)//2 leftArr,leftCount = solution(arr[:n], counter) rightArr,rightCount = solution(arr[n:], counter) newArr, add = mergeSort(leftArr, rightArr) counter=add+leftCount+rightCount return newArr, counter print (solution([5,4,3,2,1], 0)) print (solution([2,4,1,3,5], 0))
true
0f01a1e6aa57c4ed9dccf237df27db0465bae2cc
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily27.py
848
4.15625
4
""" Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). For example, given the string "([])[]({})", you should return true. Given the string "([)]" or "((()", you should return false. """ def solution(input): stack = [] open = ["{", "(", "["] close = ["}", ")", "]"] matcher = dict(zip(close,open)) for i in input: # print (stack) if i in open: stack.append(i) elif i in close: if not stack: return False if stack.pop() != matcher.get(i): return False return len(stack) == 0 def test(input, ans): assert (solution(input) == ans) input1 = "([])[]({})" input2 = "([)]" input3 = "((()" test(input1, True) test(input2, False) test(input3, False)
true
593e4d4643c9d81098828b22bc68e46c373ffa2c
pbuzzo/backend-katas-functions-loops
/main.py
1,858
4.375
4
#!/usr/bin/env python """Implements math functions without using operators except for '+' and '-' """ """ """ __author__ = "Patrick Buzzo" def add(x, y): new_num = x + y return new_num def multiply(x, y): new_num = 0 if y >= 0: for index in range(y): new_num += x else: for index in range(-y): new_num -= x return new_num # new_num = 0 # count = 0 # if (x < 0) and (y >= 0): # while count < y: # new_num = new_num + x # count += 1 # elif (x >= 0) and (y < 0): # y = -y # while count < y: # new_num = new_num + x # count += 1 # elif (x >= 0) and (y >= 0): # while count < y: # new_num = new_num + x # count += 1 # elif (x < 0) and (y < 0): # x = -x # y = -y # while count < y: # new_num = new_num + x # count += 1 # return new_num def power(x, n): """Raise x to power n, where n >= 0""" if n == 0: return 1 elif x == 0: return 0 else: new_num = x if n == 1: return x else: for index in range(n-1): new_num = multiply(new_num, x) return new_num def factorial(x): """Compute factorial of x, where x > 0""" new_num = x if x == 0 or x == 1: return 1 if x > 1: count = x - 1 while count > 0: new_num = multiply(new_num, count) count -= 1 return new_num def fibonacci(n): """Compute the nth term of fibonacci sequence Resources: http://bit.ly/2P5asH2 , http://bit.ly/2vOJDji """ a, b = 0, 1 for index in range(n): a, b = b, a + b return a if __name__ == '__main__': # your code to call functions above pass
false
8e3f51ca47d9937f5aae6b56f81bfdba273d3336
shreyashetty207/python_internship
/Task 4/Prb1.py
616
4.28125
4
#1. Write a program to create a list of n integer values and do the following #• Add an item in to the list (using function) #• Delete (using function) #• Store the largest number from the list to a variable #• Store the Smallest number from the list to a variable S = [1, 2, 3,4] S.append(56) print('Updated list after addition: ', S) (S .pop(2)) print('Updated list after deletion:',S) # sorting the list S.sort() # printing the largest element print(" Largest element ,x=", max(S)) # sorting the list S.sort() # printing the smallest element print("Smallest element, y=", min(S))
true
55dca8c77d3eed88301fd93979dbd1b6b4ad657f
brityboy/python-workshop
/day2/exchange.py
2,914
4.125
4
# def test(): # return 'hello' # this is the game plan # we are going to make # a function that will read the data in # built into this, we are going to make functions that # 1. creates a list of the differences <- we will use from collections # Counter in order to get the amounts # 2. We are going to create a function MAX that gets the max differences # and saves the date # 3. Clearly, we need a function that will read the data # 4. and a function that will hold all of the other functions and # print everything properly # def exchange_rate_csv_reader(filename): # ''' # INPUT: csv file of exchange rate data # OUTPUT: list of changes between exchange rates day to day # this file skips bank holidays # ''' # with open(filename) as f: # result = [] # line_info = [] # todaysrate = 0 # for i, line in enumerate(f): # if 'Bank holiday' not in line: # line_info = line.replace(',', ' ').split() # if i == 4: # todaysrate = round(float(line_info[2]), 2) # elif i > 4 and len(line_info)==4: # result.append(round(todaysrate - round(float(line_info[2]), 2), 2)) # todaysrate = round(float(line_info[2]), 2) # return result def exchange_rate_csv_reader(filename): ''' INPUT: csv file of exchange rate data OUTPUT: list of changes between exchange rates day to day this file skips bank holidays ''' with open(filename) as f: differences = [] dates = [] line_info = [] result = [] todaysrate = 0 for i, line in enumerate(f): if 'Bank holiday' not in line: line_info = line.replace(',', ' ').split() if i == 4: todaysrate = round(float(line_info[2]), 2) elif i > 4 and len(line_info)==4: differences.append(round(todaysrate - round(float(line_info[2]), 2), 2)) dates.append(line_info[0]) todaysrate = round(float(line_info[2]), 2) result.append(differences) result.append(dates) return result def summarize_csv_info(list): ''' INPUT: list of exchange rate differences OUTPUT: summarized count information as a string ''' from collections import Counter info_dict = dict(Counter(list[0])) sortedkeys = sorted(info_dict.keys()) result = '' print_line = '{}: {}\n' for key in sortedkeys: result += print_line.format(key, info_dict[key]) return result def get_max_change(list): ''' INPUT: list of lists where list[0]=inter-day changes and list[1]=date OUTPUT: string indicating max change and date of max change ''' max_change = max(list[0]) indices = [i for i, x in enumerate(list[0]) if x == max_change] for index in indices:
true
e71f1186e900a609cfba091f9b972f80222a0a3b
linaresdev/cursoPY3
/src/practicing/job1/item_3.py
416
4.15625
4
# Realizar un programa en Python que calcule el peso molecular (peso por cantidad de atomos solicitado # por teclado) de una molecula compuesta de dos elementos print("CARCULADORA DE PESO MOLECULAR"); peso = ( float(input("Introdusca peso del elemento a calcular:")) * int(input("Indique la cantidad del elemento espesificado:")) ) print("Peso total de la cantidad del elemento espesificado es:", peso, "g/mol" )
false
178592a57ce09b002482bc4e7638d25730b323ce
Smrcekd/HW070172
/L03/Excersise 4.py
385
4.34375
4
#convert.py #A program to convert Celsius temps to Fahrenheit #reprotudcted by David Smrček def main(): print("This program can be used to convert temperature from Celsius to Fahrenheit") for i in range(5): celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = 9/5*celsius+32 print("The temperature is", fahrenheit, "degrees Fahrenheit.") main()
true
ac4e2b8034d0c78d302a02c03fdb45ecb3026b56
Smrcekd/HW070172
/L04/Chapter 3/Excersise 15.py
421
4.21875
4
# Program approximates the value of pi # By summing the terms of series # by David Smrček import math#Makes the math library available. def main(): n = eval(input("Number of terms for the sum: ")) x = 0 m = 1 for i in range (1,2 * n + 1, 2): x = x + (m *4/i) m = -m result = math.pi - x print("The approximate value of pi is: ", result) main()
true
1c0caaffdef74eb1911756360307908310c811b2
laviniabivolan/Spanzuratoarea
/MyHangman.py
2,394
4.125
4
import random def guess_word(): list_of_words = ["starwards", "someone", "powerrangers", "marabu", "mypython", "wordinthelist", "neversurrender"] random_word = random.choice(list_of_words) return random_word def hangman_game(): alphabet = 'abcdefghijklmnoprstuvwxyqz' word = guess_word() lifes = 5 guesses = [] print('The word contains {} letters'.format(len(word))) game_over = False while game_over == False and lifes > 0: print('-' * 25) print('You have {} tries'.format(lifes)) print('-' * 25) user_word = input('Introduce one letter or entire word: ').lower() print('-' * 25) if len(user_word) == 1: if user_word not in alphabet: print('Your input is not correct, must to be alphabetic!') elif user_word in guesses: print('You have already introduced that letter') elif user_word not in word: print('Was not the right guess!') guesses.append(user_word) lifes -= 1 elif user_word in word: print('You got it!') guesses.append(user_word) else: print('Try again...') elif len(user_word) == len(word): if user_word == word: print('Your guessed was ok!') game_over = True else: print('Your guessed was not ok!') lifes -= 1 else: print('Your length of input is not ok') strcuture_of_word = '' for letter in word: if letter in guesses: strcuture_of_word += letter else: strcuture_of_word += '_' print(strcuture_of_word) if strcuture_of_word == word: print('Congrat! You won the game!') game_over = True try_again() elif lifes == 0: print('You lost the game!!!!!') game_over = True try_again() def try_again(): user_choose = input('Do you want to play again? y/n: ') print('-' * 25) if user_choose == 'y': hangman_game() else: print('Have a nice day!') quit() if __name__ == '__main__': hangman_game()
true
efcb63ba80b697680a8b907923bcbcdc609ae94e
Wmeng98/Leetcode
/Easy/merge_2_sorted_lists.py
1,295
4.21875
4
# Solution 1 - Recursive Approach # Recursivelly define the merge of two lists as the following... # Smaller of the two head nodes plus to result of the merge on the rest of the nodes # Time 0(n+m) and Space O(n+m) -> first recursive call doesn't return untill ends of l1 && l2 have been reached # Solution 2 - Iterative Approach # Can achieve the same idea via iteration # Insert elements of l2 in necessary places of l1 # Need to setup... # A false prehead to return the head of merged list # prev - node we will be adjusting the next ptr of # Stop comparison until one of l1 or l2 points to null # Time O(n+m) Space O(1) - only alloc a few pointers # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ prehead = ListNode(-1) prev = prehead while l1 and l2: if l1.val < l2.val: prev.next = l1 l1 = l1.next else: prev.next = l2 l2 = l2.next prev = prev.next # connect non-null list to end of merged list prev.next = l1 if l1 is not None else l2 return prehead.next
true
ff234acf470b12fe21ee41df3d2a2cf69bd0af91
tejalbangali/HackerRank-Numpy-Challenge
/Arrays.py
502
4.40625
4
# Task: # --> You are given a space-separated list of numbers. Your task is to print a reversed NumPy array with the element type float. # -> Input Format: A single line of input containing space-separated numbers. # -> Sample Input: 1 2 3 4 -8 -10 # -> Sample Output: [-10. -8. 4. 3. 2. 1.] import numpy def arrays(arr): arr=numpy.array(arr) arr=arr.astype(float) result=arr[::-1] return result arr = input().strip().split(' ') result = arrays(arr) print(result)
true
83243d09a2140da62c7a572d2d887e879801e104
victordity/PythonExercises
/PythonInterview/binarySearch.py
1,029
4.21875
4
import bisect def bisect_tutorial(): fruits = ["apple", "banana", "banana", "banana", "orange", "pineapple"] print(bisect.bisect(fruits, "banana")) print(bisect.bisect_left(fruits, "banana")) occurrences = bisect.bisect(fruits, "banana") - bisect.bisect_left(fruits, "banana") print(occurrences) # Number of occurrences of the word banana bisect.insort_left(fruits, "kiwi") print(fruits) def binary_iterative(elements, search_item): """Return the index of the search_item element.""" left, right = 0, len(elements) - 1 while left <= right: middle_idx = (left + right) // 2 middle_element = elements[middle_idx] if middle_element == search_item: return middle_idx if middle_element < search_item: left = middle_idx + 1 elif middle_element > search_item: right = middle_idx - 1 return None if __name__ == '__main__': elements = [3, 4, 5, 5, 9] a = binary_iterative(elements, 5) print(a)
true
38200fdf05a7f80e7bce3773a0f954ec8e3e67f0
vfperez1/AdivinaNumero
/entrada/menu.py
744
4.125
4
""" Módulo que agrupa todas las funcionalidades que permiten pedir entrada de números """ import sys def pedirNumeroEntero(): correcto = False num = 0 while (not correcto): try: num = int(input("Eliga una opción del 1 al 4: ")) correcto = True except ValueError: print('Error, introduce un número entero', file=sys.stderr) return num def pedirNumeroJuego(): correcto = False num = 0 while (not correcto): try: num = int(input("Introduzca un número: ")) correcto = True except ValueError: print('Error, introduce un número entero', file=sys.stderr) return num
false
4d51b16c7673470425579525742dd537470e48b9
loide/MITx-6.00.1x
/myLog.py
841
4.46875
4
''' This program computes the logarithm of a number relative to a base. Inputs: number: the number to compute the logarithm base: the base of logarithm Output: Logarithm value [ log_base (number) ] ''' def myLog(number, base): if ( (type(number) != int) or (number < 0)): return "Error: Number value must be a positive integer." if ( (type(base) != int) or (base < 2)): return "Error: Base value must be an integer greater than or equal 2." return recursiveRad(number, base) def recursiveRad(number, base): if base > number: return 0 if number <= 1: return 0 else: return 1 + recursiveRad(number/base, base) if __name__ == "__main__": number = int(raw_input('Insert a number: ')) base = int(raw_input('Insert the base value: ')) print myLog(number, base)
true
579e0da0253ec03a4583ba2288b552b72c0d5ced
anweshachakraborty17/Python_Bootcamp
/P48_Delete a tuple.py
295
4.15625
4
#Delete a tuple thistuple1 = ("apple", "banana", "mango") del thistuple1 print(thistuple1) #this will raise an error because the tuple no longer exists #OUTPUT window will show: #Traceback (most recent call last): File "./prog.py", line 3, in NameError: name 'thistuple1' is not defined
true
5cf51d431c50db3886d1daa7c5dc07ea19e133f7
harsh4251/SimplyPython
/practice/oops/encapsulation.py
543
4.4375
4
class Encapsulation(): def __init__(self, a, b, c): self.public = a self._protected = b self.__private = c print("Private can only be accessed inside a class {}".format(self.__private)) e = Encapsulation(1,2,3) print("Public & protacted can be access outside class{},{} ".format(e.public,e._protected)) """Name Notation Behaviour name Public Can be accessed from inside and outside _name Protected Like a public member, but they shouldn't be directly accessed from outside. __name Private Can't be seen and accessed from outside"""
true
259e6161b173cb9975c55427158b13f76750e059
c42-arun/coding-challenges-python
/src/max_product_of_3_ints/solution_2.1.py
1,772
4.125
4
''' Greedy approach - 1 loops - O(1) space (or O(n)?) - O(n) time - considers only +ve ints ''' def pushDownValues(items, fromIndex): print(f"Before push: {items[0]}, {items[1]}, {items[2]}: {fromIndex}") for i in range(len(items) - 1, fromIndex, -1): print(f"{i - 1} -> {i}") items[i] = items[i-1] print(f"After push: {items[0]}, {items[1]}, {items[2]}: {fromIndex}") int_list = [-15, -10, 7, 8, 5, 11, 12, 9] max_list = int_list[:3] max_list.sort(reverse = True) print(f"Initial values: {max_list[0]}, {max_list[1]}, {max_list[2]}") print("-------------------------------------") for i in range(len(int_list)): current_value = int_list[i] print(f"Begin iteration values: {max_list[0]}, {max_list[1]}, {max_list[2]}; {current_value}") # if we already have the number in the max list then skip if (current_value in max_list): continue # we cannot use >= because if the item is already in max_list (for eg the initial values) # then we'll still push down values # if we use > then make sure we check for 'current_value in max_list' above - otherwise # when current_value equals one of the values it is checked against next one and might # be added again if (current_value > max_list[0]): pushDownValues(max_list, 0) max_list[0] = current_value elif (current_value > max_list[1]): pushDownValues(max_list, 1) max_list[1] = current_value elif (current_value > max_list[2]): max_list[2] = current_value print(f"End iteration values: {max_list[0]}, {max_list[1]}, {max_list[2]}; {current_value}") print("-------------------------------------") print(f"Final values: {max_list[0]}, {max_list[1]}, {max_list[2]}")
false
0b2deb15577ba07a878f00d91eee617d48605bec
beekalam/fundamentals.of.python.data.structures
/ch02/counting.py
583
4.15625
4
""" File: counting.py prints the number of iterations for problem sizes that double, using a nested loop """ if __name__ == "__main__": problemSize = 1000 print("%12s%15s" % ("Problem Size", "Iterations")) for count in range(5): number = 0 #The start of the algorithm work = 1 for j in range(problemSize): for k in range(problemSize): number += 1 work += 1 work -= 1 # the end of the algorithm print("%12d%15d" % (problemSize, number)) problemSize *= 2
true
8e19018571298372b73695afb9139596e1524464
MITRE-South-Florida-STEM/ps1-summer-2021-luis-c465
/ps1c.py
1,706
4.125
4
annual_salary = float(input("Enter the starting salary:​ ")) total_cost = 1_000_000 semi_annual_raise = .07 portion_down_payment = 0.25 r = 0.04 # Return on investment total_months = 0 current_savings = 0.0 def down_payment(annual_salary: int, portion_saved: float, total_cost: int, portion_down_payment: float, r: float, semi_annual_raise: float, semi_annual_raise_after = 6 ) -> int: total_months = 0 current_savings = 0.0 while total_cost * portion_down_payment > current_savings: if total_months != 0 and (total_months % semi_annual_raise_after) == 0: annual_salary *= 1 + semi_annual_raise return_on_investment = current_savings * (r / 12) investment = (annual_salary / 12) * portion_saved current_savings += return_on_investment + investment total_months += 1 return total_months moths = 36 bisections = 0 low = 0 high = 10_000 high_before = high # ! Lower this value for a more accurate answer / more bisections ! # ! Must be greater than 1 ! epsilon = 3 while abs(low - high) >= epsilon: guess = (high + low) // 2 payment_guess = down_payment(annual_salary, guess / high_before, total_cost, portion_down_payment, r, semi_annual_raise) # print(f"Bisections: {bisections}") # print(f"Payment guess months: {payment_guess}") # print(f"Guess: {guess}\tLow/High: {low}/{high}\n") if moths < payment_guess: low = guess else: high = guess bisections += 1 if high == high_before: print(f"It is not possible to pay the down payment in {moths / 12} years.") else: print(f"Best savings rate:​ {guess / high_before}") print(f"Steps in bisection search:​ {bisections}")
true
ab872a4d32586fe8cb30a77bf6e212a8512d9c11
Andrew7891-kip/python_for_intermediates
/copying.py
918
4.21875
4
import copy # shallow copy # interferes the original org = [[0,1,2,3],[5,6,7,8]] cpy=copy.copy(org) cpy[0][1]=9 print(cpy) print(org) # shallow func copy class Student: def __init__(self,name,age): self.name=name self.age=age p1=Student('Andrew',19) p2 = copy.copy(p1) p2.age=20 print(p1.age) print(p2.age) # deep copy # not interfere the original orgy = [[0,1,2,3],[5,6,7,8]] cpyi=copy.deepcopy(orgy) cpyi[0][1]=9 print(cpyi) print(orgy) # deep copy func class Student: def __init__(self,name,age): self.name=name self.age=age class Company: def __init__(self,boss,employee): self.boss=boss self.employee=employee p1=Student('Andrew',19) p2 = copy.copy(p1) p2.age=20 # shallow copy company=Company(p1,p2) # deep copy company_clone=copy.deepcopy(company) company_clone.boss.age=50 print(company_clone.boss.age) print(company.boss.age)
false
315ace2527ebf89d6e80aea2a47047f0484f5b40
Owensb/SnapCracklePop
/snapcrackle.py
457
4.125
4
# Write a program that prints out the numbers 1 to 100 (inclusive). # If the number is divisible by 3, print Crackle instead of the number. # If it's divisible by 5, print Pop. # If it's divisible by both 3 and 5, print CracklePop. You can use any language. i = [] for i in range (1, 101): if (i % 3 ==0) & ( i % 5 ==0) : print ('CracklePop') elif (i % 5 == 0): print ('Pop') elif (i % 3 ==0) : print ('Crackle') else: print(i)
true
97b2a81aaf57fb021ca6b2c49b7bc925d98ba193
SeonMoon-Lee/pythonStudy
/class.py
1,049
4.25
4
class Human(): '''인간''' #person = Human() #person.name = '철수' #person.weight = 60.5 def create_human(name,weight): person = Human() person.name = name person.weight = weight return person Human.create = create_human person = Human.create("철수",60.5) def eat(person): person.weight+=0.1 print("{}가 먹어서 {}kg이 되었습니다.".format(person.name,person.weight)) def walk(person): person.weight-=0.1 print("{}가 걸어서 {}kg이 되었습니다.".format(person.name,person.weight)) Human.eat = eat Human.walk = walk person.walk() person.eat() ''' class Human(): """사람""" person1 = Human() person2 = Human() person1.language = '한국어' person2.language = 'English' print(person1.language) print(person2.language) person1.name = "서울시민" person2.name = "인도인" def speak(person): print("{}이 {}로 말을 합니다.".format(person.name,person.language)) speak(person1) speak(person2) Human.speak = speak person1.speak() person2.speak() '''
false
0964f1d92b02db0e9f25664c7049d657c3be4549
yy02/test
/Python/Python学习笔记/字符串操作.py
703
4.15625
4
str = 'hello world' # 转换大小写 # print(str.lower()) # print(str.upper()) # 切片操作 # slice[start:end:step] 左闭右开原则,start < value < end # print(str[2:5]) # print(str[2:]) # print(str[:5]) # print(str[::-1]) # 共有方法 # 相加操作,对字符串列表和元组都可以使用 strA = '人生苦短' strB = '我用Python' listA = list(range(10)) listB = list(range(11,20)) # print(strA+strB) # print(listA+listB) # 复制操作 * # print(strA*3) # print(listA*3) # in操作,检测对象是否存在 print('生' in strA) print(9 in listA) dictA = {'name':'zhangsan'} #对于字典判断的是key是否在字典中 print('name' in dictA) print('zhangsan' in dictA)
false
64ba459b0b322274f900e1716496e7643d90bde1
shermansjliu/Python-Projects
/Ceasar Cipher/Ceaser Cipher.py
1,888
4.21875
4
def ReturnEncryptedString(): code = input("Enter in the code you would like to encrypt") code = code.upper() newString = "" tempArr = list(code) for oldChar in tempArr: newString += EncryptKey(oldChar) print(newString) def ReturnDecryptedString(): code = input("Enter in the code you would like to decipher") code = code.upper() newString = "" tempArr = list(code) for oldChar in tempArr: newString += DecodeKey(oldChar) print(newString) def DecodeKey(char): #Create temp array for word #take i element in word array and shift it the ascii number back 5 letters asciiInt = ord(char) tempInt = ord(char) tempInt += 13 #If ascii value is greater than 90 shift the original ascii value back by 26 if(char == "!"): return char elif(char == " "): return char elif(tempInt > 90 ): asciiInt -=13 else: asciiInt += 13 #convert the ascii value to a character using the function chr() char = chr(asciiInt) #Append character to a new string return char def EncryptKey(char): asciiInt = ord(char) tempInt = ord(char) tempInt -= 13 if(char == "!"): return char elif(char == " "): return char elif(tempInt < 64 ): asciiInt +=13 else: asciiInt -= 13 #convert the ascii value to a character using the function chr() char = chr(asciiInt) #Append character to a new string return char def PromptUser(): answer = input("Do you want to decode or encrypt your message?") answer = answer.lower() if(answer == "encrypt"): ReturnEncryptedString() if(answer == "decode"): ReturnDecryptedString() print("This is Ceaser's Cipher") PromptUser() #TODO Convert letter from alphabet 13 spaces or 13 spaces up in Ascii table #Take user's input #Convert
true
48def1c3190fb8e4463f68dd478055621b12e4b6
yooshxyz/ITP
/Feb19.py
1,702
4.125
4
import random # answer = answer.strip()[0].lower() def main(): while True: user_choice_input = int(input("What Function do you want to Use?\nPlease type 1 for the No vowels function, type 2 for the random vowels function, and 3 for the even or odd calculator.\n")) if user_choice_input == 1: vowelLessCommand() elif user_choice_input == 2: randomWords() elif user_choice_input ==3: evenOdd() else: print("Please choose one of those numbers!") user_quit_option = input("If you wise to exit please press X") if user_quit_option.lower() == "x": print("Exiting....") break else: return return def vowelLessCommand(): vowels = ["a","e","i","o","u"] user_input = input("Please input your sentence: ") vowelless = "" for i in user_input: if i not in vowels: if i != vowels: vowelless = vowelless + i print(vowelless) def randomWords(): x = 0 vowels = ["a","e","i","o","u"] user_input2 = input("Please input your sentence: ") randomvalues = "" for i in user_input2: if i in vowels: i = random.choice(vowels) randomvalues += i else: randomvalues += i print(randomvalues) def evenOdd(): user3_input = float(input("Please pick a number.")) if user3_input % 2 == 0: print("The number is even!") else: print("The number is odd!") def addUp(): x = 0 user_number_input = int(input("Pick a number!")) main()
true
a09d239c09374761d9c78ae4cfd872eec416a71c
NishadKumar/leetcode-30-day-challenge
/construct-bst-preorder-traversal.py
1,585
4.15625
4
# Return the root node of a binary search tree that matches the given preorder traversal. # (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) # It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if not preorder: return None root = TreeNode(preorder[0]) current = root stack = [root] i = 1 while i < len(preorder): if preorder[i] < current.val: current.left = TreeNode(preorder[i]) current = current.left else: while True: if not stack or stack[-1].val > preorder[i]: break current = stack.pop() current.right = TreeNode(preorder[i]) current = current.right stack.append(current) i += 1 return root
true
b1d83a286acfa0d779945d7ab5f0cfbb608f735e
nandanabhishek/C-programs
/Checking Even or Odd/even_odd.py
249
4.21875
4
a = int(input(" Enter any number to check whether it is even or odd : ")) if (a%2 == 0) : print(a, "is Even !") # this syntax inside print statement, automatically adds a space between data separated by comma else : print(a, "is Odd !")
true
3507349ce69a165ef1b4165843a3ba72e09e4a12
Rishab-kulkarni/caesar-cipher
/caesar_cipher.py
1,861
4.40625
4
import string # Enter only alphabets input_text = input("Enter text to encrypt:").lower() shift_value = int(input("Enter a shift value:")) alphabet = string.ascii_lowercase alphabet = list(alphabet) def encrypt(input_text,shift_value): """ Shifts all the characters present in the input text by a fixed value(encrypting) and returns the encrypted text. """ encrypted_text = "" for ch in input_text: index = alphabet.index(ch) if index + shift_value >=26: encrypted_text+="".join(alphabet[index + shift_value - 26]) else: encrypted_text +="".join(alphabet[index + shift_value]) return encrypted_text encrypted_text = encrypt(input_text, shift_value) print("Encrypted text:",encrypted_text) def decrypt(encrypted_text): """ Brute forces through all the shift values and decrypts the given encrypted text. Uses the method encrypt() but the shift value passed is negative, inorder to decrypt. """ print("All possible messages:") for shift in range(1,27): decrypted_text = encrypt(encrypted_text,-shift) print(decrypted_text, shift) decrypt(encrypted_text) def text_to_morse(encrypted_text): """ Converts the encrpyted text into morse code. """ morse_codes = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--' ,'-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..' ] morse_alphabet_codes = dict(zip(list(alphabet),morse_codes)) print(morse_alphabet_codes) encrypted_morse = "" for ch in encrypted_text: encrypted_morse += morse_alphabet_codes.get(ch) return encrypted_morse print(text_to_morse(encrypted_text))
true
0e8366c415dd5b7ba4812b30d1a97dd5b4bf7763
Sipoufo/Python_realisation
/Ex-12/guess_number.py
1,389
4.125
4
from art import logo import random print("Welcome to the Number Guessing Game") # init live = 0 run = True # function def add_live(difficulty): if difficulty.lower() == 'easy': return 10 elif difficulty.lower() == 'hard': return 5 def compare(user, rand): if user < rand: print("Too low") elif user > rand: print("Too high") else: print(f"You got it! the answere was {guess}") # running the app while run: print(logo) print("I'm thinking of a number between 1 and 100: ") answere = random.randint(1, 101) print(f"Pssf {answere}") difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") live = add_live(difficulty) guess = 0 while guess != answere: if live == 0: print(compare(guess, answere)) print("You've run out of guesses, you lose") run = False break elif guess == answere: compare(guess, answere) run = False else: print(f"You have {live} attempts remaning to guess the number") guess = int(input("Make a guess: ")) live -= 1 compare(guess, answere) print("Guess again") again = input("Try again? 'Yes' or 'No': ") if again == 'No': run = False else: run = True
true
f55819c8e653d6b4d94ad5f74cffd6a8121ddda2
cmparlettpelleriti/CPSC230ParlettPelleriti
/Lectures/Dictionaries_23.py
2,317
4.375
4
# in with dictionaries grades = {"John": 97.6, "Randall": 80.45, "Kim": 67.5, "Linda": 50.2, "Sarah": 99.2} ## check if the student is in there name = input("Who's grade do you want? ") print(name in grades) ## if not there, add them name = input("Who's grade do you want? ").capitalize() if name in grades: print(grades[name]) else: print("This student does not have a grade for this assignment") g = input("Please enter a grade now: ") try: g = float(g) except: print("Invalid grade, assigning grade of 0 for now") g = 0 finally: grades[name] = g print(grades) # sets my_set = {"February", "January", "April"} print(my_set) my_set2 = {1,1,1,1,1,1,3,5,9,11} print(my_set2) # creating sets my_list = [10,5,5,9,3,4,9,1,2,6,8,9,4,2,5,7] my_list_to_set = set(my_list) print(my_list_to_set) ## can't put mutable objects inside a set my_mutables = {(1,2,3,4), (5,6,7,8)} ## but you can mix types my_mixed_set = {1, "ant", "blue", (1,2)} print(my_mixed_set) # set methods my_set.add("June") print(my_set) my_set.add("February") print(my_set) my_set.remove("January") print(my_set) ## union, intersection, difference odds = {1,3,5,7,9} evens = {2,4,6,8,10} pos_ints = {1,2,3,4,5,6,7,8,9,10} primes = {2,3,5,7} # union print(odds | evens) print(odds.union(evens)) # intersection print(odds & pos_ints) print(odds.intersection(pos_ints)) # difference print(odds - primes) print(odds.difference(primes)) print(primes - odds) print(primes.difference(odds)) # symmetric difference print(odds^primes) print(odds.symmetric_difference(primes)) print(primes^odds) # if i switched the order, would the answer be different? ''' Let's write some code to ask two friends their favorite music artists, and then print out a message telling them which artists they both said they like! ''' songs = {} for friend in range(0,2): f = "friend" + str(friend) print("Welcome " + f) songs[f] = set() artist = input("Name an artist you like, enter a blank string to end: ").lower() while artist != "": songs[f].add(artist) artist = input("Name an artist you like, enter a blank string to end: ").lower() print("GREAT JOB!") print("The artists you have in common are: ", ",".join(list(songs["friend0"] & songs["friend1"])))
true
781947d55ede62f31a47dc2a4c17cd7eef4007db
EduardoHenSil/testes_python3
/iteraveis/itertools/accumulate.py
650
4.28125
4
#!/usr/bin/python3 # coding: utf-8 import itertools import operator summary = """ itertools.accumulate(it, [func]) Produz somas accumuladas; se func for especificada, entrega o resultado da sua aplicação ao primeiro par de itens de it, em seguida ao primeiro resultado e o próximo item. Diferente da função functools.reduce, accumulate gera os valores a cada resultado. """ print(summary) sample = [5, 4, 2, 8, 7, 6, 3, 0, 9, 1] print("sample =", sample) print("itertools.accumulate(sample) -->", list(itertools.accumulate(sample))) print("itertools.accumulate(sample, operator.mul) -->", list(itertools.accumulate(sample, operator.mul)))
false
7a683f984c9fba0e0c3d2d53fa805e841d2d29dd
KR4705/algorithms
/routeFinder.py
1,019
4.15625
4
# need to implement a simple path finding game in python. # import pprint board = [[0]*7 for _ in range(7)] def print_grid(grid): for row in grid: for e in row: print e, print # print print_grid(board) def set_goal(a,b): board[a][b] = "g" # set_goal(3,3) # print print_grid(board) def set_block(a,b): board[a][b] = "b" set_block(4,2) set_block(2,2) set_block(3,2) set_block(5,2) set_block(1,0) set_block(1,2) set_block(1,1) print print_grid(board) def fill(board,a,b): if a<5 and b<5 and a>1 and b>1: if not board[a-1][b] == "b" and board[a-1][b] == 0: board[a-1][b] = board[a][b] + 1 if not board[a][b+1] == "b" and board[a][b+1] == 0: board[a][b+1] = board[a][b] + 1 if not board[a+1][b] == "b" and board[a+1][b] == 0: board[a][b+1] = board[a][b] + 1 if not board[a][b-1] == "b" and board[a][b-1] == 0: board[a][b+1] = board[a][b] + 1 fill(board,a-1,b) fill(board,a,b+1) fill(board,a+1,b) fill(board,a,b+1) return fill(board,3,3) print_grid(board)
false
39a97c3366248770fba81735c9c4e231b34077b9
kuwarkapur/Robot-Automation-using-ROS_2021
/week 1/assignement.py
2,292
4.3125
4
"""Week I Assignment Simulate the trajectory of a robot approximated using a unicycle model given the following start states, dt, velocity commands and timesteps State = (x, y, theta); Velocity = (v, w) 1. Start=(0, 0, 0); dt=0.1; vel=(1, 0.5); timesteps: 25 2. Start=(0, 0, 1.57); dt=0.2; vel=(0.5, 1); timesteps: 10 3. Start(0, 0, 0.77); dt=0.05; vel=(5, 4); timestep: 50 Upload the completed python file and the figures of the three sub parts in classroom """ import numpy as np import matplotlib.pyplot as plt %matplotlib inline class Unicycle: def __init__(self, x: float, y: float, theta: float, dt: float): self.x = x self.y = y self.theta = theta self.dt = dt # Store the points of the trajectory to plot self.x_points = [self.x] self.y_points = [self.y] def step(self, v: float, w: float, n:int): for i in range(n): self.theta += w *(self.dt) self.x += v*np.cos(self.theta) self.y += v*np.sin(self.theta) self.x_points.append(self.x) self.y_points.append(self.y) return self.x, self.y, self.theta def plot(self, v: float, w: float,i:int): plt.title(f"Unicycle Model: {v}, {w}") plt.title(f"kuwar's graphs {i}") plt.xlabel("x-Coordinates") plt.ylabel("y-Coordinates") plt.plot(self.x_points, self.y_points, color="red", alpha=0.75) plt.grid() plt.show() if __name__ == "__main__": print("Unicycle Model Assignment") # make an object of the robot and plot various trajectories point = [{'x':0,'y': 0,'theta': 0,'dt': 0.1, 'v':1,'w': 0.5,'step': 25}, {'x':0,'y': 0,'theta': 1.57,'dt' :0.2,'v': 0.5, 'w':1,'step': 10}, {'x':0,'y': 0,'theta': 0.77, 'dt':0.05, 'v': 5,'w': 4, 'step': 50}, ] for i in range(len(point)): x = point[i]['x'] y = point[i]['y'] theta = point[i]['theta'] dt = point[i]['dt'] v = point[i]['v'] w = point[i]['w'] n = point[i]['step'] model=Unicycle(x, y, theta, dt) position =model.step(v, w, n) x, y, theta = position model.plot(v, w, i+1)
true
b141ddc29c11db608d165e4c1a9062f27671bee6
sanjeevs/AlgoByTimPart1
/assignment3/qsort/qsort.py
2,243
4.1875
4
from math import floor def qsort(a, lhs, rhs, num_cmps): """ Sort the array and record the number of comparisons. >>> a = [2,1] >>> num_cmps = 0 >>> qsort(a, 0, 1, num_cmps) 1 >>> print(a) [1, 2] """ if((rhs - lhs) >= 1): num_cmps += (rhs - lhs) pivot = partition(a, lhs, rhs) num_cmps = qsort(a, lhs, pivot -1, num_cmps) num_cmps = qsort(a, pivot + 1, rhs, num_cmps) return num_cmps def partition(a, lhs, rhs): """ Return the correct position of the pivot element. >>> a = [1] >>> partition(a, 0, 0) 0 >>> a = [2,1] >>> partition(a, 0, 1) 1 >>> print(a) [1, 2] >>> a = [100,101,3,8,2,200,201] >>> partition(a, 2, 4) 3 >>> print(a) [100, 101, 2, 3, 8, 200, 201] """ if(len(a) == 1): return 0 else: #swap(a, lhs, rhs) idx = choose_median_pivot(a, lhs, rhs) swap(a, lhs, idx) pivot = a[lhs] i = lhs + 1 for j in range(lhs+1, rhs+1): if(a[j] < pivot): swap(a, i, j) i += 1 swap(a, lhs, i -1) return i -1 def swap(a, i, j): """ Swap the elements of the arr. >>> a = [1,2,3] >>> swap(a, 1, 2) >>> print(a) [1, 3, 2] """ a[i], a[j] = a[j], a[i] def mid(a, lhs, rhs): """ Return the middle element of arr >>> a = [8,2,4,5,7,1] >>> mid(a, 0, 5) 2 >>> a = [8,2,4,5,7,1] >>> mid(a, 1, 5) 3 """ mid = floor((lhs + rhs)/2) return mid def median_of_3(a): """ Return the median of 3 elements. >>> median_of_3([1, 4, 8]) 4 >>> median_of_3([8, 1, 4]) 4 """ tmp = a.copy() tmp.sort() return tmp[1] def choose_median_pivot(a, lhs, rhs): """ Choose the median of the value. Consider the first, last and middle value of array. Find the median an use that as the pivot. >>> choose_median_pivot([8,2,4,5,7,1], 0, 5) 2 >>> choose_median_pivot(list(range(10)), 1, 5) 3 >>> choose_median_pivot([2,1,4], 0, 2) 0 >>> choose_median_pivot([2,1,4,5], 0, 3) 0 """ mid_idx = mid(a, lhs, rhs) choices = [a[lhs], a[mid_idx], a[rhs]] mid_value = median_of_3(choices) if(mid_value == a[lhs]): return lhs elif(mid_value == a[rhs]): return rhs else: return mid_idx if __name__ == "__main__": import doctest doctest.testmod()
false
22e283d052f9b9931bf09c823dfb93dba87b33ed
Aijaz12550/python
/list/main.py
953
4.375
4
######################### ##### remove method ##### ######################### list1 = [ 1, 2, True, "aijaz", "test"] """ list.remove(arg) it will take one item of list as a argument to remove from list """ list1.remove(1) # it will remove 1 from list1 #list1.remove(99) # it will throw error because 99 is not exist print("list1",list1) ######################### ##### sorting list ##### ######################### sorting_list = [1,2 ,33, -44, 108, 9876, -44545, 444] sorting_list.sort() # it will sort the original list print(" sorting_list =",sorting_list) sorted_list = sorted(sorting_list) # it will return the sorted list without changing the original. print("sorted_list = ",sorted_list) ######################### ##### slicing list ##### ######################### s_l1 = [0, 1, 2, 3] s_c = s_l1[:] print("s_c",s_c) list2 = [1] * 3 # [1, 1, 1] list3 = [2,3] list4 = list2 + list3 # [ 1, 1, 1, 2, 3 ] print("list4",list4)
true
43224d710674f33eafd7a5d1b0feb25bfec35141
FlyingEwok/Linear-BinarySearch
/binarysearch.py
1,116
4.21875
4
def binarySearch (list, l, listLength, value): # Set up mid point variable if listLength >= l: midPoint = l + (listLength - l) // 2 if list[midPoint] == value: # return the midpoint if the value is midpoint return midPoint elif list[midPoint] > value: # Do a search to the left of midpoint for value then return that return binarySearch(list, l, midPoint-1, value) else: # Do a search to the right of midpoint for value then return that return binarySearch(list, midPoint + 1, listLength, value) else: # if value not in list then return -1 return -1 searchList = [1, 2, 3, 4, 5, 6, 7, 8, 99] # Ask user for a number try: value = int(input("Enter a number: ")) # perform the binary search on the search list result = binarySearch(searchList, 0, len(searchList)-1, value) # Print the results in a statement if result != -1: print ("Element is at index", result) else: print ("Element is not in list") except ValueError: print("That's no number! Try again.")
true
0c98cf632b5e8638d1eb2e1f576b0bf667c10fe1
YunusEmreAlps/Python-Basics
/3. Advanced/Inheritence.py
2,315
4.25
4
# Inheritence (Kalıtım) # Inheritance belirttiğimiz başka classlardaki method ve attribute'lara erişmemizi sağlar. # Diyelim ki farklı tipte çalışanlar yaratmak istiyorum IT ve HR olsun. class Employee: raise_percent = 0.5 num_emp = 0 def __init__(self, name, last, age, pay): self.name = name self.last = last self.age = age self.pay = pay Employee.num_emp += 1 def apply_raise(self): self.pay += (self.pay * Employee.raise_percent) # self.raise_percent @classmethod def set_raise(cls, amount): cls.raise_percent = amount @classmethod def from_string(cls, userstr): name, last, age, pay = userstr.split('-') return cls(name, last, int(age), float(pay)) @staticmethod def holiday_print(day): if(day == "weekend"): print("This is an off day") else: print("This is not an off day") emp_1 = Employee("Yunus Emre", "Alpu", 22, 5000) emp_2 = Employee("Yusuf Emre", "Alpu", 28, 4000) # Hangi class'tan inherit etmek istediğimizi parantezin içine yazıyoruz. # Inherit ettiğimiz class'a super/parent class, inherit edene de child/subclass deniyor. class IT(Employee): raise_percent = 1.2 def __init__(self, name, last, age, pay, lang): super().__init__(name, last, age, pay) self.lang = lang pass # Employee raise_percent attribute'unu kullanmak yerine içine belirtiğimizi kullanıyor. Kendi içerisinde bulabilirse kullanıyor. Bulamazsa inherit ettiği yere bakıyor. # IT'nin içine hiç bir şey yazmasak da, Employee'nin özelliklerine erişimi var. # IT içerisinde bulamazsa aradığını, inherit ettiği yere gidip bakacak. IT'nin içerisinde __init__ methodu yok.O yüzden Employee classının içine bakacak. it_1 = IT("Yunus", "Alp", 22, 10000, "Python") print(it_1.__dict__) class IK(Employee): raise_percent = 1.5 def __init__(self, name, last, age, pay, experience): super().__init__(name, last, age, pay) self.experience = experience def print_exp(self): print(f"This employee has {self.experience} years of experience") pass ik_1 = IK("Yun", "Alp", 22, 10000, 10) print(ik_1.__dict__)
false
15bf570be794b9919f43b5786f61a8a97eb81d31
YunusEmreAlps/Python-Basics
/2. Basic/Output.py
1,846
4.34375
4
# -------------------- # Example 1 (Output) # This is comment """ This is multi-line comments """ # if you want to show something on console # you need to use a "print" instruction # syntax: # print('Message') -> single quotes # print("Message") -> double quotes print(' - Hello World!') print(" - I love Python programming language.") # ---------- # print('I'm Yunus Emre') syntax error print(" - I'm Yunus Emre") print(" - I'm student of computer engineer.") # ---------- # print("George always says "I love you"") syntax error print(' - George always says "I love you"') print(' - “Be the change that you wish to see in the world.” Mahatma Gandhi') # ---------- # Escape sequence syntax : # \n -> new line # \t -> tab # \r -> return # \\ -> backslash # ---------- print(" - first line \n") print("\n - second line") # first line # (new line) # (new line) # second line # ---------- print(" - A \t B \t C \n") # ---------- # This is important # _-_Avatar (return) # _-_James # Output : Jamesr print(" - Avatar \r - James") print("\t\t Escape Sequence\r - Python") # ---------- # print("\") syntax error print(" - \\") # ---------- # if you want to read a paragraph you need to use: print(''' - If you choose to use your status and influence to raise your voice on behalf of those who have no voice; if you choose to identify not only with the powerful, but with the powerless; if you retain the ability to imagine yourself into the lives of those who do not have your advantages, then it will not only be your proud families who celebrate your existence, but thousands and millions of people whose reality you have helped change. We do not need magic to change the world, we carry all the power we need inside ourselves already: we have the power to imagine better. ''') # ---------- print("+"*10) # Output:++++++++++
true
f5f54b5db00added0abbf07df9fa2c38bb2e2fbc
compsciprep-acsl-2020/2019-2020-ACSL-Python-Akshay
/class10-05/calculator.py
844
4.21875
4
#get the first number #get the second number #make an individual function to add, subtract, multiply and divide #return from each function #template for add function def add(num1, num2): return (num1+num2) def sub(num1, num2): return (num1-num2) def multiply(num1, num2): return (num1*num2) def division(num1, num2): return (num1/num2) num1 = int(input("Enter the First Number")) num2 = int(input("Enter the Second Number")) option = int(input("Enter 1 for Addition \n Enter 2 for Subtration \n Enter 3 for Multiplication \n Enter 4 for Division")) if (option == 1): print("The sum is: ", add(num1,num2)) elif (option == 2): print("The difference is: ", sub(num1,num2)) elif (option == 3): print("The product is: ", multiply(num1,num2)) elif (option == 4): print("the quotient is: ", division(num1,num2))
true
8d438c71959d3fd16bffc44490bdfea783fcf61d
vassmate/Learn_Python_THW
/mystuff/ex3.py
1,312
4.8125
5
# http://learnpythonthehardway.org/book/ex3.html # This will print out: "I will count my chickens:". print "I will count my chikens:" # This will print out how much Hens we have. print "Hens", 25.0 + 30.0 / 6.0 # This will print out how much roosters we have. print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # This will print out: "Now I will count the eggs:". print"Now I will count the eggs:" # This will print out the result of the given math opertions. print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # This will print out: "Is it true that 3 + 2 < - 7?" print "Is it true that 3 + 2 < 5 - 7?" # This will print out the result of the given math operations. print 3.0 + 2.0 < 5.0 - 7.0 # This will print out the answer for the printed question: "What is 3 + 2?". print "What is 3.0 + 2.0?", 3.0 + 2.0 # This will print out the answer for the printed question: "What is 5 - 7?". print "What is 5.0 - 7.0?", 5.0 - 7.0 # This will print out : "Oh, that's why it's False.". print "Oh, that's why it's False." # THis will print out : "How about some more.". print "How about some more." # These will print out the answers for the printed questions. print "Is 5.0 > -2.0 greater?", 5.0 > -2.0 print "Is 5.0 >= -2.0 greater or equal?", 5.0 >= -2.0 print "Is 5.0 <= -2.0 less or equal?", 5.0 <= -2.0
true
1abd8eea6ff68cbb119651fc9e978bef80dfa1a8
thenickforero/holbertonschool-machine_learning
/math/0x00-linear_algebra/2-size_me_please.py
577
4.4375
4
#!/usr/bin/env python3 """Module to compute the shape of a matrix""" def matrix_shape(matrix): """Calculates the shape of a matrix. Arguments: matrix (list): the matrix that will be processed Returns: tuple: a tuple that contains the shape of every dimmension in the matrix. """ shape = [] dimension = matrix[:] while isinstance(dimension, list): size = len(dimension) shape.append(size) if size > 0: dimension = dimension[0] else: break return shape
true
79969b00b7683284a24114fa72d3b613caf1d3d2
thenickforero/holbertonschool-machine_learning
/math/0x00-linear_algebra/14-saddle_up.py
598
4.15625
4
#!/usr/bin/env python3 """Module to compute matrix multiplications. """ import numpy as np def np_matmul(mat1, mat2): """Calculate the multiplication of two NumPy Arrays. Arguments: mat1 (numpy.ndarray): a NumPy array that normally represents a square matrix. mat2 (numpy.ndarray): a NumPy array that normally represents a square matrix. Returns: numpy.ndarray: a NumPy array which is the multiplication of @mat1 and @mat2. """ return np.matmul(mat1, mat2)
true
a403e25b42db8d2b9033c06b5aac45074300d4b3
dkrusch/python
/lists/planets.py
1,109
4.40625
4
planet_list = ["Mercury", "Mars"] planet_list.append("Jupiter") planet_list.append("Saturn") planet_list.extend(["Uranus", "Neptune"]) planet_list.insert(1, "Earth") planet_list.insert(1, "Venus") planet_list.append("Pluto") slice_rock = slice(0, 4) rocky_planets = planet_list[slice_rock] del[planet_list[8]] # Use append() to add Jupiter and Saturn at the end of the list. # Use the extend() method to add another list of the last two planets in our solar system to the end of the list. # Use insert() to add Earth, and Venus in the correct order. # Use append() again to add Pluto to the end of the list. # Now that all the planets are in the list, slice the list in order to get the rocky planets into a new list called rocky_planets. # Being good amateur astronomers, we know that Pluto is now a dwarf planet, so use the del operation to remove it from the end of planet_list. # Example spacecraft list spacecraft = [ ("Cassini", "Saturn"), ("Viking", "Mars"), ] for planet in planet_list: print(planet) for craft in spacecraft: if (craft[1] == planet): print(craft[0])
true
94d4dae91040dd8a74cce61e0977cc3931760ac0
mali44/PythonPracticing
/Palindrome1.py
645
4.28125
4
#Ask the user for a string and print out whether this string is a palindrome or not. #(A palindrome is a string that reads the same forwards and backwards.) mystr1= input("Give a String") fromLeft=0 fromRight=1 pointer=0 while True: if fromLeft > int(len(mystr1)): break if fromRight > int(len(mystr1)): break checker=mystr1[fromLeft] fromLeft+=1 revChecker=mystr1[-fromRight] fromRight+=1 if (checker != revChecker): flag=0 else: flag=1 if pointer==1: print(mystr1+"is a Palindrome") else: print(mystr1+"not a Palindrome")
true
71dad1096b5699d19ad30d431d025aa12b8165f4
E-Cell-VSSUT/coders
/python/IBAN.py
2,276
4.125
4
# IBAN ( International Bank Account Number ) Validator ''' An IBAN-compliant account number consists of: -->a two-letter country code taken from the ISO 3166-1 standard (e.g., FR for France, GB for Great Britain, DE for Germany, and so on) -->two check digits used to perform the validity checks - fast and simple, but not fully reliable, tests, showing whether a number is invalid (distorted by a typo) or seems to be good; -->the actual account number (up to 30 alphanumeric characters - the length of that part depends on the country) The standard says that validation requires the following steps (according to Wikipedia): (step 1) Check that the total IBAN length is correct as per the country. (step 2) Move the four initial characters to the end of the string (i.e., the country code and the check digits) (step 3) Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11 ... Z = 35; (step 4) Interpret the string as a decimal integer and compute the remainder of that number on division by 97; If the remainder is 1, the check digit test is passed and the IBAN might be valid. ''' def country_length(name): if name == 'INDIA': return 'IN' elif name == 'USA' or name == 'UNITED STATES': return 'US' elif name == 'UK' or name == 'GREAT BRITAIN': return 'GB' elif name == 'GERMANY': return 'DE' iban = input("Enter IBAN, please: ") iban = iban.replace(' ', '') country = input('Enter your country: ').upper() iban_len = country_length(country) if not iban.isalnum(): # checking for special characters in IBAN print('Invalid characters entered') elif len(iban) < 15: # checking if the length is less than 15 print('IBAN enetered is too short') elif len(iban) > 31: # checking if the length is greater than 15 print('IBAN enetered is too long') else: # checking the iban after adding the first four characters to the end of iban iban = (iban[4:] + iban[0:4]).upper() iban2 = '' for ch in iban: if ch.isdigit(): iban2 += ch else: iban2 += str(10 + ord(ch) - ord('A')) iban = int(iban2) if iban % 97 == 1: print("IBAN entered is valid.") else: print("IBAN entered is invalid.")
true
68e650fa51502dcc2a1e15bb7b956cb0c8630c58
E-Cell-VSSUT/coders
/python/Fibonacci.py
750
4.3125
4
# -- Case-1 -->> Using Function # This is a program to find fibonacci series using simple function def fib(n): if n < 1: # Fibonacci is not defined for negative numbers return None if n < 3: # The first two elements of fibonacci are 1 return 1 elem1 = elem2 = 1 sum = 0 for i in range(3, n+1): sum = elem1+elem2 elem1, elem2 = elem2, sum # First element becomes becomes second element # Second element becomes the sum of previous two elements return sum #--Main--# for i in range(1, 10): print(i, " -->> ", fib(i)) # -- Case-2 -->> Using Recursive Function def fib_rec(n): if n < 0: return None if n < 3: return 1 return fib(n-1)+fib(n-2)
true
0a95d362e7e9afd2c4c95d3937dfd9c7914ea2d7
Ispaniolochka/lab_python
/3_3_math_sin.py
393
4.3125
4
'''Написать программу, вычисляющую значение функции (на вход подается вещественное число):''' import math def value(x): if 0.2<= x <= 0.9: print('результат:', math.sin(x)) else: print('результат:',1) element=input('Введите число:') result=value(float(element))
false
5eec04b7937ecc36999127b68edf991e68db7cf7
Remor53/lesson2
/strings.py
1,256
4.375
4
def str_check(str1, str2): """Проверяет объекты на пренадлежность типу string. Если оба объекта строки, то проверяет одинаковые ли они, если разные, то определяет какая длиннее и проверяет, является ли вторая строка словом 'learn' Ключевые аргументы: str1 -- первый объект str2 -- второй объект Возвращает: различные целые числовые значения (int), либо кортеж из двух чисел (tuple) """ type1 = str(type(str1)) type2 = str(type(str2)) if type1 != '<class \'str\'>' or type2 != '<class \'str\'>': return 0 elif len(str1) == len(str2): return 1 elif len(str1) > len(str2): if str2 == 'learn': return 2, 3 else: return 2 elif str2 == 'learn': return 3 if __name__ == '__main__': print(str_check(1, 3)) print(str_check('hello', 'hello')) print(str_check('good morning', 'hello')) print(str_check('learning', 'learn')) print(str_check('read', 'learn'))
false
faf830c550d3166f125c4b846f95de6b1047d5c7
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check02b.py
682
4.21875
4
user_provide_file = input("Enter file: ") num_lines = 0 num_words = 0 # method for opening file and assigning its contents to a var # resource: https://runestone.academy/runestone/books/published/thinkcspy/Files/Iteratingoverlinesinafile.html # file = open(user_provide_file, "r") # best practice is to use "with" to ensure the file is properly closed # resource: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files with open(user_provide_file, "r") as file: for lines in file: words = lines.split() num_lines += 1 num_words += len(words) print(f"The file contains {num_lines} lines and {num_words} words.") file.close()
true
5b9d02e8b3b62588d1de662ef4321b20097c8f10
sgriffith3/python_basics_9-14-2020
/pet_list_challenge.py
843
4.125
4
#Tuesday Morning Challenge: #Start with this list of pets: pets = ['fido', 'spot', 'fluffy'] #Use the input() function three times to gather names of three more pets. pet1 = input("pet 1 name: ") pet2 = input("pet 2 name: ") pet3 = input("pet 3 name: ") #Add each of these new pet names to the pets list. pets.append(pet1) pets.insert(1, pet2) pets = pets + [pet3] #print(pets) #print(enumerate(pets)) #for ind, val in enumerate(pets): # print(ind, val) #Using the pets list, print each out, along with their index. # #The output should look like: # #0 fido #1 spot #2 fluffy print(0, pets[0]) print(1, pets[1]) print(2, pets[2]) print(3, pets[3]) print(4, pets[4]) print(5, pets[5]) counter = 0 for pet in pets: print(counter, pet) counter += 1 # counter = counter + 1 for pe in pets: print(pets.index(pe), pe)
true
ff0c5c38ca1e0d2b8cba59966bfea5cd7a743fc8
PavlovAlx/repoGeekBrains
/dz5.py
516
4.3125
4
string1 = int(input("введите выручку")) string2 = int(input("введите издержки")) if string1 >= string2: print ("вы работаете с прибылью:", string1-string2) print ("рентабельность:", string1/string2) string3 = int(input("численность сотрудников:")) print ("прибыль на сотрудника:", (string1-string2)/string3) else: print("вы работаете с убытком:", string1 - string2)
false
d503092c169f07e614859b581774ae27fc8c058c
wreyesus/Python-For-Beginners---2
/0020. List Comprehensions.py
2,760
4.15625
4
#Comprehensions nums = [1,2,3,4,5,6,7,8,9,10] # I want 'n' for each 'n' in nums my_list = [] for n in nums: my_list.append(n) print(my_list) #Using List Comprihension my_list_com = [n for n in nums] print(my_list_com) ############ #I want 'n*n' for each 'n' in nums my_list1 = [] for n in nums: my_list.append(n*n) print(my_list) #Using List Comprihension my_list1_com = [n*n for n in nums] print(my_list1_com) #Using MAP and LAMBDA my_list_lambda = map(lambda n: n*n , nums) print(my_list_lambda) for i in my_list_lambda: print(i) #List Comprehensionss more examples:- # I want 'n' for each 'n' in nums if 'n' is even my_list = [] for n in nums: if n%2 == 0: my_list.append(n) print(my_list) #Usaing a list Comprehensions my_list_com = [n for n in nums if n%2 == 0] print(my_list_com) #Using Filter and LAMBDA my_list_Filter = filter(lambda n : n%2 == 0 , nums) print(my_list_Filter) for i in my_list_Filter: print(i) # I want a (letter, num) pair for each letter in 'abcd' and each number in '0123' my_list = [] for letter in 'abcd': for num in range(4): my_list.append((letter,num)) print(my_list) #Using List Comprehensions my_list_com = [(letter,num) for letter in 'abcd' for num in range(4)] print(my_list_com) ## Dictionary Comprehensions names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] print(zip(names, heros)) for (name,heros) in zip(names, heros):print(name,heros) # I want a dict{'name': 'hero'} for each name,hero in zip(names, heros) names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] my_dict = {} for name, hero in zip(names, heros): my_dict[name] = hero print(my_dict) #Dictionary Comprihensions: names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] my_dict = {name:hero for name , hero in zip (names, heros)} print(my_dict) # If name not equal to Peter my_dict = {name:hero for name , hero in zip (names, heros) if name != 'Peter'} print(my_dict) #Set Comprehension nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9] my_set = set() for n in nums: my_set.add(n) print(my_set) #Using Set Comprehension my_set = {n for n in nums} print(my_set) # Generator Expressions # I want to yield 'n*n' for each 'n' in nums nums = [1,2,3,4,5,6,7,8,9,10] def gen_func(nums): for n in nums: yield n*n my_gen = gen_func(nums) for i in my_gen: print(i) #Using Generator Expressions my_gen = (n*n for n in nums) for i in my_gen: print(i)
false
900733030503c1011f0df3f2e5ee794499e422b0
wreyesus/Python-For-Beginners---2
/0025. File Objects - Reading and Writing to Files.py
474
4.375
4
#File Objects - Reading and Writing to Files ''' Opening a file in reading / writing / append mode ''' f = open('test.txt','r') #f = open('test.txt','w') --write #f = open('test.txt','r+') --read and write #f = open('test.txt','a') --append print(f.name) #will print file name print(f.mode) #will give r coz it is in reading mode f.close() #another way -- which close file automatically with open('test.txt','r') as f: print(f.read())
true
412ac494347bf94d8fc4b42b4775f4516795005d
bryanjulian/Programming-11
/BryanJulianCoding/Operators and Stuff.py
1,028
4.1875
4
# MATH! x = 10 print (x) print ("x") print ("x =",x) x = 5 x = x + 1 print(x) x = 5 x + 1 print (x) # x + 1 = x Operators must be on the right side of the equation. # Variables are CASE SENSITIVE. x = 6 X = 5 print (x) print (X) # Use underscores to name variables! # Addition (+) Subtraction (-) Multiplycation (*) Division (/) Powers (**) x=5*(3/2) x = 5 * (3 / 2) x =5 *( 3/ 2) print (x) # Order of Operations average = (90 + 86 + 71 + 100 + 98) / 5 # Import the math library # This line is done only once, and at the very top # of the program. from math import * # Calculate x using sine and cosine x = sin(0) + cos(0) print (x) m = 294 / 10.5 print(m) m = 294 g = 10.5 m2 = m / g # This uses variables instead print(m2) miles_driven = 294 gallons_used = 10.5 mpg = miles_driven / gallons_used print(mpg) ir = 0.12 b = 12123.34 i = ir * b print (i) # Easy to understand interest_rate = 0.12 account_balance = 12123.34 interest_amount = interest_rate * account_balance print (interest_amount)
true
858a56861965e44d0d1b3161957ea9edd11720ef
wangweihao/Python
/2/2-15.py
511
4.1875
4
#!/usr/bin/env python #coding:UTF-8 myTuple = [] for i in range(3): temp = raw_input('input:') myTuple.append(int(temp)) for i in range(3): print myTuple[i] if myTuple[0] > myTuple[1]: temp = myTuple[0] myTuple[0] = myTuple[1] myTuple[1] = temp if myTuple[0] > myTuple[2]: temp = myTuple[0] myTuple[0] = myTuple[2] myTuple[2] = temp if myTuple[1] > myTuple[2]: temp = myTuple[1] myTuple[1] = myTuple[2] myTuple[2] = temp for i in range(3): print myTuple[i],
false
9d175894ced0e8687bb5724763722efdeb70741f
Bmcentee148/PythonTheHardWay
/ex_15_commented.py
743
4.34375
4
#import argv from the sys module so we can use it from sys import argv # unpack the args into appropriate variables script, filename = argv #open the file and stores returned file object in a var txt_file = open(filename) # Tells user what file they are about to view contents of print "Here's your file %r:" % filename # prints the contents of the file in entirety print txt_file.read() #ask user to print filename again print "Print the filename again:" #prompts user for input and stores it in given var filename_again = raw_input('> ') # opens the file again and stores as object in a new var txt_file_again = open(filename_again) # prints the contents of the file again that is stored in different var print txt_file_again.read()
true
dcc622587a5c864792d4ab073da0f5ad239907bf
Bmcentee148/PythonTheHardWay
/ex3.py
825
4.375
4
# begin counting chickens print "I will now count my count my chickens" #Hens is 25 + (30 / 6) = 30 print "Hens", 25 + 30.0 / 6 #Roosters is 100 - (25 * 3) % 4 print "Roosters", 100 - 25 * 3 % 4 #begin counting eggs print "Now I will count my eggs" #eggs is 3 + 2 + 1 - 5 + (4 % 2) - (1/4) + 6 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #Test boolean logic print "Is is true that 3 + 2 < 5 - 7?" #prints False print 3 + 2 < 5 - 7 #Asks what is 3 + 2 and then prints the answer print "What is 3 + 2? ", 3 + 2 #Asks what is 5 - 7 and then prints the answer print "What is 5 - 7?", 5 - 7 #you moron print "Oh, thats why its False" print "How about some more" #prints True print "Is is greater?", 5 > -2 #prints True print "Is is greater than or equal to?", 5 >= -2 #prints False print "Is is less than equal to?", 5 <= -2
false
c4d5cc928ee53ccfdd17c60938a7f9d0ee54e0ba
donnell794/Udemy
/Coding Interview Bootcamp/exercises/py/circular/index.py
533
4.1875
4
# --- Directions # Given a linked list, return true if the list # is circular, false if it is not. # --- Examples # const l = new List(); # const a = new Node('a'); # const b = new Node('b'); # const c = new Node('c'); # l.head = a; # a.next = b; # b.next = c; # c.next = b; # circular(l) # true def circular(li): slow = li.head fast = li.head while(fast.next and fast.next.next): slow = slow.next fast = fast.next.next if slow is fast: return True return False
true
669afade07619df314a48551e17ad102f28b249f
donnell794/Udemy
/Coding Interview Bootcamp/exercises/py/fib/index.py
608
4.21875
4
# --- Directions # Print out the n-th entry in the fibonacci series. # The fibonacci series is an ordering of numbers where # each number is the sum of the preceeding two. # For example, the sequence # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] # forms the first ten entries of the fibonacci series. # Example: # fib(4) === 3 def memoize(fn): cache = {} def helper(x): if x not in cache: cache[x] = fn(x) return cache[x] return helper @memoize def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) #memoization decreses rutime from O(2^n) to O(n)
true
8fa85e0a0b64bcf6b2175da13c5414b6f4397e90
cmattox4846/PythonPractice
/Pythonintro.py
2,522
4.125
4
# day_of_week = 'Monday' # print(day_of_week) # day_of_week = 'Friday' # print(f"I can't wait until {day_of_week}!") # animal_input = input('What is your favorite animal?') # color_input = input('What is your favorite color?') # print(f"I've never seen a {color_input} {animal_input}") #**** time of day # time_of_day = 1100 # meal_choice = "" # if time_of_day < 1200: meal_choice = 'Breakfast' # elif time_of_day > 1200 and time_of_day < 1700: meal_choice = 'Lunch' # elif time_of_day > 1700: meal_choice = 'Dinner' # print(meal_choice) # random Number # import random # number = random.randrange(0,10 +1) # print(number) # if number >= 0 and number < 3: # print('Beatles') # elif number > 2 and number < 6: # print('Stones') # elif number > 5 and number < 9: # print('Floyd') # elif number > 8 and number <= 10: # print('Hendrix') # msg = 'Python is cool!' # for number in range(7): # print(msg) # for number2 in range(11): # print(number2) # msg_hello = 'Hello' # msg_goodbye = 'GoodBye' # for count in range(5): # print(msg_hello) # print(msg_goodbye) # height= 40 # while height < 48: # print('Cannot Ride!') # height += 1 # Magic Number Game #import random # magic_numbers = random.randrange(0,100,+1) # guess = 0 # print(magic_numbers) # while guess != magic_numbers: # guess = int(input('Please enter your guess!')) # if guess > magic_numbers: # if guess > (magic_numbers - 10) or guess < magic_numbers: # print('Getting Warmer') # print('Too Low!') # elif guess < magic_numbers: # if guess < (magic_numbers + 10) or guess > magic_numbers: # print('Getting Warmer!') # print('Too High!') # elif guess == magic_numbers: # print(f'{guess} is the correct number!') # def print_movie_name(): # Fav_movie = 'Casino' # print(Fav_movie) # print_movie_name() # def favorite_band (): # band_name_input = input('Please enter your favorite band name') # return band_name_input # band_results = favorite_band() # print(band_results) # def concert_display(musical_act): # my_street = input("Please enter the street you live on") # print(f'It would be great if {musical_act} played a show on {my_street}') # concert_display("Zac Brown Band") desktop_items = ['desk', 'lamp', 'pencil'] #print(desktop_items[1]) desktop_items.append('Infinity Gauntlet') #print(desktop_items[3]) for items in desktop_items: print(items)
true
f6ddfe6d2be79149d6a0b7c7fd373e8524990574
Hadiyaqoobi/Python-Programming-A-Concise-Introduction
/week2/problem2_8.py
1,206
4.53125
5
''' Problem 2_8: The following list gives the hourly temperature during a 24 hour day. Please write a function, that will take such a list and compute 3 things: average temperature, high (maximum temperature), and low (minimum temperature) for the day. I will test with a different set of temperatures, so don't pick out the low or the high and code it into your program. This should work for other hourly_temp lists as well. This can be done by looping (interating) through the list. I suggest you not write it all at once. You might write a function that computes just one of these, say average, then improve it to handle another, say maximum, etc. Note that there are Python functions called max() and min() that could also be used to do part of the jobs. ''' hourly_temp = [40.0, 39.0, 37.0, 34.0, 33.0, 34.0, 36.0, 37.0, 38.0, 39.0, \ 40.0, 41.0, 44.0, 45.0, 47.0, 48.0, 45.0, 42.0, 39.0, 37.0, \ 36.0, 35.0, 33.0, 32.0] def problem2_8(temp_list): count_t = 0 sum_t = 0 print("Average:", sum(temp_list)/len(temp_list)) print("High:",max(temp_list)) print("Low:", min(temp_list)) problem2_8(hourly_temp)
true
c9696e77689ca80b0ec5c1a46f9e5a59857c3b57
tHeMaskedMan981/coding_practice
/problems/dfs_tree/symmetric_tree/recursive.py
995
4.21875
4
# A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None class Solution(object): def isSymmetric(self, root): if root is None: return True return self.isMirror(root.left, root.right) def isMirror(self, root1, root2): if root1 is None and root2 is None: return True if root1 is None or root2 is None: return False if root1.data != root2.data: return False return self.isMirror(root1.left, root2.right) and self.isMirror(root1.right, root2.left) # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) print ("Level order traversal of binary tree is -") print(Solution().isSymmetric(root))
true
62e3168c128f1d16bef0ec4cc31afa2e05ae9cae
IshmaelDojaquez/Python
/Python101/Lists.py
413
4.25
4
names = ['John', 'Bob', 'Sarah', 'Mat', 'Kim'] print(names) print(names[0]) # you can determine a specific positive or negative index print(names[2:4]) # you can return names at a index to a given index. Does not include that secondary index names[0] = 'Howard' # Practice numbers = [3, 6, 23, 8, 4, 10] max = numbers[0] for number in numbers: if number > max: max = number print(max)
true
e2ba3d2b834e092bd3675fbcf8dbe5c33a31f729
ajitg9572/session2
/hackerrank_prob.py
206
4.28125
4
#!/bin/python3 # declare and initialize a list fruits = ["apple","mango","guava","grapes","pinapple"] # pritning type of fruits print (type(fruits)) # printing value for fruit in fruits: print(fruit)
true
7272a47b347604d33c2e3bcca50099c1976da126
gdof/Amadou_python_learning
/rock_paper_scissor/main.py
1,345
4.34375
4
import random # We are going to create a rock paper scissor game print("Do you want a rock, paper, scissor game?") # create a variable call user_input and port the user a Yes a No user_input = input("Yes or No? ") # if the user select no print out "It is sorry to see you don't want to play" if user_input == "no": print("It is sorry to see you don't want to play") # if the user select yes prompt the user for a input of rock paper sicssor elif user_input == "yes": """ Store the user input from this elif statment into a variable, set the variable name to user_choice using python create a words variable called "choice_list" that have three string ["rock", "paper", "sicssor"] import random using python random get a random choice from the list and store it in a varibles call random_choice compare the user choice and the random choice if the user choice match the random choice print aye you guess right else say guess again """ user_choice = input("select rock, paper, sicssor? ") choice_list = ["rock", "paper", "scissor"] random_choice = random.choice(choice_list) if user_choice == random_choice: print("aye you guess right") else: print("guess again") # else the user don't choice yes or no print out wrong input else: print("wrong input")
true
30aaffce13d69354705ccb9e3c9c46e565a3b6d2
Bals-0010/Leet-Code-and-Edabit
/Edabit/Identity matrix.py
1,664
4.28125
4
""" Identity Matrix An identity matrix is defined as a square matrix with 1s running from the top left of the square to the bottom right. The rest are 0s. The identity matrix has applications ranging from machine learning to the general theory of relativity. Create a function that takes an integer n and returns the identity matrix of n x n dimensions. For this challenge, if the integer is negative, return the mirror image of the identity matrix of n x n dimensions.. It does not matter if the mirror image is left-right or top-bottom. Examples id_mtrx(2) ➞ [ [1, 0], [0, 1] ] id_mtrx(-2) ➞ [ [0, 1], [1, 0] ] id_mtrx(0) ➞ [] Notes Incompatible types passed as n should return the string "Error". """ # Approach using numpy def generate_identity_matrix(n): import numpy as np temp_n = abs(n) identity_matrix = np.zeros((temp_n,temp_n)) for i in range(temp_n): identity_matrix[i][i] = 1 if n>0: return identity_matrix else: return np.flip(identity_matrix, axis=0) # print(generate_identity_matrix(-2)) # Approach without using numpy def generate_identity_matrix_no_np(n): temp_n = abs(n) id_matrix = [[]]*temp_n for i in range(temp_n): id_matrix[i] = [0 for i in range(temp_n)] for i in range(temp_n): for j in range(temp_n): if i==j: id_matrix[i][j] = 1 if abs(n)==n: return id_matrix else: id_matrix.reverse() return id_matrix # print(generate_identity_matrix_no_np(2)) print(generate_identity_matrix_no_np(-2))
true
d07e252bff50c58d9cf0d612edbdfd78f9a7b7a7
radhikar408/Assignments_Python
/assignment17/ques1.py
349
4.3125
4
#Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. import tkinter from tkinter import * import sys root=Tk() def show(): print("hello world") b=Button(root,text="Hello",width=25,command=show) b2=Button(root,text="exit",width=25, command=exit) b.pack() b2.pack() root.mainloop()
true
dd579fcf0c2dde41709cc6a552777d799a5240f2
MattSokol79/Python_Introduction
/python_variables.py
1,289
4.5625
5
# How to create a variable # If you want to comment out more than one line, highlight it all and CTRL + / name = "Matt" # String # Creating a variable called name to store user name age = 22 # Int # Creating a variable called age to store age of user hourly_wage = 10 # Int # Creating a variable called hourly_wage to store the hourly wage of the user travel_allowance = 2.1 # Float # Creating a variable called travel_allowance to store the travel allowance of the user # Python has string, int, float and boolean values # How to find out the type of variable? # => type() gives us the actual type of value print(travel_allowance) print(age) print(hourly_wage) # How to take user data # Use input() to get data from users name1 = str(input("Please enter your name ")) # Getting user data by using input() method print(name1) # Exercise - Create 3 variables to get user data: name, DOB, age user_name = str(input("Please provide your name ")) user_dob = str(input("Please provide your date of birth in the format - dd/mm/yy ")) user_age = int(input("Please provide your age ")) print('Name: ', user_name) print('DOB: ', user_dob) print('Age: ', user_age) print('Type of variable: ') print('Name: ', type(user_name)) print('DOB: ', type(user_dob)) print('Age: ', type(user_age))
true
d7ee9dfcd9573db8b914dc96bff65c61753aceec
fadhilmulyono/CP1401
/CP1401Lab6/CP1401_Fadhil_Lab6_2.py
373
4.25
4
''' The formula to convert temperature in Fahrenheit to centigrade is as follows: c = (f-32)*5/9; Write a program that has input in Fahrenheit and displays the temperature in Centigrade. ''' def main(): f = float (input("Enter the temperature in Fahrenheit: ")) c = (f - 32) * 5 / 9 print("The temperature in Celsius is: " + str(c) + " °C") main()
true
db9eddc3ae20c784684b86d39aa675cd8764739f
fadhilmulyono/CP1401
/Prac05/CP1401_Fadhil_Prac5_3.py
292
4.40625
4
''' Get height Get weight Calculate BMI (BMI = weight/(height^2 )) Show BMI ''' def main(): height = float(input("Enter your height (m): ")) weight = float(input("Enter your weight (kg): ")) BMI = weight / (height ** 2) print("Your BMI is " + str(BMI)) main()
false
d3e53df801c4e65d76e275b9414312bdb2f618e5
fadhilmulyono/CP1401
/Prac08/CP1401_Fadhil_Prac8_3.py
607
4.3125
4
''' Write a program that will display all numbers from 1 to 50 on separate lines. For numbers that are divisible by 3 print "Fizz" instead of the number. For numbers divisible by 5 print the word "Buzz". For numbers that are divisible by both 3 and 5 print "FizzBuzz". ''' def main(): number = 0 while number < 50: number += 1 if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) main()
true
99340807f1f60f51cd4ddd83af753df01b947a89
oldpride/tpsup
/python3/examples/test_copilot_vscode.py
232
4.28125
4
#!/usr/bin/env python3 import datetime # get days between two dates def get_days_between_dates(date1, date2): return (date2 - date1).days + 1 print(get_days_between_dates(datetime.date(2018, 1, 1), datetime.date(2018, 1, 3)))
false
1550ef200015ae11c213f5b0762e33a1ae24315c
oldpride/tpsup
/python3/examples/test_nested_dict.py
210
4.40625
4
#!/usr/bin/env python3 import pprint dict1 = {} dict2 = {'a': 1, 'b': 2} dict1['c'] = dict2 print('before, dict1 = ') pprint.pprint(dict1) dict2['a'] = 3 print('after, dict1 = ') pprint.pprint(dict1)
false
382700c11c43f4aa36ccdac6076a6b3685243c66
jasigrace/guess-the-number-game
/main.py
812
4.1875
4
import random from art import logo print(logo) print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100.") number = random.randint(1, 100) def guess_the_number(number_of_attempts): while number_of_attempts > 0: print(f"You have {number_of_attempts} remaining to guess the number. ") guess = int(input("Make a guess: ")) if guess < number: print("Too low.\nGuess again.") number_of_attempts -= 1 elif guess > number: print("Too high.\nGuess again.") number_of_attempts -= 1 elif guess == number: print(f"You got it. The answer was {number}.") number_of_attempts = 0 difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") if difficulty == "easy": guess_the_number(10) else: guess_the_number(5)
true
3654c6e6941304f8e95e428b490f68e7b6bb4227
randy-wittorp/ex
/ex39.py~
2,518
4.125
4
# create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksongille' } # add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print '-' * 10 print "NY State has: ", cities['NY'] print "OR State has: ", cities['OR'] # print some states print '-' * 10 print "Michigan's abbreviation is: ", states['Michigan'] print "Florida's abbreviation is: ", states['Florida'] # do it by using the state then cities dict print '-' * 10 print "Michigan has: ", cities[states['Michigan']] print "Florida has: ", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) # print every city in state print '-' * 10 for abbrev, city in cities.items(): print "%s is in %s" % (city, abbrev) # now do both at once print '-' * 10 for state, abbrev in states.items(): print "%s state is abbreviated %s and has city %s" % ( state, abbrev, cities[abbrev]) print '-' * 10 # safely get an abbreviation by state that might not be there state = states.get('Texas', None) if not state: print "Sorry, no Texas" # get a city with a default value city = cities.get('TX', 'does not exist') print "The city for the state 'TX' is: %s" % city print """ ----------------------------------------------------------- You may now enter additional states and their corresponding abbreviations. To exit, enter [Q]""" while True: # print "Enter new state name:" new_state = raw_input("Enter new state name:") if new_state.lower() == 'q': break print "Enter abbreviation:" new_abbrev = raw_input("> ") if new_abbrev.lower() == 'q': break print "-" * 60 print "You have entered %s, abbreviated as %s." % (new_state, new_abbrev) print "Correct? [Yn]" confirmation = raw_input("> ") if confirmation.lower() == 'n': continue else: states[new_state] = new_abbrev print "Would you like to see all the states so far[Yn]?" display_states = raw_input("> ") if display_states.lower() == 'n': continue else: print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) print "-" * 60
false
48c2d231d58a0b04c6c91e529ee98bf985988857
ernur1/thinking-recursively
/Chapter-3/3.2-factorial.py
392
4.28125
4
#=============================================================================== # find the factorial of the given integer #=============================================================================== def factorial(num): if (num == 0): return 1 else: return num * factorial(num-1) if __name__ == '__main__': print "Factorial of given number is" , factorial(9)
true
752eb476bdcfb40289559b662245786b635c1766
ellen-yan/self-learning
/LearnPythonHardWay/ex33.py
362
4.15625
4
def print_num(highest, increment): i = 0 numbers = [] while i < highest: print "At the top i is %d" % i numbers.append(i) i = i + increment print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers print "The numbers: " numbers = print_num(6, 1) for num in numbers: print num
true
1ce6ad0a83e82ade475c75c40d9cf5c8fb4cac43
ellen-yan/self-learning
/LearnPythonHardWay/ex5.py
1,363
4.34375
4
my_name = 'Ellen X. Yan' my_age = 23 # not a lie my_height = 65 # inches my_weight = 135 # lbs my_eyes = 'Brown' my_teeth = 'White' my_hair = 'Black' print "Let's talk about %s." % my_name print "She's %d inches tall." % my_height print "She's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "She's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth # this line is tricky print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) print "I just want to print %%" print "This prints no matter what: %r, %r" % (my_name, my_age) # '%s', '%d', and '%r' are "formatters". They tell Python to take the variable # on the right and put it in to replace the %s with its value # List of Python formatters: # %c: character # %s: string conversion via str() prior to formatting # %i: signed decimal integer # %d: signed decimal integer # %u: unsigned decimal integer # %o: octal integer # %x: hexadecimal integer (lowercase letters) # %X: hexadecimal integer (UPPERcase letters) # %e: exponential notation (with lowercase 'e') # %E: exponential notation (with UPPERcase 'E') # %f: floating point real number # %g: the shorter of %f and %e # %G: the shorter of %f and %E # %r: print the raw data (i.e. everything); useful for debugging
true
a6f237792aef743e05e0e1d0f81e510b0926bdec
nsimsofmordor/PythonProjects
/Projects/PythonPractice.org/p2_odd_or_even.py
481
4.40625
4
# Ask the user for a number. # Depending on whether the number is even or odd, print out an appropriate message to the user. # If the number is a multiple of 4, print out a different message. # Ask for a positive number number = int(input("Enter a positive number: ")) while number < 0: number = int(input("Enter a positive number: ")) # print out if odd or even if number % 4 == 0: print("Multiple of 4") elif number % 2 == 0: print("Even") else: print("Odd")
true
ee6fcba43821b771900c0ced8ca27003e6085fd0
nsimsofmordor/PythonProjects
/Projects/PythonPractice.org/p6_sting_lists.py
287
4.53125
5
# Ask the user for a string and print out whether this string is a palindrome or not. my_str = str(input("Enter a string to check if it is a palindrome or not: ").lower()) rev_str = my_str[::-1].lower() if my_str == rev_str: print("Palindrome!") else: print("Not Palindrome!")
true
068905cbe2bea0582747af13f294ce98d8edf24f
nsimsofmordor/PythonProjects
/Projects/Python_Tutorials_Corey_Schafer/PPBT5 Dicts.py
1,064
4.375
4
# {Key:value} == {Identifier:Data} student = {'name': 'john', 'age': '27', 'courses': ['Math', 'Science']} print(f"student = {student}") print(f"student[name] = {student['name']}") print(f"student['courses'] = {student['courses']}\n") # print(student['Phone']) # throws a KeyError, sine that key doesn't exist print(student.get('phone', 'Not Found')) print() print("setting student[phone] = 555-5555") student['phone'] = '555-5555' print(student) print() print("results of student.update({'name': 'frank'})") student.update({'name': 'frank'}) print(student) print() print("deleting student['age']") del student['age'] print(student) print() print("printing the name...") name = student['name'] print(name) print("\nprinting the len of student") print(len(student)) print("\nprinting the student keys") print(student.keys()) print("\nprinting the student values") print(student.values()) print("\nprinting the student items") print(student.items()) print('\nprinting the key,value pairs') for key,value in student.items(): print (key, value)
true
14325d0779ae0aa4b96b89daddcaef7448493106
msossoman/coderin90
/calculator.py
1,165
4.125
4
def add (a, b): c = a + b print "The answer is: {0} + {1} = {2}".format(a, b, c) def subtract (a, b): c = a - b print "The answer is {0} - {1} = {2}".format(a, b, c) def multiply (a, b): c = a * b print "The answer is {0} * {1} = {2}".format(a, b, c) def divide (a, b): c = a / b print "The answer is {0} / {1} = {2}".format(a, b, c) def choice(): operation = int(raw_input("""Select operation: \n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n Enter choice (1/2/3/4):""")) if operation == 1: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") add(float(a), float(b)) elif operation == 2: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") subtract(float(a), float(b)) elif operation == 3: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") multiply(float(a), float(b)) elif operation == 4: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") divide(float(a), float(b)) else: print "Please select a valid operation" choice() if __name__ == '__main__': choice()
true
1b26680c89752d77a1f78e231a9165c4a25a004c
Ashok-Mishra/python-samples
/python exercises/dek_program054.py
864
4.4375
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Define a class named Shape and its subclass Square. The Square class has # an init function which takes a length as argument. Both classes have a # area function which can print the area of the shape where Shape's area # is 0 by default. # Hints: # To override a method in super class, we can define a method with the # same name in the super class. class Shape(object): def area(self): return 0 class Square(Shape): def __init__(self, length): print 'calling init method' self.length = length def area(self): return self.length * self.length def main(): squareObj = Square(int(raw_input('Enter Length : '))) # squareObj = Square(int('5')) print 'Area of Square is : ', squareObj.area() if __name__ == '__main__': main()
true
40746a8b06658c8d7935e4238f69e17e1d7d9315
Ashok-Mishra/python-samples
/python exercises/dek_program068.py
970
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program068: # Please write a program using generator to print the even numbers between # 0 and n in comma separated form while n is input by console. # Example: # If the following n is given as input to the program: # 10 # Then, the output of the program should be: # 0,2,4,6,8,10 # Hints: # Use yield to produce the next value in generator. # In case of input data being supplied to the question, it should be # assumed to be a console input. def evenGenerator(endValue): eveniter = 0 while eveniter <= endValue: if eveniter % 2 == 0: yield eveniter eveniter += 1 def main(endValue): result = [] evenGen = evenGenerator(int(endValue)) for res in evenGen: result.append(str(res)) # print result print ",".join(result) if __name__ == '__main__': main(raw_input("Input endLimit: "))
true
e260d508fca7871b4955a4d44eded3503d532c18
Ashok-Mishra/python-samples
/python exercises/dek_program062.py
482
4.40625
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Write a program to read an ASCII string and to convert it to a unicode # string encoded by utf - 8. # Hints: # Use unicode() function to convert. def do(sentence): # print ord('as') unicodeString = unicode(sentence, "utf-8") print unicodeString def main(): sentence = 'this is a test' do(sentence) if __name__ == '__main__': main() # main(raw_input('Enter String :'))
true
047481cff2b6856af271cecf82fbeb71e1e68ad3
Ashok-Mishra/python-samples
/python exercises/dek_program071.py
571
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program071: # Please write a program which accepts basic mathematic expression from # console and print the evaluation result. # Example: # If the following string is given as input to the program: # 35+3 # Then, the output of the program should be: # 38 # Hints: # Use eval() to evaluate an expression. def main(expression): print eval(expression) if __name__ == '__main__': expression = raw_input("Enter expression: ") main(expression) # main('34+5')
true
d502383264e8d290050e3b1384916f7888c07677
Ashok-Mishra/python-samples
/python exercises/dek_program045.py
694
4.375
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Write a program which can filter even numbers in a list by using filter # function. The list is: # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. # Hints: # Use filter() to filter some elements in a list. # Use lambda to define anonymous functions. def do(start_number, end_number): list = [value for value in range(start_number, end_number + 1)] print 'list :', list result = filter(lambda number: number % 2 == 0, list) print 'Even Number From list :', result def main(): do(int(raw_input('Enter Starting Number :')), int(raw_input('Enter Ending Number :'))) if __name__ == '__main__': main()
true
714da2929f26a6b2788bad27279aec26de30f66b
Ashok-Mishra/python-samples
/python exercises/dek_program053.py
747
4.28125
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Define a class named Rectangle which can be constructed by a length and # width. The Rectangle class has a method which can compute the area. # Hints: # Use def methodName(self) to define a method. class Ractangle(object): def __init__(self, length, width): self.length = length self.width = width def areaOfRactangle(self): return self.length * self.width def main(): ractangleObj = Ractangle( int(raw_input('Enter Value for length of Ractangle :')), int(raw_input('Enter Value for Width of Ractangle :'))) print 'Area of Ractangle is : ', ractangleObj.areaOfRactangle() if __name__ == '__main__': main()
true
ef2f0b6305acf196994ca53109035688722d342e
Ashok-Mishra/python-samples
/python exercises/dek_program001.py
913
4.125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program001 : divisibleBy7not5 # Write a program which will find all such numbers which are divisible by 7 # but are not a multiple of 5, between 2000 and 3200 (both included). # The numbers obtained should be printed in a comma-separated sequence # on a single line. # Hints: # Consider use range(#begin, #end) method def divisibleBy7not5(startLimit, endLimit): result = [] for number in range(startLimit, endLimit + 1): # "endLimit + 1" bcoz limits too,should be included # print number if number % 7 == 0 and number % 5 != 0: result.append(number) return result def main(): print 'numbers divisible by 7 and not 5' print divisibleBy7not5(int(raw_input('Enter Value:')), int(raw_input('Enter Value:'))) if __name__ == '__main__': main() # checked
true
ae0fed29cb1b49c8deb8c0807df7f222c6aae61a
Ashok-Mishra/python-samples
/python exercises/dek_program008.py
722
4.28125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program008 : # Write a program that accepts a comma separated # sequence of words as input and prints the words # in a comma-separated sequence after sorting them alphabetically. # Suppose the following input is supplied to the program: # without,hello,bag,world # Then, the output should be: # bag,hello,without,world # Hints: # In case of input data being supplied to the question, it should be # assumed to be a console input. def main(): print "sample input ", 'without,hello,bag,world' str = raw_input('Enter : ') li1 = str.split(',') # print li1 li1.sort() print li1 if __name__ == '__main__': main() # checked
true
bb8be1f8046be290b5a453dcae9774bbac3df864
analBrotherhood/UCrypt-CLI
/ucrypt.py
1,649
4.21875
4
alphabet = '=>?@[\\]678hiVWlmABCDEpqrsjkJKL01234RюБжэяЩРтшЦМйu&UмоПtлС5хКцvЧёgчwSещFTвНZ#ОькТЖЯЁфбГъуЗиргШЪ$ЮХыЫIXHЕ!ВДG"Фа%АYсЙЬИздЛoxyz<MNOPQnУЭпн9abcdef^_`{|}~ \'()*+,-./:;' def encrypt(): enc = '' msg = input('Type message for encrypting: ') key = input('Enter key for encrypting: ') for c in msg: if c in alphabet: s1 = alphabet.find(c) s1 = (s1 + int(key)) % len(alphabet) enc += alphabet[s1] else: enc += c print('Encrypted message: ' + enc) print('Key, what used for encrypting: ' + key) print('Goodbye!') def decrypt(): dec = '' msg = input('Type message for decrypting: ') key = input('Enter key for decrypting: ') for c in msg: if c in alphabet: s1 = alphabet.find(c) s1 = (s1 - int(key)) % len(alphabet) dec += alphabet[s1] else: dec += c print('Decrypted message: ' + dec) print('Key, what used for decrypting: ' + key) print('Goodbye!') def main(): print(''' <====== UCrypt v1.0 ======> What do you want? 0 - Encrypt 1 - Decrypt''') k = input('\nYou choice (0/1): ') try: int(k) except ValueError: print('Error #0. Entered choice not a number.') exit() if k == '0': encrypt() elif k == '1': decrypt() else: print('Error #1. Enter 0 or 1 for choosing.') exit() try: main() except KeyboardInterrupt: print('\nGood bye!') exit()
false