blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5b269c95f2eeed5db00155b1a25feed94cd56bfe
TomiwaJoseph/Python-Scripts
/emirp_numbers.py
745
4.34375
4
''' An emirp is a prime that results in a different prime when its decimal digits are reversed. Example: Input: 13 Output: True (13 and 31 are prime numbers) Input: 23 Output: False (23 is prime but 32 is not) Input: 113 Output: True (113 and 311 are prime numbers) ''' print() def know_prime(number): return number > 1 and not any(number % n ==0 for n in range(2, number)) def emirp(number): reversed = int(str(number)[::-1]) # find if the number and its reverse is prime return know_prime(number) and know_prime(reversed) entry = int(input('Enter your number: ')) print(emirp(entry)) print() print('Emirp numbers within your input range are:') emirp_range = [i for i in range(entry) if emirp(i)] print(emirp_range)
true
cfab197d408c4a376f486922b7f7c6bbd0377304
TomiwaJoseph/Python-Scripts
/neon_numbers.py
532
4.1875
4
''' A number is considered Neon if the sum of digits of the square of the number is equal to the number itself. Example: Input: 9 9 * 9 == 81 8 + 1 == 9 Output: True ''' print() def neon(number): squared = number ** 2 sum_of_digits = sum([int(i) for i in str(squared)]) return sum_of_digits == number entry = int(input('Enter your number: ') or '911') print(entry) print(neon(entry)) print() print('Neon numbers within your input range are:') neon_range = [i for i in range(entry) if neon(i)] print(neon_range)
true
bebc9c33456253aac57a78dd4dbf58b3854b75c3
TomiwaJoseph/Python-Scripts
/twin_prime_numbers.py
795
4.15625
4
''' A Twin prime is a prime number that is either 2 less or 2 more than another prime number. For example: (41,43) or (149,151) Example: Input: 0,15 Output: (3,5),(5,7),(11,13) ''' print() def check_prime(number): return number > 1 and not any(number % n ==0 for n in range(2, number)) def twin_prime(number): splitted = number.split(',') from_, to_ = int(splitted[0]), int(splitted[1]) # find the primes in that range find_primes = [i for i in range(from_, to_) if check_prime(i)] # loop through the primes and find the ones with a difference of 2 twins = [(x,y) for x in find_primes for y in find_primes if y-x == 2] return twins # entry = int(input('Enter your range seperated with a comma: ')) entry = input() or '0,15' print(twin_prime(entry)) print()
true
0c2ecd13b13a498ff90c14f10cd2d710c07c56da
TomiwaJoseph/Python-Scripts
/anti-lychrel_numbers.py
1,245
4.125
4
''' An anti-Lychrel number is a number that forms a palindrome through the iterative process of repeatedly reversing its digits and adding the resulting numbers. For example 56 becomes palindromic after one iteration: 56+65=121. If the number doesn't become palindromic after 30 iteratioins, then it is not an anti-Lychrel number. Don't be surprised if nearly all the numbers you enter return true! The first 3 non anti-lychrel numbers are 196, 295 and 394 Example: Input: 12 Output: True (12 + 21 = 33, a palindrome) Input: 57 Output: True (57 + 75 = 132, 132 + 231 = 363, a palindrome) ''' print() def anti_lychrel(number): num_of_iter = 1 new_number = number while 1: split_add = new_number + int(str(new_number)[::-1]) new_number = split_add if num_of_iter == 30: return False if str(split_add) == str(split_add)[::-1]: return True else: num_of_iter += 1 entry = int(input('Enter your number: ') or '400') print(anti_lychrel(entry)) print() print('Bonus') print('Non Anti-Lychrel numbers within your input range are:') lychrel_range = [i for i in range(entry) if anti_lychrel(i)] print([i for i in range(entry) if i not in lychrel_range])
true
a091e96b64e922d1c06701fa93a5bafe24258fd3
jchaclan/python
/cat.py
580
4.25
4
# Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats cat1 = Cat('Freddy', 10) cat2 = Cat('Manny', 8) cat3 = Cat('Lucy', 9) # 2 Create a function that finds the oldest cat def getOldestCat(*args): return max(args) # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 print( f'The oldest cat is {getOldestCat(cat1.age, cat2.age, cat3.age)} years old')
true
cd89199bc64100a5527d6a7729b6c52fca85afa8
dinakrasnova/lesson
/lesson2.py
2,236
4.21875
4
''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' for i in range(1,6): print(i, 0) ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. ''' sum = 0 for i in range(10): answer = int(input('Введите любую цифру: ')) if answer == 5: sum += 1 print('Количество цифр 5 равно', sum) ''' Задача 3 Найти сумму ряда чисел от 1 до 100. Полученный результат вывести на экран. ''' sum = 0 for i in range(1,101): sum+=i print(sum) ''' Задача 4 Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран. ''' mult = 1 for i in range(1,101): mult*=i print(mult) ''' Задача 5 Вывести цифры числа на каждой строчке. ''' integer_number = 2129 print(integer_number%10,integer_number//10) while integer_number>0: print(integer_number%10) integer_number = integer_number//10 ''' Задача 6 Найти сумму цифр числа. ''' x = 444 print(sum(map(int,str(x)))) ''' Задача 7 Найти произведение цифр числа. ''' x = 444 y = 1 for i in str(x): y *= int(i) print(y) ''' Задача 8 Дать ответ на вопрос: есть ли среди цифр числа 5? ''' integer_number = 213413 while integer_number>0: if integer_number%10 == 5: print('Yes') break integer_number = integer_number//10 else: print('No') ''' Задача 9 Найти максимальную цифру в числе ''' a = 1234 m = a%10 a = a//10 while a > 0: if a%10 > m: m = a%10 a = a//10 print(m) ''' Задача 10 Найти количество цифр 5 в числе ''' integer_number = 5555666 count = 0 while integer_number>0: if integer_number%10 == 5: count += 1 integer_number = integer_number//10 print(count)
false
f825c3e3fd51e813ae357890221d8287edb9f09b
brianbruggeman/lose-7drl
/lose/utils/algorithms/pathing.py
2,765
4.3125
4
# -*- coding: utf-8 -*- import operator import heapq from .distances import log_distance def create_dijkstra_map(graph, start, target=None, cost_func=None, include_diagonals=None): """Creates a dijkstra map Args: graph (list): a set of nodes start (node): the starting position target (node): the ending position; None means all nodes cost_func (callback): the cost function or distance formula include_diagonals (bool): Only use cardinal directions if False, else include all 8 possibilities Returns: dict: mapping of node: cost """ mapping = { node: cost for cost, node in dijkstra(graph, start, target=target, cost_func=cost_func, include_diagonals=include_diagonals) } return mapping def dijkstra(graph, start, target=None, cost_func=None, include_diagonals=None): """Implementation of dijkstra's algorithm as a generator. This one uses a priority queue for a stack. See: https://en.wikipedia.org/wiki/Dijkstra's_algorithm Args: graph (list): a set of nodes start (node): the starting position target (node): the ending position; None means all nodes cost_func (callback): the cost function or distance formula include_diagonals (bool): Only use cardinal directions if False, else include all 8 possibilities Yields: cost, node """ cost_func = cost_func or log_distance queue = [] heapq.heapify(queue) costs = {start: 0} heapq.heappush(queue, (costs[start], start)) yield (costs[start], start) while queue: node_cost, node = heapq.heappop(queue) node_cost = costs[node] neighbors = get_neighbors(node, include_diagonals=include_diagonals) neighbors = [ neighbor for neighbor in neighbors if neighbor in graph # short circuit on nodes not available if neighbor not in costs # short circuit on nodes already calculated ] for neighbor in neighbors: neighbor_cost = cost_func(start, neighbor) + node_cost yield (neighbor_cost, neighbor) costs[neighbor] = neighbor_cost heapq.heappush(queue, (neighbor_cost, neighbor)) if neighbor == target: break def get_neighbors(node=None, include_diagonals=None): """Creates a list of neighbors. Yields: point: a neighbor node """ if node is None: node = (0, 0) cardinals = [(0, 1), (0, -1), (1, 0), (-1, 0)] diagonals = [(1, 1), (1, -1), (-1, -1), (-1, 1)] directions = cardinals + diagonals if include_diagonals else cardinals for offset in directions: yield tuple(map(operator.add, node, offset))
true
d69954226bd6d65bb7d9fb405a1f21c95a5c55bf
brianbruggeman/lose-7drl
/lose/utils/algorithms/distances.py
2,737
4.5
4
# -*- coding: utf-8 -*- import math from itertools import zip_longest as lzip def manhattan_distance(x, y): """Calculates the distance between x and y using the manhattan formula. This seems slower than euclidean and it is the least accurate Args: x (point): a point in space y (point): a point in space Returns: int: the distance calculated between point x and point y """ diffs = [abs((xval or 0) - (yval or 0)) for xval, yval in lzip(x, y)] return sum(diffs) def euclidean_distance(x, y): """Calculates the distance between x and y using the euclidean formula. This should be the most accurate distance formula. Args: x (point): a point in space y (point): a point in space Returns: float: the distance calculated between point x and point y """ distance = 0 diffs = [abs((xval or 0) - (yval or 0)) for xval, yval in lzip(x, y)] distance = math.sqrt(sum(diff**2 for diff in diffs)) return distance def octagonal_distance(x, y): """Calculates the distance between x and y using the octagonal formula. This is a very fast and fairly accurate approximation of the euclidean distance formula. See: http://www.flipcode.com/archives/Fast_Approximate_Distance_Functions.shtml Args: x (point): a point in space y (point): a point in space Returns: int: the distance calculated between point x and point y """ distance = 0 diffs = [abs((xval or 0) - (yval or 0)) for xval, yval in lzip(x, y)] if len(diffs) != 2: raise TypeError('This distance is only valid in 2D') diff_min = min(diffs) diff_max = max(diffs) approximation = diff_max * 1007 + diff_min * 441 correction = diff_max * 40 if diff_max < (diff_min << 4) else 0 corrected_approximation = approximation - correction distance = (corrected_approximation + 512) >> 10 return distance def log_distance(x, y, func=None, k=None): """Calculates the distance between x and y using the octagonal formula. This wraps a distance function with a log output. If no distance function is provided, then euclidean is used. Args: x (point): a point in space y (point): a point in space func (callback): returning the log of a distance k (numeric): a factor [default: 1.2] Returns: int: the distance calculated between point x and point y """ if k is None: k = 1.2 if func is None: func = octagonal_distance distance = func(x, y) if distance == 0: distance = 1 / 10**10 logged_distance = 6 * math.log(distance) return logged_distance
true
4c300e2170cb75b47518e284b545201cfaafd0af
aineko-macx/python
/ch16/16_6.py
2,019
4.28125
4
import copy class Time(object): """Represents a time in hours, minutes, and seconds. """ def print_time(Time): print("%.2d: %.2d: %.2d" %(Time.hour, Time.minute, Time.second)) def add_time(t1, t2): sum = Time() sum.hour = t1.hour + t2.hour sum.minute = t1.minute + t2.minute sum.second = t1.second + t2.second if sum.second >= 60: sum.second -= 60 sum.minute += 1 if sum.minute >= 60: sum.minute -= 60 sum.hour += 1 return sum def secs(Time): return Time.hour*3600 + Time.minute*60 + Time.second def increment(Time, seconds): newTime = copy.deepcopy(Time) initial = secs(Time) total = initial + seconds hours = total//3600 rem = total%3600 minutes = rem//60 sec = rem%60 newTime.hour = hours newTime.minute = minutes newTime.second = sec return newTime def time_to_int(Time): minutes = Time.hour*60 + Time.minute seconds = minutes *60 + Time.second return seconds def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time def incr(Time, seconds): int = time_to_int(Time) temp = int + seconds newTime = int_to_time(temp) return newTime def mul_time(Time, num): intTime = secs(Time) product = intTime*num result = int_to_time(product) return result def pace(Time, dist): pace = mul_time(Time, 1/dist) return pace #Main myTime = Time() myTime.hour = 0 myTime.minute = 10 myTime.second = 30 print_time(pace(myTime, 1.5)) """ newTime = increment(myTime, 9999) print_time(newTime) ans = int_to_time(time_to_int(myTime)) print_time(ans) newTime1 = incr(myTime, 9999) print_time(newTime1) start = Time() start.hour = 9 start.minute = 45 start.second = 0 duration = Time() duration.hour = 1 duration.minute = 35 duration.second = 0 done = add_time(start, duration) print_time(done) """
true
f55cd76dfe5ccb409039ae8f53b69d48ffd33677
aineko-macx/python
/ch17/17_1.py
892
4.25
4
class Time(object): """Represents the time of day. """ def __init__(self, hour = 0, minute = 0, second = 0): self.hour = hour self.minute = minute self.second = second def print_time(self): print("%.2d: %.2d %.2d" %(self.hour, self.minute, self.second)) def time_to_int(self): return self.hour*3600 + self.minute*60 + self.second def increment(self, seconds): seconds += self.time_to_int() return int_to_time(seconds) def is_after(self, other): return self.time_to_int() > other.time_to_int() def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time start = Time() start.hour = 9 start.minute = 45 start.second = 00 end = start.increment(1337) start.print_time() end.print_time()
true
cc6c7455f19cc0beb742973aec0dd34371e3ef4c
aineko-macx/python
/ch17/17_5.py
982
4.25
4
class Point(object): """Represents a point in 2-D Cartesian space. """ def __init__(self, x = 0.0, y = 0.0): self.x = x self.y = y def __str__(self): return("(%g , %g)" % (self.x, self.y)) def __add__(self, other): if isinstance(other, Point): return self.add_point(other) else: return self.add_tuple(other) def __radd__(self, other): return self.__add__(other) def add_point(self, other): temp = Point() temp.x = self.x + other.x temp.y = self.y + other.y return temp def add_tuple(self, tuple): temp = Point() temp.x = self.x + tuple[0] temp.y = self.y + tuple[1] return temp p = Point() p.x = 3 p.y= 10 print("p = ", p) p1 = Point() p1.x = 5 p1.y = 6 print("p1 = ", p1) print("p + p1 = ", p+p1) p2 = p1+(1,1) print("p2 = p1 + (1,1) = ", p2) p3 = (1,1) + p2 print("p3 = (1,1) + p2 = ", p3)
false
82d1990426120000f438a843da0f103baf3ed5df
akfmartins/Curso-de-Python
/desafio015.py
384
4.125
4
''' Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado. ''' c = float(input("Informe a temperatura em °C: ")) f = ((9 * c) / 5) + 32 print("A temperatura de {} °C corresponde a {} °F!".format(c, f))
false
6d9f449312a335671fd358bf0482486d59eab245
SoniaB77/Exercise_12_Collections
/exercise12.2.py
267
4.25
4
tup = 'Hello' print(len(tup)) print(type(tup)) # this is a string so the length is checking the iterables of the string which is 5. tup = 'Hello', print(len(tup)) print(type(tup)) # this is a tuple so it is checking the iterables but of a tuple so this outputs 1.
true
11d167121472792a525554e7d54d1bed829a641c
ProgrammingForDiscreteMath/20170823-bodhayan
/code.py
2,748
4.46875
4
""" This is the code file for Assignment from 23rd August 2017. This is due on 30th August 2017. """ ################################################## #Complete the functions as specified by docstrings # 1 def entries_less_than_ten(L): """ Return those elements of L which are less than ten. Args: L: a list Returns: A sublist of L consisting of those entries which are less than 10. """ return [i for i in L if i < 10]#Add your code here #Test #print entries_less_than_ten([2, 13, 4, 6, -5]) == [2, 4, 6, -5] # 2 def number_of_negatives(L): """ Return the number of negative numbers in L. Args: L: list of integers Returns: number of entries of L which are negative """ return sum(i<0 for i in L)##YOUR CODE REPLACES THIS # TEST #print number_of_negatives([2, -1, 3, 0, -1, 0, -45, 21]) == 3 # 3 def common_elements(L1, L2): """ Return the common elements of lists ``L1`` and ``L2``. Args: L1: List L2: List Returns: A list whose elements are the common elements of ``L1`` and ``L2`` WITHOUT DUPLICATES. """ return list(set(L1).intersection(L2)) # your code goes here #TEST #print common_elements([1, 2, 1, 4, "bio", 6, 1], [4, 4, 2, 1, 3, 5]) == [1, 2, 4] #4 def fibonacci_generator(): """ Generate the Fibonacci sequence. The Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21,... is defined by a1=1, a2=1, and an = a(n-1) + a(n-2). """ i,j=1,1 while True: yield i i,j=j,i+j# Hint: use the ``yield`` command. #TEST f = fibonacci_generator() #print f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next() #[f.next() for f in range(10)] #== [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] #5 def largest_fibonacci_before(n): """ Return the largest Fibonacci number less than ``n``. """ f=fibonacci_generator() i=f.next() j=f.next() while j<n: i=j j=f.next() #Your code goes here. return i #TEST #print largest_fibonacci_before(55) == 34 #6 def fact(n): if n==0: return 1 else: return n*fact(n-1) def catalan_generator(): """ Generate the sequence of Catalan numbers. For the definition of the Catalan number sequence see `OEIS <https://www.oeis.org/A000108>`. """ i=0 while True: yield fact(2*i)/(fact(i)*fact(i+1))#Your code goes here. i+=1 #TEST #c = catalan_generator() #print [c.next() for i in range(10)] #== [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862] #7 ### CREATE YOUR OWN FUNCTION. Make sure it has a nice docstring. # See https://www.python.org/dev/peps/pep-0257/ # for basic tips on docstrings.
true
97deeac8f41eec71854d110f529d35053203302b
YongCloud/Python
/housing_loan_calculator.py
1,673
4.4375
4
''' A simple housing loan calculator ''' def average_capital(amount,rate,term): ''' Average Capital amount: loan amount rate: interest rate(per year) term: loan term(years) ''' print('===Average Capital===') mon_principal = amount / (12 * term) mon_rate = rate / 12 sum_i = 0; for i in range(12 * term): interest = (amount - i * mon_principal) * mon_rate sum_i += interest print("#{} monthly payment:{:.2f}".format(i + 1,mon_principal + interest)) return sum_i def average_capital_plus_interest(amount,rate,term): ''' Average Capital Plus Interest amount: loan amount rate: interest rate(per year) term: loan term(years) ''' print('===Average Capital Plus Interest===') mon_rate = rate / 12 mon_pay = amount * (mon_rate / (1 - (1 + mon_rate) ** (-12 * term))) print("monthly payment:{:.2f}".format(mon_pay)) sum_principal = 0 sum_i = 0 for i in range(12 * term): interest = (amount - sum_principal) * mon_rate print("#{} month interest:{:.2f}".format(i + 1,interest)) sum_i += interest sum_principal += mon_pay - interest return sum_i if __name__ == "__main__": amount,rate,term = eval(input("Please input loan amount,interest rate and years:")) sum_i = average_capital(amount,rate,term) print("Total Interest:{:.2f}".format(sum_i)) sum_j = average_capital_plus_interest(amount,rate,term) print("Total Interest:{:.2f}".format(sum_j)) print("Average Capital Saving Interest:{:.2f}".format(sum_j - sum_i)) print("===Real Interest per year:{:.4f}===".format((1 + rate / 12) ** 12 - 1))
false
b6c12ae165a10fa29347189009f7e60edba15f91
215shanram/lab4
/lab4-exercise4.py
1,163
4.25
4
import sqlite3 #connect to database file dbconnect = sqlite3.connect("lab4.db"); #If we want to access columns by name we need to set #row_factory to sqlite3.Row class dbconnect.row_factory = sqlite3.Row; #now we create a cursor to work with db cursor = dbconnect.cursor(); #execute insetr statement cursor.execute('''insert into table2 values (1, 'door', 'kitchen')'''); cursor.execute('''insert into table2 values (2, 'temperature', 'kitchen')'''); cursor.execute('''insert into table2 values (3, 'door', 'garage')'''); cursor.execute('''insert into table2 values (4, 'motion', 'garage')'''); cursor.execute('''insert into table2 values (5, 'temperature', 'garage')'''); dbconnect.commit(); #execute simple select statement cursor.execute('SELECT * FROM table2'); print("Display all Kitchen sensors") cursor.execute('SELECT * FROM table2 WHERE zone = "kitchen"'); for row in cursor: print(row['sensorID'],row['type'],row['zone'] ); print("Display all Door sensors") cursor.execute('SELECT * FROM table2 WHERE type = "door"'); #print data for row in cursor: print(row['sensorID'],row['type'],row['zone'] ); #close the connection dbconnect.close();
true
76b8b31d7c66daa0600fe3d738803c15899c544c
btab2273/functions
/path_exists.py
946
4.3125
4
# Define path_exists() def path_exists(G, node1, node2): """ Breadth-first seach algorithim This function checks whether a path exists between two nodes( node1, node2) in graph G. """ visited_nodes = set() # Initialize the queue of cells to visit with the first node: queue queue = [node1] # Iterate over the nodes in the queue for node in queue: # Get neighbors of the node neighbors = G.neighbors(node) # Check to see if the destination node is in the set of neighbors if node2 in neighbors: print('Path exists between nodes {0} and {1}'.format(node1, node2)) return True break else: # Add neighbors of current node that have not yet been visited queue.extend([n for n in neighbors if n not in visited_nodes]) # Check to see if the final element of the queue has been reached if node == queue[-1]: print('The path does not exist between nodes {0} and {1}'.format(node1, node2)) return False
true
09b72fc9f5de9115ebf38fb41cdf7db89821e245
noobkid2411/Random-Programs
/list-sort.py
870
4.1875
4
# sorting using custom key friends= [ {'Name': 'Phoebe', 'age': 35, 'salary': 9000}, {'Name': 'Rachel', 'age': 30, 'salary': 8000}, {'Name': 'Ross', 'age': 25, 'salary': 10000}, {'Name': 'Chandler', 'age': 30, 'salary': 15000}, {'Name': 'Joey', 'age': 29, 'salary': 8000}, {'Name': 'Monica', 'age': 30, 'salary': 15000}, ] # custom functions to get friends' info def get_name(friends): return friends.get('Name') def get_age(friends): return friends.get('age') def get_salary(friends): return friends.get('salary') # sort by name (Ascending order) friends.sort(key=get_name) print(friends, end='\n\n') # sort by Age (Ascending order) friends.sort(key=get_age) print(friends, end='\n\n') # sort by salary (Descending order) friends.sort(key=get_salary, reverse=True) print(friends, end='\n\n')
false
f3c75aa885aa7fabed4400e78a8c5410fb648f89
jeandy92/Python
/ExerciciosDSA/Exercicios_Capitulo_3/Exercicios - Loops e Condicionais/ex002.py
325
4.15625
4
# Exercício 2 - Crie uma lista de 5 frutas e verifique se a fruta 'Morango' faz parte da lista fruits = ['Pinneaple', 'WaterMellon', 'Strawberry', 'Apple', 'Lemon'] #fruits = ['Pinneaple', 'WaterMellon', 'Apple', 'Lemon'] for fruit in fruits: if (fruit == 'Strawberry'): print('The list contains Strawberry')
false
b644ba60f87f1ff5c4bdfa9311698112fd6f59a1
paul-tqh-nguyen/one_off_code
/old_sample_code/misc/vocab/vocab.py
1,572
4.40625
4
#!/usr/bin/python # Simple program for quizzing GRE vocab import random import os if __name__ == "__main__": os.system("clear") definitions = open('./definitions1.csv', 'r') # load GRE words from .csv file # We want to split the words by part of speech so that when quizzing, the quizzee cannot guess the answer based on the part of speech of the word in question nouns = dict() verbs = dict() adjs = dict() for defn in definitions: # Separate words by part of speech x=defn.replace('\x00', '').split("\t") if len(x)==3: if ( x[1] == "n"): nouns[x[0]] = x[2][:-1] elif ( x[1] == "v"): verbs[x[0]] = x[2][:-1] elif ( x[1] == "adj"): adjs[x[0]] = x[2][:-1] else: print "Failed to load entry: "+str(x) for i in xrange(50): # Ask questions # pick which part of speech of the word we will quiz on # Side effect is that we will ask approximately teh same amount of questions on each part of speech # This differs from just picking words at random since the number of words for each part of speech may nto be equal partOfSpeech = [nouns, verbs, adjs][random.randint(0,1)] word = random.choice(partOfSpeech.keys()) # pick word answer = random.randint(1,4) # Which choice will be the right answer print word+":" for j in xrange(1,5): print j,": ", if (j != answer): print random.choice(partOfSpeech.values()) else: print partOfSpeech[word] print "" while ( raw_input('Guess: ')[0] != str(answer) ): print "Try Again..." print "\nCorrect!\n"+word+": "+partOfSpeech[word]+"\n\n\n"
true
e0178e180e7f08eff52d9c9e878e23e8ecfe5e5c
FariaTabassum/Python-Basic
/program18(operators).py
978
4.6875
5
''' Operators in python 1.Arithmetic operators 2.Assignment operators 3.Comparison operators 4.logical operators 5.Identity operators 6.Membership operators 7.Bitwise operators ''' #Arithmetic operators print("Arithmetic operator:\n") print("5+6 is ",5+6) print("5-6 is ",5-6) print("5/6 is ",5/6) print("5**6 is ",5**6) print("5 % 6 is ",5 % 5) print("15 // 6 is ",15 // 6) #Assignment operators print("\n Assignment operators:") x=5 print(x) x+=7 print(x) #Comparison operators print("\nComparison operators:") i = 5 print(i<=5) #logical operators print("\n logical operators:") a = True b = False print(a and b) print ( a or b) #Identity operators print("\n Identity operators") a = 4 b = 9 print( a is not b) #.Membership operators print("\n Membership operators:") list = [2,3,5,6,89,23] print( 89 in list) print(43 in list) print( 43 not in list) #Bitwise operators print("\n Bitwise operators") # 0 - 00 # 1 - 01 # 2 - 10 # 3 - 11 print ( 0 & 1)#and print( 0 | 1)# or
false
654e9a81c02402214df6d7f0e3f2ba226375d205
sanika2106/if-else
/next date print.py
826
4.34375
4
# Write a Python program to get next day of a given date. # Expected Output: # Input a year: 2016 # Input a month [1-12]: 08 # Input a day [1-31]: 23 # The next date is [yyyy-mm-dd] 2016-8-24 date=int(input("enter the date:")) if date>=1 and date<=31: print("now enter the month") month=int(input("enter the month:")) if month>=1 and month<=12: print("plz enter the year now") year=int(input("enter the year:")) if year>=0 and year<=2021: print(date+1,"/",month,"/",year) else: print("plz enter valid year") else: print("plz enter the valid month") else: print("plz enter valid date")
true
c516eed37f3a04549028b078464756a786711002
sanika2106/if-else
/16link.py
429
4.1875
4
# c program to check weather the triangle is equilateral ,isosceles or scalene triangle side1=int(input("enter the number:")) side2=int(input("enter the number:")) side3=int(input("enter the number:")) if(side1==side2 and side2==side3 and side1==side3): print("it's a equilateral triangle") elif(side1==side2 or side2==side3 or side1==side3): print("it's a isosceles triangle") else: print("it's a scalene triangle")
true
4dd716f7a3114ec557a8da4758acff8f4dd1d074
sanika2106/if-else
/2nd.py
604
4.21875
4
#leap year # year=int(input("enter the number:")) # if year%4==0: # print("its leap year") # year2=int(input("enter the number")) # if year2%400==0: # print("its also a leap year") # else: # print("its not leap year") # else: # print("its also not a leap year") year=int(input("enter the year:")) if year%4==0 and year%100!=0 or year%400==0: print("its leap year") # year2=int(input("enter the year:")) # if year%100!=0: # print("its also leap year") # else: # print("no its not leap year") else: print("sorry its not leap year")
false
b60fe06fd61994d24e2c6292c0266f2179d1ced9
sanika2106/if-else
/q13.py
658
4.15625
4
age=int(input("enter the number")) if age>=5 and age<=18: print("can go to school") elif age>=18 and age<=21: print("""1.can go to school, 2.can vote in election""") elif age>=21 and age<=24: print("""1.can go to school, 2.can vote in election, 3.can drive a car""") elif age >=24 and age<=25: print("""1.can go to school, 2.can vote in election, 3.can drive a car, 4.can marry""") elif age >25: print("""1.can go to school, 2.can vote in election, 3.can drive a car, 4.can marry, 5.can legally drink""") else: print("can not legally drink")
true
4c7c531576a1c5fd956a08ec5dfc454509604ec0
sanika2106/if-else
/prime number.py
306
4.21875
4
#prime number num=int(input("enter the number:")) if num==1 or num==0: print("not a prime number") elif num%2!=0 and num%3!=0 and num%5!=0 and num%7!=0: print("prime number") elif num==2 or num==3 or num==5 or num==7 : print("it is also a prime number") else: print("not a prime number")
true
44f57eb1192b6e2059ab3ffafc1e35f7ce39ef44
saurabh00031/PYTHON-TUTS-
/tut54.Instance&ClassVariables.py
2,842
4.3125
4
#.............................................................................................. #self-practicing:- #intance and class variables class student: leaves=10 harry=student() larry=student() harry.std=12 harry.marks=100 harry.leaves=10 print("leaves of harry : " ,harry.leaves) #instances variables & cant chnage class variable larry.std=11 larry.marks=97 larry.leaves=20 print("leaves of larry : " ,larry.leaves) #instances variables & cant chnage class variable print("class variable value : ", student.leaves) #................................................................................................................. #.............................................................................................................. #some Concepts in python inheritance ...single inheritances class Employee: leaves=10 def __init__(self,aname,adegree,aage): self.name=aname self.degree=adegree self.age=aage def printdetails(self): print(f"this is {self.name} ....studies as {self.degree} student\n in WCE \n is currently {self.age} years old\n") class Employee: leaves=11 def __init__(self,aname,adegree,aage): self.name=aname self.degree=adegree self.age=aage def printdetails(self): print(f"this is {self.name} ....studies as {self.degree} student\n in WCE \n is currently {self.age} years old\n") @classmethod def change_leaves(cls,aleaves): cls.leaves=aleaves @classmethod #used as alternative constructor def from_dash(cls,string): return cls(*string.split("-")) @staticmethod def printplz(string): print("this is string printing using static method ,"+string) class Prog(Employee): #here,i have inherited Employee class in Prog class: def __init__(self,aname,adegree,aage,alang): self.name=aname self.degree=adegree self.age=aage self.lang=alang def goodDay(self): print(f"harry wishes you good day to {self.name}\n") def showDetails(self): print(f"{self.lang}") harry=Employee("saurabh","CS","21") larry=Employee("patil","IT","20") karan=Employee.from_dash("Karan-ENTC-24") ssp=Prog("saurabhP","CS","20",[[1,2],[3,4],[5,6]]) karan.printplz("Saurabh") #this both r possible here....... Employee.printplz("Saurabh") harry.leaves=11 harry.change_leaves(8) print(harry.leaves) #harry.goodDay() ssp.showDetails() #................................................................................................................................. #.......................................................................................................................
false
720179901f16379215f0160e45b410f039462b33
A-Chornaya/Python-Programs
/LeetCode/same_tree.py
1,823
4.15625
4
# Given two binary trees, write a function to check if they are the same or not. # Two binary trees are considered the same if they are structurally identical and the nodes have the same value. ''' Example 1: Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Example 2: Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorder(self, p): result = [] if p: result.append(self.inorder(p.left)) result.append(p.val) result.append(self.inorder(p.right)) return result def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if self.inorder(p) == self.inorder(q): return True else: return False p = TreeNode(1) p.left = TreeNode(2) # p.right = TreeNode(1) q = TreeNode(1) # q.left = TreeNode(1) q.right = TreeNode(1) s = Solution() print(s.inorder(p)) print(s.inorder(q)) print(s.isSameTree(p, q)) ''' [[[], 2, []], 1, [[], 1, []]] [[[], 1, []], 1, [[], 1, []]] False ''' p = TreeNode(1) p.left = TreeNode(2) # p.right = TreeNode(1) q = TreeNode(1) # q.left = TreeNode(1) q.right = TreeNode(1) s = Solution() print(s.inorder(p)) print(s.inorder(q)) print(s.isSameTree(p, q)) ''' [[[], 2, []], 1, []] [[], 1, [[], 1, []]] False ''' p = TreeNode(1) p.left = TreeNode(2) p.right = TreeNode(1) q = TreeNode(1) q.left = TreeNode(2) q.right = TreeNode(1) s = Solution() print(s.inorder(p)) print(s.inorder(q)) print(s.isSameTree(p, q)) ''' [[[], 2, []], 1, [[], 1, []]] [[[], 2, []], 1, [[], 1, []]] True '''
true
d5efc35e0ef0f9c25258247625e9063c8fdd5a92
AhmedFakhry47/Caltech-Learn-from-data-cours-homework-
/PLA.py
736
4.15625
4
''' A simple code (Script) to illustrate the idea behind perception learning algorithm ''' import numpy as np import matplotlib.pyplot as plt ##First step is generating data D = np.random.rand(3,1000) threshold = .4 #target function represented in weights f = np.array([0.2,0.8,0.5]).reshape((3,1)) Y = (np.sum((f*D),axis=0)>threshold).astype(int) Y[Y==0] = -1 ##Start Applying PLA W = np.zeros(3) # Initialization of weights by zeros h = 0 # The current hyposis N = 1000 # Number of training examples #Start learning for _ in range(10000): for i in range(N): h = 1 if (np.sum(W * D[:,i]) > .4) else -1 if (h != Y[i]): #Update step in case of miss-classified points W+= Y[i]*D[:,i] print(W)
true
486705e17f2ad4eb0ad7a421deb1319818f4142d
umeshchandra1996/pythonpractice
/palindrome.py
312
4.1875
4
num=int(input("Enter the number ")) numcopy=num #copy num for compare whith reverse reverse=0 while num>0: reminder=num%10 #find reminder reverse=(reverse*10) + reminder num//=10 if(numcopy == reverse): print("Yes It is a plaindrome number ") else: print("It is not plaindrome number ")
true
95fccfec6fdce9dc9c580d33362cc6bcc83a82c7
Nsk8012/30_Days_Of_Code
/Day_9/3_Logical&Condition.py
314
4.28125
4
# Logical condition - and & or # and n = 5 if n > 0 and n % 2 == 0: print('Even Positive') elif n > 0 and n % 2 == 1: print('Odd Positive') elif n == 0: print('Zero') else: print('Negative NUmber') # or n = 0 if n > 0 or n == 0: print('Not Negative Number') else: print('Negative Number')
false
52b50a64102f7813ab4c7dc2a20df989963965e9
Nsk8012/30_Days_Of_Code
/Day_5/2_List_with_value.py
780
4.53125
5
# Initialing the value fruits = ['banana', 'orange', 'mango', 'lemon', 'apple'] print('Fruits:', fruits) print('Length of Fruits List:', len(fruits)) # List can have items of different data types. lst = ['Nishanth', 15, True, {'Country': 'India', 'City': 'Coimbatore'}] print(lst) # Index of list # [a, b, c, d, e] # 0, 1, 2, 3, 4 - In Positive Indexing # -5,-4,-3,-2,-1 - In Negative Indexing # calling values in list by index ls = ['a', 'b', 'c', 'd', 'e'] print(ls[2]) # calling 3rd value in index print(ls[-1]) # calling last value in index # Unpacking the list by assigning the values a, b, c, *rest = ls # the index value will be assigned to this variables seperated by , print(a) print(rest) # *rest is used for collecting other values in a upacked list
true
265d3fe67eefc5514a347f467ef3e2d4639b174f
Nsk8012/30_Days_Of_Code
/Day_8/1_Creating_Dictionaries.py
504
4.1875
4
# 30_Days_Of_Code # Day 8 # Dictionary will have key:value. empty_dict = {} # Dictionaries with Values dct = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4'} print(dct) # len is used to find the length od dicitionaries print(len(dct)) # Accessing Dictionary Items by calling keys init. print(dct['Key1']) print(dct['Key3']) # also by Get() function print(dct.get('Key2')) # -----------------------------------------------------------------------------------------------------
true
719da2eb3374940257fa83a687556275a47f2351
BlaiseGD/FirstPythonProject
/RockPapScis.py
1,963
4.3125
4
from random import randrange reset = 'y' while reset == 'y': print("This is rock, paper, scissors against a computer!\ny means yes and n means no\nEnter 1 for rock, 2 for paper, or 3 for scissors") #1 is rock 2 is paper 3 is scissors for compInput computerInput = randrange(1, 4) userInput = int(input()) if(userInput == 1 and computerInput == 3): print("\n\nYou Win\n!") elif(userInput == 2 and computerInput == 1): print("\n\nYou Win!\n") elif(userInput == 3 and computerInput == 2): print("\n\nYou Win!\n") elif(userInput == computerInput): print("\n\nYou tied\n") else: print("\n\nYou lose!\n") print("Your input was " + str(userInput) +"\nThe computer input was " + str(computerInput) + "\nDo you want to play again\n") reset = input() #The commented code is the original and is much cleaner to play #The uncommented code is the shortest I could get it with it retaining full functionality #from random import randrange #import os #clear = lambda: os.system('clear'); #reset = 'y'; #while reset == 'y': #print("This is rock, paper, scissors against a computer!") #print("y means yes and n means no"); #print("Enter 1 for rock, 2 for paper, or 3 for scissors") #1 is rock 2 is paper 3 is scissors for compInput #computerInput = randrange(1, 4); #userInput = int(input()); #if(userInput == 1 and computerInput == 3): # clear(); # print("You Win!"); #elif(userInput == 2 and computerInput == 1): # clear(); # print("You Win!"); #elif(userInput == 3 and computerInput == 2): # clear(); # print("You Win!") #elif(userInput == computerInput): # print("You tied"); #else: # print("You lose!") #print("Your input was " + str(userInput)) #print("The computer input was " + str(computerInput)) #print("Do you want to play again?"); #reset = input(); #clear();
true
7faf361b63dbd5d85da99313cd55a9e57eaefec5
beebeebeeebeee/python-practice
/bmi_calculator.py
561
4.40625
4
#bmi calculator #bmi function def bmi_calculator(height, weight): bmi = round(weight / ((height / 100) ** 2), 2) if bmi < 18.5: status = "underweight" elif 18.5 <= bmi < 24: status = "normal" elif 24 <= bmi < 27: status = "overweight" else: status = "obesity" return [bmi, status] #main name = input("input your name: ") bmi, status = bmi_calculator(int(input("input your height in cm: ")), int(input("input your weight in kg: "))) print("Hi {}! Your bmi is {} and it is {}.".format(name, bmi, status))
false
b2d81645b2694214cc0b952a6f0abc694113c8d2
nstrickl87/python
/working_with_lists.py
2,909
4.28125
4
#Looping Through Lists magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) #More WOrk in a Loop magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title()) #makign Numerical Lists using the range function #Range off by one starts counting from first value and stops counting att he second value off by one for value in range (1,5): print(value) #Print 1 through 5 for value in range (1,6): print(value) #Using range to make a list of Numbers numbers = list(range(1,6)) print(numbers) #List only even numbers between 1 and 10 #Starts at 2 and then adds 2 until reaches second value. even_numbers = list(range(2,11,2)) print(even_numbers) squares = [] for value in range(1,11): squares.append(value**2) print(squares) #Simple Stats with numbers digits = list(range(0,10)) print(digits) print(min(digits)) print(max(digits)) print(sum(digits)) #List Comprehensions a;;pws up to generate this same list in just one line of code. squares = [value**2 for value in range (1,11)] print(squares) #Slicing and List #To make a slice you indicate the first and last element you want to work with players = ['nathan', 'caitlin','hazel', 'pat','brett','wayland'] print(players[0:3]) #First three elements in the list #want 2nd 3rd and 4th person in a list print(players[1:4]) #Without a starting index python assumes the start of the list print(players[:4]) #Want all items in a list starting formt eh second item print(players[1:]) #Negative index returns an element a certain distance from the end of the list # Return last 3 players from listaZ print(players[-3:]) #Looping through a slice print("Last 3 players in the list:") for name in players[-3:]: print(name) #Copying a List family = players[:] print(players) print(family) #Tupule print("\n======== Tuples ========\n\n") #Lists Work Well for storing sets of items that can change throughout the life of a program. The ability to modify lists is particularly # Lists good for list of users on a website or a list of characters in a game. #Sometimes we wantt ot create a list of items that cannot change Tuples allow for this. #Python referes to values that cannot change as immutable. An Immutable list is a tuple dimensions = (200,50) print(dimensions[0]) print(dimensions[1]) #Tuples are defined with () instead of the [] #Looping through Tuple for dimension in dimensions: print(dimension) #Writing over a Tuple #Although you cannot modify a Tuple., You can assign a new value to a variable that holds a tuple. #So if we wanted to redefine the tuple we can print("Oringinal Dimensions:") for dimension in dimensions: print(dimension) dimensions = (400,100) print("New Dimensions") for dimension in dimensions: print(dimension) #use tuples when we do not want values to change in a program as they are a simple data structure.
true
6c6293507679501315a1dcf6b5816ce937dc1d42
BC-csc226-masters/a03-fall-2021-master
/a03_olorunpojuessangd.py
1,267
4.1875
4
# Author: David Olorunpoju-Essang # Username: olorunpojuessangd # Assignment: A03: Fully Functional Gitty Psychedelic Robotic Turtles # Purpose: Draws a fractal tree #Reference : https://www.youtube.com/watch?v=RWtNQ8RQkO8 #Google doc link: https://docs.google.com/document/d/1AVxiZuugCxoRw1HFxaOiRBXjW_VQFrHNXVA4CwW8-qU/edit?usp=sharing import turtle def draw_tree(i): #the parameter i defines when we call the function if i<10: #Once a value of 10 is achieved the turtle reverses return else: david.fd(i) david.left(30) draw_tree(3*i/4) #The equation determines the extensiveness and length of the branch patterns david.right(60) draw_tree(3*i/4) david.left(30) david.backward(i) def main(): wn = turtle.Screen() turtle.bgcolor("skyblue") wn.title("Here is a tree") global david david = turtle.Turtle() david.color("blue") david.shape("turtle") david.pensize(7) david.pencolor("green") david.penup() david.setpos(0,-200) #lowers the turtle's placment in the screen david.left(90) david.speed(0) david.pendown() draw_tree(100) draw_tree() turtle.done() #Keeps the window open until the turtle has completed executing the function main()
true
07d5cb0b86979e01d27520837279bf378d3c4f82
BC-csc226-masters/a03-fall-2021-master
/ayisie_A03.py
1,569
4.25
4
# Author : Ebenezer Ayisi # Username: ayisie # google link : https://docs.google.com/document/d/1EN02kKmUNzDABtUjf3uC-kj8b4T7asFKH69ek9Z7bSg/edit?usp=sharing # Assignment: T03: Turtles # Purpose: To very simply demonstrate the turtle library to demo shapes and using images for shapes import turtle def draw_eyes(je): """ draw eyes of the face""" je.begin_fill() je.circle(20) je.end_fill() je.penup() je.backward(55) je.begin_fill() je.circle(20) je.end_fill() def draw_face(je): """draw the shape of the face""" je.penup() je.setpos(-120, -10) je.pendown() je.left(-90) je.circle(90,180) je.forward(78) je.left(90) je.forward(180) je.left(90) je.forward(82) def draw_hair(je): """draw the hair of the head""" je.speed(0) je.left(90) je.forward(-20) je.left(90) je.forward(130) for i in range(-140,-20, 15): je.circle(50,100) je.penup() je.seth(70) je.setpos(i,100) je.pendown() for i in range(-20,100, 15): je.circle(-100,50) je.penup() je.seth(70) je.setpos(i,100) je.pendown() je.penup() je.setpos(70, 100) je.pendown() je.seth(0) je.right(90) je.forward(110) je.left(90) je.forward(-10) def main(): """docstring for main""" # Create window screen wn = turtle.Screen() wn.bgcolor("blue") je = turtle.Turtle() je.pensize(10) draw_eyes(je) draw_face(je) draw_hair(je) wn.exitonclick() main()
false
456158d879e62a796234c946d7c3432254872e98
BC-csc226-masters/a03-fall-2021-master
/a03_bridgemanc.py
1,507
4.34375
4
# Author: Cameron Bridgeman # Username: bridgemanc # # Assignment: A03 :Fully Functional Psychedelic Robotic Turtles # Purpose: To learn how to draw something complex using RGB color values, functions, and more. ################################################################################# # Acknowledgements: # I learned how to make an ellipse using stack overflow and the turtle library. # ################################################################################# """ https://docs.google.com/document/d/1MRXaVI8EXFYSslI0LNRlnHnRB7RjeiekIddHja_8Lks/edit?usp=sharing Cameron Bridgeman """ import turtle wn = turtle.Screen() wn.bgcolor("gray") turtle.pensize(8) def function_1(): #draws the face and hair of the alien turtle.penup() turtle.goto(0, -100) turtle.pendown() turtle.circle(130) turtle.penup() turtle.goto(0, 160) turtle.pendown() turtle.left(90) turtle.goto(5, 220) turtle.goto(20, 160) function_1() def function_2(): #draws the eye of the alien turtle.penup() turtle.goto(30, 75) turtle.pendown() turtle.colormode(255) turtle.fillcolor(70, 50, 100) turtle.begin_fill() turtle.circle(40) turtle.end_fill() function_2() def main(): #draws the mouth of the alien turtle.penup() turtle.right(180) turtle.forward(120) turtle.left(90) turtle.forward(-70) turtle.right(90) turtle.pendown() turtle.circle(30, 180) turtle.left(90) turtle.forward(60) main() wn.exitonclick()
false
732fb7258b5baae253205e6fbf4c21c49948f15b
rupeshkumar22/tasks.py
/basic/fibonacci.py
1,179
4.25
4
from typing import List def matrixMul(a, b): """ Returns the product of the given matrices """ # Initializing Empty Matrix c = [[0, 0], [0, 0]] # 2x2 matrix multiplication. Essentially O(1) for i in range(2): for j in range(2): for k in range(2): c[i][j] = (c[i][j] + (a[i][k] * b[k][j])) # Returning the products return c def fibonacci(number:int) -> int: """ Returns the n'th fibonacci sequence number >>> fibonacci(number=10) 55 """ # Initializing Magic Matrix a = [[1, 1, ], [1, 0]] # Initializing Identity Matrix res = [[1, 0], [0, 1]] # Fast Exponentiation (log(n) complexity) while number: if number & 1: res = matrixMul(res, a) number >>= 1 a = matrixMul(a, a) # Return the nth fibonacci number. Could also return res[0][1] instead. return res[1][0] def fibonacciSequence(number:int) -> List[int]: """ Returns a list of first n fibonacci numbers >>> fibonacciSequence(number=10) [0,1,1,2,3,5,8,13,21,34,55] """ return [fibonacci(num) for num in range(number + 1)]
true
6b63098f3c1fdeb2fe23804b79d7881edbbbd8a5
MRajibH/100DaysOfCode
/DAY07/classes.py
678
4.21875
4
# OOP - Programming Paradigm # In OOP we think about world in terms of objects # Objects might store information or support the ability todo some operations # OOP helps you to create new types or you can say customized types e.g. 2D Values # class = A templete for a type of objects class point(): # It'll called automaticly every time when creating a new point def __init__(self, input1, input2): self.x = input1 self.y = input2 inpt1 = input("Enter The value of X coordinate: ") inpt2 = input("Enter The value of Y coordinate: ") p = point(inpt1, inpt2) print(f'the value of x coordinate is = {p.x}') print(f'the value of y coordinate is = {p.y}')
true
f02d92449a70f0e6365fb7ce764bfb91cbdef928
azarateo/bnds
/python_workspace/as/unicode.py
207
4.15625
4
print('Hello. This program will show you different unicode characters,'+ 'well at least the ones Python 3 can print') for x in range(32, 127): print "Character with number %d is %s in hex %X" % (x,x,x)
true
896f9a1d5526e06de47c6e4e870458ba81c82d44
842679600/MyPython
/面向对象.py
840
4.125
4
#对象=属性+方法,类名是大写字母开头 #面象对象的特征1.封装(信息屏蔽技术)2.继承 3.多态(名字一样,但是类不一样) #OOA面向对象分析,oop面向对象编程 ood:面向对象设计 #slef 相当于c+的指针,每个类都是需要self第一个参数 msg='' class Python_first_class(): def fisrtdef(self,name): self.name = name print('你好'+self.name) x=Python_first_class() x.fisrtdef('pp') #什么是继承 class Mylist(list): pass List1=Mylist() List1.append(1) List1.append(3) List1.append(1) print(List1) #_init_ Python中的魔法方法 class Ball: def __init__(self,name): self.name=name def kick(self): print("该死的谁踢我啊"+self.name) x=Ball('小白熊') x.kick() #y=Ball()会报错,提示需要加入参数name
false
8bc79e0d2a65ddca96589a3659beed116986b221
garikapatisravani/PythonDeepLearning
/ICP2/StringAlternative.py
311
4.21875
4
# Author : Sravani Garikapati # program that returns every other char of a given string starting with first # Ask user to enter a string s = str(input("Enter a string: ")) # Use slicing to get every other character of string def string_alternative(s): print(s[::2]) if __name__ == '__main__': string_alternative(s)
true
1dca25eb10e1ea42cfaa5efada2c760a0d177f3a
rgraveling5/SDD-Task2a---Record-Structure-Lists-
/main.py
973
4.28125
4
#Record structure #Rachael Graveling #28/08/2020 # List to store all records student_records = [] # Number of records number_of_students = 3 # Loop for each student for x in range(number_of_students): student = [] student.append(input('Please enter name: ')) student.append(float(input('Please enter age : '))) while student[1] < 1 or student[1] > 150 or not student[1].is_integer(): print('Error. Must be a whole number between 1 & 150') student[1] = float(input('Please enter age : ')) student[1] = int(student[1]) student.append(float(input('Please enter height : '))) while student[2] < 1 or student[2] > 2.5: print('Error. Must be a number between 1 & 2.5') student[2] = float(input('Please enter height : ')) student.append(input('What is your home town?: ')) # Add the student record to list of records student_records.append(student) # Print the records for x in student_records: print(x)
true
1f0b4de15cf6e721462a4a7f1eb0384e082759f0
Aneesh540/python-projects
/NEW/one.py
1,237
4.125
4
""" 1) implementing __call__ method in BingoCage class which gives it a function like properties""" import random words = ['pandas', 'numpy', 'matplotlib', 'seaborn', 'Tenserflow', 'Theano'] def reverse(x): """Reverse a letter""" return x[::-1] def key_len(x): """Sorting a list by their length""" return sorted(x, key=len) def key_reverse(x): """Sorting a list by reverse spelling here reverse() f(x) is defined by us and key should be a function without execution""" return sorted(x, key=reverse) print(key_reverse(words)) print(sorted(words, key = lambda y:y[::-1])) # EVEN CLASS INSTANCE CAN BE TREATED AS FUNCTION BY IMPLEMENTING __call__ METHOD class BingoCage: """Giving a random element""" def __init__(self, items): self.item = list(items) random.shuffle(self.item) def pick(self): try: return self.item.pop() except: raise LookupError("Picking from empty") def __call__(self, *args, **kwargs): return self.pick() if __name__ == '__main__': foo = BingoCage(range(2, 20, 2)) print(foo) print("see that foo() and foo.pick() act in similar manner") print(foo.pick()) print(foo())
true
44f1fc9e2a4a0d4daf2dfb19f95b68c4242dd23f
Aneesh540/python-projects
/closures/closures2.py
761
4.3125
4
""" A closure is a inner function that have access to variables in the local scope in which it was created even after outer function has finished execution""" import logging def outer_func(msg): message=msg def inner_func(): # print(message) print(msg) return inner_func hello=outer_func('hello') print('hello bcomes %s ' %(hello.__name__)) hello() logging.basicConfig(filename='example.log',level=logging.INFO) def logger(function): def log_func(*args): logging.info('Running "{}" with arguments {}'.format(function.__name__,args)) print(function(*args)) return log_func def add(x,y): return x+y def sub(x,y): return x-y add_logger=logger(add) sub_logger=logger(sub) add_logger(3,4) sub_logger(9,10) sub_logger(33,-99)
true
4ee9ad807758a023149d0b45efe19768a8757386
Aneesh540/python-projects
/closures/decorators.py
1,185
4.59375
5
""" Decorators are used to add functionality to functions without changing them in this module we'll be using functional decorators """ # Example 1 def decorator_function(original_func): def wrapper_function(): """return original function with execution""" print('wrapper xecte this before {}'.format(original_func)) return original_func() return wrapper_function def display(): print('display function() is running') decorateddisplay=decorator_function(display) print('___________________________________\n') decorateddisplay() print(decorateddisplay.__name__) print('+++++++++++++++++++++++++++++++++++') # Example 2/3 def taple_func(): print(" I'am chinu taple") taple_func=decorator_function(taple_func) taple_func() print('________________________________________________________') taple_func() print(taple_func.__name__) @decorator_function def foo_n_bar(): print('wrapper statment xecuteb4 ME bcoz of @decorator_function') foo_n_bar() print(foo_n_bar.__name__) #>>>>>>>>>>>>>>>>>> THE CONCLUSION <<<<<<<<<<<<<<<<<<<<< # adding @decorator_function above a function is equal to # function = decorator_function(function) # see deco-2.py for more info
false
4de9a04857f0e838acb52dba77a7ba5a98c303d7
meghaggarwal/Data-Structures-Algorithms
/DSRevision/PythonDS/bst.py
809
4.125
4
from dataclasses import dataclass @dataclass class Bst(): data:int left:object right:object def insertNode(data, b): if b is None: return Bst(data, None, None) if data < b.data: b.left = insertNode(data, b.left) else: b.right = insertNode(data, b.right) return b b = None b = insertNode(1, b) insertNode(2, b) insertNode(3,b) def traverse_in_order(root): if root is None: return if root.left is not None: traverse_in_order(root.left) print(root.data) if root.right is not None: traverse_in_order(root.right) if __name__ == "__main__": traverse_in_order(b) # 2 3 4 5 6 7 # void inorderTraversal(struct node * root) { # if(!root): # return # inorderTraversal(root->left) # print(root->data) # }
true
c24699269a2bdc789332da8b5a523930e6a0d616
mike1806/python
/udemy_function_22_palindrome_.py
439
4.25
4
''' Write a Python function that checks whether a passed string is palindrome or not. Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. ''' def palindrome(x): x = x.replace(' ','') # This replaces all spaces " " with no space ''. (Fixes issues with strings that have spaces) return x == x[::-1] # check through slicing palindrome('nurses run')
true
88149ebc6508f5f6b031a1c98f572ea28d0f2b33
jpsampaio/ExEcommIT
/Ex42.py
674
4.15625
4
while True: n1 = float(input("\n Escreva o lado 1 do triângulo: ")) n2 = float(input(" Escreva o lado 2 do triângulo: ")) n3 = float(input(" Escreva o lado 3 do triângulo: ")) if(n1 > 0 and n2 > 0 and n3 > 0 and n1 <= n2+n3 and n2 <= n1+n3 and n3 <= n1+n2): if(n1 == n2 and n1 != n3 or n1 == n3 and n1 != n2 or n2 == n3 and n1 != n2): print("\n - O Triângulo é Isósceles !") elif(n1 == n2 and n2 == n3): print("\n - O Triângulo é Equilátero !") else: print("\n - O Triângulo é Escaleno !") print("-=-"*31) else: print(" - Não pode formar um triângulo")
false
bf9d8f5013c8791f8df90f0f9c50095ed39de6cc
cpd67/Languages
/Python/Python3/Practice3.py
1,911
4.1875
4
#Python program for counting the number of times a letter appears in a string. #Also, learned that locals are NOT reassigned in for loop... def findMax(lis): """Finds the max element in a list.""" index = [0] m1 = [-999999999] #Special use case: empty list if len(lis) == 0: return -1, -1 #Special use case: list of size 1 elif len(lis) == 1: return lis[0], 0 #Normal case else: for n in range(len(lis)): if lis[n] > m1[0]: m1[0] = lis[n] index[0] = n #http://stackoverflow.com/questions/9752958/how-can-i-return-two-values-from-a-function-in-python return m1[0], index[0] #index = 4, max = 1000 lis2 = [4, 8, 16, -1, 1000] m1, in1 = findMax(lis2) print("The max of lis2 is:", m1) print("The index of " + str(m1) + " is " + str(in1)) #Special use case 1 lis3 = [10000000] m2, in2 = findMax(lis3) print("The max of lis3 is:", m2) print("The index of " + str(m2) + " is " + str(in2)) #index = 0, max = 10 lis4 = [10, -1] m3, in3 = findMax(lis4) print("The max of lis4 is:", m3) print("The index of " + str(m3) + " is " + str(in3)) #Utility function for finding index in a sequence def findIndex(element, sequence): """Finds the index of an element in a sequence.""" for n in range(len(sequence)): if element == sequence[n]: return n return -1 def countReps(st1): """Counts the number of repetitions a letter appears in a string sequence.""" letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g' 'h' 'i','j','k','l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v' 'w', 'x', 'y', 'z'] counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for n in st1: index = findIndex(n, letters) counts[index] += 1 mx, letterInd = findMax(counts) lett = letters[letterInd] print("The most frequent letter is " + str(lett) + ", its count is " + str(mx)) #Test 1 st1 = "blaah" countReps(st1) st2 = "cowboy beep boop boop bop" countReps(st2)
true
f0cc6b193e1a77e194295927cea914fe3f1c7424
cpd67/Languages
/Python/Python3/Practice5.py
573
4.25
4
#!/bin/python # Dice Rolling Simulator # THIS CODE ONLY WORKS WITH PYTHON3 import random MIN = 1 MAX = 7 def rollDice(): print("Let's roll some dice!") print("Rolling...") print("The dice roll is: " + str(random.randrange(MIN, MAX))) rollDice() while True: x = input('Would you like to roll again? ') if x in ("y", "Y", "yes", "YES", "ye"): print ("Okay!") rollDice() continue elif x in ("n", "N", "no", "NO"): print ("Fine. Partypooper.") break print ("I didn't understand that. Please try again.")
true
d1acf74226395891e904adb871c7adad36c15ef4
Wattabak/quickies
/selection-sort-python/selection_sort.py
2,371
4.1875
4
""" Time complexity: Worst case: [Big-O] O(n^2) Average case: [Big-theta] ⊝(n^2) Best case: [Big-Omega] Ω(n^2) How it works: - find the position of the minimum element; - swap this element with the first one (because in the sorted array it should be the first); - now regard the sub-array of length N-1, without the last value (which is already "in right place"); - find the position of maximum element in this sub-array (i.e. second to maximum in the whole array); - swap it with the last element in the sub-array (i.e. with position N-2); - now regard the sub-array of the length N-2 (without two last elements); - algorithm ends when "sub-array" decreases to the length of 1. About: inefficient on large lists worse than insertion sort Variants: Heapsort: uses implicit heap data structure to speed up finding and removing the lowest datum, is faster with the same basic idea Bingo sort: items are ordered by repeatedly looking through the remaining items to find the greatest value and moving all items with that value to their final location. """ import argparse import logging from typing import Any, Iterable, TypeVar logger = logging.getLogger(__name__) def selection_sort_first_try(array: Iterable) -> Iterable: """Uses maximums, not minimums, also recursive, not the usual way it would be done""" if len(array) <= 1: return array max_index = array.index(max(array)) array[-1], array[max_index] = array[max_index], array[-1] array[:-1] = selection_sort(array[:-1]) return array def selection_sort(array: Iterable) -> Iterable: """In place sorting algorithm that is simple but inefficient""" for i in range(len(array)): min_idx = i for j in range(i+1, len(array)): if array[min_idx] > array[j]: min_idx = j array[i], array[min_idx] = array[min_idx], array[i] return array if __name__ == "__main__": parser = argparse.ArgumentParser( description="Sort elements using Selection Sort algorithm" ) parser.add_argument('values', metavar='V', type=int, nargs='+', help='values to sort') array = parser.parse_args().values length = len(array) sorted_array = selection_sort(array) print( f"out: {sorted_array};\narray_length: {length};" )
true
2b3155ea06158cec47b36bc822688f83024aeccf
do-py-together/do-py
/examples/quick_start/nested.py
1,369
4.15625
4
""" Nest a DataObject in another DataObject. """ from do_py import DataObject, R class Contact(DataObject): _restrictions = { 'phone_number': R.STR } class Author(DataObject): """ This DataObject is nested under `VideoGame` and nests `Contact`. :restriction id: :restriction name: :restriction contact: Nested DataObject that represents contact information for this author. """ _restrictions = { 'id': R.INT, 'name': R.STR, 'contact': Contact } class VideoGame(DataObject): """ This DataObject is nested under nests `Author`. :restriction id: :restriction name: :restriction author: Nested DataObject that represents author information for this video game. """ _restrictions = { 'id': R.INT, 'name': R.NULL_STR, 'author': Author } # Data objects must be instantiated at their **init** with a dictionary and strict True(default) or False. instance = VideoGame({ 'id': 1985, 'name': 'The Game', 'author': { 'id': 3, 'name': 'You Lose', 'contact': { 'phone_number': '555-555-5555' } } }, strict=False) print(instance) # output: VideoGame{"author": {"contact": {"phone_number": "555-555-5555"}, "id": 3, "name": "You Lose"}, "id": 1985, "name": "The Game"}
true
d99461ef2af3705856402a4cfa25029512521a11
WillianSagas/teste
/2018-2S/noite/aula7/matriz_test.py
1,409
4.21875
4
# Para criar uma lista com 5 elementos '_' # ex. ['_', '_', '_', '_', '_'] print("Lista com elementos iguais") lista = [] for i in range(5): lista.append('_') print("Lista: ", lista) # Alternativa lista_alternativa = ['_' for i in range(5)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma lista com 6 numeros # ex. [0, 1, 2, 3, 4, 5] print("Lista com numeros na sequencia") lista = [] for i in range(6): lista.append(i) print("Lista: ", lista) # Alternativa lista_alternativa = [i for i in range(6)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma lista com 6 numeros pares # ex. [0, 2, 4, 6, 8, 10] print("Lista com 6 numeros pares na sequencia") lista = [] for i in range(6): lista.append(i * 2) print("Lista: ", lista) # Alternativa lista_alternativa = [i * 2 for i in range(6)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma matriz com elementos repetidos # ex. [ ['_', '_', '_'], # ['_', '_', '_'], # ['_', '_', '_'] # ] print("Matriz 3x3 com elementos repetidos") matriz = [] for l in range(3): linha = [] for c in range(6): linha.append('_') matriz.append(linha) print("Matriz: ", matriz) # Alternativa matriz_alternativa = [['_' for c in range(3)] for l in range(3)] print("Modo Alternativdo de criar matriz: ", matriz_alternativa)
false
80c95e36826f3d3aa0c32986f35024d67b8e7609
carlagouws/python-code-samples
/How tall is the tree.py
1,167
4.21875
4
# ****************************************************************************************** # Description: # Program asks the user how tall the tree is # User inputs the height of the tree in number of rows, e.g. "9" produces a height of 9 rows ''' How tall is the tree : 5 # ### ##### ####### ######### # ''' # ****************************************************************************************** # Variables: # Number of rows (rows) # Number of iterations (i) # Number of hashtags = i*2 - 1 # Number of spaces = rows - i # Receive user input and make integer rows = int(input('How tall is the tree?: ')) # Body of pine tree i = 1 while i <= rows: # Insert required amount of spaces NumSpaces = rows - i for spaces in range(NumSpaces): print(" ", end = "") # Insert required amount of hashtags NumHashtags = i*2 - 1 for hashtags in range(NumHashtags): print("#", end = "") # Enter print() # Increment iteration i += 1 # Base of pine tree BaseSpaces = rows - 1 for spaces in range(BaseSpaces): print(" ", end="") print("#")
true
4f624c48797695f31507d40cf0c0a84b15fad99c
krishankansal/PythonScripts
/Files/e.py
511
4.1875
4
def count_the(filename): ''' Total number of appeareances of word 'the' in file''' try: f = open(filename) contents = f.read() appeareances = contents.lower().count('the') print(f"The file {filename} has word 'the' appereared {appeareances}. times") except FileNotFoundError: msg = f"sorry! file {filename} do not exists" print(msg) filenames = ['boys_book.txt','abc.abc','alice.txt','margret.txt'] for filename in filenames: count_the(filename)
true
dd7ad1c4bb038caab7a793e4b24ff4b657b8dc8c
Bryantmj/iteration-1
/iteration.py
2,203
4.15625
4
# Make a local change # Make another local change # Make a change from home # iteration pattern # [1, 5, 7 ,8 , 4, 3] def iterate(list): # standard for loop with range # for i in range(0, len(list)): # print list[i] # for each loop for item in list: print item def print_list(list): print "" def add_one(list): # standard for loop with range for i in range (0, len(list)): list[i] += 1 return list def print_scores(names, scores): for i in range(0, len(names)): print names[i] , " scored " , scores[i] # filter patterns - a type of iteration # filter pattern def congratulations(names, scores): for i in range(0, len(names)): if (scores[i] == 100): print "Congrats ", names[i], "! You got a perfect score!" # accumulation pattern - type of iteration # keep track of other data as we go def sum(numbers): total = 0 for n in numbers: total += n return total def max(numbers): current_max = numbers[0] for n in numbers: if n > current_max: current_max = n return current_max def alternating_sum(numbers): total = 0 for i in range(0, len(numbers)): if i == 0 or i % 2 == 1: total += numbers[i] else: total -= numbers[i] return total # def alternating_sum(numbers): # total = numbers[i] # for i in range(0, len(numbers)): # if i % 2 == 0: # total += numbers[i] # else: # total -= numbers[i] # return total def sum_outside(numbers, min, max): total = 0 for n in numbers: if not (min <= n and n < max): total += n return total def count_close_remainder(numbers, divisor): count = 0 for n in numbers: remainder = n % divisor if remainder <= 1 or remainder == divisor-1: count += 1 return count def double_down(numbers, target): result = [maybe_doubled(numbers[0], numbers[0], target)] for i in range(1, len(numbers)): result.append(maybe_doubled(numbers[0], numbers[1-1], target)) return result def maybe_doubled(n, prev_n, target): distance = abs(n - target) if n < prev_n or distance <= 3: return 2 * n return n def standarad_deviation(n, numbers, mean): total = 0 for n in numbers: total += n n / len(numbers) = mean numbers - mean = difference difference^2 = new_mean
true
de773b5afd4597a2f89027b50b0f75a89a530085
VinceSevilleno/variables
/developmentexercise2.py
373
4.375
4
#Vince Sevilleno #24/09/2014 #Development Exercise 2 print("This program will convert a given value in degrees Fahrenheit into degrees Centigrade:") print() fahrenheit=int(input("Please enter any value of temperature:")) centigrade=(fahrenheit-32)*(5/9) print() print("The value {0} degrees Fahrenheit is equal to {1} degrees Centigrade.".format(fahrenheit,centigrade))
true
acd07f7c71a7a5e941ef5be46fe296ae65a47e32
sunruihua0522/SIG-PyCode
/Python Study/buldin property.py
1,004
4.15625
4
class People: '这是一个测试类的内置属性的测试' PeopleNumber = 0 def __init__(self, Name, Age, Address='none'): People.PeopleNumber += 1 self.Name = Name self.Age = Age self.Address = Address def __del__(self): People.PeopleNumber -=1 def SayHello(self): print('%s say :"Hello everyone, i am %s, i am %d years old, i live in %s"'%(self.Name,self.Name,int(self.Age),self.Address)) def PrintCount(self): print('当前计数%d'%People.PeopleNumber) if __name__=='__main__': P1 = People('孙蓦寻',5,'苏州市吴中区') P1.SayHello() ''' 下面是类的内置属性的测试 ''' print('__doc__: ',P1.__doc__) print('__dict__: ', P1.__dict__) print('__module__: ', P1.__module__) '''测试类的构造与析构函数''' P1.PrintCount() del P1 #P1.PrintCount() #此时就会报错,因为P1对象已经被销毁了 print(People.PeopleNumber) exit()
false
d60cc8f46dbf6738555f7a715869f1e38e7ca033
girl-likes-cars/MIT_programming_course
/Newton square root calculator.py
577
4.21875
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 16:52:15 2018 @author: Maysa """ #Set the epsilon and the square root you want to find #Pick a random starting point for your guess (let's say, guess/2) epsilon = 0.01 k = int(input("Give me a number whose square root you want to find! ")) guess = k/2.0 iterations = 0 while guess*guess - k >= epsilon: guess = guess - ((guess**2 - k)/(2*guess)) iterations = iterations + 1 print("Square root of",k,"is approximately",guess) print("It squares to equal",guess*guess) print("Iterations:",iterations)
true
eb4481b19aa8e9c0116ae88a69b596192a05cf9c
AlvaroMenduina/Jupyter_Notebooks
/Project_Euler/41.py
1,564
4.125
4
""" Project Euler - Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? """ import numpy as np import itertools def is_prime(n): prime = True if n % 2 == 0 and n != 2: return False elif n % 2 != 0 and n != 2: for factor in np.arange(3, int(np.sqrt(n)) + 1, 2): if n % factor == 0: return False return prime def pandigitals_n(n): """ Function that returns all n-pandigital numbers generated from the digits [1, 2, ..., n] """ digits = list(np.arange(1, n+1)) permutations = list(itertools.permutations(digits)) pandigits = [] for perm in permutations: s = '' for digit in perm: s += str(digit) # Ignore the even numbers, as they are not prime if s.endswith('2') == False and \ s.endswith('4') == False and\ s.endswith('6') == False and \ s.endswith('8') == False: pandigits.append(int(s)) return pandigits if __name__ == "__main__": pandigitals_primes = [] for n in np.arange(1, 10): print("\nCompute pandigital numbers up to %d" %n) pandigitals = pandigitals_n(n) for p in pandigitals: if is_prime(p): pandigitals_primes.append(p) print("\nLargest pandigital number that is prime: ", pandigitals_primes[-1])
true
fcf684ff90ae780d7070caef6ecfced3749e5c8c
Charlieen/python_basic
/python_tutorial/NumberAndString.py
2,942
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 8 09:13:37 2021 @author: dzgygmdhx """ # print(2+2) # print(8/3) # print(17//3) # print(17%3) # print(5**2) width =20 height= 3*9 print(width * height) # begin string '' " " \ \n r print('I like "you", but "you" do not like me') print("I like 'you', but 'you' do not like me") print('I like \'you\', but "you" do not like me') print('I like \'you\', but \'you\' do not like me') print('I like "you",\nbut "you" do not like me') print('I like "you",\n but "you" do not like me') print(r'I like "you",\nbut "you" do not like me') print(r'c:\some\home') #string multiple lines # End of lines are automatically included in the string, you can use a # \ at the end of the line to avoid this print("""\ i like you? yes i like you really? sure you can see, it is very easy way to do it """ ) print("hello " *3 + 'python world' + 'good!'*2) print("hello " *3 , 'python world' , 'good!'*2) # Two or more string literals (i e the ones enclosed between quotes) # This is only works with two literals though,not with variables or expressions: print('a' 'b') print('i like you so much' 'you ?' ' are you sue? ') word ="Python" print(word[0]) # for i in word: # print(i) # for (index,i) in word: # print(index) # print(i) # +---+---+---+---+---+---+ # | P | y | t | h | o | n | # +---+---+---+---+---+---+ # 0 1 2 3 4 5 6 # -6 -5 -4 -3 -2 -1 print(word[-1]) # String inner string [] , index, slicing are all support print(word[1:2]) print(word[:6]) # [start:end] print(word[:2]) # index 0 1 start: 0 print(word[:-2]) # index -6 -5 -4 -3 start: -6 print(word[-5:-2]) #index -5 -4 -3 # use index when too large will get error but use slice ,no error print(word[:1000]) # pirnt(word[1000]) # no # String in python is immutable print(type(word)) # 'str' object does not support item assignment # word[1]='ddd' print(type(1)) print(type(None)) print(type(True)) # List in python squares=[1,4,9,16,25] print(squares[:3]) squares[0] =1000 # list mutalbe print(squares[:3]) print(squares[:3]+[10,20]) # TypeError: can only concatenate list (not "int") to list # print(squares[:3]+10) print(type(squares)) squares.append(10) print(squares) print(squares[:3] +[(1,2)]) squares[:-3] =[1979,1980] print(squares) squares[:] =[] print(squares) # <class 'builtin_function_or_method'> print(type(len)) print(len(squares)) # list can be nest and can hold any class type nestList=[1,[2,3],(2,3),{'dd':'ddd'}] print(nestList) # First Steps Towards Programming # demonstrating that the expression on the rihgt-hand side are all evaluated first # before any of the assignment take place. The right-hand side expression are evaluated # from the left to the right a,b,c =0,1,0 while a<10: print(a) print(c) a,b,c = b,a+b,c+b+a+b
true
a5e324794898c9ed9a024dcb506366e9617c1694
mvimont/FoundationsofMeasurement
/Chapter1/ThreeProceduresBasicMeasurement/Ordinal/ordinal.py
1,948
4.21875
4
import sys import random #Covers contens of Chapt 1, 1.1.1 pages 2 - 3 #Purpose here to define fundamental concepts (greater than, addition, etc) in definition/conditions used in book #length is here used as means to illustrate attribution of quantities to qualitative observations #transitive property def is_greater(a, b): if a > b: return True return False #"We require a > b only if the function of a is grea ter than the functino of b #In transitve property in this case, a and be are results of functions #Ordinal relationships fullfilable by all numeric cases, except where a ~ b def is_equivalent(a, b): if not a > b and not a < b: return True return False #We assign to first rod any number, a larger rod a larger number, a smaller rod a smaller, etc. #In event a ~ b.Procedure for ordinal measuremnt is only suitable in the event precision yields allows for it if __name__== "__main__": a_values = random.sample(range(0, sys.maxsize), 1000) b_values = random.sample(range(0, sys.maxsize), 1000) ord_dict = {'a': a_values, 'b': b_values} for value_index in range(len(ord_dict['a'])): a = ord_dict['a'][value_index] b = ord_dict['b'][value_index] output_tuple = (a, b) try: if is_greater(a, b): result = 1 print('a with value %s is greater than b with value %s' % output_tuple) elif is_greater(b, a): result = 2 print('a with value %s is less than b with value %s' % output_tuple) elif is_equivalent(a, b): result = 3 print('a with value %s is equal to b with value %s' % output_tuple) else: result = 666 assert result != 666 except AssertionError: print('The foundations of science are a lie and humanity is doomed. DOOOOOMMMMMED') raise
true
029d436bddee58022eaa2c619b3adccf19f34884
SeanRosario/assignment9
/lk1818/data.py
1,129
4.125
4
''' This module is for data importing, transforming, and merging. ''' import pandas as pd import numpy as np def load_data(): #this function reads the files and creates two data frames: countries and income in desired format. countries = pd.DataFrame(pd.read_csv('./countries.csv')) income = pd.DataFrame(pd.read_csv('./indicator_gapminder_gdp_per_capita_ppp.csv')) income = income.transpose() #transpose income data set so that row indexes are years return [countries, income] def merge_by_year(countries, income, year): ''' Provide a function called merge_by_year(year) to merge the countries and income data sets for any given year. The result is a DataFrame with three columns titled Country, Region, and Income. ''' try: int(year) except KeyError: print ('Invalid input type.') else: try: merged_income = countries.join(income.ix[str(year)], how='inner') except KeyError: print ('Invalid year.') else: merged_income.columns = ['Country', 'Region', 'Income'] return merged_income
true
8075bf6e3f2b4e9551fc405d348704ea7e757286
nglongceh/HWbyNglong
/BubbleSort.py
504
4.125
4
def BubbleSort(list): for i in range(len(list)): for j in range(len(list)-1): # Ascending list if list[j] > list[j+1]: temp = list[j] list[j] = list[j+1] list[j+1] = temp return list def main(): list = [] lenList = int(input('Enter the length of list: ')) for i in range(lenList): n = int(input()) list.append(n) print(list) print(BubbleSort(list)) main()
false
ed784f7a6638216dc456eccbe7adcf8172234450
Mukesh-SSSDIIT/python2021_22
/Sem5/Collections/List/list_basic3.py
686
4.125
4
list1 = ["aaa","bbb","ccc"] list2 = [111,222,333] list3 = list1 + list2 print(list1) print(list2) print(list3) # Another way to join to lists. # for i in list2: # list1.append(i) # print(list1) # Use extend method list1.extend(list2) print(list1) list4 = list([1,2,3,4]) print(list4) list5 = [10,20,10,20,30,40,30] # Returns the number of elements with the specified value print(list5.count(30)) # Returns the index of the first element with the specified value print(list5.index(20)) # Adds an element at the specified position print(list5) list5.insert(2,100) print(list5) list6 = [10,5,20,15,30] list6.reverse() print(list6) list6.sort(reverse=True) print(list6)
true
851f4795a81b7ea502e7f1e88e745206b7a989c8
mlnance/JHU_Class_Material
/comp_prot_pred_and_des/hw1/MLN_hw1_q2a.py
877
4.46875
4
#!/usr/bin/python __author__="morganlnance" ''' Homework 1 Question 2a Usage: ./script.py <nth number of Fibonacci sequence> Example: ./MLN_hw1_q2a.py 5 ''' ########### # IMPORTS # ########### import sys ############# # FUNCTIONS # ############# def fib(num): # num == 0 # if asking for the 0th fib number, return 0 if num == 0: return 0 # num == 1 # if asking for the 1st fib number, return 1 if num == 1: return 1 # num > 1 # otherwise, return the sum of fib(num-1) and fib(num-2) if num > 1: return fib(num-1) + fib(num-2) # otherwise, negative number given, return None else: return None ######## # MAIN # ######## try: print "\nFibonacci number %s is %s\n" %(sys.argv[1], fib(int(sys.argv[1]))) except: print "\nPlease give me a number for the Fibonacci sequence\n" sys.exit()
false
f4fe9dd155371769e419497fc24a46f0ead30cfd
NathanCrowley/Coding_Challenges
/Python_Challanges/Medium_difficulty/Email_generator.py
770
4.3125
4
class Employee: def __init__(self,first,second): self.first = first self.second = second def email(self): email = self.first.lower() + '.' + self.second.lower() + '@company.com' return email def fullname(self): fullname = self.first + ' ' + self.second return fullname def firstname(self): return self.first def secondname(self): return self.second #-----------------------------------Create instances of Employee object-------- emp_1 = Employee("John", "Smith") emp_2 = Employee("Mary", "Sue") emp_3 = Employee("Antony", "Walker") #--------------------------------------TEST---------------------------------- print(emp_1.fullname()) print(emp_2.email()) print(emp_3.firstname())
false
cac27739601b117356d19c3a8bad348ac16863a9
bilaleluneis/LearningPython
/abstract_class.py
1,708
4.375
4
from abc import ABC, abstractmethod __author__ = "Bilal El Uneis and Jieshu Wang" __since__ = "June 2018" __email__ = "bilaleluneis@gmail.com" """ Animal is an abstract class and I shouldn't be able to create instance of it, but in python there is no abstract keyword or feature that is part of the language construct, there is API that simulate such behaviour by extending ABC class (Abstract Base Class).I also found that I could break it and create instance of it unless I introduce an abstract method using abstractmethod decorator in this example. """ class Animal (ABC): def __init__(self, category=None): self.category = category super().__init__() @abstractmethod def speak(self): print("not sure what sound I should make!!") class Dog (Animal): def __init__(self): super().__init__() self.category = "Canine" def speak(self): print("Wooof!!") class Cat (Animal): def __init__(self): super().__init__() self.category = "Feline" def speak(self): print("Meaw!!") class Rat (Animal): def __init__(self): super().__init__() self.category = "Rodent" def speak(self): print("Whatever a Rat says!!") class NewlyDiscoveredAnimal (Animal): def __init__(self): super().__init__() self.category = "new category" def speak(self): super().speak() # start of running code if __name__ == "__main__": # animal = Animal() # if uncommented this will throw error, you cant create instance of abstract class collectionOfAnimals: [Animal] = [Cat(), Rat(), Dog(), NewlyDiscoveredAnimal()] for animal in collectionOfAnimals: animal.speak()
true
592b8c16c6ed624d8ae70f240be8be978780dee0
Mahay316/Python-Assignment
/Homework/homework1/assign1.py
663
4.125
4
# 1. 元素输出和查找 # 请输出0-50之间的奇数,偶数,质数 # 能同时被2和3整除的数 from math import sqrt # 练习使用列表解析式生成列表 odd = [x for x in range(51) if x % 2 == 1] print("奇数:") print(odd) even = [x for x in range(51) if x % 2 == 0] print("偶数:") print(even) # 练习使用循环判断质数 print("质数:") for i in range(2, 51): for j in range(2, int(sqrt(i)) + 1): if i % j == 0: break else: print(i, end=' ') print() # 练习使用列表解析式生成列表 arr = [x for x in range(51) if x % 2 == 0 if x % 3 == 0] print("能被2和3整除的数:") print(arr)
false
399124fad7d11889f36237589336c1da625d3587
Mahay316/Python-Assignment
/Homework/homework6/assign4.py
1,060
4.1875
4
# 4. 封装一个学生类,有姓名、年龄、性别、语文成绩、数学成绩和英语成绩 # 封装方法,求单个学生的总分,平均分,以及打印学生的信息 class Student: GENDER_MALE = '男' GENDER_FEMALE = '女' def __init__(self, name, age, gender, score): self.name = name self.age = age self.gender = gender # score为元组,依次保存语文、数学和英语成绩 self.score = score def __str__(self): info = f'姓名: {self.name} 性别: {self.gender} 年龄: {self.age}\n' score = f'语文: {self.score[0]} 数学: {self.score[1]} 英语: {self.score[2]}' return info + score def get_total(self): return sum(self.score) def get_average(self): return sum(self.score) / len(self.score) def info(self): print(self.__str__()) if __name__ == '__main__': s = Student('Peter', 18, Student.GENDER_MALE, (99, 89, 88)) s.info() print('总分:', s.get_total(), '平均分:', s.get_average())
false
09383d8e3d90a1801c149c2506d78660d790c983
JuliaGu808origin/pyModul1
/extraLabba/extra2/extra2/extra2.1.py
341
4.59375
5
# Write a Python program to get the dates 30 days before and after from the current date # !可以顯示再漂亮一點 import datetime today = datetime.datetime.now() before = today - datetime.timedelta(days=30) after = today + datetime.timedelta(days=30) print(f"Today: {today}, \n30 days before: {before}, \n30 days after: {after}")
true
979d8e871ff93c499b1e2c5fa30084f399b60655
JuliaGu808origin/pyModul1
/extraLabba/extra2/extra2/extra2.2.py
795
4.34375
4
######################################################### # Write a Python program display a list of the dates # for the 2nd Saturday of every month for a given year. ######################################################### import calendar try: givenYear = int(input("Which year -> ")) except: print("Wrong year number !") if givenYear: for month in range(1,13): eachMonth = calendar.monthcalendar(givenYear, month) first_sat_month = eachMonth[0] second_sat_month = eachMonth[1] third_sat_month = eachMonth[2] if first_sat_month[calendar.SATURDAY]: saturday = second_sat_month[calendar.SATURDAY] else: saturday = third_sat_month[calendar.SATURDAY] print(f"{calendar.month_abbr[month]} {saturday}")
true
e97220295929a55b8a4d67316cc7a53371ae156b
Jatin7385/Temperature-Converter
/Temperature_Converter.py
1,685
4.34375
4
def options(): print("Which conversion would you like me to do?") print("1)Celcius to Farenheit") print("2)Celcius to Kelvin") print("3)Farenheit to Celcius") print("4)Farenheit to Kelvin") print("5)Kelvin to Celcius") print("6)Kelvin to Farenheit") print("7)Quit Program") choice = int(input("Enter your choice")) return choice def accept(): temperature=input("Enter the temperature") return temperature #FORMULAS:F-32/9=C/5;K=C+273.15;F-32/9=K-273.15/5 def one(temp): F=((9*temp)/5)+32 return F def two(temp): K=temp+273.15 return K def three(temp): C=5*((temp-32)/9) return C def four(temp): C=5*((temp-32)/9) K=C+273.15 return K def five(temp): C=temp-273.15 return C def six(temp): C=temp-273.15 F=((9*C)/5)+32 return F choice=0 while choice!=7: choice=int(options()) if choice==7: quit() temp=float(accept()) if choice==1: F=one(float(temp)) print(f"The converted temperature is {F} Farenheit") elif choice==2: K=two(float(temp)) print(f"The converted temperature is {K} Kelvin") elif choice==3: C=three(float(temp)) print(f"The converted temperature is {C} degree Celcius") elif choice==4: K=four(float(temp)) print(f"The converted temperature is {K} Kelvin") elif choice==5: C=five(float(temp)) print(f"The converted temperature is {C} degree Celcius") elif choice==6: F=six(float(temp)) print(f"The converted temperature is {F} Farenheit") elif choice==7: quit() else: print("Wrong input") quit()
false
5d13fd5fed6c1f1fc198039f4f8249ea33c73a31
smraus/python-assignments
/28 octal to decimal.py
246
4.40625
4
#---- 28 octal to decimal conversion ---- print('Octal to decimal conversion\n') octal = input('Enter octal number : ') octal = octal[::-1] decimal = 0 for i, bit in enumerate(octal): decimal += int(bit) * 8 ** i print('Decimal :' , decimal)
false
c58dc265baa1f9ad0d4530ed428f44c1eba98726
smraus/python-assignments
/27 binary to decimal.py
253
4.4375
4
#---- 27 binary to decimal conversion ---- print('Binary to decimal conversion\n') binary = input('Enter binary number : ') binary = binary[::-1] decimal = 0 for i, bit in enumerate(binary): decimal += int(bit) * 2 ** i print('Decimal :' , decimal)
false
08f51078381095f447623fed68837c911cedb949
smraus/python-assignments
/08 startswithIs.py
517
4.375
4
#--------8 program to get a new string from a given string where "Is" has been added to the front------- def main(): while True: try: string = input('Enter a string : ') if string.startswith('Is'): print('Your string' , string , 'is correct.') else: new_string = 'Is'+string print('Your string' , string , 'has been formatted to' , new_string) break except: print('Invalid entry.') main()
true
a85ccfc169daf20fc4ced387b9d51cdcdc7ef556
smraus/python-assignments
/37 number palindrome.py
834
4.25
4
#---- program to reverse the digits of a given number and add it to the original, If the sum is not a palindrome repeat this procedure ---- def number(): num_inp = input('Enter digits : ') num_inp_rev = num_inp[::-1] num_total_inp = int(num_inp) + int(num_inp_rev) num_total_inp = str(num_total_inp) num_totalrev = num_total_inp[::-1] while True : if num_total_inp != num_totalrev : print('The final sum of' , num_inp , 'and' , num_inp_rev ,'is' , num_total_inp ,'\nIts reverse is' , num_totalrev , 'and its not a palindrome.\ninput again') number() break else: print('The final sum of' , num_inp , 'and' , num_inp_rev ,'is' , num_total_inp ,'\nIts reverse is' , num_totalrev , 'and its a palindrome.') break number()
false
f1a30558ce9da0d7f2f57b4782dc406b9e19f819
smraus/python-assignments
/16 x1y1 x2y2.py
757
4.3125
4
#-----16 program to compute the distance between the points (x1, y1) and (x2, y2)---- from math import sqrt def main(): while True: try: print('Enter the pairs in the format x,y') x1_y1 = input('Enter x1,y1 : ') x2_y2 = input('Enter x2,y2 : ') first = x1_y1.split(',') second = x2_y2.split(',') result = calculate(first, second) print('The distance between the points' , x1_y1 , 'and' , x2_y2 , 'is' ,result) break except: print('Invalid entries, enter digits in the given format') def calculate(f, s): r1 = (int(s[0]))**2 - (int(f[0]))**2 r2 = (int(s[1]))**2 - (int(f[1]))**2 r3 = sqrt(r1 + r2) return r3 main()
true
3d4a19f5a378a454403c21abe780ee3a62fe9cc7
qainstructorsky2/gitleeds2021c1
/demos/lambda.py
416
4.59375
5
choices = { "R":,Rock "P": Paper, "S: Scissors" } # Get the user's choice of the three user_choice = input("\nType R, P, or S to play against the computer: ") # Print what the user's choice, so she knows what she picked print user_choice # Make sure the user input is valid if user_choice in choices: print "You chose %s." % user_choice else: print "Your choice of %s is not a valid choice." % user_choice
true
d02059f5953986a9aaa0680b42321c3f58336189
rob19gr661/Python-Tutorials
/Python/2 - Reading And Writing Files/Writing_Files.py
680
4.125
4
""" Writing Files: """ # Testing the "a" operation """ Test_file = open("Testtest.txt", "a") # Remember that append will add something to the end of the file Test_file.write("\nToby - Official poopscooper") # We add the typed line to the end of the document Test_file.close() """ # Testing the "w" operation # Remember that "w" will overwrite the entire file if the same filename is used # A entirely new file can be created by simply changing the filename in the "open()" function Test_file = open("Testtest.txt", "w") Test_file.write("\nToby - Official poopscooper") # The typed line will be the only thing in the overwritten file Test_file.close()
true
b029fb0cd22c7c7a4c6ae93dc85e2d6223f804e6
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/Strings/434_number_of_segments_in_string.py
560
4.28125
4
# Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. # # Please note that the string does not contain any non-printable characters. # # Example: # # Input: "Hello, my name is John" # Output: 5 def countSegments(s): """ :type s: str :rtype: int """ # Credits: https://leetcode.com/problems/number-of-segments-in-a-string/solution/ count = 0 for i in range(len(s)): if (i == 0 or s[i-1] == " ") and s[i] != " ": count += 1 return count
true
9b0583e881f7ae10553828b4051968d8b0619a5e
AmitKulkarni23/Leet_HackerRank
/CrackingTheCodingInterview/Bit Manipulation/ith_bit_set.py
795
4.15625
4
""" Python program to check if ith bit is set in the binary representation of a given number To check if the ith bit is set or not (1 or not), we can use AND operator And the given number with 2^i. In 2 ^ i only the ith bit is set. All the other bits are zero. If numb & ( 2 ^ i) returns a non-zero number then the ith bit in the given number is set How to get 2 ^ i. Use the left -shift operator <<( i.e 1 << i) """ def ith_bit_set(numb, i): """ Method to check if the ith bit is set in a given number :param numb: integer :param i: integer i :return: true, iff the ith bit is set in teh given number Example: N = 20 = {10100}2 => ith_bit_set(20, 2) returns True """ if numb & (1 << i): return True return False print(ith_bit_set(20, 2))
true
fd0d1ff9f35f40b9159edd85135d069a02b562b4
AmitKulkarni23/Leet_HackerRank
/Dynamic_Programming/rod_cutting.py
957
4.15625
4
# Given a rod of certain lenght and given prices of different lenghts selling in the # market. How do you cut teh rod to maximize the profit? ################################### def get_cut_rod_max_profit(arr, n): """ Function that will return maximum profit that can be obtained by cutting teh rod into pieces and selling those pieces at market value L -> lenght of final rod arr -> array of prices Credits -> https://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ Time Complexity -> O(n ^ 2) """ # Use dynamic programming # Create a 2D array cache = [0 for _ in range(n+1)] cache[0] = 0 for i in range(1, n+1): max_val = float("-inf") for j in range(i): max_val = max(max_val, arr[j] + cache[i - j -1]) cache[i] = max_val return cache[n] # Examples arr = [1, 5, 8, 9, 10, 17, 17, 20] L = len(arr) print(get_cut_rod_max_profit(arr, L))
true
c5d38264a6fc929dad3989817c2965fa3c67c0e6
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/Trees/226_invert_binary_tree.py
1,294
4.40625
4
# Invert a binary tree. # # Example: # # Input: # # 4 # / \ # 2 7 # / \ / \ # 1 3 6 9 # Output: # # 4 # / \ # 7 2 # / \ / \ # 9 6 3 1 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # Time COmplexity : O(n) -> n is teh number of nodes in teh tree # Space COmplexity -> O(n) -> The queue can contain all nodes in each level # in the worst case def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ # We will try to use a iterative approach if root is None: return None queue = [root] while queue: current_node = queue.pop(0) # Swap the nodes temp = current_node.left current_node.left = current_node.right current_node.right = temp # Add left and right nodes to teh queue if they are present if current_node.left: queue.append(current_node.left) if current_node.right: queue.append(current_node.right) return root
true
f5e0e4edbdb2beb39e967a2edbc8d0f246649079
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/Strings/844_backspace_string_compare.py
989
4.25
4
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. # # # # Example 1: # # Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac". # Example 2: # # Input: S = "ab##", T = "c#d#" # Output: true # Explanation: Both S and T become "". # Example 3: # # Input: S = "a##c", T = "#a#c" # Output: true # Explanation: Both S and T become "c". # Example 4: # # Input: S = "a#c", T = "b" # Output: false # Explanation: S becomes "c" while T becomes "b". def backspaceCompare(S, T): """ :type S: str :type T: str :rtype: bool """ s_list = [] t_list = [] for x in S: if x != "#": s_list.append(x) else: if s_list: s_list.pop() for y in T: if y != "#": t_list.append(y) else: if t_list: t_list.pop() return "".join(s_list) == "".join(t_list)
true
ff3dc719301e1f8dbcfc28964d43173e79c7278d
AmitKulkarni23/Leet_HackerRank
/Dynamic_Programming/maximum_sum_increasing_subsequence.py
1,346
4.25
4
# Given an array of n positive integers. # Write a program to find the sum of maximum sum subsequence of the given array such that the intgers in # the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, # then output should be 106 (1 + 2 + 3 + 100), # if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and # if the input array is {10, 5, 4, 3}, then output should be 10 # Source -> https://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-sum-increasing-subsequence/ def max_sum_incr_subseq(arr): """ Function that returns the sum of teh maximum sum increasing subsequence of the given array Example: max_sum_incr_subseq([1, 101, 2, 3, 100, 4, 5] ) -> 106 """ # Copy/ Clone the entire array into a different array msis = arr[:] # Iterate through the arr for i in range(1, len(arr)): for j in range(i): # Do what? # Compare the elements # Then check the sum if arr[j] < arr[i] and msis[i] < msis[j] + arr[i]: # Then update msis[i] = msis[j] + arr[i] # Return the max value in msis array return max(msis) # Test Examples: arr = [1, 101, 2, 3, 100, 4, 5] arr_2 = [3, 4, 5, 10] print("MSIS is ", max_sum_incr_subseq(arr_2))
true
9a640edb1c2cea9743d4b651dbbae43095032d20
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/Trees/572_subtree_of_another_tree.py
2,144
4.15625
4
# Given two non-empty binary trees s and t, check whether tree t # has exactly the same structure and node values with a subtree of s. # A subtree of s is a tree consists of a node in s and all of this node's descendants. # The tree s could also be considered as a subtree of itself. # # Example 1: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # Given tree t: # 4 # / \ # 1 2 # Return true, because t has the same structure and node values with a subtree of s. # Example 2: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # / # 0 # Given tree t: # 4 # / \ # 1 2 # Return false. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ #Credits -> https://leetcode.com/problems/subtree-of-another-tree/discuss/102729/Short-Python-by-converting-into-strings return self.do_pre_order_traversal(t) in self.do_pre_order_traversal(s) def do_pre_order_traversal(self, node, x_string): """ Helper function """ if not node: return "$" return "^" + str(node.val) + "#" + self.do_pre_order_traversal(node.left) + self.do_pre_order_traversal(node.right) # Time Complexity O(m * n) # Space Complexity : O(n) -> where n is the number of nodes in s def best_leetcode_sol(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ return traverse(s,t); def equals(x, y): """ Helper function """ if not x and not y: return True if x is None or y is None: return False return x.val==y.val and equals(x.left,y.left) and equals(x.right,y.right) def traverse(s, t): """ Helper Function """ return s is not None and ( equals(s,t) or traverse(s.left,t) or traverse(s.right,t))
true
a8dce32f98177322594dbd445b955acfa98c6fcb
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/merge_2_sorted_linked_lists.py
2,896
4.125
4
# Merge 2 sorted linked lists # Return the new merged list # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # My Solution - Very poor performance - beats only 26% of python submissions # Runtime for 208 test cases = 88ms # Sometimes - this is giving a runtime of 60ms class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # Iterate through the first list # and store all the values of nodes in a # list first_ll_values = [] # If the second list is empty, return the # first list if not l2: return l1 # If the first list is empty, return the # second list if not l1: return l2 # Iterate through the first list and capture all the values # in a list first_ll_values = [] while l1: first_ll_values.append(l1.val) l1 = l1.next # Iterate through the second list and capture all the values # in a list second_ll_values = [] while l2: second_ll_values.append(l2.val) l2 = l2.next # Now we have all the values in 2 lists # These lists should be merged and sorted sorted_merged_list = sorted(first_ll_values + second_ll_values) # Iterate through this sorted_merged_list and create # a new ListNode for each item and link the next for this item as the # next item in the list for i in range(len(sorted_merged_list) - 1): ListNode(sorted_merged_list[i]).next = sorted_merged_list[i+1] return sorted_merged_list # # Recursive Solution from discussion portal in # # Leetcode ( https://leetcode.com/problems/merge-two-sorted-lists/discuss/9735/Python-solutions-(iteratively-recursively-iteratively-in-place).) # # NOT MY SOLUTION # # Runtime : 76ms # if not l1 or not l2: # return l1 or l2 # if l1.val < l2.val: # l1.next = self.mergeTwoLists(l1.next, l2) # return l1 # else: # l2.next = self.mergeTwoLists(l1, l2.next) # return l2 # # Iterative solution, in-place # # NOT MY SOLUTION # # Runtime : 68ms # if None in (l1, l2): # return l1 or l2 # dummy = cur = ListNode(0) # dummy.next = l1 # while l1 and l2: # if l1.val < l2.val: # l1 = l1.next # else: # nxt = cur.next # cur.next = l2 # tmp = l2.next # l2.next = nxt # l2 = tmp # cur = cur.next # cur.next = l1 or l2 # return dummy.next
true
ed006d939bae223afdd788f0becae5ffe29e2ad3
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/Bit_Manipulation/number_of_1_bits.py
1,081
4.375
4
# Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). # # Example 1: # # Input: 11 # Output: 3 # Explanation: Integer 11 has binary representation 00000000000000000000000000001011 # Example 2: # # Input: 128 # Output: 1 # Explanation: Integer 128 has binary representation 00000000000000000000000010000000 # ALGORITHM: Brian Kernighan’s Algorithm # Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set # bit(including the righmost set bit). So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)), # we unset the righmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count. # Beauty of the this solution is number of times it loops is equal to the number of set bits in a given integer. def hammingWeight(n): """ :type n: int :rtype: int """ count = 0 while n > 0: n = n & (n - 1) count += 1 return count # Examples: n = 128 print(hammingWeight(n))
true
b2af5b93ed6b9fc6fa6503ed5ad1b93caae1ea70
AmitKulkarni23/Leet_HackerRank
/LeetCode/Medium/BFS/199_binary_tree_right_side_view.py
1,605
4.3125
4
# Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. # # Example: # # Input: [1,2,3,null,5,null,4] # Output: [1, 3, 4] # Explanation: # # 1 <--- # / \ # 2 3 <--- # \ \ # 5 4 <--- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ # Credits -> https://leetcode.com/problems/binary-tree-right-side-view/solution/ # Time Complexity -> O(n) # Space Complexity -> O(n) # n -> height of the tree right_most_val = dict() max_depth = -1 stack = [(root, 0)] while stack: node, depth = stack.pop() if node is not None: max_depth = max(depth, max_depth) # Set default -> Sets the value to default value # if this key is not already present # Note: The dict is of the form {depth : node.val} right_most_val.setdefault(depth, node.val) # Append the left node first( because we want to pop the right node) # as we want the right side view stack.append((node.left, depth + 1)) stack.append((node.right, depth + 1)) return [right_most_val[d] for d in range(max_depth + 1)]
true
6e65a2c082edad96b92dc17dced5ed6615e22433
AmitKulkarni23/Leet_HackerRank
/LeetCode/Medium/DFS/439_ternary_expression_parser.py
2,830
4.5625
5
# Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume that the given expression is valid and only consists of digits 0-9, ?, :, T and F (T and F represent True and False respectively). # # Note: # # The length of the given string is ≤ 10000. # Each number will contain only one digit. # The conditional expressions group right-to-left (as usual in most languages). # The condition will always be either T or F. That is, the condition will never be a digit. # The result of the expression will always evaluate to either a digit 0-9, T or F. # Example 1: # # Input: "T?2:3" # # Output: "2" # # Explanation: If true, then result is 2; otherwise result is 3. # Example 2: # # Input: "F?1:T?4:5" # # Output: "4" # # Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: # # "(F ? 1 : (T ? 4 : 5))" "(F ? 1 : (T ? 4 : 5))" # -> "(F ? 1 : 4)" or -> "(T ? 4 : 5)" # -> "4" -> "4" # Example 3: # # Input: "T?T?F:5:3" # # Output: "F" # # Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: # # "(T ? (T ? F : 5) : 3)" "(T ? (T ? F : 5) : 3)" # -> "(T ? F : 3)" or -> "(T ? F : 5)" # -> "F" -> "F" # Runtime : 76ms def parseTernary(expression): """ :type expression: str :rtype: str """ # Credits -> https://leetcode.com/problems/ternary-expression-parser/discuss/92185/Short-Python-solutions-one-O(n) # Time COmplexity -> O(n) stack = [] for c in reversed(expression): stack.append(c) # print("Stack is ", stack) if stack[-2:-1] == ['?']: # print("We are here") # print("stack[-3]", stack[-3]) # print("stack[-5]", stack[-5]) # print("stack[-1]", stack[-1]) stack[-5:] = stack[-3 if stack[-1] == 'T' else -5] return stack[0] # Runtime : 32 ms def parseTernary(expression): """ :type expression: str :rtype: str """ while len(expression) > 2: count = 0 for x in range(2, len(expression)): if expression[x] == '?': count += 1 elif expression[x] == ':': count -= 1 if count == -1: if expression[0] == 'T': expression = expression[2:x] else: expression = expression[x+1:] break else: return expression return expression # Examples: express = "T?2:3" print(parseTernary(express))
true
3c9e6d1bc56f8b97daada933d42d642542d3cd5c
AmitKulkarni23/Leet_HackerRank
/LeetCode/Easy/Bit_Manipulation/power_of_2.py
362
4.21875
4
# Given an integer, write a function to determine if it is a power of two. # # Example 1: # # Input: 1 # Output: true # Example 2: # # Input: 16 # Output: true # Example 3: # # Input: 218 # Output: false def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ if n > 0: return (n & n - 1) == 0 return False
true
efe5f93bbda6a8c7729f320e8f93bf710218ef32
lv888/fizzbuzz
/fizzbuzzLV.py
384
4.25
4
#fizzbuzzattemptsLV # Example output: "1 2 fizz 4 buzz fizz 7" # fizz for numbers divisible by three # buzz for numbers divisible by five i = int(input("Enter a number: ")) num = 0 while num < i: num += 1 if num == 0: continue if num%3 == 0: print("fizz") continue if num%5 == 0: print("buzz") continue print(num) exit()
false
58589846f783e636a07f40bb1c9a67441cbe9bdd
giancarlo358/cracklepop
/crackle_pop.py
686
4.25
4
#Write a program that prints out the numbers 1 to 100 (inclusive). #If the number is divisible by 3, print Crackle instead of the number. #If it's divisible by 5, print Pop. #If it's divisible by both 3 and 5, print CracklePop. You can use any language. #custom range start = 1 end = 101 my_range = range(start,end) divisor_three = 3 divisor_five = 5 #function def cracklepop(number, divisor): return number % divisor == 0 # what is my residual #loop for i in my_range: result = "" if cracklepop(i, divisor_three): result += "Crackle" if cracklepop(i, divisor_five): result += "Pop" print(i if result == "" else result) #https://repl.it/GICd
true
08772f0631dc9181b1edfafce557153778c8cb97
UjjwalP08/Basics-Of-Python
/No_06_dictonary.py
1,576
4.65625
5
a = {"key": "value", "greet": "good morning", "jay": "studyman", "mehul": "FEKU"} # Here a is dictionary in python dictionary start with curly brackets{} """Dictionary is collection of key and value pairs""" print(a) print(a["key"]) print(a["greet"]) # here this the key and we print the value of key a["ritik"] = "Gk" a["Anurag"] = "free fire" # using this we can add element in dictionary print(a) # using update({key:value}) function we can add elements in dictionary a.update({"Deva": "free fire pro"}) a.update({"Ayushman": "Too mature"}) print(a) # using del we can delete or remove elements in dictionary del a["greet"] del a["jay"] print(a) d1 = a.copy() del d1["key"] print(a) print(d1) a["bhaji"] = {"free fire": "noob", "cricket": "noob", "pavn": "roll"} # some times we can make a dictionary inside the dictionary above example print(a) d = a # d is new dictionary and a is our old dictionray del a["key"] """If we copy our dictionary in other dictionary and if we change in other dictionary so change also show in our dictionary becloz here other dictionray is pointer and point to our old dictionay and if we do change new dictionary so change also happen in old dictionary so remove this proble we can use copy() function""" print(a) print(d) # print both dictionary # Use the copy function d2 = a.copy() # d2 is new and a is old dictionary del d2["bhaji"] print(d2) print(a) # this time only change happen in new dictionary d2 print(a.keys()) # print all the a dictionary key print(a.items()) # print all the a dictionary key values or items
false
f592d4f598ec510ad260fb6133460514ea38e7d4
UjjwalP08/Basics-Of-Python
/Exercises/Exercise 1.py
353
4.125
4
"""In This exercise we can take input from user and compiler return according to its out put Eg:- Key now we can provide some details about it.""" a = {"key": "Use to open lock", "greet": "Means to Call about Good mornig", "IT": "Study of Website and Computer"} "" print(a.keys()) print("Enter Key which details you want to show") b=input() print(a[b])
true
c4a9d247b4095d2db4b6de8e86656368b1014a8c
UjjwalP08/Basics-Of-Python
/Practice/1.py
762
4.21875
4
""" ---------> Program of printing star pattern <--------- """ n=input("Enter the value of n:-") n=int(n) # for value in range(n,0,-1): # for itm in range(1,value+1): # print("*",end=" ") # print() # # for values in range(1,n+1): # print(values) for i in range(1,n+1): for j in range(1,i+1): print(" * ",end=" ") print() for i in range(n,0,-1): for j in range(1,i+1): print(" * ",end=" ") print() for i in range(1,n+1): for j in range(1,n-i+1): print(" ",end=" ") for k in range(1,i+1): print(" * ",end=" ") print() for i in range(n,0,-1): for j in range(1,n-i+1): print(" ",end=" ") for k in range(1,i+1): print(" * ",end=" ") print()
false