blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bdbbc9410629a84e3ae9eac3679a64f1fbdea304
VNCS7/py-ex
/etec/03-Estutura de Repeticao/ex_44.py
688
4.15625
4
#44. Crie um programa que classifique os nadadores nas categorias de acordo com sua idade: #Infantil A – de 5 à 7 anos; #Infantil B – de 8 à 10 anos; #Juvenil A – de 11 à 13 anos; #Juvenil B - de 14 à 17 anos; #Senior – a partir de 18 anos. nadador = 1 while(nadador <=5): nadador+=1 id = int(input("\nDigite a idade: ")) if id >= 5 and id <= 7: print("\nCategoria: Infantil A") elif id >= 8 and id <= 10: print("\nCategoria: Infantil B") elif id >= 11 and id <= 13: print("\nCategoria: Juvenil A") elif id >= 14 and id <= 17: print("\nCategoria: Juvenil B") elif id >= 18: print("\nCategoria: Senior")
false
c940ea15a5350d54dcb533887bd4641a55e720a4
AraqueGD/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,516
4.125
4
#!/usr/bin/python3 """ Matrix Function Dived One Divisor """ def matrix_divided(matrix, div): """ Parameter: - Matrix = A list the Int or FLoats - Div = Number Divisor Errors: - ZeroDivisorError = division by zero - TypeError = div must be a number - TypeError = The matrix must contain more than one element - TypeError = Each row of the matrix must have the same size - TypeError = matrix must be a matrix (list of lists) of intege rs/floats RETURN = New List Elements Divided """ new_list = [] if (div is 0): raise ZeroDivisionError("division by zero") elif (type(div) is not float and type(div) is not int): raise TypeError("div must be a number") if(len(matrix) <= 1): raise TypeError("The matrix must contain more than one element") for a in matrix: if (len(a) != len(matrix[0])): raise TypeError("Each row of the matrix must have the same size") for i in matrix: for x in i: if (type(x) is not int and type(x) is not float): raise TypeError("matrix must be a matrix (list of lists) of " "integers/floats") x = - 1 for b in matrix: new_list.append([]) x += 1 for h in range(len(b)): new_list[x].append(round(b[h] / div, 2)) return new_list
true
3dd8d84e3846323f8f37e6c433d1b8d6d4a3b533
AraqueGD/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
470
4.3125
4
#!/usr/bin/python3 """ Function Print Square """ def print_square(size): """ Function Print Square and Erros Function """ if (type(size) is not int): raise TypeError("size must be an integer") elif (size < 0): raise ValueError("size must be >= 0") elif (size < 0 and type(size) is float): raise TypeError("size must be an integer") for i in range(size): print('#' * size, end="") print()
true
bca41a8153e031e8ea01a9fae1e2dbcac84b3b32
hb162/Algo
/Algorithm/Ex_150320.py
831
4.1875
4
""" There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 unique ways: 1, 1, 1, 1 2, 1, 1 1, 2, 1 1, 1, 2 2, 2 What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X={1, 3, 5}, you could climb 1, 3, or 5 steps at a time. """ def nums_way(n): if n == 0 or n == 1: return 1 result = [0] * (n+1) result[0] = 1 result[1] = 1 for i in range(2, n+1): result[i] = result[i-1] + result[i-2] return result[n] print(nums_way(5)) """ Độ phức tạp O(n) """
true
ece549aac50d69034959b09b2c22bcda0d2b303c
hb162/Algo
/Algorithm/Ex_130320.py
1,163
4.34375
4
""" You are given an array of integers. Return the largest product that can be made by mutiplying any 3 integers in the array. """ def largest_product(list): if len(list) <= 2: return None max_index1 = 0 max_index2 = -1 max_index3 = -1 for i in range(1, len(list)): if list[i] > list[max_index1]: max_index3 = max_index2 max_index2 = max_index1 max_index1 = i elif list[i] > list[max_index2] or max_index2 == -1: max_index3 = max_index2 max_index2 = i elif list[i] > list[max_index3] or max_index3 == -1: max_index3 = i min_index1 = 0 min_index2 = -1 for i in range(1, len(list)): if list[i] < list[min_index1]: min_index2 = min_index1 min_index1 = i elif list[i] < list[min_index2] or min_index2 == -1: min_index2 = i result = max(list[max_index1] * list[max_index2] * list[max_index3], list[min_index1] * list[min_index2] * list[max_index1]) return result list = [0, 0, -1, 1, 5] print(largest_product(list)) """ Độ phức tạp: O(n) """
true
a7d7390b0c616c00df96ac44ffeff71631c2e6f5
AngelDelunadev/python102
/sum_list.py
609
4.25
4
number_list = [36,93,55,42,12,24,100,-34] total =0 biggest_num = float("-inf") smallest_num = float("inf") even_num = [] positive_num = [] for num in number_list: if num >= 0: positive_num.append(num) if num % 2 == 0: even_num.append(num) if num < smallest_num: smallest_num = num total = total + num if num > biggest_num: biggest_num = num print("%s is the total"% total) print("%s is the biggest number "%biggest_num) print("%s is the smallest number " % smallest_num) print("Even numbers") print(even_num) print("Positive numbers") print(positive_num)
true
37e8e557f0bcc7bb3a5113e6ce9395601c7037fa
IonatanSala/Python
/advanced/argparse_in_python.py
2,379
4.5
4
# Argparse is a module that allows for neat and familiar option and argument parsing for our python prgrams # Automatically generates the usage # Has inbuilt help function # Auto formats the output for the console # It interfaces with the python system nodule to grab the arguments from the command line # Supports checking and making sure required arguments are provided # parser = argparse.ArgumentParser() # parser.add_argument('num', help="help text", type=int) # args = parser.parse_args() # print args.num # Positional arguments are required arguments that we need for our program to complete. # Positional arguments do not require the dash(-) because it is not an option. # in the case of the fibonacci program this is the number num to count up to # Optionsal Arguments # As their title indicates, the optional arguments are optional. # The -h option is laready inbuilt by default # We can create as many as we like and argparse will handle it # Like the positional arguments the help will be automatically added to the help output. # parser.add_argument("--quiet", help="help text", action="store_true") # Mutually Excusive Arguments # You can select one option or another option, but not both # This can be done with a group # Automatically generates an output telling the user can only pick one, should they try to use both # create a program that calculates the nth fibionacci number # Optional output number to file. "--output" # Add a short option aswell. "-o" # Add help for the optional output import argparse def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a def Main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-v', '--verbose', action="store_true") group.add_argument('-q', '--quite', action="store_true") parser.add_argument("num", help="The fibonacci number you wish to calculate.", type=int) parser.add_argument("-o", "--output", help="Output result to a file.", action="store_true") args = parser.parse_args() result = fib(args.num) if args.verbose: print("The " + str(args.num) + "th fib number is " + str(result)) elif args.quite: print(result) else: print("Fib("+ str(args.num) + ") = " + str(result)) if args.output: f = open("fibonacci.txt", "a") f.write(str(result)+ "\n") f.close() if __name__ == '__main__': Main()
true
1f92979ac5092e5dbd65dadedff18cb4a53caf3f
HermanMolodchikov/python_learn
/L29HomeWork.py
1,230
4.28125
4
def odd_ball(arr): """ :param arr: получаем список :type arr: list :return: возвращаем сравнение """ return arr.index('odd') in arr print(odd_ball(["even", 4, "even", 7, "even", 55, "even", 6, "even", 10, "odd", 3, "even"])) # True print(odd_ball(["even", 4, "even", 7, "even", 55, "even", 6, "even", 9, "odd", 3, "even"])) # False print(odd_ball(["even", 10, "odd", 2, "even"])) # True print(["even", 4, "even", 7, "even", 55, "even", 6, "even", 10, "odd", 3, "even"].index(55)) # True print(10 in ["even", 4, "even", 7, "even", 55, "even", 6, "even", 10, "odd", 3, "even"]) # True print(11 in ["even", 4, "even", 7, "even", 55, "even", 6, "even", 10, "odd", 3, "even"]) # True def find_sum(n): return sum(i for i in range(n + 1) if i % 3 == 0 or i % 5 == 0) ''' ''' # res = 0 # for i in range(n + 1): # if i % 3 == 0 or i % 5 == 0: # res += i # return res print(find_sum(5)) # return 8 (3 + 5) print(find_sum(10)) # return 33 (3 + 5 + 6 + 9 + 10) names = ["Rayn", "Kieran", "Herman", "Anna", "John", "Alexander"] def get_names(arr): return [i for i in arr if len(i) == 4] print(get_names(names))
false
1843e5a28cf0a2c434f789ff73fa3fb75d208aee
kirankumar2079/competivtive-programming
/urionlinejudge/simplecalculate(1010).py
918
4.15625
4
*** In this problem, the task is to read a code of a product 1, the number of units of product 1, the price for one unit of product 1, the code of a product 2, the number of units of product 2 and the price for one unit of product 2. After this, calculate and show the amount to be paid. Input The input file contains two lines of data. In each line there will be 3 values: two integers and a floating value with 2 digits after the decimal point. Output The output file must be a message like the following example where "Valor a pagar" means Value to Pay. Remember the space after ":" and after "R$" symbol. The value must be presented with 2 digits after the point. Input Samples Output Samples 12 1 5.30 16 2 5.10 VALOR A PAGAR: R$ 15.50 *** item1=list(map(float,input().split())) item2=list(map(float,input().split())) total=item1[1]*item1[2]+item2[1]*item2[2] print("VALOR A PAGAR: R$ {0:.2f}".format(total))
true
76b1a24ff36bbe3eeb046df05c736746d0cd034f
krapivani/TicTacToe
/main.py
1,257
4.40625
4
from tictactoe import TicTacToe import random def main(): """ create an instance of TicTacToe class""" t = TicTacToe() #get the value of whose turn it is X or O board_state = random.choice([t.STATES.NAUGHT_TURN, t.STATES.CROSS_TURN]) """ use a while loop to intrectively play TicTacToe and save the board state run loop until someone wins or its draw get the valid user input for location in form of row,col call place_marker funtion on user input and print the updated board state """ while board_state != t.STATES.NAUGHT_WON and board_state != t.STATES.CROSS_WON and board_state != t.STATES.DRAW: print(board_state) val = input('Enter location in format row,column:').split(',') turn = 'x' if (board_state == t.STATES.CROSS_TURN) else 'o' row = int(val[0]) col = int(val[1]) if row not in range(0,3) or col not in range(0,3) or t.board[row][col] != ' ': print('Please enter valid location in format row,column') continue board_state = t.place_marker(turn,row,col) print(t.board[0]) print(t.board[1]) print(t.board[2]) print(board_state) if __name__ == "__main__": main()
false
85823d0ba058769f372317efad8eda143645051c
JVorous/ProjectEuler
/problem46.py
1,246
4.125
4
''' It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? ____ OBSERVATIONS for any odd composite, n, that satisfies n = p + 2x^2, where p is prime and x is a natural number only need study primes that are less than n-2 since both p and x are non-zero integers it follows that x is strictly less than (n/2)^.5 ''' import time import math from problem27 import list_primes, is_prime def gold_num(n): prime_list = list_primes(n - 2) is_gold_num = False for k in range(1, int(math.sqrt(n / 2) + 1)): p = n - 2*k**2 if p in prime_list: is_gold_num = True break return is_gold_num # driver code if __name__ == '__main__': start_time = time.time() done = False n = 33 while not done: n += 2 if not is_prime(n) and not gold_num(n): done = True print('Result: {}'.format(n)) print('Runtime: {}'.format(time.time() - start_time))
true
af5d0a9517c9bb0ed113f25eb41363dc0c55d5fa
Thunderqz1/pythontools
/todo.py
1,333
4.53125
5
# CREATE A TO-DO List app within Terminal # This App will store all the items in an array and display it everytime we # add an item to the list and delete an item from the list # Application needs to allow the user to ADD an item to the list # Application needs to allow the user to DELETE an item from the list # Application needs to allow the user to print out the current to-do list u_array = [] print("\n") print("Welcome to ToDo! Please add to your list :)") print(""" *Commands* done / close = exit application print = print out your list remove = prompt list to remove an item """) while True: userin = input(">: ") if userin == 'done' or userin == 'close': exit() elif userin == 'print' or userin == 'Print': print("Here is your list", u_array) elif userin == 'remove' or userin == 'Remove': print("What would you like remove?") print(u_array) delete = input("rm*: ") try: u_array.remove(delete) print("*",delete, "has been removed *") except: print("Sorry, invalid input") try: u_array.append(userin) if userin == 'remove' or userin == 'Remove' or userin == 'print' or userin == 'Print': del u_array[-1] except: print("Sorry, invalid input.")
true
74358cd2320d81dc8a1d0369c47dd1e65247ab0f
aldrinpscastro/PythonExercicios
/EstruturaDeRepeticao/ex019.py
774
4.125
4
maior = 0 menor = 0 soma = 0 opcao = ' ' while opcao != 'N': opcao = ' ' numero = -1 while numero < 0 or numero > 1000: numero = int(input('Digite um número: ')) if numero < 0 or numero > 1000: print('Você deve digitar um número 0 e 1000.') if menor == 0: menor = numero if numero > maior: maior = numero if numero < menor: menor = numero soma += numero while opcao not in 'SN' or not opcao: opcao = str(input('Quer continuar: [S/N] ')).upper() if opcao not in 'SN' or not opcao: print('Opção inválida. Tente novamente.') print(f'O maior número digitado foi {maior}. O menor número digitado foi {menor}. E a soma de todos os números é igual a {soma}.')
false
48f9fa66a37913fc00cee3c18b7e73f2a236e192
mmveres/pyLesson1
/lesson03/oop/__main__.py
405
4.28125
4
from lesson03.oop.car import Car from lesson03.oop.list_car import ListCar if __name__ == '__main__': car1 = Car("Ford", 100, 10) cars = [Car("Ford1", 130, 20), Car("Ford3", 120, 10), Car("Ford2", 100, 30)] car_list = ListCar(cars) car_list.append(Car("Ford4", 110, 15)) print(car_list.aver()) print(car_list) for car in car_list: print(car)
true
a7e6bc85389f54819c53ed1beddbd5310e3fab06
eselyavka/python
/is_word_palindrome.py
789
4.1875
4
#!/usr/bin/env python import sys def solution(raw_word): word = raw_word.lower().strip() word_len = len(word) equals = False for i in range(word_len): j = (i+1)/-1 equals = word[i] == word[j] if not equals: return equals return equals def solution_reversed(raw_word): word = raw_word.lower().strip() return list(word) == list(reversed(word)) def solution_slice(raw_word): word = raw_word.lower().strip() return word == word[::-1] if __name__ == '__main__': if len(sys.argv) == 2: IS_PALINDROME = "is" if solution_slice(sys.argv[1]) else "is not a" print "The word '{}' {} palindrome".format(sys.argv[1], IS_PALINDROME) else: raise ValueError('Only one word at a time supported')
false
1b054c7747926a64f0f94eaeaa0a23d40920b062
eselyavka/python
/leetcode/solution_189.py
2,573
4.125
4
#!/usr/bin/env python import unittest class Solution(object): def rotate_temp_arr(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ arr = [None for _ in nums] for i in range(len(nums)): arr[(i+k)%len(nums)] = nums[i] for i in range(len(nums)): nums[i] = arr[i] def _reverse(self, nums, start, end): while start < end: temp = nums[start] nums[start] = nums[end] nums[end] = temp start += 1 end -= 1 def rotate_reverse(self, nums, k): n = len(nums) k %= n self._reverse(nums, 0, n - 1) self._reverse(nums, 0, k - 1) self._reverse(nums, k, n - 1) def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ self.rotate_reverse(nums, k) class TestSolution(unittest.TestCase): def setUp(self): self.solution = Solution() def test_rotate(self): arr = [1, 2, 3, 4, 5, 6, 7] self.solution.rotate(arr, 3) self.assertEqual(arr, [5, 6, 7, 1, 2, 3, 4]) arr2 = [1, 2] self.solution.rotate(arr2, 0) self.assertEqual(arr2, [1, 2]) self.solution.rotate(arr2, 1) self.assertEqual(arr2, [2, 1]) arr3 = [1, 2] self.solution.rotate(arr3, 3) self.assertEqual(arr3, [2, 1]) def test_rotate_temp_arr(self): arr = [1, 2, 3, 4, 5, 6, 7] self.solution.rotate_temp_arr(arr, 3) self.assertEqual(arr, [5, 6, 7, 1, 2, 3, 4]) arr2 = [1, 2] self.solution.rotate_temp_arr(arr2, 0) self.assertEqual(arr2, [1, 2]) self.solution.rotate_temp_arr(arr2, 1) self.assertEqual(arr2, [2, 1]) arr3 = [1, 2] self.solution.rotate_temp_arr(arr3, 3) self.assertEqual(arr3, [2, 1]) def test_rotate_reverse(self): arr = [1, 2, 3, 4, 5, 6, 7] self.solution.rotate_temp_arr(arr, 3) self.assertEqual(arr, [5, 6, 7, 1, 2, 3, 4]) arr2 = [1, 2] self.solution.rotate_temp_arr(arr2, 0) self.assertEqual(arr2, [1, 2]) self.solution.rotate_temp_arr(arr2, 1) self.assertEqual(arr2, [2, 1]) arr3 = [1, 2] self.solution.rotate_temp_arr(arr3, 3) self.assertEqual(arr3, [2, 1]) if __name__ == '__main__': unittest.main()
false
549f90445b884e58c1ab823e7cd55ec8a45ee7aa
DunwoodyME/meng2110
/05_conditionals/3_triangle.py
746
4.21875
4
# -*- coding: utf-8 -*- ''' 3_triangle.py Ex 5-3: Checks if 3 sticks could form a triangle Daniel Thomas Sept 4, 2017 ''' def is_triangle(a, b, c): ''' Takes three stick lengths and checks if they could form a triangle.''' if a >= (b+c): print('No') elif b >= (a+c): print('No') elif c >= (a+b): print('No') else: print('Yes') def check_triangle(): ''' Prompts user to input 3 stick length, and checks if they could form a triangle''' print('\n Enter three stick lengths, and check if they will make a triangle') a = int(input(' First stick: ')) b = int(input(' Second stick:')) c = int(input(' Third stick: ')) #print(' Result: ', end=' ') is_triangle(a,b,c) check_triangle()
true
3c9430e8cc4548dbf732bdf2d8ac3d3764015b1e
DunwoodyME/meng2110
/11_dictionaries/birds.py
1,312
4.125
4
# -*- coding: utf-8 -*- """ birds.py Analyzes bird data - Homework for Think Python Chapter 11 Daniel Thomas October 12, 2017 """ def get_data(filename): ''' Reads the bird observations in a csv data file and calculates total count Returns: dictionary of birds: observances ''' fin = open(filename) h = fin.readline().strip().split(',') birdlist = dict() for line in fin: vals = line.strip().split(',') birdlist[vals[0]] = birdlist.get(vals[0],0) + int(vals[1]) return birdlist def invert_dict(d): inverse = dict() for key in d: val = d[key] inverse.setdefault(val,[]).append(key) return inverse def top_n(d, n): ''' Displays the birds that were sighted n or more times in the dataset ''' print('\n Birds reported {} or more times in 2017:'.format(n)) for key in sorted(d): if d[key] >= n: print(' {0:23} {1:4} reported'.format(key, d[key])) def add_sighting(d, birdname, number): ''' Add a sighting to the birdlist dictionary ''' d[birdname] = d.get(birdname,0) + number def print_name(): print(__name__) birds = get_data('bird_data.csv') add_sighting(birds, 'Wild Turkey', 6) top_n(birds, 10) inverted = invert_dict(birds) print(inverted[4]) print(__name__)
true
27260b7e4540c8d14111bb26bf904bb07a272e76
tarangon5225/pnp
/TomasArango_MundoBanana.py
1,631
4.4375
4
bananas = [] def turn_right(): repeat 3: turn_left() ''' Funcionalidad: Caminar hacia el frente 4 posiciones. Pre: Reeborg está en x=1 || x=5 && mira hacia la derecha || mira hacia la izquierda Pos: Reeborg está en x=1 || x=5 && mira hacia la derecha || mira hacia la izquierda ''' def walk(): while front_is_clear(): racimo = recolectar_bananas() if racimo != 0: bananas.append(racimo) move() ''' Funcionalidad: Cambia de fila en x=5. Pre: Reeborg está en x=5 && mira hacia la derecha Pos: Reeborg está en x=5 && y=+1 && mira hacia la izquierda ''' def change_lineR(): turn_left() racimo = recolectar_bananas() if racimo != 0: bananas.append(racimo) move() turn_left() ''' Funcionalidad: Cambia de fila en x=1. Pre: Reeborg está en x=1 && mira hacia la izquierda Pos: Reeborg está en x=1 && y=+1 && mira hacia la derecha ''' def change_lineL(): turn_right() racimo = recolectar_bananas() if racimo != 0: bananas.append(racimo) move() turn_right() def walk_world(): think(1) repeat 3: walk() change_lineR() walk() change_lineL() walk() change_lineR() walk() return bananas def recolectar_bananas(): num_bananas = 0 while object_here("banana"): take("banana") num_bananas += 1 return num_bananas print(walk_world()) ################################################################ # WARNING: Do not change this comment. # Library Code is below. ################################################################
false
ba3d56b181f3e07451a361f34dae9963c2021e36
tugee/dap2020
/part01-e16_transform/src/transform.py
303
4.1875
4
#!/usr/bin/env python3 def transform(s1, s2): S=s1.split() S2=s2.split() S=map(int,S) S2=map(int,S2) multiplication = [a*b for a,b in zip(S,S2)] print(multiplication) return multiplication def main(): transform("1 5 3", "2 6 -1") if __name__ == "__main__": main()
false
bbc42a34ecebe46f3b6a76421485829b15a91967
tugee/dap2020
/part01-e07_areas_of_shapes/src/areas_of_shapes.py
970
4.1875
4
#!/usr/bin/env python3 import math def main(): while(1): inp=input("Choose a shape (triangle, rectangle, circle):" ) if(inp == ""): break if inp=="triangle": base=int(input("Give base of the triangle:" )) height=int(input("Give height of the triangle:" )) print("The area is "+'{:07.6f}'.format(base*height/2)) continue if inp=="rectangle": base=int(input("Give width of the rectangle:" )) height=int(input("Give height of the rectangle:" )) print("The area is "+'{:07.6f}'.format(base*height)) continue if inp=="circle": radius=int(input("Give radius of the circle:" )) print("The area is "+'{:07.6f}'.format(radius**2*math.pi)) continue else: print("Unknown shape!") continue # enter you solution here if __name__ == "__main__": main()
true
f95aef547992fb66ebdf329e39c2e626c051d5a1
nlt7/Hello-World
/ps6 q4 if else elif.py
596
4.1875
4
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> richter = float(input("Enter a magnitude on the Richter scale: ")) Enter a magnitude on the Richter scale: 8.0 >>> if richter >= 8.0 : print("Most structures fall") Most structures fall >>> elif richter >= 6.0 : print("Many buildings considerably damaged, some collapse") elif richter >= 4.5 : print("Damage to poorly constructed buildings") else: print("No destruction of buildings")
true
eb77bd07295a8b1d3b914abd2ccdf7abc1c56c28
nlt7/Hello-World
/numbers.py
502
4.1875
4
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> # Store input numbers >>> num1 = input('Enter first number: ') Enter first number: 1 >>> num2 = input('Enter second number: ') Enter second number: 2 >>> # Add two numbers >>> sum = float(num1) + float(num2) >>> #Display the sum >>> print('The sum of {0} and {1} is {2}' .format(num1, num2, sum)) The sum of 1 and 2 is 3.0 >>>
true
bdbab16f8f6cfa9eaafd707ee93747fc8ff67f2a
manishym/ml_python
/week1/ex1.py
1,592
4.15625
4
#!/usr/bin/env python # Description: Solves ex1 of machine learning course in python # Purpose: This is part of machine learning course. # Author: Manish M Yathnalli # Date: Sun-28-April-2013 # Copyright 2013 <"Manish M Yathnalli", manish.ym@gmail.com> import scipy.io import numpy as np import matplotlib.pyplot as plt from demo1 import cost, gradient_descent def add_ones_to(X): j = np.asmatrix(np.ones(len(X))).getT() return np.append(j, X, 1) def plotData(X, y): """This function will plot data as explained in ex1 plotData (none) -> none Since it just plots data, we cannot do doctests Author: Manish M Yathnalli Date: Sun-28-April-2013 """ plt.plot(X, y, 'rx') plt.xlabel("X") plt.ylabel("y") plt.show() def main(): """This function will setup variables and will do the doctest Author: Manish M Yathnalli Date: Sun-28-April-2013 """ import doctest d = scipy.io.loadmat("ex1data1.mat") X = np.asmatrix(d['ex1data1'])[:, 0] y = np.asmatrix(d['ex1data1'])[:, 1] theta = np.matrix([[0], [0]]) print "Plotting data..." iterations = 1500 alpha = 0.01 plotData(X, y) X = add_ones_to(X) print cost(X, y, theta) theta, hist = gradient_descent(X, y, alpha, iter=iterations) # No need for theta in my gradient descent. print "Theta found by gradient_descent:", theta htheta = theta.getT() * X.getT() plt.plot(X[:, 1], y, 'rx', X[:, 1], htheta.getT()) plt.xlabel("Training Data") plt.ylabel("Hypothesis") plt.show() #plotData(y, htheta) doctest.testmod() if __name__ == '__main__': main()
true
ac4aede42bf8d786acd3c5c813df5df0e1015d6e
danielrdj/A109_Python
/GraphicalBouncingBall/Ball.py
1,936
4.1875
4
######################################### # Daniel Johnson # Assignment 6.2 # 4/26/19 # # Description: This program simulates a bouncing ball # # Inputs: There is no user input # # Outputs: This outputs a graphical ball bouncing # # Resources used: # https://stackoverflow.com/questions/2679418/how-to-get-the-coordinates-of-an-object-in-a-tkinter-canvas # Frank Witmer's example code ######################################### import random import tkinter class Ball: def __init__(self, canvas, color, size): self.color = color self.velocity = random.randint(5, 10) self.size = size canvas.update() #print(canvas.winfo_width()) self.location_x = random.randint(40, canvas.winfo_width() - 40) self.location_y = random.randint(40, canvas.winfo_height() - 40) #self.location_x = 100 #self.location_y = 20 self.canvasID = canvas.create_oval(self.location_x, self.location_y, self.location_x + size, self.location_y - size, fill=color, width=1) def update_location(self, canvas): #Adjusts height of the ball according to gravity self.location_y += self.velocity self.velocity += 32 #Checks to see if the ball has bounced if self.location_y > canvas.winfo_height(): self.location_y = (canvas.winfo_height()) - ((self.location_y - (canvas.winfo_height())) * 0.5) self.velocity = -0.5 * self.velocity self.velocity += 32*1.5 #Stops ball at the bottom after it loses enough velocity and height if 32 > self.velocity > 0 and self.location_y > canvas.winfo_height(): self.location_y = 500 self.velocity = 0 #print("previous height:", 500-self.location_y_previous) def get_delta_y(self,canvas): return self.location_y - canvas.coords(self.canvasID)[3] def get_canvasID(self): return self.canvasID
true
0b7b394b63a39fcc391b78247b8c692648952a65
NotQuiteHeroes/SchoolProjects
/ProgrammingFundamentals/BasicFunctions.py
595
4.21875
4
# Paige Eckstein # 7/19/2015 # This program will demonstrate various ways to use functions in Python # The main function def main(): welcome_message() # causes welcome_message to run goodbye_message() # causes goodbye_message to run # This function is to welcome people to my program def welcome_message(): print('Welcome to my programming using functions') print('My name is Paige Eckstein') # This function is to say goodbye def goodbye_message(): print('Goodbye!') # This is the main function that starts the program in motion main() # calls main
true
41ff5d223974efcddebc3eee1ffde0b5257be382
terence4wilbert/Programs
/Python/Circle.py
272
4.125
4
class Circle: pi = 3.14159 def __init__(self, radius): self.radius = radius def area(self): return Circle.pi * self.radius * self.radius Circle.pi ## 3.14159 c = Circle(10) print("PI Constent ", c.pi) ## 3.14159 print(c.area()) ## 314.159
false
4afb1e139d23f1d6b90060002cf639792befeb18
Rasegaprabakar/Python_codes
/Merging_two_strings.py
839
4.125
4
# program to merge characters of 2 strings into a single string by taking characters alternatively. Input : S1= "ravi" S2="teja" output: rtaevjia def merge_of_string(): list_string =[] string1= input() string2 = input() length1 = len(string1) length2=len(string2) if(length1>length2): for i in range(0,length1): if(i<length2): list_string.append(string1[i]) list_string.append(string2[i]) else: list_string.append(string1[i]) else: for i in range(0,length2): if(i<length1): list_string.append(string1[i]) list_string.append(string2[i]) else: list_string.append(string2[i]) print(list_string) if __name__ == '__main__': merge_of_string()
false
bc458ced3186c628f85cdbf025ac3c4ce8ecade4
Atharva321/LetusDevOps-Python
/Day_2/Symmetric_Difference.py
1,333
4.40625
4
""" ================================================================ Questions Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both. Input Format The first line of input contains an integer, . The second line contains space-separated integers. The third line contains an integer, . The fourth line contains space-separated integers. Output Format Output the symmetric difference integers in ascending order, one per line. Sample Input STDIN Function ----- -------- 4 set a size M = 4 2 4 5 9 a = {2, 4, 5, 9} 4 set b size N = 4 2 4 11 12 b = {2, 4, 11, 12} Sample Output 5 9 11 12 ============================================================== """" elements_M = int(input()) #M = input() #M = M.split() """ The set function converts the list into set and the map funciton converts the string input into integer when input is splitted by split function Ex. using map and split "1 2 3" ==>[1,2,3]""" set_M = set(map(int,input().split())) #set_M = set(M) elements_N = int(input()) set_N = set(map(int,input().split())) Sym_diff = sorted((set_M.difference(set_N)).union(set_N.difference(set_M))) for i in range(0,len(Sym_diff)): print(Sym_diff[i])
true
a096e311ad84a69c9f8afcb6349e27091e1c30ea
yglj/learngit
/PythonPractice/廖雪峰Python/5.1map函数.py
751
4.1875
4
#map()函数接收两个参数,一个是函数,一个是Iterable #map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。 a=[1,2,3,4,5,6] b=[7,8,9,0] c=map(None,a,b) d=map(lambda x:x+1,a) #匿名函数作参 print(d) print(next(c)) for i in d: print(i) def m(x): return x*x for i in map(m,b): print(i) #d = map(m,a) #返回一个迭代器 Iterator是惰性序列 #print(next(d)) ''' #等价于 l = [] for i in a: print(l.append(m(i))) print(l) ''' b = list(map(str,b)) print(b) ''' def f(x): return x*x r=map(f,[1,2,3,4,5,6,7,8,9]) print(list(r)) #map()作为高阶函数,事实上它把运算规则抽象了 s=list(map(str,[1,2,3,4,5,6,7,8,9])) print(s) '''
false
338b59e28236c3089ee3693f8f39c9d9bdca5d88
yglj/learngit
/PythonPractice/乱七八糟的基础练习/6.for循环.py
582
4.3125
4
''' #for...in循环语句,在一系列对象上进行迭代(Iterates),遍历序列中的每一个项目 for i in range(0,5): for j in range(0,i+1): print('*',end=' ') print() i=bool('False') #Returns True when the argument x is true, False otherwise(0,None,False), #is a subclass of the class int print(i) a=input('moolk') print(a) ''' for i in range(1,10): #range()生成数字序列 左开右闭 for j in range(1,i+1): print(i,'*',j,end=" ") #语句用(‘ ’)隔开 print() #换行 else: print("九九乘法表")
false
900cc0273f3e84c18042faa3eac82c64024bf709
yglj/learngit
/PythonPractice/乱七八糟的基础练习/11.引用.py
695
4.21875
4
print('Simple Assignment') shoplist=['apple','mango','carrot','banana'] #mylist 只是指向同一对象的另一种名称 mylist =shoplist #我购买了第一项项目,所以我将其从列表中删除 del shoplist[0] print('shoplist is',shoplist) print('mylist is',mylist) #注意到 shoplist和 mylist二者都 #打印出了其中都没有apple的同样的列表,以此我们确认 #它们指向的是同一个对象 print('Copy by making a full slice') #通过生成一份完整的切片制作一份列表的副本 mylist = shoplist[:] # 删除第一个项目 del mylist[0] print('shoplist is',shoplist) print('mylist is', mylist) #注意到现在两份列表已出现不同
false
ef62d0f7f83ef90853d652695d63784c71f63dca
yglj/learngit
/PythonPractice/廖雪峰Python/4.迭代器.py
1,251
4.3125
4
''' 可以直接作用于for循环的对象统称为可迭代对象:Iterable 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。 可以使用isinstance()判断一个对象是否是Iterator对象 #生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 把list、dict、str等Iterable变成Iterator可以使用iter()函数 Iterator甚至可以表示一个无限大的数据流, 例如全体自然数。而使用list是永远不可能存储全体自然数的 1.凡是可作用于for循环的对象都是Iterable类型; 2.凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列; 3.集合数据类型如list、dict、str等是Iterable但不是Iterator, 4.可以通过iter()函数获得一个Iterator对象。 可迭代对象(list...)>迭代器(next()) > 生成器(yield) Python的for循环本质上就是通过不断调用next()函数实现的 ''' for x in [1,2,3,4,5]: pass #等价于 it=iter([1,2,3,4,5]) # 首先把list变成迭代器(iter()) while True: try: x=next(it) # 获得下一个值 except StopIteration: # 遇到StopIteration就退出循环 break
false
099989ac48a3ce84a40ca8078bc49e85f505c746
chintan2011/python-learns
/average_of_list_numbers.py
238
4.125
4
numbers = int(input("Enter the numbers of elements to be inserted: ")) arr = [] for i in range(0,numbers): el = int(input("Enter Element:")) arr.append(el) avg = sum(arr)/numbers print("Average of elements in the list",round(avg,2))
true
246a328d3c381cc2ef1943d3a17d6705e9f71da1
JeterG/100DaysOfCode
/Edabit-Python/longestAlternatingSubstring.py
1,303
4.40625
4
# Given a string of digits, return the longest substring with alternating odd/even or even odd digits. If two or more substring have the same lenght, return the substrings that occur first. def longest_substring(digits): #Keep track of all the substrings that occur in the string that follow the pattern. substirings=[] substirings.append(2) print (substirings) # longest_substring(3) digits="225424272163254474441338664823" combined=[] sequence=True substring='' substrings=[] # while sequence: for number in digits: #if the substring is empty then it can start off as either even or odd. if not substring: if int(number)%2==0: substring+=number combined.append((number,'Even')) else: substring+=number combined.append((number,'Odd')) else: if int(substring[-1])%2==0 and int(number)%2!=0 : substring+=number combined.append((number,'Odd')) elif int(substring[-1])%2!=0 and int(number)%2==0 : substring+=number combined.append((number,'Even')) else: if len(substring)>=2: substrings.append(substring) substring='' else: substring='' print(substrings)
true
8862ac2d23999d4a481d5889cbd51c04471283dd
Inna99/homework
/homework7/task1.py
749
4.15625
4
""" Given a dictionary (tree), that can contains multiple nested structures. Write a function, that takes element and finds the number of occurrences of this element in the tree. Tree can only contains basic structures like: str, list, tuple, dict, set, int, bool """ from typing import Any def find_occurrences(tree: dict, element: Any, count=0) -> int: """takes element and finds the number of occurrences of this element in the tree""" values = tree.values() if getattr(tree, "values", None) else tree for elem in values: if elem == element: count += 1 elif isinstance(elem, (list, tuple, set, dict)): count = find_occurrences(elem, element, count=count) # type: ignore return count
true
cf6eb8a6407e9e1b15bb81fafc14e9d19d57c7ca
Inna99/homework
/homework11/task2.py
955
4.1875
4
""" You are given the following code: class Order: morning_discount = 0.25 def init(self, price): self.price = price def final_price(self): return self.price - self.price * self.morning_discount Make it possible to use different discount programs. Hint: use strategy behavioural OOP pattern. https://refactoring.guru/design-patterns/strategy Example of the result call: def morning_discount(order): ... def elder_discount(order): ... order_1 = Order(100, morning_discount) assert order_1.final_price() == 75 order_2 = Order(100, elder_discount) assert order_2.final_price() == 10 """ from homework11.strategy import BasicDiscount, DayDiscount, NoDiscount, Order if __name__ == "__main__": # pragma: no cover orders = [ Order(100, NoDiscount()), Order(100, BasicDiscount(0.20)), Order(100, DayDiscount([i for i in range(0, 32)], 0.20)), ] for order in orders: print(order)
true
a628a4cac196c6aab4da575f3af31b6fca06d246
Ahsanul-kabir/Python-Learning-Codes
/Mosh_13_Comparison Operators.py
296
4.40625
4
''' if temperature is greather than 30 it's a hot day otherwise if it's less then 10 it's a cold day otherwaise it's neither hot nor cold ''' temp = 25 if temp > 30: print("it's a hot day") elif temp < 10: print("it's a cold day") else: print("it's neither hot nor cold")
true
3175c395a6989fb1c80241a457d596f04ade7e89
radomirbrkovic/algorithms
/sort/exercises/09_convert-an-array-to-reduced-form-set-1-simple-and-hashing.py
639
4.1875
4
# Convert an array to reduced form https://www.geeksforgeeks.org/convert-an-array-to-reduced-form-set-1-simple-and-hashing/ def convert(arr, n): tmp = arr.copy() tmp.sort() m = {} val = 0 for i in range(n): m[tmp[i]] = val val += 1 for i in range(n): arr[i] = m[arr[i]] def printArr(arr, n): for i in range(n): print(arr[i], end = " ") # Driver Code if __name__ == "__main__": arr = [10, 20, 15, 12, 11, 50] n = len(arr) print("Given Array is ") printArr(arr, n) convert(arr , n) print("\n\nConverted Array is ") printArr(arr, n)
false
3a039c05ec9df98835465b889c12a17481195748
kazy0324/math_with_python
/Ch2/exercise/2-3.py
2,193
4.15625
4
# -*- coding: utf-8 -*- ## メソッド,パッケージの読み込み from matplotlib import pyplot as plt import math ##グラフの描図 def draw_graph(x, y): plt.plot(x, y) plt.xlabel("x-coordinate") plt.ylabel("y-coordinate") plt.title("Projectile motion of a ball") ##不動小数点の範囲の生成(時刻 t の生成) def frange(start, final, interval): numbers = [] while start < final: numbers.append(start) start = start + interval return numbers ## 投射運動 (u は初速 (initial velocity),theta は投射の角度) def draw_trajectory(u, theta): ## 角度 theta のラジアンへの変換 theta = math.radians(theta) ## 重力加速度 g g = 9.8 ## 全飛行時間 t_flight = 2*(u*math.sin(theta)/g) ## 0秒から全飛行時間の0.001刻みでの算出 intervals = frange(0, t_flight, 0.01) ## x軸とy軸の座標を格納するための配列 x = [] y = [] ## 時刻 t における座標軸の計算 for t in intervals: ## Sx の計算式 [p.51] x.append(u*math.cos(theta)*t) ## Sy の計算式 [p.52] y.append((u*math.sin(theta)*t) - 0.5*g*t*t) ## 描図 print("全飛行時間: {t_flight}".format(t_flight = t_flight)) print("最大水平距離: {max_height}".format(max_height = max(y))) print("最大垂直距離: {max_length}".format(max_length = max(x))) draw_graph(x, y) if __name__ == "__main__": # 初速の配列 u_list = [] # 角度の配列 theta_list = [] # index index = 1 # ユーザーからの入力 n = int(input("How many trajectories?: ")) while n > len(u_list): u_list.append(float(input("Enter the initial velocity for trajectory {index} (m/s):".format(index = index)))) theta_list.append(float(input("Enter the angle of projection for trajectory {index} (degrees):".format(index = index)))) index += 1 for j in list(range(3)): draw_trajectory(u_list[j], theta_list[j]) #plt.legend(["20", "40", "60"]) plt.savefig("/Users/kazy/Dropbox/Script/_Python/python_math_book/Ch2/image/2-4.pdf") plt.show()
false
98eed8aaee4ab38479cc882f30f1bca7ee152614
mtparagon5/CalculatingDistance_Python
/CalculatingDistanceInSpace.py
2,943
4.5
4
# first we will create an introduction so the user will understand def intro(): introduction = print("This program will calculate the distance between two points " + "in space given their respective X, Y, and Z coordinates" + "\n" + "(Hint: If your two points are 2-dimensional, your Z-coordinates will be 0)") return introduction # in order to calculate the distance between two points # we'll need to know the coordinates of the two points # create a function to get user defined coordinates def get_coordinates(): # we will use try/except to try and account for bad input # we can also gather all of the values at once using the map function while True: try: (x1, y1, z1, x2, y2, z2, *other ) = map(float, input("Enter X, Y, and Z coordinates for both points" + "\n(Separate your values with a comma): ").split(",")) # we can print the given coordinates so the user can verify they are correct print("Point 1: [{}, {}, {}] \nPoint 2: [{}, {}, {}]".format(x1, y1, z1, x2, y2, z2)) # if there are too many values we can let the user know and show them which value was extra if other: print ('you entered too many coordinates') print() print(other) # if the input is bad we'll give the user a little more guidance except ValueError: print("-------------------------------------------------------------------------") print("The coordinates should only contain numbers and be separated with a comma") # we'll also print a new line to allow some space between the instructions print() else: return x1, y1, z1, x2, y2, z2 # next we'll add our own square root function def sqrt(x): square_root = x**(1/2) return square_root # create a function to calculate distance using the coordinates provided by the user def calculate_distance(given_coordinates): coordinates = [] for coordinate in given_coordinates: coordinates.append(coordinate) diff_Xs = abs(coordinates[0] - coordinates[3]); diff_Ys = abs(coordinates[1] - coordinates[4]); diff_Zs = abs(coordinates[2] - coordinates[5]); distance = sqrt((diff_Xs**2) + (diff_Ys**2) + (diff_Zs**2)); return round(distance, 3); # create a function to print the calculated distance between the two points def display_distance(calculated_distance): print("The distance between points (X1, Y1, Z1) and (X2, Y2, Z2) = " + str(calculated_distance)) # here we'll put it all together so it can be run by soley calling main() def main(): intro() coordinate_values = get_coordinates() calculated_distance = calculate_distance(coordinate_values) display_distance(calculated_distance)
true
53673d5665703a3e187fcda6930fa06091c02630
LucasAsil/Pyquestions
/ex075.py
799
4.15625
4
"""Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla.No final mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares.""" nums = (int(input("Digite um valor; ").strip()), int(input("Digite um valor; ").strip()), int(input("Digite um valor; ").strip()), int(input("Digite um valor; ").strip())) print(f"Você digitou os valores {nums}") print(f"O valor 9 apareceu {nums.count(9)} vez.") if 3 in nums: print(f"O valor 3 foi digitado na posição {nums.index(3)+1}.") else: print("O valor 3 não foi digitado em nenhuma posição.") print(f"Os números pares foram; ", end="") for n in nums: if n % 2 == 0: print(n, end=", ")
false
16c472ff17dc715ca3e0e3c27735b0fa75d5ebbf
LucasAsil/Pyquestions
/ex042.py
1,035
4.15625
4
"""Refaça o EXERCICIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: - Equilátero: todos os lados são iguais - Isósceles: dois lados iguais - Escaleno: todos os lados diferentes""" lado1 = float(input('Digite o primeiro valor: ').strip()) lado2 = float(input('Digite o segundo valor: ').strip()) lado3 = float(input('Digite o terceiro valor: ').strip()) #Conferindo possiblidade de formar TRIÂNGULO if lado1 + lado2 > lado3 and lado1 + lado3 > lado2 and lado2 + lado3 > lado1: print('É possivel formar um triângulo com os seguimentos acima') if lado1 == lado2 == lado3: print('Todos os lados são iguais, é um triângulo EQUILÁTERO') elif lado1 != lado2 and lado1 != lado3 and lado2 != lado3: print('Todos os lados são diferentes, é um triângulo Escaleno') else: print('Apenas dois lados são iguais, é um triângulo ISÓSCELES') else: print('Não é possivel formar um triângulo com os seguimentos acima')
false
bed41306d31624499b794b2857def4325e281637
iamsantoshyadav/getting-hands-on-python
/Python scripts/class_simple_example1.py
1,134
4.28125
4
#%% #This program is just an example of learning basic concept about oops concept class even_odd : #"even_odd is our class name or for understand it we can assume that it is just a templete " even=0 #this data usder tha class are atributes of tha class odd=0 def no_even(self,string): #when we decdeare any function in any class is calle method for words in string : if words in ("a","e","i","o","u","A","E","I","O","U"): self.even=self.even+1 print("No of even words in given data : ",self.even) def no_odd(self,string) : for words in string : if words not in ("a","e","i","o","u","A","E","I","O","U"): self.odd=self.odd+1 print("No of odd cherecter is : ",self.odd) var=even_odd() #here var is class even_odd type data=input("Enter any type of data : ") var.no_even(data)# herewe can undertand with this followig expression too even_odd.no_even(data) whre var=even_odd() var.no_odd(data) #folowing syntex just tell about types of class and also direction of class type veriable print(type(var)) print(dir(var))
false
4054c9068e9545d080e5171245d8c24c8a6f43cb
nosoccus/python-online-course
/TASK_4/matrix.py
566
4.4375
4
my_list = [] temp_list = [] n = int(input('Enter number of rows: ')) m = int(input('Enter number of columns: ')) print("Please, input elements of matrix one by one") # Заповнюємо нашу матрицю через консоль for i in range(n): for j in range(m): temp_list.append(int(input())) my_list.append(temp_list) temp_list = [] print("Original matrix is: ") for row in my_list : print(row) # Транспонуємо t_matrix = zip(*my_list) print("\nTransposed matrix is: ") for row in t_matrix: print(list(row))
false
b0244ffe97bad17fe64e44991878f74cd0abf6dd
Brandon-Pampuch/Intro-Python-I
/src/13_file_io.py
995
4.25
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ with open('./foo.txt', 'r') as f: read_data = f.read() # We can check that the file has been automatically closed. f.closed # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file with open('./foo.txt', 'r') as e: read_data = e.read() print(read_data) e.closed # YOUR CODE HERE # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain with open('./bar.txt', 'w') as t: write_data = t.write(' hello \n I am \n Brandon') t.closed with open('./bar.txt', 'r') as u: read_data = u.read() print(read_data) u.closed # YOUR CODE HERE
true
0340f9d741aa22805fd0314f2695e3c5c5eaa863
shrutijai1/Basic-Programs
/Basic_1.py
455
4.25
4
#print addition of two numbers number1 = int(input("Enter first number : ")) # taking input form user for first number1 number2 = int(input("Enter first number : ")) # taking input form user for second number2 print("addition of two number is", number1+number2) sum = number1+number2 #second way using fromating print("Sum of {0} and {1} is {2}" .format(number1, number2, sum) ) print("Sum of {0} and {1} is {2}".format(number1, number2, sum))
true
fceed80582710f3dd5cc9670083a8d1eaf7d290f
pyslow/dnvip
/code/day04/dn_day04_Slow.py
1,033
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/5/26 11:00 # @Author : Slow # @File : dn_day04_Slow.py # @Software: PyCharm # 第一题: num_list = [[1,2],['tom','jim'],(3,4),['ben']] # 1. 在’ben’后面添加’kity’ # num_list[3].append('kity') # 2. 获取包含’ben’的list的元素 # for ite in num_list: # if 'ben' in ite: # print(ite) # 3. 把’jim’修改为’lucy’ # num_list[1][1]='lucy' # print(num_list) # 4. 尝试修改3为5,看看 # num_list[2][0]=5 因为是元组不能修改 # 5. 把[6,7]添加到[‘tom’,’jim’]中作为第三个元素 # num_list[1].append([6,7]) # print(num_list) # 6.把num_list切片操作: # num_list[-1::-1] print(num_list[0::2]) print(num_list[-1::-1]) # 第二题: numbers = [1,3,5,7,8,25,4,20,29] # 1.对list所有的元素按从小到大的顺序排序 numbers.sort() print(numbers) # 2.求list所有元素之和 numsum=0 for num in numbers: numsum+=num print(numsum) # 3.将所有元素倒序排列 numbers[-1::-1]
false
bf8a77a4af80afd05de456e0f22fedf6eb9e5b9d
BryantLuu/dailycodingproblems
/352.py
2,848
4.5
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Palantir. A typical American-style crossword puzzle grid is an N x N matrix with black and white squares, which obeys the following rules: Every white square must be part of an "across" word and a "down" word. No word can be fewer than three letters long. Every white square must be reachable from every other white square. The grid is rotationally symmetric (for example, the colors of the top left and bottom right squares must match). Write a program to determine whether a given matrix qualifies as a crossword grid. Upgrade to premium and get in-depth solutions to every problem. If you liked this problem, feel free to forward it along so they can subscribe here! As always, shoot us an email if there's anything we can help with! """ def check_connected(x, y, crossword, visited): if x >= len(crossword) or x < 0 or y >= len(crossword) or y < 0: return 0 if (x, y) in visited: return 0 if crossword[x][y] == 1: visited.append((x, y)) return (check_connected(x + 1, y, crossword, visited) + check_connected(x - 1, y, crossword, visited) + check_connected(x, y + 1, crossword, visited) + check_connected(x, y - 1, crossword, visited)) + 1 return 0 def get_flat(crossword): new_list = [] for row in crossword: new_list.extend(row) return new_list def all_connected(crossword): y = None for index in range(len(crossword[0])): if crossword[0][index] == 1: y = index return check_connected(0, y, crossword, []) == sum(get_flat(crossword)) def valid_row(row): count = 0 for square in row: if square == 1: count += 1 else: if count < 3 and count != 0: return False count = 0 if count < 3 and count != 0: return False return True def is_symmetric(crossword): new_list = [] for row in crossword: new_list.extend(row) reversed_list = list(new_list) reversed_list.reverse() return new_list == reversed_list def is_valid_crossword(crossword): columns = [*zip(*crossword)] is_valid = True for row in crossword: is_valid = is_valid and valid_row(row) for column in columns: is_valid = is_valid and valid_row(column) is_valid = is_valid and is_symmetric(crossword) is_valid = is_valid and all_connected(crossword) return is_valid def main(): is_valid_crossword([ [0, 1, 1, 1, 1, 1], [0, 1, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], ]) # is_valid_crossword([[1, 0], [0, 1]]) if __name__ == '__main__': main()
true
4448730c019bb27a012760a7d92b09b54f09100a
miaomiaotao9/obds_training
/bubble_sort.py
1,296
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 22 10:29:54 2020 @author: mjabeen """ """Find the maximum number number_list = [26, 54, 93, 17, 77, 31, 44, 55, 20] max_number = number_list[0] Create a loop to find this for number in number_list: if number > max_number: max_number = number print (max_number)""" """Sorting - using the selection sort algorithm >>> selection_sort.py""" """start by turning above code into function""" number_list = [26, 54, 93, 17, 77, 31, 44, 55, 20] # Outer loop - use j to define length of list, going down to zero, excluding last variable #'Stepping loop' for j in range (len(number_list), 1, -1): for i in range (0, j-1, 1): #Inner loop - 'swapping loop': pushing largest number to the end if number_list[i]>number_list[i+1]: #pairwise comparisons temp = number_list[i] #creating temporary variable number_list [i] = number_list[i+1] #swapping variables (line 31 - 32) number_list[i+1] = temp print(number_list) #instead of i or j think about using meaningful variable names for ease of interpreting code # e.g. j = step/iteration, i = current index of position in list
true
b1c0f51cb4b1d8df996e1e21b082f312740d71b3
yucdong/courses
/ucb_cs61A/lab/lab01/lab01_extra.py
652
4.21875
4
"""Coding practice for Lab 1.""" # While Loops def factors(n): """Prints out all of the numbers that divide `n` evenly. >>> factors(20) 20 10 5 4 2 1 """ orig = n while orig >= 1: if n % orig == 0: print (orig) orig = orig - 1 def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 """ product = 1 while k > 0: product = product * n n = n - 1 k = k - 1 return product
false
0bf0ac446b569b6bd330520eea802575e2c1d3f6
yucdong/courses
/ucb_cs61A/lab/lab04/utils.py
952
4.15625
4
def make_city(name, lat, lon): """ >>> city = make_city('Berkeley', 0, 1) >>> get_name(city) 'Berkeley' >>> get_lat(city) 0 >>> get_lon(city) 1 """ return [name, lat, lon] def get_name(city): """ >>> city = make_city('Berkeley', 0, 1) >>> get_name(city) 'Berkeley' """ return city[0] def get_lat(city): """ >>> city = make_city('Berkeley', 0, 1) >>> get_lat(city) 0 """ return city[1] def get_lon(city): """ >>> city = make_city('Berkeley', 0, 1) >>> get_lon(city) 1 """ return city[2] from math import sqrt def distance(city_1, city_2): """ >>> city1 = make_city('city1', 0, 1) >>> city2 = make_city('city2', 0, 2) >>> distance(city1, city2) 1.0 """ lat_1, lon_1 = get_lat(city_1), get_lon(city_1) lat_2, lon_2 = get_lat(city_2), get_lon(city_2) return sqrt((lat_1 - lat_2)**2 + (lon_1 - lon_2)**2)
false
31ab9afff6469973f14b01fca33cb2726feef845
Whitatt/myRepository
/Python-Projects/Python_if.py
302
4.28125
4
num1 = 12 key = False if num1 == 12: if key: print('Num1 is equal to Twelve and they have the key!') else: print('NUm1 is equal to Twelve and they Do NOT have the key!') elif num1 < 12: print('Num1 is less than Twelve!') else: print('Num1 is NOT equal to Twelve!')
true
f547ff4de1a016f2b10697eb1f2cf284f6bfc69f
Kevialito/LiClipse-Workspace
/variables/variablesOutlinesss.py
781
4.375
4
''' This outline will help solidify concepts from the Variables lesson. Fill in this outline as the instructor goes through the lesson. ''' a=4 a=5 #Float a=3.45 a=2.1 #String a = "string" name = "Kevin" #Boolean a=True a=False #List a = [3, 4, 5, 6] a= ["stringOne, stringTwo"] a= [True, False, True] a= [1.1, 2.2, 1.1] varA= 1 vara= 2 print(vara) print(a) var= 4 var= "string" varTwo= var print(varTwo) b = [a, varA, var] List = ("a", "b", "c") print(list) print(list[0]) listVar = list[0] print(listVar) string = "Kevin" print(string[0]) print(5) print("string") print(True) print(list) print(string) ''' Syntax Logical ''' var= 4 name= 4 name= "Kevin" varThree= 0 var=varThree Kevin = "name" print(Kevin) Titles= "Kevin" print(Titles)
true
e9f1f8b1cba8f9e6097a5868f1bd426f0e2d695e
dgpshiva/PythonScripts
/Tree_MaxSumRootToLeaf.py
2,066
4.21875
4
# Find the max sum inside binary tree from root to leaf # and print the path from that leaf to the root class Node: def __init__(self, data): self.data = data self.left = self.right = None class BTree: def __init__(self): self.root = None self.maxSum = None # variable to store the max sum value self.targetNode = None # variable to hold the target leaf node to which sum is max from root def findTargetLeafNode(self, node, curSum): if node: # For every node keep summing the node values curSum += node.data # If the node is a leaf if node.left is None and node.right is None: # Check if this is the target leaf node if curSum > self.maxSum: self.maxSum = curSum self.targetNode = node # Store this target leaf node self.findTargetLeafNode(node.left, curSum) self.findTargetLeafNode(node.right, curSum) def printPathToTargetLeaf(self, node): if node is None: return False # Whenever we find our target leaf node, this becomes True and we print the node value. # And from there we keep returning True, so path from this target node to root gets printed if node == self.targetNode or self.printPathToTargetLeaf(node.left) or self.printPathToTargetLeaf(node.right): print node.data return True if __name__ == '__main__': tree = BTree() tree.root = Node(10) tree.root.left = Node(-2) tree.root.right = Node(7) tree.root.left.left = Node(8) tree.root.left.right = Node(-4) tree.findTargetLeafNode(tree.root, 0) tree.printPathToTargetLeaf(tree.root) print tree.maxSum print "" tree.root = Node(10) tree.root.left = Node(7) tree.root.right = Node(-2) tree.root.left.left = Node(-4) tree.root.left.right = Node(8) tree.findTargetLeafNode(tree.root, 0) tree.printPathToTargetLeaf(tree.root) print tree.maxSum
true
4492cf153290b7cde63f1131b81ece58edb2b202
dgpshiva/PythonScripts
/Practice_Array_BinarySearchWithEmpties.py
1,226
4.21875
4
# Perform binary search in array of strings that may have empty strings # Eg. input: ["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""] def binarySearch(input, value): if not input: return None first = 0 last = len(input) - 1 mid = (first+last)//2 # If mid value is an empty string, # find the immediate left or right non-empty value # and set mid to that if input[mid] == "": left = mid - 1 right = mid + 1 while left >= first and right <= last: if input[left] != "": mid = left break if input[right] != "": mid = right break left += 1 right -= 1 if input[mid] == value: return input[mid] if input[mid] < value: return binarySearch(input[mid+1 : last+1], value) else: return binarySearch(input[first : mid], value) if __name__ == '__main__': input = ["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""] print binarySearch(input, "ball") print binarySearch(input, "cat") print binarySearch(input, "") print binarySearch(input, "at")
true
09baf877aba323b9ee9848f4d1c403e4749fccc2
YogalakshmiS/thinkpython
/chapter 8/Exc 8.3.py
1,424
4.375
4
'''Exercise 8.12. ROT13 is a weak form of encryption that involves “rotating” each letter in a word by 13 places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’. Write a function called rotate_word that takes a string and an integer as parameters, and that returns a new string that contains the letters from the original string “rotated” by the given amount. For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”. You might want to use the built-in functions ord, which converts a character to a numeric code, and chr, which converts numeric codes to characters. Potentially offensive jokes on the Internet are sometimes encoded in ROT13. If you are not easily offended, find and decode some of them.''' import string def rotate_letter(let, n): if let.upper(): start_word = ord('A') elif let.lower(): start_word = ord('a') else: return let k = ord(let) - start_word i = (k + n) % 26 + start_word return chr(i) def rotate_word(word, n): result = '' for let in word: result = result + rotate_letter(let, n) return result print(rotate_word('yoga', 7)) print(rotate_word('laptop', -10)) print(rotate_word('work', 9))
true
c3a95c9ed1dd189ea32732434ddde55b70f233f2
YogalakshmiS/thinkpython
/chapter 3/Exc 3.5.py
1,176
4.65625
5
''' Exercise 3.5. This exercise can be done using only the statements and other features we have learned so far. 1. Write a function that draws a grid like the following: 30 Chapter 3. Functions + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + Hint: to print more than one value on a line, you can print a comma-separated sequence: print '+', '-' If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line. print '+', print '-' The output of these statements is '+ -'. A print statement all by itself ends the current line and goes to the next line ''' def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_beam(): print('+ - - - -') def print_post(): print('| ') def print_beams(): do_twice(print_beam) print('+') def print_posts(): do_twice(print_post) print('|') def print_row(): print_beams() do_four(print_posts) def print_grid(): do_twice(print_row) print_beams() print_grid()
true
6766e53ca07cd84908151d083847aa1384747fdd
sinharahul/algo_training
/dynamic_prog/longest_palindromic_subsequence/longest_palindromic_substring.py
1,269
4.3125
4
#!/usr/bin/env python """ Given a string, find the longest substring which is palindrome. For example, if the given string is 'forgeeksskeegfor', the output should be 'geeksskeeg'. """ def max_palindrome(s, ini, end): """ Returns a tuple with ini and end of max palindrome found from initial (ini, end)""" while ini > 0 and end < len(s)-1: if s[ini - 1] == s[end + 1]: ini -= 1 end += 1 else: break return ini, end def longest_palindrome(s): result = '' max_len = 0 for i in range(len(s) - 1): if s[i] == s[i + 1]: ini, end = max_palindrome(s, i, i + 1) if end - ini > max_len: max_len = end - ini result = s[ini:end+1] if i == 0: continue if s[i - 1] == s[i + 1]: ini, end = max_palindrome(s, i - 1, i + 1) if end - ini > max_len: max_len = end - ini result = s[ini:end+1] return result def test(s): print ("Longest palidrome substring of {} is {}".format( s, longest_palindrome(s))) test("forgeeksskeegfor") test("forgeekskeegfor") test("forrofabc") test("abcforrof") test("abcdefgh") test("1234567654345678987654321")
false
f0a01841cbcc2d97cfac73560a3bc1c1da27e906
jbobo/leetcode
/reverse_linked_list_3_pointer.py
1,044
4.15625
4
#!/usr/bin/env python3 class ListNode: def __init__(self, val, next=None): self.val = val self.next = next def print_list(self): pointer = self print(pointer.val) while pointer.next: pointer = pointer.next print(pointer.val) def reverse_list(head): lead_pointer = None mid_pointer = head trail_pointer = None while mid_pointer: # stash the next element lead_pointer = mid_pointer.next # set the mid pointer to the previous element mid_pointer.next = trail_pointer # previous is moved up to the current node trail_pointer = mid_pointer # update the current node from the stashed value mid_pointer = lead_pointer # lead_pointer = mid_pointer.next return trail_pointer if __name__ == "__main__": test_list = ListNode("A", ListNode("B", ListNode("C", ListNode("D")))) test_list.print_list() reversed_list = reverse_list(test_list) reversed_list.print_list()
true
0fcae2059a0b3ed612bc47126f928153dd146c25
jbobo/leetcode
/merge_k_sorted_lists.py
1,130
4.1875
4
#!/usr/bin/env python3 """ Implement an algorithm to merge K sorted linked lists. This solution pushes each node value into a min-heap/p-queue and then pushes each value from the heap into a new sorted linked list """ from heapq import heappush, heappop class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge_k_lists(lists): min_heap = [] for node in lists: while node: heappush(min_heap, node.val) node = node.next if min_heap: sorted_list_head = ListNode(heappop(min_heap)) pointer = sorted_list_head while min_heap: pointer.next = ListNode(heappop(min_heap)) pointer = pointer.next return sorted_list_head return None if __name__ == "__main__": # [[1,4,5],[1,3,4],[2,6]] lists = [ ListNode(1, ListNode(4, ListNode(5))), ListNode(1, ListNode(3, ListNode(4))), ListNode(2, ListNode(6)) ] merged_list = merge_k_lists(lists) while merged_list: print(merged_list.val) merged_list = merged_list.next
true
f39be9c3223e9ddfa0921ed3a337fe3c6b88a7f1
garyCC227/python_practice
/noteOfPython/Note1.py
1,631
4.15625
4
''' 1 - List comprehensions 2 - iterator and generator 3. decorator ''' ####### List comprehensions # Use [] make code shorter print([i for i in range(10) if i%2 ==0]) seq = ['one','two','three'] print(["{}, {}".format(i,element) for i, element in enumerate(seq)]) ########iterator and generator ##__iter__ this magic function take thing to iterator i = iter('abc') print(next(i)) print(next(i)) ##generator by Yield def myGenerator(): for i in range(5): yield i i = myGenerator() print(next(i)) print(next(i)) #generator.send() #send() can pass value to a yield expreesion, such a controll return def hello(): while True: answer = (yield) if answer == 'yes': yield "I love you" elif answer == 'no': yield "I hate you" free = hello() print(next(free)) print(free.send('yes')) print(next(free)) print(free.send('no')) #generator.close(), generator.throw() ''' like in erro handling: try: except: #throw go here finally: #close go here ''' ##generator shorter expression ## like list comprehensions, but use () to instead [] iter = (i for i in range(10) if i % 2 == 0) print(iter) ##itertools ##islice ''' useage: itertools.islice(iterator, start, end, step) like list slice ''' ##groupby ''' useage: itertools.groupby(data) : similar to 'uniq' in linux = group dulicate element , as long as they are adjacent. ''' from itertools import * def compress(data): return ((len(list(group)), name) for name, group in groupby(data)) print(list(compress('get uppppppppppp'))) ###################################################### ########### decorator
false
9545c527b41c1db5f1e41cb4c0e150852aba55f2
Lily-Mbugua/BMI-Calculator
/Simple BMI Calculator.py
857
4.25
4
# Write your height in meters height = float(input("Enter your height : ")) print(height) # Write your weight in kilograms weight = float(input("Enter your weight : ")) print(weight) bmi = round(weight / (height * height) , 2) print("") print("Your body mass index is : ", bmi) print("") if(bmi < 18.5): print("Oh no, you are under weight") if(bmi > 18.5 and bmi <= 24.9): print("Perfect! you're just right. Normal weight") if(bmi >= 25 and bmi <= 29.9): print(" Wake up call, it seems you're Over Weight") if(bmi >= 30 and bmi <= 34.9): print("You are mildly obese or in other words Obese class 1") if(bmi >= 35 and bmi <= 39.9): print("You are more than average obese or in simpler terms class 2)") if(bmi >= 40): print("You are extremely obese or in other words class 3)") #Keep pushing ! #AkiraChix #CodeHive
true
1857254dde6af827ab9af3f1cb49f2bff369b63a
atharva-tendle/programming-questions
/hackerrank/python/easy/zip.py
349
4.125
4
# get number of students and the subjects n, x = map(int, input().split()) # create a list of subject grades subjects = [] # add the grades for all subjects for _ in range(x): subjects.append(list(map(float, input().split()))) # return the average grades for each student for s_grades in zip(*subjects): print(sum(s_grades)/len(s_grades))
true
dbd8a60385caba6788ac71ffbc56628bf3dfb3c6
prav2508/python
/Operator overloading.py
680
4.15625
4
class Student: def __init__(self,m1,m2): self.m1 = m1 self.m2 = m2 def __add__(self, other): #overloaded method to add 2 objects s1 = self.m1 + other.m1 s2 = self.m2 + other.m2 s3 = Student(s1,s2) return s3 def __str__(self): #overloaded method of print method return "[m1={},m2={}]".format(self.m1,self.m2) s1 = Student(77,89) s2 = Student(74,99) s3 = s1 + s2 print("s3 marks are {},{}".format(s3.m1,s3.m2)) print("---------------------------") print(s3) #it calls __str__() method behind the scene, so to print the object value we need to overload it.. print("---------------------------")
false
0a010f62edf223c0fd70ef51fb1f86dd98ea1d11
ashish3x3/competitive-programming-python
/Hackerrank/is_tree_bst.py
2,327
4.125
4
""" Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ import sys def check_binary_search_tree_(root, min=-sys.maxint, max=+sys.maxint): if root is None: return True if root.data >= max: return False if root.data <= min: return False left = check_binary_search_tree_(root.left, min, root.data) right = check_binary_search_tree_(root.right, root.data, max) return left & right ''' Why does he need these min and max values? I tried comparing the root with left and right nodes and then making the recursion, but it fails on 6 test cases I started with this aproach too, however this only checks that the children nodes are correct for the parent node only. Consider the case where your root node is 100, then we traverse down the left side a couple of times and come to a node that is 50. Let's say the left child is 10, and the right is 999. This will pass because the code only checks the immediate children, however it is not a BST because 999 is much bigger than the root node, 100. ''' ''' # Python program to check if a binary tree is bst or not INT_MAX = 4294967296 INT_MIN = -4294967296 # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Returns true if the given tree is a binary search tree # (efficient version) def isBST(node): return (isBSTUtil(node, INT_MIN, INT_MAX)) # Retusn true if the given tree is a BST and its values # >= min and <= max def isBSTUtil(node, mini, maxi): # An empty tree is BST if node is None: return True # False if this node violates min/max constraint if node.data < mini or node.data > maxi: return False # Otherwise check the subtrees recursively # tightening the min or max constraint return (isBSTUtil(node.left, mini, node.data -1) and isBSTUtil(node.right, node.data+1, maxi)) # Driver program to test above function root = Node(4) root.left = Node(2) root.right = Node(5) root.left.left = Node(1) root.left.right = Node(3) if (isBST(root)): print "Is BST" else: print "Not a BST" '''
true
f944aba94a49bd800e82ae0cb5af353e05d92afd
ashish3x3/competitive-programming-python
/Hackerrank/Algorithms/Strings/find_index_which_makes_string_a_palindrome.py
2,148
4.28125
4
''' You are given a string that is either already a palindrome or can be made into a palindrome by removing a single character. We must consider the following cases: If the string is already a palindrome, is the answer (because no character need be removed). The index of the middle character is also accepable if the string is a palindrome of odd length. The index of either of the two middle characters is also acceptable in the case of a palindrome of even length. If the given string is not a palindrome, we must find character that, once removed, will make it a palindrome. We can do this by checking if str[i] == str[N - 1 - i] where is the length of the string for all starting from . Once this condition fails, all we have to do is to check if str[0:i-1] + str[i+1:N-1] is a palindrome. If it is a palindrome, we print the value of i; otherwise, we print the value of n-1-i. ''' n=int(raw_input()) for n0 in range(n): s=list(raw_input()) if list(reversed(s))==s: print -1 else: for i in range(0,(len(s)/2)+1): if s[i]!= s[-(i+1)]: break del s[i] if list(reversed(s))==s: print i else: print len(s)-i # len(s)+1-i but our l-i is -(i+1) i.e for i =0, j =-1 i.e end element ###################################################### T = input() for _ in xrange(T): S = raw_input() l = len(S) a = -1 for i in xrange(l): if S[i] != S[l - 1 - i]: x = S[:i] + S[i + 1:] if x == x[::-1]: a = i else: a = l - 1 - i break print a ######################################################### T = int(raw_input()) def is_palin(s): return s == s[::-1] for t in xrange(T): s = raw_input() n = len(s) l = 0 r = n-1 ans = -1 while l < r: if s[l] != s[r]: if is_palin(s[:l]+s[l+1:]): ans = l break else: ans = r break l += 1 r -= 1 print ans
true
8046986327a54a171cbce16e04eda3b90ff6b0bb
ashish3x3/competitive-programming-python
/IDeseve/Strings/print-all-anagrams-together.py
2,679
4.3125
4
http://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/ ''' Let us understand the steps with following input Sequence of Words: "cat", "dog", "tac", "god", "act" 1) Create two auxiliary arrays index[] and words[]. Copy all given words to words[] and store the original indexes in index[] index[]: 0 1 2 3 4 words[]: cat dog tac god act 2) Sort individual words in words[]. Index array doesn’t change. index[]: 0 1 2 3 4 words[]: act dgo act dgo act 3) Sort the words array. Compare individual words using strcmp() to sort index: 0 2 4 1 3 words[]: act act act dgo dgo 4) All anagrams come together. But words are changed in words array. To print the original words, take index from the index array and use it in the original array. We get "cat tac act dog god" ''' # A Python program to print all anagarms together # structure for each word of duplicate array class Word(object): def __init__(self, string, index): self.string = string self.index = index # Create a DupArray object that contains an array # of Words def createDupArray(string, size): dupArray = [] # One by one copy words from the given wordArray # to dupArray for i in xrange(size): dupArray.append(Word(string[i], i)) return dupArray # Given a list of words in wordArr[] def printAnagramsTogether(wordArr, size): # Step 1: Create a copy of all words present in # given wordArr. # The copy will also have orignal indexes of words dupArray = createDupArray(wordArr, size) # Step 2: Iterate through all words in dupArray and sort # individual words. for i in xrange(size): dupArray[i].string = ''.join(sorted(dupArray[i].string)) # Step 3: Now sort the array of words in dupArray dupArray = sorted(dupArray, key=lambda k: k.string) # Step 4: Now all words in dupArray are together, but # these words are changed. Use the index member of word # struct to get the corresponding original word for word in dupArray: print wordArr[word.index], # Driver program wordArr = ["cat", "dog", "tac", "god", "act"] size = len(wordArr) printAnagramsTogether(wordArr, size) # This code is contributed by BHAVYA JAIN Time Complexity: Let there be N words and each word has maximum M characters. The upper bound is O(NMLogM + MNLogN). Step 2 takes O(NMLogM) time. Sorting a word takes maximum O(MLogM) time. So sorting N words takes O(NMLogM) time. step 3 takes O(MNLogN) Sorting array of words takes NLogN comparisons. A comparison may take maximum O(M) time. So time to sort array of words will be O(MNLogN).
true
44662b5e91714dc26505af6eead4d43202411e7b
neong83/algorithm_practices
/ex15 - graph.py
1,268
4.125
4
""" graph data structure https://www.python.org/doc/essays/graphs/ 1. build it out 2. find path from A -> B 3. find all path 4. find shortest path 5. find locations in map that connect to other location (except headquarter A) Test Data A -> B => 1 -> 2 A -> C B -> C B -> D C -> D D -> C E -> F F -> C """ from collections import defaultdict paths = [(1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (4, 3), (5, 6), (6, 3)] def convert_path_to_graph(routes): graph = defaultdict(list) for a, b in routes: graph[a].append(b) return graph def find_import_locations_in_graph(locations, graph, visited_locations): for location in locations: if location not in visited_locations: visited_locations.append(location) if location in graph.keys(): yield location yield from find_import_locations_in_graph( graph[location], graph, visited_locations ) print(f"paths = {paths}") graph = convert_path_to_graph(paths) print(f"graph = {dict(graph)}") route_for_root_location = graph[paths[0][0]] # print(route_for_root_location) print( f"import routes = {list(find_import_locations_in_graph(route_for_root_location, graph, []))}" )
true
989f7b5b90b0067481a00e68aad76c4def3726a7
neong83/algorithm_practices
/ex18 - nearest post office.py
2,250
4.25
4
""" Map: _ _ _ _ _ _ _ is blank spot _ _ _ _ _ _ o is post office location _ _ _ _ o _ suggestion is to use BFS to solve this problem _ o _ _ _ _ _ _ _ _ _ o _ _ _ o _ _ """ from typing import Dict from collections import defaultdict, deque def build_map_data(post_offices) -> Dict: matrix = defaultdict(dict) for x in range(6): for y in range(6): has_post_office = 0 if (x, y) in post_offices else -1 # print(f"x={x} y={y} has_office={has_post_office}") matrix[x][y] = has_post_office return matrix def is_post_office(point, city_map): return True if city_map[point[0]][point[1]] == 0 else False def possible_directions(x, y): yield x - 1, y yield x + 1, y yield x, y - 1 yield x, y + 1 def get_neighbours_from_node(point, map): for x, y in possible_directions(*point): if x in map.keys() and y in map[x].keys(): yield (x, y) def bfs_nearest_office_in_map(office, city_map): print(f"--- start at {office}") visited_locations = set() queue = deque() queue.append([office]) while queue: path = queue.popleft() # get the first path from queue node = path[-1] # get the last location from current path print(f" - current location: {node}") if node not in visited_locations: for neighbour in get_neighbours_from_node(node, city_map): new_path = list(path) # make a new copy of the current path new_path.append(neighbour) # add the new location to the path queue.append(new_path) print(f" - new path: {new_path}") if neighbour != office and is_post_office(neighbour, city_map): return new_path visited_locations.add(node) return -1 post_office_locations = [(1, 3), (3, 5), (4, 2), (5, 4)] city_map = build_map_data(post_office_locations) print(city_map) for office in post_office_locations: path = bfs_nearest_office_in_map(office, city_map) print(f"Path to closest post office from {office} to {path[-1]} is '{path}'")
false
3a328971fd1835f06afcc6040798ce91904c64e9
ndcampbell/practice_questions
/chapter_8/question_1.py
754
4.1875
4
#child up stairs N times. can hop 1, 2, 3 steps. How many different ways can the child run up the stairs. def step_hops(n): if n == 0: return 1 elif n < 0: return 0 total = step_hops(n-1) total += step_hops(n-2) total += step_hops(n-3) return total #using dynamic programming def step_hops_dyn(n, memo): if n == 0: return 1 elif n < 0: return 0 if memo[n-1]: return memo[n-1] else: total = step_hops_dyn(n-1, memo) + step_hops_dyn(n-2, memo) + step_hops_dyn(n-3, memo) memo[n-1] = total return memo[n-1] if __name__ == "__main__": examples = [100, 3, 4, 10] for example in examples: print(step_hops_dyn(example, [False]*example))
true
4742874c7bf0fc442d69bea0a13c4a0fa94e23e2
ndcampbell/practice_questions
/chapter_1/question_7.py
827
4.125
4
#rotate matix: given an image represented by NxN matrix, each pixel is 4 bytes, rotate the image by 90 degrees. Can it be done in place? # example: # 1 2 3 4 # 1 2 3 4 # 1 2 3 4 # 1 2 3 4 # # Output: # 1 1 1 1 # 2 2 2 2 # # # #Python doesnt specifically have matrices. Using a nested list. Can use numpy for matrix if more complicated logic is necessary def rotate_matrix(matrix): width = len(matrix) new_matrix = [] for i in range(width): new_matrix.append([0]*width) for j in range(width): new_matrix[i][-j] = matrix[i][i] return new_matrix def print_matrix(matrix): for row in matrix: print(str(row)) if __name__ == "__main__": example = [ [1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]] rotate_matrix(example)
true
c5c5d384428557dd1eac0c3c83819cb3a80d404e
TharindaNimnajith/ML_IP_AIE
/Day 1/5.0 Dictionaries.py
892
4.15625
4
x = [10, 20, 46, 78, 32] print(x[2]) print() std1 = [123, 'John', 91, 89, 78] print(std1[0]) print() #Dictionaries #Similar to Associative Arrays in PHP #Using key names instead of the numerical values of the array elements #Key names can be any name of any type (int, float, string etc.) #For example a key name can be: 'ID', "ID", 45, 4.52 etc. #dict1 = {key1: value1, key2: value2, key3: value3, key4: value4} std1 = {'ID': 123, 'name': 'John', 'maths': 91, 'physics':89, 'chemestry':78} print(std1['ID']) print(std1['name']) print(std1['maths']) print(std1['physics']) print(std1['chemestry']) print(std1) print() std1 = {'ID': 123, 45: 'John', 45.2: 91, "physics":89, 'chemestry':78} print(std1['ID']) print(std1[45]) print(std1[45.2]) print(std1['physics']) print(std1["physics"]) print(std1["chemestry"]) print(std1['chemestry']) print(std1)
true
4d0daf14ba84408d73a53d389a7b624034486781
TharindaNimnajith/ML_IP_AIE
/Day 1/3.0 Lists.py
813
4.25
4
#There are no arrays in Python #There are lists, tuples and dictionaries in Python #List: x = [10, 20.32, 'John', "c", (6 + 2j)] #As Python doesn't consider data types, the list x can have any type of data print(x) #No loop is needed to print the list print(len(x)) #size/length of the array/list print(x[1:3]) #print from element 1 to 3 (element 3 is not included) print(x[1]) #print element 1 print(x[1:]) #print from element 1 to the end print(x[:3]) #print from the beginning (element 0) to element 3 (element 3 - not included) print() x = [10, 20, 46, 78, 32, 12, 43, 12] print(x[1:3]) print(x[1]) print(x[1:]) print(x[:3]) print() print(max(x)) print(min(x)) print(sum(x)) print() #Modifying the list (Assign items/values to the list) x[2] = 0 print(x)
true
a2cbe97808c5a68184e3e467af40387b4cbbf475
ipcoo43/reactone
/lesson194.py
677
4.1875
4
# Bubble Sort # [ 핵심 로직 ] n, n+1 # 1) 첫 번째, 두번째 비교 해서 두번째 더 작은면 첫 번째와 자리 바꿈 # 2) numbers = [7,3,2,9] print('start = [7,3,2,9]') first = numbers[0] second = numbers[1] print(first, second) temp = first first = second second = temp print(first, second) print('[3,7,2,9]') print() numbers = [7,3,2,9] first = numbers[0] third = numbers[2] print(first, third) temp = first first = third third = temp print(first, third) print('[3,7,2,9]') print() numbers = [2,3,7,9] first = numbers[0] fourth = numbers[3] print(first, fourth) temp = first first = fourth fourth = temp print(first, fourth) print('[2,7,3,9]')
false
b6262d49a5dd55e2a236d39834b9392cc73467ef
jacqueline-homan/PythonEmailing
/read_data.py
1,879
4.34375
4
# Reading and writing to csv files in Python import csv ACCEPTED_MSG = """ Hi {}, We are thrilled to let you know that you are accepted to our programming workshop. Your coach is {}. Look forward to seeing you there! Thank you, Workshop Organizers """ REJECTED_MSG = """ Hi {}, We are very sorry to let you know that due to the high number of applications, we could not fit you into the workshop at this time. We hope to see you next time. Thank you, Workshop Organizers """ csv_file = open('/home/jacque/Desktop/applicants.csv') for row in csv_file: print(row) csv_file.close() csv_file2 = open('/home/jacque/Desktop/applicants.csv') csv_reader = csv.reader(csv_file2, delimiter=',') for row in csv_reader: print(row) csv_file2.close() csv_file3 = open('/home/jacque/Desktop/applicants.csv') csv_reader = csv.reader(csv_file3, delimiter=',') next(csv_reader) for row in csv_reader: name, email, accepted, coach, language = row print(name, email, accepted, coach, language) csv_file3.close() csv_file4 = open('/home/jacque/Desktop/applicants.csv') csv_reader = csv.reader(csv_file4, delimiter=',') next(csv_reader) for row in csv_reader: name, email, accepted, coach, language = row if accepted == "Yes": msg = ACCEPTED_MSG.format(name, coach) else: msg = REJECTED_MSG.format(name) print("Send email to: {}".format(email)) print("Email content:") print(msg) csv_file4.close() # using `with` and `as`, we don't need the file.close() function with open('/home/jacque/Desktop/applicants.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) for row in csv_reader: name, email, accepted, coach, language = row if accepted == "Yes": msg = ACCEPTED_MSG.format(name, coach) else: msg = REJECTED_MSG.format(name) print("Send email to: {}".format(email)) print("Email content:") print(msg)
true
796f328641d07421a04e88fd653e47347691ee72
reaganb/gdeck
/cards.py
2,828
4.25
4
import random class Card: SUIT_SET = {'SPADES', 'HEARTS', 'CLUBS', 'DIAMONDS'} RANK_SET = {'A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'} def __init__(self, suit, rank): """ The constructor method consist of an error handling that strictly identifies if the suit and rank values are correct based from the class attribute sets. Arguments: suit -- the suit value rank -- the rank value """ try: if suit.upper().strip() not in Card.SUIT_SET \ or rank.upper().strip() not in Card.RANK_SET: raise ValueError(f'{rank.upper().strip()} of {suit.upper().strip()} ' f'is not a valid Card!') self.suit = suit.upper().strip() self.rank = rank.upper().strip() except ValueError as e: self.suit = None self.rank = None print(e) def __str__(self): return f"{self.rank} of {self.suit}" def __repr__(self): return f"{self.rank} of {self.suit}" class Deck: # The cards class attribute containing the list of Card class objects. cards = [Card(sl, rl) for sl in Card.SUIT_SET for rl in Card.RANK_SET] def __init__(self): """ Upon object instantiation, the cards will be shuffled.""" self.shuffle() def __getitem__(self, position): return repr(Deck.cards[position]) def __len__(self): return len(Deck.cards) @staticmethod def shuffle(): """ The function for shuffling the Class attribute cards""" print("\nShuffling cards.... done!\n") random.shuffle(Deck.cards) if __name__ == '__main__': # The starting point of the script, the Card and Deck class will be used here. card = Card(suit="hearts", rank='A') # Instantiate the card object from the Card class print(card) # Print the card object deck = Deck() # Instantiate the deck object from the Deck class and shuffle its cards print("Number of cards from the deck: ", len(deck)) print("10th card: ", deck[9]) print("1st to 10th card: ", deck[:10]) print("1st to 10th with 2 step card: ", deck[:10:2]) print("Last to First card: ", deck[::-1]) print("Randomly pick a card: ", random.choice(deck)) # Using the choice function of class random on object deck deck.shuffle() # Shuffle the cards from the deck object print("9th card: ", deck[9]) print("1st to 10th card: ", deck[:10]) print("1st to 10th, 2 step card: ", deck[:10:2]) print("Last to First card: ", deck[::-1]) print("Randomly pick a card: ", random.choice(deck)) # Using the choice function of class random on object deck
false
071bf367a40999f73d1f4a06d3c7b504cbb8fb3f
purna-manideep/Python
/ifStatements.py
1,179
4.25
4
# -*- coding: utf-8 -*- num = 5 if num == 5: print(num) if num: print(num) num = 0 if num == 0: print(num) if num: print(num) num = -1 if num == -1: print(num) if num: print(num) text = "Python" if text: print(text) text = "" if text: print(text) python_course = True if python_course: print("This will execute") aliens_found = False if aliens_found: print("This will NOT execute") l = [] if l: print(l) l1 = [1,2,3] if l1: print(l1) # NOT IF: num = 5 if num != 5: print("This will not execute") python_course = True if not python_course: print("This will also not execute") # MULTIPLE IF: num = 5 python_course = True if num and python_course: print("this will execute") if num or python_course: print("this will also execute") if num: if python_course: print("this will execute") # Ternary If Statements a = 20 b = 50 print("bigger" if a > b else "smaller") h = 32 if h > 50: print("Greater than 50") elif h < 20: print("Less than 20") else: print("Between 20 and 50") h = 32 if h > 50: print("Greater than 50") else: if h < 20: print("Less than 20") else: print("Between 20 and 50")
false
ff36422282ff8a460dfdec5bbda89e998be2c959
abbad/code-snippets-and-algorithms
/python_snippets/uniquify_set.py
1,109
4.125
4
''' Transform the following list of items into the one below. Input: ['nutella', 'cake', 'chocolate', 'chips'] Output: ['n', 'ca', 'cho', 'chi'] ''' def uniquify(org_list, item): string_range = 1 result_string = item[0] for val in org_list: flag = True if val != item: while flag: target_string = val[:string_range] if result_string == target_string: string_range += 1 result_string = item[:string_range] else: flag = False continue return result_string def get_shopping_list(org_list): """ A function that takes a list and returns a shorter list. """ # Iterate over the items. result = [] for item in org_list: # Check if character is unique within the list. result.append(uniquify(org_list, item)) return result if __name__ == '__main__': org_list = ['nutella', 'cake', 'chocolate', 'chips'] shortened_list = get_shopping_list(org_list) print(shortened_list)
true
5e15baf246bc760b6ddb8c40d036c451dc437992
abbad/code-snippets-and-algorithms
/python_snippets/max_leaf_node.py
1,030
4.1875
4
# Find the sum of all left leaves in a given binary tree. # Example: # 3 # / \ # 9 20 # / \ # 15 7 # # 1 # 2 3 # 4 5 # # There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. class Node(object): def __init__(self, right, left, val): self.right = right self.left = left self.val = val def __repr__(self): return '%r' % self.val def get_left_leaf_sum(node, acc_sum): if not node: return acc_sum if node.left and not node.left.left and not node.left.right: acc_sum += node.left.val + get_left_leaf_sum(node.right, acc_sum) else: return get_left_leaf_sum(node.right, acc_sum) + get_left_leaf_sum(node.left, acc_sum) return acc_sum if __name__ == '__main__': node_15 = Node(None, None, 15) node_7 = Node(None, None, 7) node_20 = Node(node_7, node_15, 20) node_9 = Node(None, None, 9) node_3 = Node(node_20, node_9, 3) print(get_left_leaf_sum(node_3, 0))
true
0d93642d449801f2df10c0f176ed03d82606d3c9
konfer/PythonTrain
/src/train/assignment/2/24.py
426
4.1875
4
#coding:utf-8 while True: string=raw_input("Your string to encrypt was:\n") rotString='' for s in string: num=ord(s) if num >=65 and num<78 : num+=13 elif num>=78 and num<=90: num-=13 elif num>=97 and num<110: num+=13 elif num>=110 and num<122: num-=13 rotString+=chr(num) print rotString
false
cb8ecadd283fa0df8266b83c21cba500c0e66621
CSC1-1101-TTh9-S21/samplecode
/week9/sumproduct.py
780
4.28125
4
# take two ints, return product and sum def twoints(x,y): a = x+y b = x*y return b, a # Oneliner version! # return a*b, a+b # take two ints, submit them to twoints() # return True if product > sum, False otherwise def bigger(x,y): c = twoints(x,y) if c[0] > c[1]: return True else: return False ## alternative naming elements of returned tuple ## a,b = twoints(x,y) ## if a > b: ## return True ## else: ## return False # main def main(): int1 = 8 int2 = -2 answer = bigger(int1, in2) if answer == True: print("The sum of {} and {} is less than the product".format(8,-2)) else: print("The sum of {} and {} is greater than the product".format(8,-2)) main()
true
bfee4ccb9b5aef7a45f6a0a37c189a2d701fd041
CSC1-1101-TTh9-S21/samplecode
/week4/vaccine-priority.py
1,953
4.125
4
## Option #1: Ask all questions in advance ## then use and and or operators healthcare = input("Are you a healthcare worker? y or n ") covidface = input("Are you a covid facing? y or n ") assistedliving = input("Do you live in an assisted living facility? y or n ") age = int(input("What is your age? ")) comorbidity = int(input("How many comorbidities do you have? ")) essential = input("Are you an essential worker? y or n ") phase = -1 if (healthcare == "y" and covidface == "y") or (age > 65 and assistedliving == "y"): phase = 1 elif age > 75 or (healthcare == "y" and covidface == "n"): phase = 2 elif age > 65 or comorbidity == 2 or (essential == "y" and comorbidity == 1): phase = 3 else: phase = 4 print("You are in phase {}".format(phase)) ## Option #2: Have nested if statements. ## Only ask questions if you need to know the answer! phase = -1 healthcare = input("Are you a healthcase worker? (y or n) ") if healthcare == "y": covidfacing = input("Are you covid facing? (y or n) " ) if covidfacing == "y": phase = 1 else: phase = 2 else: age = int(input("What is your age? ")) if age > 75: assistedliving = input("Do you live in assisted living? ") if assistedliving == "y": phase = 1 else: phase = 2 elif age > 65: assistedliving = input("Do you live in assisted living? ") if assistedliving == "y": phase = 1 else: phase = 3 else: comorb = int(input("How many comorbidities do you have? ")) if comorb >= 2: phase = 3 elif comorb == 1: essential = input("Are you an essential worker? ") if essential == "y": phase = 3 else: phase = 4 print("You are in phase {}".format(phase))
false
292a8998eef9929d77f9aa5b7faff5f29abb245b
CSC1-1101-TTh9-S21/samplecode
/week3/posorneg.py
616
4.28125
4
# This function determines whether a number is # positive, negative, or 0. # The parameter, n, is a number (float or int). def kindofnumber(n): if n < 0: print("negative") elif n > 0: print("positive") else: print("zero") # Here is the main() function definition. # It asks the user to enter a number. # Then it calls the oddeven() function. def main(): # I convert the input to float to allow decimal numbers! mynumber = float(input("Enter an number: ")) # Calling my custom function. kindofnumber(mynumber) # Here's where I run the main() function. main()
true
7e6702ebebd5ec92392dada60b34b8d1d3404bc1
StartAmazing/Python
/venv/Include/tuling/chapter1/oop2.py
631
4.125
4
# 类的例子 # 注意类的定义 class Student(): name = "Peking University" age = 19 def sayHi(self): self.name = 'Beijing University' print("I love {}".format(self.name)) return None def sayHello(): print("My school is {}".format(__class__.name)) return None # 实例化 Alice = Student() print(Alice.name) Alice.sayHi() # 类的变量作用于的问题 # 类变量: 属于类自己的变量 # 实例变量: 属于实例的变量 print(Student.name) Alice.name = "Oxford University" print(Alice.name) Student.sayHi(Alice) print(Student.name) Student.sayHello()
false
c227323f3a8cccb78e590285e4b7706115ee5bf2
Mindy-cm19/Pythonlearning
/test4.py
1,799
4.125
4
# 假设Python没有提供int()函数,自己写一个把字符串转化为整数的函数。(map reduce) from functools import reduce digit={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} def str2int(x): def cha2num(s): return digit[s] return reduce(lambda x,y : x*10 + y , map(cha2num,x)) str2int('135789')+1 # 练习1:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字 # 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: def normalize(name): return name[0].upper()+name[1:].lower() # 测试: L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) # 练习2:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积: def prod(L): return reduce(lambda x,y : x*y , L) print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) # 练习3:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456: s='1237.456' len(s) s.index('.') digit={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} # (1)只能用于有小数点存在时 def str2float(s): def chr2num(x): if x=='.': pass else: return digit[x] return reduce(lambda x,y : x*10 + y , filter(None,map(chr2num,s)))/(10**(len(s)-s.index('.')-1)) # (2)改进:用于所有字符串数字 def str2float(s): digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def chr2num(x): return digit[x] if '.' in s: return reduce(lambda x,y:x*10+y , map(chr2num,s.replace('.','')))*pow(10,s.index('.')+1-len(s)) else: return reduce(lambda x,y:x*10+y , map(chr2num,s))
false
be36038f733235526402e797b8bfc7541be49310
MohdFazalm99/beginner_py
/5-Basic Calculator.py
268
4.34375
4
num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = float(num1) + float(num2) print(result) # Important! always remember that you have to use int or float datatype for adding an input number because python # take every input as a string
true
825cd72d0fd421d48c633201d8ecca792b5ef3bd
MohdFazalm99/beginner_py
/10-functions.py
496
4.21875
4
def say_hi(): # in python function is declared using def . print("Hello user") say_hi() # here we are calling our function def say_name(name): # this is an example of function with parameters print("Hello " + name) say_name("Mike") def say_age(name, age): print("Hello " + name + "you are " + str(age)) # suppose we gave age in integer so we have to use str function so that python will understand that the number is string say_age("Steve", 45) say_age("Mike", 36)
true
7494ddd8387b5058c794865d430d977d4f209e3e
pallavi-ghimire/python_assignment_dec15
/split.py
376
4.25
4
string = input("Enter your full name: ") list1 = string.split() if(len(string)==2): (first_name, last_name) = list1 print("first_name: ", first_name) print("Last name: ", last_name) elif(len(string)==3): (first_name, middle_name, last_name) = list1 print("First_name: ",first_name) print("Middle name: ",middle_name) print("Last name: ",last_name)
true
75b02432fa3bb8f14a1fbdb27e07ccd009e2642f
VirajDeshwal/DataStructure-And-Algo
/LinkList-Python/Count-Of-Nodes.py
990
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 8 02:54:50 2019 @author: SitchAI """ class Node: def __init__(self, data): self.data = data self.next = None class LinkList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) #Assign the new data into Node new_node.next = self.head # assign the next of new Node as head self.head = new_node #assign the head to point to new node #Count the number of Nodes in a link List def Count(self): temp = self.head count = 0 #Loop while end of Link list while(temp): count +=1 temp = temp.next return count if __name__=='__main__': llist = LinkList() llist.push(1) llist.push(3) llist.push(1) llist.push(2) llist.push(1) print ("Count of nodes is :",llist.Count())
true
375e849222768a059b22e0e12d77aace962a3a40
SprutSDM/Lab_1
/caesar.py
947
4.46875
4
def encrypt_caesar(plaintext, shift): """ Encrypts plaintext using a Caesar cipher. >>> encrypt_caesar("PYTHON") 'SBWKRQ' >>> encrypt_caesar("python") 'sbwkrq' >>> encrypt_caesar("") '' """ ciphertext = '' for elem in plaintext: if ord(elem) < 97: ciphertext += chr(65 + (ord(elem) + shift - 65) % 26) else: ciphertext += chr(97 + (ord(elem) + 3 - 97) % 26) return ciphertext def decrypt_caesar(ciphertext, shift): """ Decrypts a ciphertext using a Caesar cipher. >>> decrypt_caesar("SBWKRQ") 'PYTHON' >>> decrypt_caesar("sbwkrq") 'python' >>> decrypt_caesar("") '' """ plaintext = '' for elem in ciphertext: if ord(elem) < 97: plaintext += chr(65 + (ord(elem) - shift - 65 + 26) % 26) else: plaintext += chr(97 + (ord(elem) - shift - 97 + 26) % 26) return plaintext
false
9c417049b375ef99891feb1c40fa66f7c81be49d
igorssmanoel/python_noobs
/listas.py
896
4.21875
4
""" linha = input().split() """ linha = ['a', 'b', 3] # 0 1 2 # acessar primeira posicao print(linha[0]) # ultima posicao print(linha[-1]) print(linha[len(linha)-1]) # penultima posicao print(linha[-2]) texto = "igor manoel" # posicao especifica print(texto[0:4]) # ordenar lista linha = [5, 3, 2, 9, 8] linha.sort() # Ordena em ordem crescente print(linha) linha.sort(reverse=True) # Ordena em ordem decrescente print(linha) linha.append(12) # Adiciona valor na lista linha.append(12) print(linha) linha.pop() # remove o ultimo item ou index passado por parametro linha.remove(12) # remove o primeiro item encontrado pelo valor print(linha) # Dicionario dic = {"chave_1": 1, "chave_2": 2} dic["chave_3"] = 3 # adicionar dic.pop("chave_1") # Remove item pela chave del dic["chave_1"] # Remove item pela chave print(dic)
false
286bb1815161688dbdfd5a961bb9562cd119deeb
MpRonald/Numpy
/Numpy/NumPy Set Operations.py
2,390
4.46875
4
# -*- coding: utf-8 -*- # What is a Set # A set in mathematics is a collection of unique elements. # Sets are used for operations involving frequent intersection, union and # difference operations. # Create Sets in NumPy # We can use NumPy's unique() method to find unique elements from any array. # E.g. create a set array, but remember that the set arrays should only be 1-D # arrays. # Example # Convert following array with repeated elements to a set: import numpy as np arr = np.array([1, 1, 1, 2, 3, 4, 5, 5, 6, 7]) x = np.unique(arr) print(x) # Finding Union # To find the unique values of two arrays, use the union1d() method. # Example # Find union of the following two set arrays: import numpy as np arr1 = np.array([1, 2, 3, 4]) arr2 = np.array([3, 4, 5, 6]) newarr = np.union1d(arr1, arr2) print(newarr) # Finding Intersection # To find only the values that are present in both arrays, use the # intersect1d() method. # Example # Find intersection of the following two set arrays: import numpy as np arr1 = np.array([1, 2, 3, 4]) arr2 = np.array([3, 4, 5, 6]) newarr = np.intersect1d(arr1, arr2, assume_unique=True) print(newarr) # Note: the intersect1d() method takes an optional argument assume_unique, # which if set to True can speed up computation. It should always be set to # True when dealing with sets. # Finding Difference # To find only the values in the first set that is NOT present in the seconds # set, use the setdiff1d() method. # Example # Find the difference of the set1 from set2: import numpy as np set1 = np.array([1, 2, 3, 4]) set2 = np.array([3, 4, 5, 6]) newarr = np.setdiff1d(set1, set2, assume_unique=True) print(newarr) # Note: the setdiff1d() method takes an optional argument assume_unique, which # if set to True can speed up computation. It should always be set to True # when dealing with sets. # Finding Symmetric Difference # To find only the values that are NOT present in BOTH sets, use the setxor1d() # method. # Example # Find the symmetric difference of the set1 and set2: import numpy as np set1 = np.array([1, 2, 3, 4]) set2 = np.array([3, 4, 5, 6]) newarr = np.setxor1d(set1, set2, assume_unique=True) print(newarr) # Note: the setxor1d() method takes an optional argument assume_unique, which # if set to True can speed up computation. It should always be set to True when # dealing with sets.
true
9b3d18f82cf990077a6a56e8bcf3bf804a45a739
shadykhatab/python-tutorilas-
/170_code_challenges/40_code_challenge_solution.py
668
4.3125
4
""" write a function that capitalizes the first and fourth letters of a name ex: capitalize("macdonald") --> MacDonald """ # solution 1 def capitalize(name): first_letter = name[0] in_between = name[1:3] fourth_letter = name[3] rest = name[4:] return first_letter + in_between + fourth_letter + rest result = capitalize("macdonald") print(result) result = capitalize("macarthur") print(result) # solution 2 def capitalize(name): first_half = name[:3] second_half = name[3:] return first_half.capitalize() + second_half.capitalize() result = capitalize("macdonald") print(result) result = capitalize("macarthur") print(result)
true
378ce3687f6ae988bbcb16a1939f62092a520de1
shadykhatab/python-tutorilas-
/170_code_challenges/10_code_challenge_solution.py
1,405
4.5
4
""" Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd. Example 1: lesser_of_two_evens(2, 4) output: 2 explanation: the two parameters 2 and 4 are even numbers, therefore, we'll return the smallest even number Example 2: lesser_of_two_evens(2, 5) output: 5 explanation: the first parameter 2 is even, but the second parameter 5 is odd, therefore, we'll return the greatest number Example 3: lesser_of_two_evens(7, 5) output: 7 explanation: the two parameters are odd, therefore, we'll return the greatest number """ # first solution def lesser_of_two_evens(a, b): if a % 2 == 0 and b % 2 == 0: if a < b: result = a else: result = b else: if a > b: result = a else: result = b return result # testing solution 1 res1 = lesser_of_two_evens(2, 4) print(res1 == 2) res2 = lesser_of_two_evens(2, 5) print(res2 == 5) res3 = lesser_of_two_evens(7, 5) print(res3 == 7) # solution 2 # we can use built in functions from python min and max def lesser_of_two_evens(a, b): if a % 2 == 0 and b % 2 == 0: return min(a, b) else: return max(a, b) res1 = lesser_of_two_evens(2, 4) print(res1 == 2) res2 = lesser_of_two_evens(2, 5) print(res2 == 5) res3 = lesser_of_two_evens(7, 5) print(res3 == 7)
true
18b22ed92869a8ca6845ce42c6c0f547225bca15
edwardmpearce/adventofcode
/2020/Day6/sol.py
2,623
4.125
4
#!/usr/bin/env python3 """ --- Day 6: Custom Customs --- https://adventofcode.com/2020/day/6 Part 1: Size of set union as the number of elements which are in *any* of the subsets Part 2: Size of set intersection as the number of elements in *all* of the supersets """ def main(): results = {"passengers": 0, "groups": 0, "any_yes_group_sum": 0, "all_yes_group_sum": 0} # Read through input file recording the set of positive responses from each group responses = {"any_yes": set(), "all_yes": set("abcdefghijklmnopqrstuvwxyz")} with open("input.txt", 'r') as file: for line in file: # Check for empty line, which signals the end of a group of form responses if line != "\n": results["passengers"] += 1 # Collect the set of questions to which this passenger answered 'yes' yes_questions = set(line.strip()) # Union the set of positive responses from this form with the rest of the group responses["any_yes"] |= yes_questions # Intersect to find questions which all respondents in the group answered positively responses["all_yes"] &= yes_questions else: # Record the current group into the results variable results["groups"] += 1 results["any_yes_group_sum"] += len(responses["any_yes"]) results["all_yes_group_sum"] += len(responses["all_yes"]) # Reset the `responses` variable for the next group of passengers responses["any_yes"] = set() responses["all_yes"] = set("abcdefghijklmnopqrstuvwxyz") # Add the form reponses summary from the last group in the input file if len(responses["any_yes"]) > 0: results["groups"] += 1 results["any_yes_group_sum"] += len(responses["any_yes"]) results["all_yes_group_sum"] += len(responses["all_yes"]) # Print the counts for number of passengers, groups, and questions answered positively by group print(f"Found {results['passengers']} passengers collected into {results['groups']} groups.") print("For each group, we counted the number of questions to which anyone answered 'yes'.") print(f"Part 1: The sum of these 'any_yes' question counts is {results['any_yes_group_sum']}.") print("For each group, we counted the number of questions to which everyone answered 'yes'.") print(f"Part 2: The sum of these 'all_yes' question counts is {results['all_yes_group_sum']}.") return 0 if __name__ == "__main__": main()
true
b8fb1711539442c47d1605fce32a95ca8aeb8d78
pittcat/Algorithm_Practice
/leetcode/isPerfectSquare-367.py
894
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false """ class Solution: def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ if num == 1: return True first = 1 last = num - 1 while last - first > 1: mid = (first + last) // 2 mid_value = mid * mid if mid_value > num: last = mid else: first = mid if first * first == num or last * last == num: return True else: return False # # moe = Solution() # re = moe.isPerfectSquare(16) # print(re)
true
b095342a442b41237ff4c938d47c31999a06c39f
LukasKurinec/MRM_Modelling
/RiskModel/liab/general.py
2,702
4.125
4
""" The aim of the general module is mainly for developer helping purposes """ import pandas as pd import sys import os def open_csvfile(name, index_col=None, skiprows=None, usecols=None, separator=','): """ reading csv files :param name: file name (without .csv extension) :param index_col: number of index column :param skiprows: don't read the first X rows (requires a number) :param usecols: read only given columns (requires a list of number, like [0,1,2]) :param separator: what separator to use, text e.g. '\t' :return: Pandas DataFrame """ df = pd.read_csv('inputfiles/' + name + '.csv', skiprows=skiprows, usecols=usecols, sep=separator, index_col=index_col).fillna(0) df.columns = df.columns.str.lower() return df def write_to_excel(df, filename): """ write one sheet into an excel file :param df: must be Pandas DataFrame :param filename: path/filename (without extension) """ df.to_excel(filename + '.xlsx') def dict_to_series(dictionary): series = pd.Series(dictionary) return series def dict_to_df(dictionary, orient='column'): """ create a Pandas DataFrame from dictionary :param dictionary: the dictionary :param orient: column or index, column is the default :return: Pandas DataFrame """ df = pd.DataFrame.from_dict(dictionary, orient=orient) return df def look_for_in_df(df, category, line): """ searching within a Pandas DataFrame :param df: must be a Pandas DataFrame :param category: column name, text :param line: number of line or label :return: the value for a given category and age """ try: return df.loc[line, category] except KeyError: print("couldn't locate \"" + str(category) + "\"") def change_value_in_df(df, category, line, value): """ change a value within a Pandas DataFrame :param df: must be a Pandas DataFrame :param category: column name, text :param line: row number or indexed label :param value: change to """ try: df.loc[line, category] = value except: print("Unexpected error:", sys.exc_info()[0]) def connectMySQL(): """ storing connection parameters in source code only suitable for testing """ try: import MySQLdb user = '' pw = '' host = '' db = '' conn = MySQLdb.connect(host=host, user=user, passwd=pw, db=db) c = conn.cursor() return c, conn except Exception as e: return str(e) # Disable def blockPrint(): sys.stdout = open(os.devnull, 'w') # Restore def enablePrint(): sys.stdout = sys.__stdout__
true
ef7cd4b95f9d0f1d5dd8b6793ed738c6122aa934
brendengoetz/galvanize-assignments
/strings_lsts_assignment_GOETZ.py
2,817
4.28125
4
#A work in progress here. Only have parts 1 and 2 (almost) finished #in order to un-comment an assignment question script... #highlight the desired section, then type cmd+/ #warm up 1 #this is just the final version of the script. i did not save the incremental steps along theway user_input = raw_input('Add this: ') my_str = 'This String was not Chosen Arbitrarily...' my_str = my_str + user_input print my_str #warm up 2 #this is just the final version of the script. i did not save the incremental steps along theway user_input = raw_input('Add this to the list: ') my_list = [1, 'hello', 2, 'there', 3, 'list'] if len(user_input) < 8: my_list.append(user_input) else: my_list.append(4) print my_list #warm up 3 #this is just the final version of the script. i did not save the incremental steps along theway user_number = int(raw_input('Min length to be printed: ')) my_list = ['hello', 'there', 'python', list('list'), '!'] longer_list = [] for element in my_list: if len(element) > user_number: longer_list.append(element) print longer_list ###Assignment begins here ###Written in Python 3.5 ## Part 1 - Practice with For Loops #Sum numbers up to the inputted number my_num = int(input('Enter a number to find the sum down from: ')) result = 0 for num in range(1, my_num+1): result = num + result print(result) #Write a script that computes and prints the factorial of a user inputted number. my_num = int(input('You want a factorial? Enter a number: ')) result = 1 for num in range(1, my_num+1): result = result*num print (result) #Write a script that determines whether or not a user inputted number is a prime my_num = int(input('See if this numer is prime: ')) for x in range(2, my_num): result = my_num%x if result == 0: print(str(my_num) + ' is NOT prime') break else: print(str(my_num) + ' is a prime') ## Part 2 - Practice with Strings #1 Write a script that obtains the count of a user inputted letter in a user inputted string my_str = input('Write something: ').lower() my_let = input('Now choose a letter from what you wrote: ').lower() print(my_str.count(my_let)) #2 Write a script that checks if a user inputted string ends in an exclamation point my_str = input('Write something: ') if my_str.endswith('!'): print(my_str.upper()) else: print(my_str.lower()) #3 Write a script that removes all of the vowels in a user inputted string. my_str = input('Write something: ') vowels = [ 'a','e','i','o','u'] new = my_str for char in my_str: if char in vowels: new = new.replace(char, '') print(new) #4 Write a script that makes every other letter of a user inputted string capitalized Struggling to get this one... Can have it my_str = input('Write something: ') #for char in my_str: print(my_str[::2].upper())
true
ec0f3bed5d96dee3b1adc8a5f8d77049468c866b
DamianLC/210CT
/210CT Week 1.py
1,631
4.15625
4
import random ##function to randomly shuffle a list of numbers def randShuffle(n): shuffledLst = [] #empty list while len(n) > 0: randNum = random.choice(n) #picks a random number shuffledLst.append(randNum) #adds the number to the list n.remove(randNum) #removes the number from the orignal list return(shuffledLst) ##function to count the amount of trailing 0s in a factorial number def factorialZeros(number): zeroCount = 0 #counter for the trailing 0s factorialNum = 1 #start of the factorial caluclation revFactorial = [] for i in range(1,number+1): #iterates through each number of the user input to calculate the factorial factorialNum = factorialNum * i for reverse in str(factorialNum): #reverses the factorial by placing each integer at the beginning revFactorial.insert(0, reverse) for zeros in revFactorial: #counts the amount of zeros in a factorial until it reaches a number that isn't a zero if zeros == "0": zeroCount += 1 else: break return(zeroCount) print(randShuffle([5,3,8,6,1,9,2,7])) print("\n-----------------\n") print(factorialZeros(10)) print("\n-----------------\n") print(factorialZeros(5)) print("\n-----------------\n") print(factorialZeros(1)) print("\n-----------------\n") print(factorialZeros(0)) print("\n-----------------\n") print(factorialZeros(-2))
true