blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
110a9cd9f877bb7ea3b2928597aa883809a78589
sushil-dubey/AI
/hungry.py
267
4.125
4
hungry = input("are you hungry?") if hungry=="yes": print("Eat something") print("Eat burger") print("Eat fries") else: thursty = input("are you thursty?") if thursty="yes": print("Drink water") print("Drink soda") elese: print("DO your homework")
false
1ea8939ea8bc9bd72143f6e30e12b192072a9128
mckenziejoyce/cs591_c2_assignment_5
/Problem2.py
1,730
4.125
4
import math def choose_shape(shape): if(shape=='C'): print("Please input a radius: ") radius = input() return circle(radius) if(shape=='R'): print("Please input a length: ") length = input() print("Please input a breadth: ") breadth = input() return rectangle(length, breadth) if(shape=='S'): print("Please input a length: ") length = input() return square(length) else: return "Not a valid shape" def circle(radius): area = math.pi*(radius*radius) circumference = 2*math.pi*radius area = round(area, 2) circumference = round(circumference, 2) print_result('C', area, circumference) return area, circumference def square(length): area = (length*length) perimeter = 4*length print_result('S', area, perimeter) return area, perimeter def rectangle(length, breadth): area = (length*breadth) perimeter = 2*length + 2*breadth print_result('R', area, perimeter) return area, perimeter def print_result(shape, input1, input2): if(shape=='C'): return "Area of circle: " + str(input1) + " Circumference of circle: " + str(input2) if(shape=='R'): return "Area of rectangle: " + str(input1) + " Perimeter of rectangle: " + str(input2) if(shape=='S'): return "Area of square: " + str(input1) + " Perimeter of square: " + str(input2) def main(): print("Type C, R, or S, to choose between Circle, Rectangle, or Square.") shape = input() input1, input2 = choose_shape(shape) print(print_result(shape, input1, input2)) if __name__ == '__main__': main()
true
1cd6edce3b8a9aa38d6ad3ce71abdf307cefbfb1
njbsanchez/parsing
/fit-to-width.py
1,398
4.59375
5
""" Write a function that prints a string, fitting its characters within char limit. It should take in a string and a character limit (as an integer). It should print the contents of the string without going over the character limit and without breaking words. For example: >>> fit_to_width('hi there', 50) hi there Spaces count as characters, but you do not need to include trailing whitespace in your output: >>> fit_to_width('Hello, world! I love Python and Hackbright', ... 10) ... Hello, world! I love Python and Hackbright Your test input will never include a character limit that is smaller than the longest continuous sequence of non-whitespace characters: >>> fit_to_width('one two three', 8) one two three """ def fit_to_width(string, limit): """Print string within a character limit.""" print_phrase = [] line_to_add = "" words = string.split(" ") for word in words: if len(line_to_add) == 0: line_to_add = word elif len(word) + len(line_to_add) >= limit: print_phrase.append(line_to_add) line_to_add = word else: line_to_add += " " + word print_phrase.append(line_to_add) for line in print_phrase: print(line) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print('\n✨ ALL TESTS PASSED!\n')
true
445c8ee74abb2a2d3e40b875a1eedd4926edbef2
nicoletteheath/python
/She_Codes_exercises/functions.py
923
4.125
4
# Question 1 #(F - 32)*5/9 = C # fahrenheit_temperature = input("what is the temperature in fahrenheit? ") # celsius_temperature = (float(fahrenheit_temperature) - 32.0) * 5.0 / 9.0 # print(f"{celsius_temperature:.2f}") def convert_fahrenheit(temp_in_fahrenheit): celsius_temperature = (float(temp_in_fahrenheit) - 32.0) * 5.0 / 9.0 return celsius_temperature print(convert_fahrenheit(113)) #Question 2 #mean is the sum divided by the count (average of the numbers) def calculate_mean(total_sum, num_items): mean = total_sum / num_items return mean print(calculate_mean(50, 10)) # output_numbered_list = False # number_list = [] # while output_numbered_list == False: # number = input("Enter a number") # if number == "": # output_numbered_list = True # else: # number_list.append(int(number)) # return(number_list) # total_sum = sum(number_list) # num_items = len(number_list)
true
75bdf6daccb3fbd0c7d019ff07d989ef4cdf2915
nicoletteheath/python
/She_Codes_exercises/variables&user_input.py
897
4.15625
4
# question 1 first_int = 3 second_int = 9 result = first_int + second_int print(result) first_int = -3 second_int = 9 result = first_int + second_int print(result) first_float = 3.0 second_int = -9 result = first_float + second_int print(result) # question 2 first_int = 3 second_int = 9 result = first_int * second_int a = "*" b = "=" print(first_int, a, second_int, b, result) first_int = -3 second_int = 9 result = first_int * second_int a = "*" b = "=" print(first_int, a, second_int, b, result) irst_float = 3.0 second_int = -9 result = first_float * second_int a = "*" b = "=" print(first_float, a, second_int, b, result) # question 3 distance_km = input("Enter a distance in km") #finish this off once I have done functions #question 4 print("What is your name?") name = input() print("what is your height in cms?") height = input() print(name + " is " + height + "cms tall")
true
bb9ab4d35dab30fad8bb85b193c6186142c6d590
rajkumarvishnu/PyLessons
/ex30.py
442
4.21875
4
people = 40 cars = 40 busses = 40 if cars > people: print "we should take the cars" elif cars < people: print "we should not take the cars" else: print "we cant decide" if busses > cars: print "That's too many busses" elif busses<cars: print "may be we could take the busses" else: print "we still can't decide" if people > busses: print "Alright, lets just take teh busses" else: print "Fine, let's stay home then"
true
2e790ff77af48d96a793834b82b92cd626ea9638
elisha1165/Homework
/Python/38/hw38.py
1,374
4.3125
4
number_list = [1,2,3,4,5,6,7,8,9,10] for number in number_list: for number2 in number_list: print(number * number2) import random the_number = random.randint(1, 100) try: number_guessed = int(input('Please choose a number from 1 - 100 ')) except NameError as n: print( 'You entered a symbol other than a number. You can start the game over and play by the rules') except ValueError as e: print( 'You entered a symbol other than a number. You can start the game over and play by the rules') while number_guessed != the_number: if number_guessed > 100 or number_guessed < 1: try: number_guessed = int(input( 'The number you chose is invalid. Please choose a number between 1 and 100 ')) except ValueError as e: print( 'You entered a symbol other than a number. You can start the game over and play by the rules') break msg = 'Guess a higher number' if number_guessed < the_number else 'Guess a lower number' print(msg) try: number_guessed = int(input('Please try again ')) except ValueError as e: print( 'You entered a symbol other than a number. You can start the game over and play by the rules') break if number_guessed == the_number: print(f'You guessed the number! It was {the_number} ')
true
8cc48cf5ea75cb110c764b25ecc34c9aa6e509e9
alem-classroom/student-algo-and-data-structures-atykhan
/queue/queue.py
692
4.15625
4
class Queue: def __init__(self): # initialize Queue such that there is a list called 'values' where you store elements # 'front' which is the index of the element that is on the front of the queue # 'back' which is the index of the element that is on the back of the queue def enqueue(self, value): # add value to the queue def get_front(self): # return value that is first in the queue def dequeue(self): # remove first element of the queue and return it # if queue is empty, return "Queue is empty" def get_size(self): # return size of the queue def clear(self): # clear the queue
true
f0c5e303e7b79ba9ffdc9901ab7c630a24fb4f42
burmeseitman/dictionaryattack
/passwordcracker.py
436
4.15625
4
import hashlib found = False passhash = input("Enter SHA-256 password Hash value: ") dictwords = open("passwordlist.txt", "r") for word in dictwords: encryptword = word.encode("utf-8") hashvalue = hashlib.sha256(encryptword.strip()).hexdigest() if hashvalue == passhash: print("Bingo! Password Found.") print("This is Password >> " + word) found = True break if found == False: print("Password not found in the list")
true
a229789affda08814ca049b922adc112da016e84
vitaly-krugl/interview-prep
/cracking_problems/reverse_array/reverse_array.py
331
4.21875
4
def reverseArray(array): """Reverse elements of the array in place :param array: list of values to reverse in place :return: None """ for i in xrange(len(array) // 2): otherIdx = len(array) - i - 1 currentVal = array[i] array[i] = array[otherIdx] array[otherIdx] = currentVal
true
ee68793b7a99b0033c9ab27497aa46ebcf6fbaf3
anmolbava/Basic-Logic-Builing-python-programs-
/recursion.py
203
4.1875
4
def recursion(n): if (n==1 or n==2): return 1 num1=recursion(n-1) num2=recursion(n-2) sum = num1 + num2 print (sum) return sum n=int(input()) print(recursion(n))
false
e496702bd5f99161d94ce8ff09b2308ce3ced211
dziedzic-l/Practice-Python
/13_Fibonacci.py
408
4.28125
4
# Get number of numbers to display how_many = int(input('How many numbers to display: ')) def fibonacci(x): '''Returns list of fibonacci numbers''' if x == 0: return [] if x == 1: return [1] else: fibonacci = [0, 1] for n in range(2, x + 1): fibonacci.append(fibonacci[n - 1] + fibonacci[n - 2]) return fibonacci print(fibonacci(how_many))
true
fd6c2f902147fe3c21d5bd637948f4af11d04138
dziedzic-l/Practice-Python
/15_Reverse_Word_Order.py
1,162
4.375
4
# Method 1 def reverse_word_order_1(text): '''Returns string with reversed word order''' # Split a string into a list where each word is a list item words = text.split(' ') # The join() method takes all items in an iterable # and joins them into one string return ' '.join(words[::-1]) # Method 2 def reverse_word_order_2(text): '''Returns string with reversed word order''' reversed_words = [] words = text.split(' ') # For each word position in text # Example: # 0 1 2 3 4 # | I | like | programming | in | Python # -5 -4 -3 -2 -1 # ↑ # We start here for word_position in range(-1, -len(words) - 1, -1): # Make list of words in reversed order reversed_words.append(words[word_position]) return ' '.join(reversed_words) text = '' # While text variable is empty while text.strip() == '': # Get the text typed by the user text = input('Type something... ') # Print the results print(reverse_word_order_1(text)) print(reverse_word_order_2(text))
true
fb731162f68d994600d40fa92767a2fea52b519c
c4rl0sFr3it4s/Python_Analise_De_Dados
/_estudoPython_solid/passagem_de_argumentos.py
1,149
4.15625
4
'''passagem de argumentos pela linha de comando Todas as funções padroes do python é build in Passagem pelo usuário pelo input, E a saida usando o terminal modulo sys permite utilizar algumas coisas do sistema operacional ['c:/Users/Ticar/Desktop/_estudoPython/passagem_de_argumentos.py'] arg 0, é sempre o caminho do arquivo python sistema operacional abrir o terminal e rodar o arquivo .py ele vai abrir no argumento 0, que é o nome do arquivo agora colocando mais argumento ele vai passando do sistema operacional para nosso script. Pela linha de comando passa argumento, scripts para rodar em modo texto para o cara poder executar rapidamente ''' import sys ''' variável dentro da sys, arg1 metodo, arg2 vai ser n1, arg3 vai ser n2 arg1 o metodo que o sistema vai ter que fazer arg2 operador arg3 operando ''' argumentos = sys.argv def soma(n1, n2): return n1 + n2 def sub(n1, n2): return n1 - n2 if argumentos[1] == "soma": resp = soma(float(argumentos[2]), float(argumentos[3])) elif argumentos[1] == "sub": resp = sub(float(argumentos[2]), float(argumentos[3])) print(resp)
false
b716b9987677efa593f1ca3370f866328c6753fe
DavidMarquezF/InfoQuadri2
/Practica 7/MergeSort.py
1,046
4.28125
4
#!/usr/bin/env python #-*- coding: utf-8 -*- def mergeSort(l): """ retorna una nova llista ordenada segons el merge sort >>> mergeSort([10,5,25,1,4,3,5,68,2,9]) [1, 2, 3, 4, 5, 5, 9, 10, 25, 68] >>> mergeSort([256,44,32,56,2,134]) [2, 32, 44, 56, 134, 256] """ list = l[:] if len(list)>1: mid=len(list)/2 lefthalf=list[:mid] righthalf=list[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i<len(lefthalf) and j<len(righthalf): if lefthalf[i] < righthalf[j]: list[k]=lefthalf[i] i+=1 else: list[k]=righthalf[j] j+=1 k+=1 while i<len(lefthalf): list[k]=lefthalf[i] i+=1 k+=1 while j<len(righthalf): list[k]=righthalf[j] j+=1 k+=1 return list if (__name__ == "__main__"): l=[54,26,93,17,77,31,44,55,20] print mergeSort(l)
false
4213ff88f8a20f864a7acd107df76d32f4d57966
BelleMardy/all_pracs
/week_01/loops.py
311
4.125
4
# Display all the odd numbers between between 1 and 20 with a space between each for i in range(1, 21, 2): print(i, end=" ") print() # Count in 10's from 0 to 100 for i in range(0, 101, 10): print(i, end=" ") print() # Count down from 20 to 1 for i in range(20, 0, -1): print(i, end=" ") print()
true
b42e3ac91804eb6c264fbb74b68039370bacefcc
BelleMardy/all_pracs
/week_02/prac_console_random.py
2,349
4.28125
4
print("""help(random.randint) Help on method randint in module random: randint(a, b) method of random.Random instance Return random integer in range [a, b], including both end points. """) print("""help(random.randrange) Help on method randrange in module random: randrange(start, stop=None, step=1, _int=<class 'int'>) method of random.Random instance Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. """) print("""help(random.uniform) Help on method uniform in module random: uniform(a, b) method of random.Random instance Get a random number_int in the range [a, b) or [a, b] depending on rounding. """) print(""" print(random.randint(5, 20)) 18 What did you see on line 1. A random number_int between and inclusive of 5 and 20. What was the smallest number_int you could have seen. 5 What was the largest number_int you could have seen. 20 ______________________________________________________________ print(random.randrange(3, 10 , 2)) 7 What did you see on line 2. A random number_int between and inclusive of 3 and 9, excluding 10. Starting at 3 3 (3+2) 5 (5+2) 7 (7+2) 9 What was the smallest number_int you could have seen. 3 What was the largest number_int you could have seen. 9 ______________________________________________________________ NOT SURE ABOUT THIS ONE print(random.uniform(2.5, 5.5)) 4.487295499375918 help(random.uniform) Help on method uniform in module random: uniform(a, b) method of random.Random instance Get a random number_int in the range [a, b) or [a, b] depending on rounding. What did you see on line 3. A random number_int between and inclusive of 2.5 and 5.5, depending on rounding, however it seems the rounding goes to 15 decimal points. What was the smallest number_int you could have seen. 2.500000000000000 What was the largest number_int you could have seen. 5.500000000000000 ______________________________________________________________ """) import random # should be at top, however for this exercise keeping module close to program print(random.randint(1, 4)) print(random.randrange(3, 10, 2)) print(random.uniform(2.5, 5.5))
true
fdff0280dfd923fc0a229d182772c503ae743364
BelleMardy/all_pracs
/week_04/intermediate_exercise_1.py
512
4.125
4
numbers = [] for i in range(5): number = float(input("Number: >>> ")) numbers.append(number) for i in range(1): number_line = 0 print("Number {}, first number: {}".format(i + 1, (numbers[0]))) print("Number {}, last number: {}".format(i + 1, numbers[4])) print("Number {}, smallest number: {}".format(i + 1, min(numbers))) print("Number {}, largest number: {}".format(i + 1, max(numbers))) print("Number {}, average number: {:.2f}".format(i + 1, sum(numbers) / (len(numbers))))
true
591df7f003d20db5916acfa78925769918153dfa
bhishanpdl/Programming
/Python/online_learning/codewars/n2_increasing_sum_seq/decompose.py
2,631
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def decompose(n): """Example n = 11, result = [1, 2, 4, 10].""" goal = 0 result = [n] print('{} {} {}'.format('result = ', result, '')) # result = [11] while result: current = result.pop() print('{} {} {}'.format('current = ', current, '')) # current = 11 goal += current ** 2 print('{} {} {}'.format('goal = ', goal, '')) # goal = 121 for i in range(current - 1, 0, -1): print('{} {} {}'.format('\ni = ', i, '')) # i = 10 print('{} {} {}'.format('goal = ', goal, '')) print('{} {} {}'.format('goal - (i ** 2) = ', goal - (i ** 2), '')) # goal - (i ** 2) = 21 if goal - (i ** 2) >= 0: print('{} {} {}'.format('goal = ', goal, '')) print('{} {} {}'.format('goal - (i ** 2) = ', goal - (i ** 2), '')) goal -= i ** 2 result.append(i) if goal == 0: result.sort() return result return None if __name__ == "__main__": a = decompose(11) print(a) # My little sister came back home from school with the following task: given a # squared sheet of paper she has to cut it in pieces which, when assembled, # give squares the sides of which form an increasing sequence of numbers. # At the beginning it was lot of fun but little by little we were tired of # seeing the pile of torn paper. So we decided to write a program that could # help us and protects trees. # # Task # # Given a positive integral number n, return a strictly increasing # sequence (list/array/string depending on the language) of numbers, # so that the sum of the squares is equal to n². # # If there are multiple solutions (and there will be), # return the result with the largest possible values: # # Examples # # decompose(11) must return [1,2,4,10]. Note that there are actually two ways # to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² # but don't return [2,6,9], since 9 is smaller than 10. # # For decompose(50) don't return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] # since [1, 1, 4, 9, 49] doesn't form a strictly increasing sequence. # # Note # # Neither [n] nor [1,1,1,…,1] are valid solutions. If no valid solution exists, # return nil, null, Nothing, None (depending on the language) or "" # (Java, C#) or {} (C++). # # The function "decompose" will take a positive integer n and return the # decomposition of N = n² as: # # [x1 ... xk] # Hint # # Very often xk will be n-1.
false
e06d9d786d7658c7916b64c6a348fba99a9718d4
bhishanpdl/Programming
/Python/data_manipulation/pandas/dropna_subset_isnull_notnull_isfinite/pd_dropna.py
950
4.5
4
#!python # -*- coding: utf-8 -*-# # # Author : Bhishan Poudel; Physics Graduate Student, Ohio University # Date : Jan 7,2017 # Ref: http://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas # -dataframe-whose-value-in-certain-columns-is-nan # Imports import pandas as pd import numpy as np def main(): df = pd.DataFrame(np.random.randn(10, 3)) df.ix[::2, 0] = np.nan df.ix[::4, 1] = np.nan df.ix[::3, 2] = np.nan # print(df) df1 = df.dropna() # drop all rows that have any NaN values # print(df1) df1 = df.dropna(how='all') # drop only if ALL columns are NaN # print(df1) df1 = df.dropna(thresh=2) # Drop row if it does not have at least two # print(df1) df1 = df.dropna(subset=[1]) # Drop only if NaN in specific column # print(df1) df1 = df[pd.notnull(df[1])] # suggested by Wes (author of Pandas) print(df1) if __name__ == '__main__': main()
false
3e16c07827c1dd4deb5ba18d65b283a7923be8db
bhishanpdl/Programming
/Python/plotting/plotting1/legends_and_text_annotations/legends_outside.py
1,509
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author : Bhishan Poudel # Date : Mar 24, 2016 # Ref : http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot # Example 1 (legens inside the plot) import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) ax.legend() plt.show() # Example 2 (legends right side of the plot) import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$'%i) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show() ##============================================================================= # Example 3 (legend below the plot) import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): line, = ax.plot(x, i * x, label='$y = %ix$'%i) # Shrink current axis's height by 10% on the bottom box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) # Put a legend below current axis ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=5) plt.show()
true
8cb9bbc1924b069ee3c3ce3b0b5b9fc60d30da99
bhishanpdl/Programming
/Python/interesting/keyboard_input.py
564
4.34375
4
#!/usr/bin/python # -*- coding: utf-8 -*- #keyboard input # raw_input is used to read text (strings) from the user: # name=raw_input('Enter your name : ') # print ("Hi %s, Let us be friends!" % name); # print (30 * '*') # # # input is used to read integers # age = input("What is your age? ") # print "Your age is: ", age # type(age) #keyboard input name = raw_input("What's your name? ") print("Nice to meet you " + name + "!") age = input("Your age? ") print("So, you are are already " + str(age) + " years old, " + name + "!") age = float(age) print(age+2)
true
f5ec40734f1155a4aa2cac72c40971a9d0df29ec
bhishanpdl/Programming
/Doxygen/argsparse/square_choice1.py
957
4.25
4
#!python # -*- coding: utf-8 -*- """ **Author:** Bhishan Poudel; Physics PhD Student, Ohio University **Date:** Oct 05, 2016 **Last update:** Jul 14, 2017 Fri **Usage:**:: python square_choice1.py 12 """ # Imports import argparse def square_choice1(): """Calcuate power. Usage: python square_choice1.py 12 """ parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity") args = parser.parse_args() answer = args.square**2 if args.verbosity == 2: print("the square of {} equals {}".format(args.square, answer)) elif args.verbosity == 1: print("{}^2 == {}".format(args.square, answer)) else: print(answer) if __name__ == '__main__': square_choice1()
true
c59ee55cf2cd16a27ddf6e5175415fa8b1f812c5
HninPwint/adv_dsi_lab_2
/src/features/dates.py
493
4.21875
4
def convert_to_date(df, cols:list): ''' Convert the specified columns of the dataframe into datetime Parameters ---------- df : pd.dataframe Input dataframe cols: list List of columns to be converted Returns ------- pd.DataFrame Pandas dataframe with converted columns ''' import pandas as pd for col in cols: if col in df.columns: df[col] = pd.to_datetime(df[col]) return df
true
ec55a168a1225107af6d389a58a7e13fe90ec0fc
ABortoc/leetcode
/merge_sorted_array.py
1,384
4.34375
4
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. Example 1: Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Example 2: Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] """ # def merge(nums1, m, nums2, n): # if m == 0: # nums1.clear() # nums1.extend(nums2) # elif n == 0: # return # else: # for elem in range(n): # nums1.pop() # nums1.extend(nums2) # nums1.sort() def merge(nums1, m, nums2, n): idx_1 = m - 1 idx_2 = n - 1 idx_add = m + n - 1 while idx_2 >= 0: if idx_1 >= 0 and nums1[idx_1] > nums2[idx_2]: nums1[idx_add] = nums1[idx_1] idx_1 -= 1 else: nums1[idx_add] = nums2[idx_2] idx_2 -= 1 idx_add -= 1 # nums1 = [1, 0] # m = 1 # nums2 = [2] # n = 1 # nums1 = [1,2,3,0,0,0] # m = 3 # nums2 = [2,5,6] # n = 3 # nums1 = [-1,0,0,0,3,0,0,0,0,0,0] # m = 5 # nums2 = [-1,-1,0,0,1,2] # n = 6 # nums1 = [1] # m = 1 # nums2 = [] # n = 0 nums1 = [4,0,0,0,0,0] m = 1 nums2 = [1,2,3,5,6] n = 5 merge(nums1, m, nums2, n) print(nums1)
true
7ffcb2a981eae0727640aa195a19e6a6a05dd4ea
diamondson/TASK2
/task2.py
211
4.28125
4
names = ["Manas", "Almaz", "Meerim", "Aibek"] names2 = ["Mirbek", "Meerim", "Almaz"] names3 = [] for name in names: if name not in names2: names3.append(name) for names in names3: print(names)
false
813e200957275ccf31827b2aa905a2520c068c91
dawnshue/practice_algorithms
/LeetCode/4_sorted-array-median.py
1,199
4.125
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). """ import math def median(nums1, nums2): m = len(nums1) n = len(nums2) get_avg = ((m + n) % 2 == 0) median_pos = int(math.ceil(float(m + n)/2)) - 1 #print("median pos: {}, {}, {}".format(m+n,(m+n)/2,median_pos)) m_pos = 0 n_pos = 0 for x in range(median_pos): #print("{}, {}, {}, {}".format(m_pos, n_pos, nums1[m_pos], nums2[n_pos])) if(nums1[m_pos] < nums2[n_pos]): m_pos += 1 else: n_pos += 1 if(nums1[m_pos] < nums2[n_pos]): median = nums1[m_pos] m_pos += 1 else: median = nums2[n_pos] n_pos += 1 if get_avg: if(nums1[m_pos] < nums2[n_pos]): median = float(median + nums1[m_pos]) / 2 else: median = float(median + nums2[n_pos]) / 2 return median def log_median(nums1, nums2): m = len(nums1) n = len(nums2) nums1 = [1, 4] nums2 = [2, 4] print("{}".format(median(nums1, nums2))) """ But this does not satisfy the time constraint """
true
4385cd9555e306dd6855e536188f7362e01a80be
LYTXJY/python_full_stack
/Code/src/hellopython/第二章/test/time.py
1,593
4.25
4
import time mytime = time.time() print(mytime) print("自从1970年1月1号起始,过去了", mytime, "秒") #以小时,分钟,秒的格式进行输出 hours = None minutes = None seconds = None #测试账号 # past_time = 365 * 24 * 60 * 60 past_time = time.time() print(past_time) past_time = int(past_time) print(past_time,"秒") hours = past_time // 3600 seconds =past_time - hours * 3600 minutes = seconds // 60 seconds = seconds - minutes * 60 print("距离1970年1月1号已经过去了", hours,"小时", minutes, "分钟", seconds, "秒") #增加天与年 days = None months = None years = None days = hours // 24 hours = hours % 24 months = days // 30 days = days % 30 years = months // 12 months = months % 12 print("距离1970年1月1号已经过去了", years,"年", months,"月", days,"天", hours,"小时", minutes, "分钟", seconds, "秒") #参考答案 import time mytime = time.time() seconds = int(mytime) % 60 #分钟,小时都是60的整数倍,所以,不能被60整除的,就是留下来的秒 hours = int(mytime) // 3600 minutes = (int(mytime) - int(mytime) // 3600 * 3600)#剩余的秒数 minutes = (minutes - seconds) // 60 print("距离1970年1月1号已经过去了", hours,"小时", minutes, "分钟", seconds, "秒") #说实话,这个例子逻辑不是很清晰,只能作为参考。 ''':arg 假如时间3959秒 3959%60=59秒 3959//3600=1小时 (3959 - 1 * 3600 -59 )//60 '''
false
024d1f46ed2a94bcecbe14a69dfb095b6ce29a26
LYTXJY/python_full_stack
/Code/src/hellopython/第二章/test/test1.py
360
4.28125
4
#变量没进行赋值,不可调用 # num#NameError : name "num" is not defined # print(num) #地址问题?地址赋值 str1 = "calc" str2 = "calc" print(id(str1), id(str2)) str1 = "calc" str2 = "calc2" print(id(str1), id(str2)) #地址赋值啥意思 #在python中, 给变量赋值, 其本质是传递新的变量的地址
false
50972fed365d199763f1d4345d45a82f0f090811
Leoscience/UdemyPythonCourse
/ProgramFlowControl/FlowChallenge1.py
1,928
4.34375
4
# Create a program that takes an IP address entered at the keyboard # and prints out the number of segments it contains, and the length of each segment. # # An IP address consists of 4 numbers, separated from each other with a full stop. But # your program should just count however many are entered. # Examples of the input you may get are: # 127.0.0.1 # .198.168.0.1 # 10.0.123456.255 # 172.16 # 255 # # So your program should work even with invalid IP Addresses. We're just interested in the # number of segments and how long each one is. # # Once you have a working program, here are some more suggestions for invalid input to test: # .123.45.678.91 # 123.4567.8.9 # 123.156.289.10123456 # 10.10t.10.10 # 12.9.34.6.12.90 # '' - that is, press enter without typing anything # # This challenge is intended to practise for loops and if/else statements, so although # you could use other techniques (such as splitting the string up), that's not the # approach we're looking for here. input_prompt = ("Please enter an IP Address. An IP address consists of 4 numbers, " "separated from each other with a full stop: ") input_ip = input(input_prompt) if input_ip[-1] != '.': input_ip += '.' segment_number = 1 segment_length = 0 # i = '' # for i in input_ip: # if i == '.': # print("Segment no. {0}:\t\t{1}".format(segment_number, segment_length)) # segment_number += 1 # segment_length = 0 # else: # segment_length += 1 # # Unless the final character in the IP Address was a '.', then we haven't printed the last segment # if i != '.': # print("Segment no. {0} contains {1} characters.".format(segment_number, segment_length)) for i in input_ip: if i == '.': print("Segment no. {0}:\t\t{1}".format(segment_number, segment_length)) segment_number += 1 segment_length = 0 else: segment_length += 1
true
eff8fbb21d6686edb15df35ef6a4fa7d113af957
daewon/quiz_with_shon
/interview/problem/checkRegex.py
1,737
4.34375
4
# -*- coding: utf-8 -*- """ You have to write a function checkRegex() which takes two strings as input, one string represents a regex expression and other is an input string to match with the regex expression passed as the other parameter. Return true if it matches, else false. Regex may contain characters ‘a-z’, ‘.’ and ‘*’ where ‘.’ matches any character and ‘*’ means 0 or more occurrences of the previous character preceding it. Examples: 1) a*b matches b,ab,aab 2) a.b matches aab, abb, acb,…, azb 3) .* matches all the valid strings formed by using the lowercase letters """ def checkRegex(pattern, text): if len(pattern) == 0 and len(text) == 0: return True elif len(pattern) == 0: return False if len(pattern) == 1: p1, p2 = pattern[0], '' else: p1, p2 = pattern[0], pattern[1] if text[0] == p1: if p2 == '*': j = 0 while text[j] == p1: j += 1 return checkRegex(pattern[2:], text[j:]) else: return checkRegex(pattern[1:], text[1:]) else: if p1 == '.': if p2 == '*': if len(pattern) == 2: return True else: p3 = pattern[2] j = 0 while text[j] != p3: j += 1 return checkRegex(pattern[2:], text[j:]) else: return checkRegex(pattern[1:], text[1:]) else: if p2 == '*': return checkRegex(pattern[2:], text) else: return False def run(pattern, text): print pattern, text, checkRegex(pattern, text) run("a*b", "b") run("a*b", "ab") run("a*b", "aabb") run(".*", "aabb") run(".*bb", "bb")
true
99aaf279f9eff75d166c79f149f3c5dcb9a674ae
Rathour1/week-7
/RPSGame.py
2,578
4.25
4
from random import randint player_lives = 5 computer_lives = 5 # available weapons => store in an array choices = ["Rock", "Paper", "Scissors"] player = False # make the computer pick one item at random computer = choices[randint(0,2)] # define a win or lose function instead of the procedural way def winorlose(status): # handle win or lose based on the status we pass in print("Called the win or lose function") print("**************************************") print("You", status, "!", "Would you like to play again?") choice = input("Y / N: ") if choice == "Y" or choice == "Y": # reset the game # change global variables global player_lives global computer_lives global player global computer player_lives = 5 computer_lives = 5 player = false computer = choices[randint(0, 2)] elif choice == "N" or choice =="n": print("You chose to quit") exit() while player is False: print("===================================") print("Player Lives:", player_lives, "/5") print("AI Lives:", computer_lives, "/5") print("===================================") print("Choose your weapon!\n") player = input("Rock, Paper or Scissors?\n") # check to see if you picked the same thing if (player == computer): print("Tie! Live to shoot another day") elif player == "Rock": if computer == "Paper": # computer won player_lives -= 1 print("You lose", computer, "covers", player,"\n") else: print("You Win!", player, "smashes", computer, "\n") computer_lives -= 1 elif player == "Paper": if computer == "Scissors": player_lives -= 1 print("You Lose!", computer, "cuts", player, "\n") else: print("You win!", player, "covers", computer, "\n") computer_lives -= 1 elif player == "Scissors": if computer == "Rock": player_lives -= 1 print("You lose!", computer, "smashes", player, "\n") else: print("You win!", player, "cuts", computer, "\n") computer_lives -= 1 elif player == "Quit": exit() else: print("Not a valid option. Check again, and check your spelling!\n") # handle win or lose if player_lives is 0: winorlose("lost") elif computer_lives is 0: winorlose("won") player = False computer = choices[randint(0, 2)]
true
c097cdcec3069c4844c33a1134a25dbb40db686f
Oleksandr015/NIX_edu_solutions
/task_9/nineth_task.py
755
4.1875
4
"""создайте функцию-генератор, которая принимает на вход два числа, первое - старт, второе - end. генератор в каждом цикле должен возвращать число и увеличивать его на 1 при итерации генератор должен начать с числа start и закончить итерации на числе end т.е. при вызове for i in my_generator(1, 3): print(i) в консоли должно быть: 1 2 3""" def my_generator(start, stop): for num in range(start - 1, stop): yield num + 1 if __name__ == '__main__': for item in my_generator(1, 9): print(item)
false
c1963329962fa74879206bec8cdda1e36e016917
VladShat111/Hillel
/homework2.py
1,232
4.1875
4
Exit = None while Exit != 0: a = input("Enter first number or string: ") b = input("Enter second number or string: ") c = input("Enter operation: ") valid_operation = "+-/*//%" valid_numbers = "0123456789" if c not in valid_operation: print("Error. Invalid symbol") def calculator(x, y, z): try: if z == "+": if x and y in valid_numbers: print(int(x) + int(y)) else: print(x + y) elif z == "-": print(float(x) - float(y)) elif z == "*": print(float(x) * float(y)) elif z == "/": print(float(x) / float(y)) elif z == "//": print(float(x) // float(y)) elif z == "%": print(float(x) % float(y)) else: return False except ZeroDivisionError: print("Error: Go to school :) _zero_division_") except ValueError: print("Error. Check your entering value For string you can only use '+' operation.") calculator(a, b, c) Exit = int(input("Enter '1' to continue. Otherwise enter 0 to exit: "))
false
e0ee6ee0442e7c3fd385c478136ad2408ee536f4
jlesca/python-variables
/conversion-numbers.py
577
4.375
4
# CONVERTIR TIPO DE DATOS NUMERICOS # Podemos convertir el tipo de dato de una variable asignandole el nuevo tipo de dato. a = 1 # int b = 1.5 # float c = 1j # complex x = float(a) # El tipo de dato int pasará a ser float y = int(b) # El tipo de dato float pasará a ser int z = complex(a) # El tipo de dato int pasará a ser complex print(x) # Esto muestra 1.0 print(y) # Esto muestra 1 print(z) # Esto muestra (1+0j) print(type(x)) # Mostrará class 'float' print(type(y)) # Mostrará class 'int' print(type(z)) # Mostrará class 'complex' input() # Salgo del programa.
false
35a1840078cbb6bc626356471133b235288f1733
soniya-mi/python
/reverse-vowels-of-a-string.py
648
4.15625
4
s = "leetcode" vowel = [ "a" , "e" , "i" , "o" , "u"] new_list="" for elem in s: if elem in vowel: new_list=new_list+elem length=len(new_list) new_str="" for elem in s: if elem not in vowel: new_str=new_str+elem else: new_str=new_str+new_list[length-1] length=length-1 print(new_str) ''' Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once. Example 1: Input: s = "hello" Output: "holle" Example 2: Input: s = "leetcode" Output: "leotcede" '''
true
631faeb3b7763f04582400e73956f489dafcad9d
GoghSun/leetcode
/平衡二叉树.py
2,502
4.1875
4
```python3 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None // 自上而下的 暴力方法 class Solution: def isBalanced(self, root: TreeNode) -> bool: if(root == None): return True return abs(self.deepth(root.left) - self.deepth(root.right)) <2 \ and self.isBalanced(root.left) and self.isBalanced(root.right) def deepth(self,root:TreeNode): if root == None: return 0 else: return max(self.deepth(root.left),self.deepth(root.right)) +1 // 自下而上的 快速方法 class Solution: # Return whether or not the tree at root is balanced while also returning # the tree's height def isBalancedHelper(self, root: TreeNode) -> (bool, int): # An empty tree is balanced and has height -1 if not root: return True, -1 # Check subtrees to see if they are balanced. leftIsBalanced, leftHeight = self.isBalancedHelper(root.left) if not leftIsBalanced: return False, 0 rightIsBalanced, rightHeight = self.isBalancedHelper(root.right) if not rightIsBalanced: return False, 0 # If the subtrees are balanced, check if the current tree is balanced # using their height return (abs(leftHeight - rightHeight) < 2), 1 + max(leftHeight, rightHeight) def isBalanced(self, root: TreeNode) -> bool: return self.isBalancedHelper(root)[0] 作者:LeetCode 链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 class Solution: def isBalanced(self, root: TreeNode) -> bool: return self.depth(root) != -1 def depth(self, root): if not root: return 0 left = self.depth(root.left) if left == -1: return -1 right = self.depth(root.right) if right == -1: return -1 return max(left, right) + 1 if abs(left - right) < 2 else -1 作者:jyd 链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/balanced-binary-tree-di-gui-fang-fa-by-jin40789108/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
true
9693bf0c50328a2fb61c458944ef3a18537ee31d
NichWayoe/ave_project
/hdfsh.py
357
4.15625
4
x = 0 count = 0 user = "" # allows the code to run until the user inputs exit while user != "EXIT": user_input = input("enter number ").upper() if user_input.isnumeric(): count += 1 x += float(user_input) else: break # prints out the average after the user has entered exit print("Your average is " + str(x / count))
true
2d28aa85ccd6074333bc8f68cf2c391403d3a5bf
dail-p/budg-intensive
/day_3/data_structure/task_1/implementation.py
1,312
4.1875
4
class Tuple: """ Создает неизменяемый объект, с упорядоченной структурой, методами count и index. При создание принимается последовательность объектов """ def __init__(self, *args): self._tuple = args def __getitem__(self, key): return self._tuple[key] def __str__(self): return str(self._tuple) def count(self, value): """ Возвращает число раз появления value в объекте Args: value: Элемент число вхождения которого ищется в объекте """ count = 0 for item in self._tuple: if item == value: count += 1 return count def index(self, value): """ Возвращает индекс первого вхождения элемента в объекте Args: value: Элемент индекс которого ищется в объекте """ for count, item in enumerate(self._tuple): if item == value: return count else: raise ValueError a = Tuple(1, 2, 3) print(a)
false
771bb0e9a64fbe2ff3fef7a3335f55fe23b6b892
Anishamiah/CS3612017
/Exercise 8.py
657
4.125
4
print("Exercise 8a) \n:"); a=[1,2,3] print ("list a=", a); print("Exercise 8b) \n:"); b=a print("list b=a is",b); print("Exercise 8c) \n:"); b[1]=3 print("Exercise 8d) \n:"); print(a, "list a is changed when a value is changed in the same position in b"); print("Exercise 8e) \n:"); c=a[:] print("Exercise 8f) \n:"); c[2]=0 print("Exercise 8g) \n:"); print ("list a:",a, "No changes were made to a. \n"); def set_first_elem_to_zero(l): l[0] = 0; return l; n = [1,2,3]; print("List: " , n); print("After changing first entry to zero:" , set_first_elem_to_zero(n), "the original list can still be called, even though a new version exists.") ;
true
ff018c7fd06d6fe855ad9bdebcb2d793233ee464
jaffarbashirshk/Learning-Python
/Decision_making/divisibility.py
431
4.5
4
# Check weather a number is divisible by 2 and 3 or not number = int(input("Enter a number: ")) if number % 2 == 0: #print("Number is divisible by 2 but not by 3") if number % 3 == 0: print(f"{number} is divisible by both 2 and 3") else: print(f"{number} is divisible by 2 but not 3") else: if number % 3 == 0: print(f"{number} is divisible by 3 but not 2") else: print(f"{number} is neither divisible by 2 nor by 3")
false
8876a75fd807c6e79e724fa1301e2a0f676f8d6c
quant-om/python
/rangefun.py
1,038
4.1875
4
# Loops # for loop for val in range(1, 10): # do something print(f"value: {val}") # for loop for val in range(1, 10): # do something print(f"value: {val}") if val == 6: break for val in range(0, 20, 2): # do something print(f"value: {val}") if val == 18: break for val in range(1, 4): # do something print(f"value: {val}") # while loop print("Demonstrating while loop.") val = 0 while val < 10: print(f"val = {val}") val = val + 1 mlist1 = [1, 2, 3, "quantom", 'dictionary', 5, 6.9] mtup1 = (1, 2, 3, "quantom", 'dictionary', 5, 6.9) print(f"mlist1 is {mlist1}") for val in mlist1: print(f"list val = {val}, type={type(val)}") if val == 5: print("FIVE.....") for val in mtup1: print(f"Tuple val = {val}") print("End of program.") for val in mlist1: if isinstance(val, int): print(f"val+100 = {val+100}") # Write a program to print tables tableno = 1524567 for val in range(1, 11): print(f"{tableno} X {val} = {tableno * val}")
false
a0f501f3c60feb7d7c2afe5e792d5a6701b03622
tanaostaf/python
/lab17_2.py
825
4.21875
4
from math import pow import timeit print("power by 3: ") print("shift power : " + str(timeit.timeit('10 << 3',number = 1000000))) print("power by operator: " + str(timeit.timeit('10 ** 3',number = 1000000))) print("math_pow : " + str(timeit.timeit('pow(10.0, 3)',number = 1000000))) def reverse(s : str): return "".join(reversed(s)) print("---------------------------------------") print("reverse list of strings: ") print("by loop : " + str(timeit.timeit('for _ in data: _ = "".join(reversed(_))', "data = ['math', 'test', 'pow', 'shift']", number = 100000 ))) print("by map() : " + str(timeit.timeit('map(reverse, data)', "data = ['math', 'test', 'pow', 'shift']", number = 100000, globals = {'reverse' : globals().get('reverse')} ))) input ('Press ENTER to exit')
false
55870b7a3d38a8fbfbe62ae171988cc456e02164
NickyGuants/Python-Practice-Projects
/startingOutWithPython/Chapter3/shippingCharges.py
514
4.46875
4
'''A program that asks the user to enter he weight of a package and displays the shipping charges''' weight_of_package=int(input("Enter the weight of package in pounds: ")) if weight_of_package<=2: shipping_charges=weight_of_package*1.5 elif weight_of_package<=6: shipping_charges=weight_of_package*3.0 elif weight_of_package<=10: shipping_charges=weight_of_package*4.0 else: shipping_charges=weight_of_package*4.75 print("Your shipping charges are: ${charges}".format(charges=shipping_charges))
true
a071037d619d8e44e4698920b77ed9bba2b692d8
dariadiatlova/plot_templates
/src/plotly/line_chart.py
744
4.4375
4
import pandas as pd import plotly.express as px import numpy as np def plot_line_chart(df: pd.DataFrame, title: str, y: str = 'y', x: str = 'x',): """ Create dataframe with at least 2 columns for x and y axis. Pass df to the function with the column names corresponded to the x and y axis :param df: pandas dataframe with data for x and y axis :param title: your plot title :param y: the name of df column with data to plot over y axis :param x: the name of df column with data to plot over x axis :return: None """ px.line(df, x=x, y=y, title=title).show() # DF example df = pd.DataFrame({'sin(x)': [np.sin(i) for i in range(100)], 'x': range(100)}) plot_line_chart(df, y="sin(x)", title='Sin(x)')
true
25a8af3622af43038325964f9105506ec7dd537b
oleksiishkoda/PythonCore
/HomeW/04/04.3.py
227
4.125
4
# 3. Вивести на екран таблицю множення (від 1 до 9). x = 1 while x < 10: for y in range(1,10): print("%2d * %d = %2d"%(y, x, y * x),end = " ") x += 1 print("\n")
false
cbf24cc06ac0f4e5dcd7e6c0c89bc1cd7499fa0c
barvilenski/daily-kata
/Python/rgb_to_hex_conversion.py
700
4.4375
4
""" Name: RGB To Hex Conversion Level: 5kyu Instructions: The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned. The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value. The following are examples of expected output values: rgb(255, 255, 255) # returns FFFFFF rgb(255, 255, 300) # returns FFFFFF rgb(0,0,0) # returns 000000 rgb(148, 0, 211) # returns 9400D3 """ def rgb(r, g, b): r = max(0, min(r, 255)) g = max(0, min(g, 255)) b = max(0, min(b, 255)) return "{:02X}{:02X}{:02X}".format(r, g, b)
true
c82095442442f313ebc04e0326103267fd79c1e3
barvilenski/daily-kata
/Python/product_of_consecutive_fib_numbers.py
1,574
4.25
4
""" Name: Product of consecutive Fib numbers Level: 5kyu Instructions: The Fibonacci numbers are the numbers in the following integer sequence (Fn): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... such as F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying F(n) * F(n+1) = prod. Your function productFib takes an integer (prod) and returns an array: [F(n), F(n+1), true], if F(n) * F(n+1) = prod. If you don't find two consecutive F(m) verifying F(m) * F(m+1) = prod you will return [F(m), F(m+1), false], F(m) being the smallest one such as F(m) * F(m+1) > prod. Examples productFib(714) # should return [21, 34, true], # since F(8) = 21, F(9) = 34 and 714 = 21 * 34 productFib(800) # should return [34, 55, false], # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55 Notes: Not useful here but we can tell how to choose the number n up to which to go: we can use the "golden ratio" phi which is (1 + sqrt(5))/2 knowing that F(n) is asymptotic to: phi^n / sqrt(5). That gives a possible upper bound to n. You can see examples in "Example test". References http://en.wikipedia.org/wiki/Fibonacci_number http://oeis.org/A000045 """ def productFib(prod): fib1, fib2 = 0, 1 cur_prod = fib1 * fib2 while cur_prod <= prod: if cur_prod == prod: return [fib1, fib2, True] fib2 = fib1 + fib2 fib1 = fib2 - fib1 cur_prod = fib1 * fib2 return [fib1, fib2, False]
true
00d07c24b3b474ec852aeaac49a284709399ed77
lavish-jain/Small-Projects
/Pythagorean Triples Checker/main.py
625
4.34375
4
from pythagorean_triples import Triples def main(): while 1: side_a = input("Enter the length of first side: ") side_b = input("Enter the length of second side: ") side_c = input("Enter the length of third side: ") triplets = Triples(side_a, side_b, side_c) if triplets.checkTriples(): print("The sides are Pythagorean Triplets") else: print("The sides are not Pythagorean Triplets") choice = input("Do you want to continue? (Y/N)") if choice == 'y' or choice == 'Y': continue else: break main()
true
686c922ef8de20b6c14a93961f4539cb62bd6ea5
mollymahar/HW09
/HW09_ex12_03.py
2,055
4.53125
5
#!/usr/bin/env python # Exercise 3 # (1) Write a function called most_frequent that takes a string and prints the # chars in decreasing order of frequency. (compare and print in lowercase) # Ex. >>> most_frequent("aaAbcc") # a # c # b ############################################################################### # Imports import re # Body def most_frequent(s): """This function takes a string and returns single characters on separate lines in order of decreasing frequency in the original string.""" frequency = {} # eliminate spaces and punctuation new_s = re.split('\W+', s) new_s = ''.join(new_s) for item in new_s.lower(): # set everything to lowercase # set frequency to zero as default and add one for each appearance frequency[item] = frequency.setdefault(item, 0) + 1 # invert it so we can sort by frequency freq_by_freq = [(y,x) for (x,y) in frequency.items()] # then actually sort by frequency decreasing = sorted(freq_by_freq, reverse=True) for each in decreasing: print each[1] ############################################################################### def main(): # DO NOT CHANGE BELOW print("Example 1:") most_frequent("abcdefghijklmnopqrstuvwxyz") print("\nExample 2:") most_frequent("The quick brown fox jumps over the lazy dog") print("\nExample 3:") most_frequent("Lorem ipsum dolor sit amet, consectetur adipiscing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna " "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " "ullamco laboris nisi ut aliquip ex ea commodo consequat. " "uis aute irure dolor in reprehenderit in voluptate velit " "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia " "deserunt mollit anim id est laborum.") print("\nExample 4:") most_frequent("Squdgy fez, blank jimp crwth vox!") if __name__ == '__main__': main()
true
c44005ade856a47013b13938d237e36345f8553d
rebornwwp/design-pattern-python
/Creational-patterns/builder.py
2,129
4.40625
4
""" Separate the construction of a complex object from its representation so that the same construction process can create different representations. """ import abc class Director(object): """ Construct an object using the Builder interface. """ def __init__(self): self._builder = None def construct(self, builder): self._builder = builder self._builder._build_part_a() self._builder._build_part_b() self._builder._build_part_c() class Builder(metaclass=abc.ABCMeta): """ Specify an abstract interface for creating parts of a Product object. """ def __init__(self): self.product = Product() @abc.abstractmethod def _build_part_a(self): pass @abc.abstractmethod def _build_part_b(self): pass @abc.abstractmethod def _build_part_c(self): pass class ConcreteBuilder(Builder): """ Construct and assemble parts of the product by implementing the Builder interface. Define and keep track of the representation it creates. Provide an interface for retrieving the product. """ def _build_part_a(self, a=1): self.product.a = a print("build part a") return self def _build_part_b(self, b=2): self.product.b = b print("build part b") return self def _build_part_c(self, c=3): self.product.c = c print("build part c") return self def get_product(self): return self.product class Product(object): """ Represent the complex object under construction. """ pass def main(): concrete_builder = ConcreteBuilder() director = Director() director.construct(concrete_builder) product = concrete_builder.product print(product.a) print(product.b) print(product.c) print("="*40) # 链式构建处理 concrete_builder._build_part_a(10)._build_part_b(11)._build_part_c(12) product = concrete_builder.get_product() print(product.a) print(product.b) print(product.c) if __name__ == "__main__": main()
true
f874b0b817ba73376e949e5afce9ed043d0ae1f3
first-thangs-first/CSE6040X_Computing_for_Data_Analysis
/work/module_0/python_essentials/data_transformation/drill.py
833
4.25
4
names = ["Peter", "Lois", "Meg", "Chris", "Stewie", "Brian"] ages = [41, 40, 16, 17, 1, 18] """ Assume that the ages in ages correpond to the names in names by index. Write a Python module which: Assigns to the variable family a list of tuples in which the first element of each tuple is a name and the second element is the associated age. Assigns to the variable name2age a dictionary mapping names to ages. Assigns to the variable sorted_family the elements of family sorted by age. Assigns to the variable adults the members of family with an age of 18 or greater. """ family = [(names[index], ages[index]) for index in range(len(names))] name2age = {names[index]: ages[index] for index in range(len(names))} sorted_family = sorted(family, key=lambda member: member[1]) adults = [member for member in family if member[1] >= 18]
true
d736f6ddcb5c75fb526652ce4e74d5113018b6fd
felipe-gdr/project-euler
/pe019.py
1,608
4.1875
4
''' Counting Sundays =========================== You are given the following information, but you may prefer to do some research for yourself. - 1 Jan 1900 was a Monday. - Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' from problem import Problem class Pe019(Problem): def execute(self): day, date, month, year, count = [1, 1, 0, 1900, 0] while year * 10000 + month * 100 + date <= 20001231: days_in_month = self.daysInMonth(year, month) year = year + ((month / 11 + date / days_in_month) / 2) month = (month + (date / days_in_month)) % 12 date = (date % days_in_month) + 1 day = (day + 1) % 7 if year >= 1901 and date == 1 and day == 0: count += 1 print year, month, date, day return count def daysInMonth(self, year, month): if month == 1: if year % 100 == 0: if year % 400 == 0: return 29 else: return 28 elif year % 4 == 0: return 29 else: return 28 elif month in [8, 3, 5, 10]: return 30 else: return 31 Pe019().main()
true
a408cdf1d5becc62c8db174e84c0f1a0b847c50d
Faleirol/Yr11-assessment-
/num_character function.py
664
4.15625
4
num_character_list = ["1 character", "A duo", "3 character", "A group (4+)"] print(num_character_list) num_answer = ["1 character", "one character", "One Character", "One character", " ONE CHARACTER", "1 CHARACTER", "A duo", "a duo", "A DUO", "a Duo", "duo", "Duo", "DUO", "3 character", "3 Character", "3 CHARACTER", "Three character", "three character", "Three Character", "three Character", "THREE CHARACTER", "A group", "a group", "A Group", "A GROUP"] num_character_fun = "" while num_character_fun not in num_answer: num_character_fun = 'z' num_character_fun = input("Pick an amount of main character(s)") print("In loop") print("Out of loop")
false
d354aa5ddd6d64394941a53e5681cda4e0a17619
tollo/ICPP
/remove_duplicates.py
423
4.1875
4
# Introduction to Computation and Programming using Python # Remove duplicates from two strings def removeDups(L1, L2): """Assumes that L1 and L2 are lists. Removes any element from L1 that also occurs in L2""" for e1 in L1[:]: # [:] makes a copy of the list for loop before mutating if e1 in L2: L1.remove(e1) L1 = [1, 2, 3, 4] L2 = [1, 2, 5, 6] removeDups(L1, L2) print('L1 = ', L1)
true
d1785cf34d0dca9efcfb7b5610d75af22b442d10
JitenKumar/PythonPracticeStepByStep
/Advanced Python Modules/Collection Module/Defaultdict/defaultdict.py
713
4.1875
4
''' defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory) as a default data type for the dictionary. using default dict is faster than using the same as dict.set_default methods ''' from collections import defaultdict # normal dictionary d = {'k1':1} print(d['k1']) # will print 1 # print(d['k2']) will give an KeyError # using the default dict dct = defaultdict(object) # takes an object print(dct['k1']) # will give location and type as object for it in dct: print(it) # will print the key dict2 = defaultdict(lambda: 1) print(dict2['4']) # will print 1 dict2['k2'] = 4 print(dict2['k2']) # will print 4
true
13fe8009c60b8b4c46fe96c60accbce3189111dc
JitenKumar/PythonPracticeStepByStep
/Advanced Python Modules/Collection Module/NamedTuple/namedtuple.py
635
4.375
4
# normal tuple from collections import namedtuple tp = (1,2,34,5,6) print(tp[1]) ''' Each kind of namedtuple is represented by its own class, created by using the namedtuple() factory function. The arguments are the name of the new class and a string containing the names of the elements. You can basically think of namedtuples as a very quick way of creating a new object/class type with some attribute fields. ''' t = namedtuple('Human', 'name age gender maritalstatus') jitender = t('jitender', 22, 'male', 'Single') print(jitender) print(jitender.name) print(jitender.maritalstatus) print(jitender.age) print(jitender.gender)
true
8d4a305ca900810494e96a06d38f4d47e53bf941
mitchypi/ITP115
/ITP115_A1_Pi_Mitch.py
2,795
4.4375
4
# Mitch Pi, mpi@usc.edu # ITP 115, Spring 2020 # Assignment 1 # Description: #This program asks for user input and #creates a a mad libs style story from the user's inputs #collects user inputs for story, only checks if verb1 ends with an "ing" verb1 = input("Enter a verb that ends with ing: ") #checks if the input for verb1 ends with ing while not verb1.endswith ("ing"): verb1 = input("Please enter a verb that ends with ing: ") friend1 = input("Enter the name of a friend: ") adj1 = input ("Enter an adjective to describe your friend: ") appreciate1 = input ("Enter a trait you appreciate about your friend: ") school1 = input ("Enter the school your friend goes to: ") #Uses try except to check if user input can be converted into float, takes user input if True time = (input ("Enter a number that contains a decimal: ")) timeIsFloat = False while timeIsFloat is False: try: float(time) timeIsFloat = True except ValueError: time = (input("Please Enter a number that contains a decimal: ")) #Uses try except to check if user input can be converted into int, takes user input if True int1 = input ("Now enter a integer: ") isInt1 = False while isInt1 is False: try: int(int1) isInt1 = True except ValueError: int1 = input("Please enter a integer: ") int2 = input ("And another integer: ") isInt2 = False while isInt2 is False: try: int(int2) isInt2 = True except ValueError: int2 = input("Please enter a integer: ") int3 = input ("And one last integer: ") isInt3 = False while isInt3 is False: try: int(int3) isInt3 = True except ValueError: int3 = input("Please enter a integer: ") #finally converts the inputs for numbers into actual numbers in case I need to do math timeReal = float(time) int1Real = int(int1) int2Real = int(int2) int3Real = int(int3) #math equation, division sign returns float value so I'm okay with using integers in the equation mathnum = (int1Real+int2Real)/2+3 #converts the inputs from the floats and numbers back into strings just in case storynum2 = str(timeReal) storynum = str(mathnum) storynum3 = str(int3Real) #prints the story using user inputs print("Today you are "+"\'"+verb1+"\'"" with your very " "\'"+adj1+"\'"" friend "+"\'"+friend1+"\'.") print( "You appreciate how they are "+"\'"+appreciate1+"\'.") print("The two of you have been friends for " +"\'"+storynum+"\'"+" years and you have been " +"\'"+verb1+"\'"+" for "+"\'"+storynum2+"\'"+" hours." ) print("\'"+friend1+"\'"+" has been a student at "+"\'"+ school1+"\'"+" for "+"\'"+storynum3+"\'"+" year(s).") print("You two had fun spending time with each other. The end.")
true
7ad2ad87994d551b1a070295de4c15d2d2c8a948
jaydenwhyte/Learn-Python-The-Hard-Way
/ex20.py
1,489
4.3125
4
# import argv from sys from sys import argv # get arguments script, input_file = argv # define print_all function, which takes 1 argument (f) def print_all(f): # print the contents of f print f.read() # define the rewind function, which takes 1 argument (f) def rewind(f): # move the file pointer back to the beginning of file f f.seek(0) # define the print_a_line function, which takes 2 arguments (line_count, f) def print_a_line(line_count, f): # print line_count, then a line from file f print line_count, f.readline() # set current_file variable to a file pointer to input_file current_file = open(input_file) # print string print "First let's print the whole file:\n" # call print_all function with current_file as an argument print_all(current_file) # print string print "Now let's rewind, kind of like a tape." # call rewind function with current_file as an argument rewind(current_file) # print string print "Let's print three lines:" # set current_line to 1 current_line = 1 # call print_a_line function with current_line and current_file as arguments print_a_line(current_line, current_file) # set current line to itself + 1 current_line += 1 # call print_a_line function with current_line and current_file as arguments print_a_line(current_line, current_file) # set current line to itself + 1 current_line += 1 # call print_a_line function with current_line and current_file as arguments print_a_line(current_line, current_file)
true
2bea67faf26f9430f8632e4cbb49ea2c79ec88fd
erfan-khalaji/countDistinctSongPlayed
/mainScript.py
1,901
4.25
4
''' How many people played how many times. This function takes a dataset and efficiently produces an output dataset which gives info about how many clients played how many distinct songs. following steps are followed. 1- Read the input data 2- Select only the data related to the specified date (August 10) 3- For each client determine how many unique songs are played 4- Count how many clients played same number of distinct songs 5- Create output data ''' def distinct_song_client(mainData): #Selecting the data of August 10 dataAugust = mainData[mainData['PLAY_TS'].str.contains('10/08/')] client_distinct = list() #Making a list of clients with unique values client_IDs_unique = dataAugust.CLIENT_ID.unique() for c in client_IDs_unique: #Selecting the data for each particular client data_clientBased = dataAugust[dataAugust['CLIENT_ID']==c] #Selecting all the unique songs that client played and add the total sum to the list client_distinct.append(data_clientBased['SONG_ID'].nunique()) #DELETING all data related to the client to reduce the amount of iterations in the next round dataAugust = dataAugust[dataAugust['CLIENT_ID'] != c] #Sorting the number of times distinct songs played by all clients client_distinct.sort() #Using collection library to produce the frequency of each distinct play based on the occurance of the number counter=collections.Counter(client_distinct) #Sorting the produced dictionary counter = {k: v for k, v in sorted(counter.items(), key=lambda item: item[1])} #Turning the dictionary to dataframe output = pd.DataFrame(counter.items()) #Changing the name of columns to be meaningful output.columns = ['DISTINCT_PLAY_COUNT', 'CLIENT_COUNT'] #returning a pandas dataframe which involves the desired output return output
true
c91537c2eec27ea6b4277df20e9d6ed371abd537
fabixneytor/Utp
/ciclo 1/Ejercicios Python/holamundo.py
2,800
4.34375
4
#esto es un comentario de una linea en python ''' esto es una impresion en consola del hola Mundo ''' print('-------------') print('Hola Mundo') print('-------------') #salto de linea \n ''' Hola Mundo con salto de linea \n ''' print("Hola\nMundo") #primer ejercicio print("el conocimiento\nes el principio del todo") print("---------------------\n--piensa diferente--\n---------------------") #tabulador \t print("usuario:\tfabixneytor@hotmail.com") #ejericio 2 print("mostrar en consola:") print("user:\tpepito_perez") print("pass:\t12345") print("rol:\tadmin") #ejercicio 3 print("Bienvenido\nHora de ingreso:\t14:00") #ejercicio 4 print("------------------\n--Bienvenido\t:)\n--A la disrupcion\n--Del conocimiento\n------------------") #como crear una variable a = 8 b = a c = a+b print(c) print("primer valor a") a = 8 print(a) print("segundo valor a") a = 10 print(a) print("tercer valor a") a = 3.344 print(a) #ejercicio 5 lado1 = 5 lado2 = 5 lado3 = 5 lado4 = 5 a = b = c = d = 5 perimetro = lado1+lado2+lado3+lado4 perimetro = a+b+c+d print(perimetro) #5, 10, 15 suma lado1, lado2, lado3 = 5.5,10,15 perimetro2 = lado1 + lado2 + lado3 print(perimetro2) # tipo de datos o variable f: int = 8 g: float = 10.5 print(type(f)) print(type(g)) #castear una variable h: int = int(g) print(h) #castear variables con sus respectivos valores number = 10 mensaje1 = "el valor de numer" mensaje2 = " Es: "+str(number) mensaje_final = mensaje1 + mensaje2 #muestra en pantalla print(mensaje_final) #concatenar palabras y numeros perimetro = 30 mensaje = str(perimetro)+"cm" print(mensaje) #ejercicio 6 ''' mes = 30 semana = 7 semana_por_mes = aqui va el resultado numero de semanas en el mes: ---- ''' mes = 30 semana = 7 semana_por_mes = int(mes/semana) print("numero de semanas en el mes: "+str(semana_por_mes)) #ejercicio 7 ''' promedio ventas: dia1 = 50000 dia2 = 120000 dia3 = 80000 promedio ventas = ''' dia1 = 50000 dia2 = 120000 dia3 = 80000 promedio_ventas1 = (dia1+dia2+dia3) /3 print("El primer promedio de ventas es: "+str(promedio_ventas1)) #segundo promedio de ventas promedio_ventas2 = 30000 suma = promedio_ventas2 + int(promedio_ventas1) print("suma:", suma) palabra, valor = "suma", suma print(palabra, valor, "palabra") #multiplicacion y elevado multiplicacion = 5 * 2 elevado = 5 ** 2 print(multiplicacion) print(elevado) #funcion def mi_primera_funcion(): suma1 = (5+10) return suma1 print("el suma1 es:"+str(mi_primera_funcion()) ) print("el promedio es:"+str(mi_primera_funcion()) ) print("numero de participantes:"+str(mi_primera_funcion()) )
false
ffca14493ba2e1473391908730274d921aa47e77
rakvihaan/GCI2018-TaskCCE
/Task by CCExtractor.py
306
4.125
4
for i in range(1,11): print("GCI is great!!") print("Hey there, what is your name?") name=input() print("Hello {}, please to meet you!".format(name)) def reversedname(name): return"".join(reversed(name)) print("Did you know that your name spelled backwards is '{}'!!".format(reversedname(name)))
true
bdf42fef1872e84dfdc4ce75b66bf482d9324316
boojoom/Password_generator
/password_generator.py
1,110
4.15625
4
#password generator import random import string import sys print("Password generetor - the program will generate random\n8 characters password of different stregth.\n") def passw(): sec = str(input("How strong dou you want your password to be? \nChoose between weak, medium or strong: ")).lower() if sec == 'weak': letters = string.ascii_letters passw = ''.join(random.choice(letters) for i in range(8)) print("Your password is:", passw) elif sec == 'medium': letters = string.ascii_letters numbers = string.digits passw = ''.join(random.choice(letters + numbers) for i in range(8)) print("Your password is:", passw) elif sec == 'strong': letters = string.ascii_letters numbers = string.digits punct = string.punctuation passw = ''.join(random.choice(letters + numbers + punct) for i in range(8)) print("Your password is:", passw) passw() exit = str(input("Do you want to generate another password[y/n]?: ")).lower() while exit == 'y': passw() exit = str(input("Do you want to generate another password[y/n]?: ")).lower() if exit == 'n': print("Exiting program") sys.exit()
true
bbc181343ce8f63377f863b012fd499714589230
PDXChloe/PDXcodeguild
/Python/lab19_palindrome_anagram.py
298
4.375
4
# # # reverse = "abcdefg" # print(reverse[::-1]) # # word = input("Enter a word to check if it is a palindrome...") def check_palindrome(word): if word == word[::-1]: print(word + ", is palindrome") else: print(word + ", is not palindrome") check_palindrome("racecar")
true
93c08a30efc77a95922c4b7add674840b6a54e34
PDXChloe/PDXcodeguild
/Python/lab17-numbertophrase2.py
1,495
4.125
4
#Version 2 Hundreds final, does both two digit and three digit. ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] teens = ["ten","eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] hundreds = ["one-hundred", "two-hundred", "three-hundred", "four-hundred", "five-hundred", "six-hundred", "seven-hundred", "eight-hundred", "nine-hundred"] user_num = int(input("Give me an one, two or three digit number...>>>\n")) #get user input, put in variable. def num2phrase(num): tens_digit = num // 10 #finding the tens digit ones_digit = num % 10 #finding the ones digit if num < 10: #uses the list return(ones[num]) elif num < 20 and num > 10: #uses the list return(teens[ones_digit]) elif ones_digit == 0: #uses the list return(tens[tens_digit-2]) else: #uses the dictionary return(tens[tens_digit-2] + "-" + ones[ones_digit]) if user_num > 99: h_digit = (user_num // 10) // 10 # or user_num//100 last_two = user_num - (h_digit * 100) #just need the last two-digit to feed back into the num2phrase function. print(hundreds[h_digit - 1] + "-" + num2phrase(last_two)) else: print(num2phrase(user_num)) # tens_of_hun = (user_num // 10) - (h_digit * 10) # ones_of_hun = user_num % 10
true
5d1040f0910cdb6a3c26d6358e535f7181b8366d
PDXChloe/PDXcodeguild
/Python/lab14-problem1.py
725
4.125
4
# ''' # Return the number of letter occorrances in a string. # # >>>count_letter("i", "Antidisestablishmentterianism") # # >>>count_letter("p", "Pneumonoultramicroscopicsilicovolcanoconiosis") # ''' # def count_letter(char, word): # for letter in word: def count_letter(char, word): letter_count = 0 for letter in word: if letter == char: letter_count += 1 print("The letter " + char + " occurs " + str(letter_count) + " times.") char = "q" word = "asdfkjhaewiufhilusdbfviuqqqqhsfuyiahweku" count_letter(char, word) # # def count_letter(char_to_find, text): # count = 0 # for char in text: # if char == char_to_find # count += 1 # return count #
false
92a6eaa0f09ebd312e5abbd66438b5ddf4cd51f9
PDXChloe/PDXcodeguild
/Python/lab31_atm.py
2,153
4.15625
4
class AtmAccount: def __init__(self, balance=0, interest_rate=0.001): self.balance = balance #set this variable to itself and then set the def__init__ variable to default amount. self.interest_rate = interest_rate self.transactions = [] #print("account balance: $" + str(balance)) def check_balance(self): return self.balance #used as checkpoint for def deposit(self, amount): self.balance += amount self.transactions.append(f'user deposited: ${amount}') def check_withdraw(self, amount): return self.balance - amount >= 0 def withdraw(self, amount): self.balance -= amount self.transactions.append(f'user withdraw: ${amount}') def calc_interest(self): amount_interest = float(self.balance) * self.interest_rate return amount_interest def print_transactions(self): for transaction in self.transactions: print(transaction) amount = input("Enter the amount of money to make a new account") new_account = AtmAccount(int(amount), 0.001) while True: command = input("What would you like to do (deposit (d), withdraw (w), check balance (cb), history (h) or quit (q)?").lower() if command == 'quit' or command == 'q': print("Goodbye") break if command == 'deposit' or command == 'd': amount = input("How much would you like to deposit?") new_account.deposit(int(amount)) print(f'account balance: ${new_account.balance}.') if command == 'withdraw' or command == 'w': amount = input('How much would you like to withdraw?') if new_account.check_withdraw(int(amount)) == False: print(f'${amount} is over your current balance of: ${new_account.balance}.') else: new_account.withdraw(int(amount)) print(f'You have withdrawn: ${amount}.\nCurrent balance: ${new_account.check_balance()}.') if command == 'check balance' or command == 'cb': print(f'Balance: {new_account.check_balance()}') if command == 'history' or command == 'h': new_account.print_transactions()
true
6cc62590e94ba72b90ac44764cc74798a78dd4be
PDXChloe/PDXcodeguild
/Python/lab11-avenumbers2.py
412
4.125
4
#Version 2 nums = [] print("Welcome to Average Numbers") while True: user_input = input("Enter a number or 'done'.") if user_input == "done": break nums.append(user_input) print(nums) total = 0 for num in nums: total += int(num) average = total/len(nums) print(str(nums) + "\nThis is your list of numbers.") print(str(average) + "\nThis is the average of your list of numbers.")
true
666e069b7dc7482c3c0e8f356485df4015632073
jamiegill/fizz_buzz
/1.1.6_fizz_buzz.py
529
4.34375
4
# Fizz Buzz application # Every number divisible by 3 should be labeled 'Fizz' # Every number divisible by 5 should be labeled 'Buzz' # Every number divisible by 3 AND 5 should be labeled 'Fizz Buzz' n = 100 counter = 0 while counter < n: counter += 1 fizz = counter / 3 buzz = counter / 5 fizz_buzz = counter / 3 /5 if fizz_buzz == int(fizz_buzz): print('fizz_buzz') elif fizz == int(fizz): print('fizz') elif buzz == int(buzz): print('buzz') else: print(counter)
false
1fd0670f0708fde344dabf34adc9a3d026ea3293
ddc0021/InstructorGradingProgram
/GradingSystem/Semester.py
497
4.15625
4
class Semester: #Initializes fields title = "" #Initializes a new Semester object def __init__(self, title): #A Semester has a title and list of courses self.title = title global course_list course_list = [] #Creates a new Course object def create_courses(self, title): from Course import Course temp = Course(title) #Adds this new Course to the parent Semester's list of courses course_list.append(temp)
true
9e5892aaf551faab22f14d20e91599f6bf52bfe9
hoang7276/PythonProgrammingCourseFirstYear
/S07 - Homework Solution/S07 Students.py
334
4.25
4
def main(): print("This program will print the name of your student after inputing it") StudentName = input("Enter the name of a student (press <Enter> to quit)>> ") while StudentName != "": print(StudentName) StudentName = input("Enter the name of a student (press <Enter> to quit)>> ") main()
true
78f46de0406be8ba015da8977879e00d073db86e
hoang7276/PythonProgrammingCourseFirstYear
/S07 - Homework Solution/S07 AverageNumbersSentinel.py
1,047
4.375
4
# This program will calculate the average of numbers entered by the user # The amount of numbers to average will not be decided beforehand def main(): print("This program will calculate the average of all the numbers you enter") SumOfNumbers = 0.0 # Initialized as floats since I will ask for floats AvgOfNumbers = 0 # Accumulator to count amount of numbers to average AvgSentinel = input("Enter a number (press <Enter> to quit)>> ") # Sentinel/data identifier for the loop while AvgSentinel != "": x = float(AvgSentinel) # Sentinel checked, now convert to data SumOfNumbers = SumOfNumbers + x AvgOfNumbers = AvgOfNumbers + 1 AvgSentinel = input("Enter a number (press <Enter> to quit)>> ") # Get sentinel again to iterate print("\nThe average of numbers entered is", SumOfNumbers/AvgOfNumbers) main()
true
bb50099bd4722a5a08b135bea886e7e1da57cc52
hoang7276/PythonProgrammingCourseFirstYear
/S03 - Homework solution/Celsius2Fahrenheitwithloop.py
430
4.21875
4
#Celsius2Fahrenheit.py # A program to convert Celsius temps to Fahrenheit def main(): print("this program will ask celsius degrees and convert them to fahrenheit 5 times") for i in range(5): celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = (9/5) * celsius + 32 print("The temperature is ",fahrenheit," degrees Fahrenheit. Celsius degrees were ", celsius) main()
true
fcfe20152e95c3458d52a2a6a02322f7317d8a95
xjy520/AID2006
/123/month1/day12/exercise06.py
1,863
4.1875
4
""" 转换字符串 __str__ ---> 对人友好 __repr__ ---> 对机器友好 """ # class Person: # def __init__(self,name,age): # self.name = name # self.age = age # 对象 -> 字符串: 没有语法限制 # def __str__(self): # return "我叫%s,今年%d"%(self.name,self.age) #必须是return # def __repr__(self): # return "Person('%s',%d)"%(self.name,self.age) # # # p01 = Person("悟空",24) # #打印自定义对象 # print(p01) #本质: # message = p01.__str__()#自定义对象 ---> 字符串 # print(message) #价值:将字符串作为python代码执行 # message = p01.__repr__() # "Person('悟空',25)" # p02 = eval(message) # 执行("Person('悟空',25)") # p01.name = "大圣" #更改p01 # print(p02) #不会影响p02 # # class Phone: # def __init__(self,brand,color,price): # self.brand = brand # self.color = color # self.price = price # # def __str__(self): # return "%s手机%s颜色的价格是%s"%(self.brand,self.color,self.price) # # class Employees: # def __init__(self,cid,did,name,money): # self.cid = cid # self.did = did # self.name = name # self.money = money # # def __str__(self): # return "%s的编号是%s,部门编号是%s,月薪是%s"%(self.name,self.cid,self.did,self.money) # # p01 = Phone("华为1","蓝",5999) # print(p01) # e01 = Employees(1001,9002,"师傅",60000) # print(e01) class Phone: def __init__(self,brand,color,price): self.brand = brand self.color = color self.price = price def __repr__(self): return "Phone('%s','%s',%d)"%(self.brand,self.color,self.price) p01 = Phone("华为","白色",10000) print(p01) p02 = eval(p01.__repr__()) p01.brand = "苹果" print(p02) print(p01)
false
8501b2eb43ddb5109af4af0280c515fd38e3eba1
xjy520/AID2006
/123/month1/day11/exercise02.py
2,590
4.25
4
""" 三大特征 1.封装 定义:将一些基本数据类型复合程一个自定义类型 优势:将数据与对数据的操作相关联 代码可读性更高 """ """ 行为封装 创建类型时,应该保障数据在有效范围内 对外提供必要功能(如:读取年龄,修改年龄),隐藏实现细节(保护年龄范围) 1.方法内部操作私有变量(私有变量是真是储存的数据) 2.@property 在创建属性对象并且将下面的方法作为参数 再将对象的地址交给下面的方法名称关联 属性名 = property(读取方法) 3.@age.setter 属性名.setter(写入方法) """ # 需求:保护数据有效范围 22 - 30 class Wife: def __init__(self, name, age): self.name = name self.age = age @property #创建属性对象 property(读取方法) def age(self): return self._age #会执行age(self,value)函数 @age.setter def age(self, value): if 22 < value < 30: self._age = value else: raise Exception("我不要") w01 = Wife("双儿", 25) """ 练习: 创建敌人类 创建实例变量并保证数据在有效范围内 姓名,血量,攻击 0-100 1-30 """ class Enemy: def __init__(self, name, hp, damage): self.name = name self.hp = hp self.damage = damage @property def hp(self): return self.__hp @hp.setter def hp(self, value): if 0 <= value <= 100: self.__hp = value else: raise Exception("血量错误") @property def damage(self): return self.__damage @damage.setter def damage(self, value): if 0 <= value <= 30: self.__damage = value else: raise Exception("数据错误") e01 = Enemy("灭霸", 100, 30) print(e01.name) print(e01.hp) print(e01.damage) """ 私有成员 : 只能在类中访问,类外不能访问 做法 : 以双下划线命名 本质 : 看上去成员名称为__data,实际_MyClass__data 双下划线家名称 单下划线加类名加双下划线加名称 """ # class MyClass: # def __init__(self): # self.__data = 10 # # def __func01(self): # print("func01") # # # m01 = MyClass() # # print(m01.__data) #不能在类外访问私有变量 # #不建议 # m01._MyClass__data = 20 # print(m01._MyClass__data) # print(m01.__dict__)
false
6d5d136b855a8756662916c4f9d26fc8550ade79
xjy520/AID2006
/123/month1/day11/exercise05.py
1,052
4.65625
5
""" 分而治之 将一个大的需求分解为许多类 每个类处理一个独立的功能 变则疏之 变化的地方进行分装 """ """ 封装设计思想 分而治之 变则疏之 """ # 需求:老张开车去东北 # 变化:老张 老李 老王 (数据不同)---> 使用对象区分 # 车 飞机 轮船 (行为不同)---> 使用类区分 # 写法1:直接创建对象调用 # 语义 :老张每次使用新车去某地 # 写法2:在构造函数中创建对象 # 语义 :老张每次开自己的车去某地 # 写法3:对象通过参数传递 # 语义 :老张使用(参数)去某地 class Person: def __init__(self,name): self.name = name # 2. self.car = Car() def go_to(self,position): #3. def go_to(self,position,car) print(self.name,"去",position) # 2. self.car.run() # 1.car = Car() # 1.car.run() class Car: def run(self): print("开汽车") lz = Person("老张") car = Car() #3. lz.go_to("东北",car) #3.
false
38ce0754f632d7bc2854e3db6bb99570a39e0fb5
BenjaminKamena/pythonadvanced
/agorithm/practice.py
782
4.1875
4
# converting strigs to list # first converter # String to List of Strings string1 = "Benjamin kamena is a progrmammer" print(string1) print(type(string1)) print(string1.split()) # second converter # String to List of Characters print(string1) print(type(string1)) print(list(string1)) # third converter # List of Strings to List of Lists print(string1) string2 = string1.split() list = list(map(list, string2)) print(list) # fourth converter # CSV to List string2 = "Benjamin, kamena, is, a, progrmammer" print(string2) print(type(string2)) print(string2.split(',')) # fifth converter #A string consisting of Integers to List of integers string3 = "1 2 3 4 5 6 7 8 9" print(string3) print(type(string3)) list1 = list(string3.split()) list2 = list(map(int, list1)) print(list2)
false
7799d00bedeecd3952cef1f3fcd77c6f50f50302
BrianFs04/holbertonschool-web_back_end
/0x00-python_variable_annotations/7-to_kv.py
365
4.15625
4
#!/usr/bin/env python3 """to_kv string and int/float to tuple""" from typing import Union, Tuple def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]: """Returns a tuple: The first element of the tuple is the string k. The second element is the square of the int/float v and should be annotated as a float. """ return(k, v * v)
true
7f2d49ee5f9208357053d72c0947a6aad452585a
antonylu/leetcode2
/Python/867_transpose-matrix.py
1,567
4.1875
4
""" transpose-matrix https://leetcode.com/problems/transpose-matrix/ Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] Note: 1 <= A.length <= 1000 1 <= A[0].length <= 1000 """ class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ # Approach #3, copy in place R, C = len(A), len(A[0]) ans = [[None] * R for _ in range(C)] for r, row in enumerate(A): for c, val in enumerate(row): ans[c][r] = val return ans # Approach #2, brute force row_no = len(A) column_no = len(A[0]) ans = [] for i in range(column_no): #3 row = [] for j in range(row_no): #2 row.append(A[j][i]) ans.append(row) return ans # Approach #1, use numpy # import numpy as np return np.array(A).transpose().tolist() if __name__ == '__main__': s = Solution() tc = ([[1,2,3],[4,5,6],[7,8,9]], [[1,2,3],[4,5,6]]) ans = ([[1,4,7],[2,5,8],[3,6,9]], [[1,4],[2,5],[3,6]]) for i in range(len(tc)): r = s.transpose(tc[i]) print (r) assert(r == ans[i])
true
c457a4e95f859df8ff45e112a62b56cbee2767c3
antonylu/leetcode2
/Python/832_flipping-an-image.py
1,767
4.34375
4
""" https://leetcode.com/problems/flipping-an-image/description/ Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. Example 1: Input: [[1,1,0],[1,0,1],[0,0,0]] Output: [[1,0,0],[0,1,0],[1,1,1]] Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] Example 2: Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Notes: 1 <= A.length = A[0].length <= 20 0 <= A[i][j] <= 1 """ xrange = range class Solution(object): def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ # Approach #1, naive # # flip : list.reverse() # invert: lambda x: 0 if x ==1 else 1 # # O(n), 73ms for i, r in enumerate(A): r.reverse() A[i] = [0 if c == 1 else 1 for c in r] return A if __name__ == '__main__': s = Solution() tc = [ [[1,1,0],[1,0,1],[0,0,0]], [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] ] ans = [ [[1,0,0],[0,1,0],[1,1,1]], [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] ] for i in range(len(tc)): r = s.flipAndInvertImage(tc[i]) print (r) assert(r == ans[i])
true
18d54c9c94ed280fef2c2db1df2e5cf42ffbc190
antonylu/leetcode2
/Python/575_distribute-candies.py
1,664
4.40625
4
""" https://leetcode.com/problems/distribute-candies/description/ Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. Example 1: Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies. Example 2: Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies. Note: The length of the given array is in range [2, 10,000], and will be even. The number in given array is in range [-100,000, 100,000]. """ class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ # Approach #1, use set to remove duplicates # O(n), 4% # # return min(len(candies)//2, len(set(candies))) sn = len(set(candies)) n = len(candies)//2 return n if sn>n else sn if __name__ == '__main__': s = Solution() tc = [ [1,1,2,2,3,3],[1,1,2,3] ] ans = [ 3,2 ] for i in range(len(tc)): r = s.distributeCandies(tc[i]) print (r) assert(r == ans[i])
true
7095ec5da1d58c815ea19f9672e60c20cd9530a1
antonylu/leetcode2
/Python/232_implement-queue-using-stacks.py
2,713
4.21875
4
""" https://leetcode.com/problems/implement-queue-using-stacks/description/ Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). """ class MyQueue(object): # Approach #1, # suppose pop runs less than push in overall test cases # push is the same as stack push # pop from left is actually implemented by pop all from right and push back until the last one O(n) # # use stack as queue # # Queue |1|2|3 <-- push # Stack |1|2|3 <-- push # # Queue <-|1|2|3 pop # Stack |1|2|3 --> pop to another stack len()-1 times, pop 3, push back from antoher stack # # use list.append as push # list.pop as pop # list[0] as peek # # pop O(n), others O(1), 29ms, 98% def __init__(self): """ Initialize your data structure here. """ self.myqueue = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: void """ self.myqueue.append(x) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ tmp = [] for i in range(len(self.myqueue)-1): tmp.append(self.myqueue.pop()) tmp.reverse() ans = self.myqueue.pop() for j in tmp: self.myqueue.append(j) return ans def peek(self): """ Get the front element. :rtype: int """ return self.myqueue[0] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return len(self.myqueue) == 0 # Your MyQueue object will be instantiated and called as such: if __name__ == "__main__": obj = MyQueue() obj.push(1) obj.push(2) obj.push(3) param_2 = obj.pop() param_3 = obj.pop() param_4 = obj.pop() print(param_2) print(param_3) print(param_4)
true
1b809587d22b601d3ea9b683c1d8654ee1423e59
fdossantos95/CURSO-DE-PYTHON
/mundo1/exe014.py
262
4.21875
4
'''Crie um programa que converta uma temperatura em graus Celsiuse converta para graus Fahrenheit.''' print('-'*60) c = float(input('Qual a temperatura em graus Celsius? ')) f = (c * 9 / 5) + 32 print('{}°C é equivalente a {}°F.'.format(c, f)) print('-'*60)
false
8bfe41950653680678c57ce5dbeb573256a2504d
fdossantos95/CURSO-DE-PYTHON
/mundo1/exe009.py
572
4.1875
4
'''Criar um programa que leia um número e mostre a sua tabuada.''' print('-'*40) n = int(input('Digite um número para saber a sua tabuada: ')) print('{} X 1 = {:2} '.format(n, (n*1))) print('{} X 2 = {:2} '.format(n, (n*2))) print('{} X 3 = {:2} '.format(n, (n*3))) print('{} X 4 = {:2} '.format(n, (n*4))) print('{} X 5 = {:2} '.format(n, (n*5))) print('{} X 6 = {:2} '.format(n, (n*6))) print('{} X 7 = {:2} '.format(n, (n*7))) print('{} X 8 = {:2} '.format(n, (n*8))) print('{} X 9 = {:2} '.format(n, (n*9))) print('{} X 10 = {:2}'.format(n, (n*10))) print('-'*40)
false
d1f9e9d00277144f442aef27ee5c1541f0472f3e
t83955832/260201076
/hw02/hw_02_prepare.py
525
4.3125
4
#print("I am calculating the distance between "+departure+" and "+arrival) if departure in name_of_city: if arrival in name_of_city: if departure==arrival: print("Enter a different province!") else: arrival=input("Arrival province:\n").upper() else: print("Province not found!") arrival=input("Arrival province:\n").upper() else: print("Province not found!") departure=input("Departure province:\n").upper()
true
21f2ef0bc40de570adae906ab6ba9b568a790844
mariachacko93/luminarDjano
/luminarproject/regularexpressions/quantifiers.py
394
4.125
4
from re import* pattern="aaaaaaaaabaaabbbbaabbaaaa" # x="a+" #check single a and sequence of a # x="a*" # x="a?" # x="^a" #check the pattern start with a or not # x="a$" #check if the given pattern end with a # x="a{2}" #will check for 2 number of a's x="a{2,3}" #min 2 a's and max 3 a's matcher=finditer(x,pattern) for match in matcher: print(match.start(),"position") print(match.group())
true
ce931a63830347be8a1135f3985cf895fab8c57f
damnit1989/python
/map_reduce.py
803
4.28125
4
# -*- coding: utf-8 -*- # map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 # 再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数, # reduce把结果继续和序列的下一个元素做累积计算,其效果就是: # reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) 'a how to use map(),reduce() module example' __author__ = 'lmm' L = [1, 2, 3, 4, 5] new_l = map(str, L) print new_l def test(x): return x*x print map(test, L) def chr_func(x): return x+'_'+x print map(chr_func, 'abcdef') from functools import reduce def fn(x,y): return x*10 + y print(reduce(fn,[1,3,5,7,9]))
false
ba0f0ac156c24cf87f2ec82ec5eb5b0d2f0aa705
Mega-Barrel/college-python
/Experiment-no3/3.1.py
1,266
4.53125
5
# Write a program to implement Class, Object, Static method and inner class. # 1. class: class empty: pass print('------------/------------') # 2. Object: class student: print('Hello World!') a = student() print('------------/------------') # 3. static method: '''static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. ''' class Calculator: @staticmethod def multiplyNums(x, y): return x * y print('Product:', Calculator.multiplyNums(15, 2)) print('------------/------------') # 4. inner class: class Student: def __init__(self,name,rollno): self.name = name self.rollno = rollno # Always create object of innerclass in main class. self.lap = self.Laptop() def show(self): print(self.name , self.rollno) # Calling laptop show method self.lap.show() class Laptop: def __init__(self): self.brand = "dell" self.cpu = 'i3' self.ram = 8 def show(self): print('Laptop configuration: ') print(self.brand, self.cpu, self.ram, 'GB') s1 = Student('Saurabh', 2) s1.show() lap1 = Student.Laptop()
true
863684501bfabe2dd0ff9d9f6081bb89af3202ce
edromero86/Python
/ex44c.py
1,503
4.5
4
class Parent(object): def altered(self): print "PARENT altered()" class Child(Parent): def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() print "CHILD, AFTER PARENT altered()" dad = Parent() son = Child() dad.altered() son.altered() # The third wat to use inheritance is a special case of overriding where you want to alter the behavior before or after the Parent class version runs. # You first override the function just like in the last example, but then you use a Python built-in function named super to get the Parent version to call. # The import lines here are 9-11, where in the Child I do the following when son.altered() is called. # 1. Because I've overridden Parent.altered the Child.altered version runs, and line 9 executed like you'd expect. # 2. In this case, I want to do a before and after, so after line 9, I want to use super to get the Parent.altered version. # 3. On line 10, I call super(Child, self).altered(), which is a lot like the getattr function you've sued in the past, but it's aware of inheritance and will get the Parent class for you. # You should be able to read this as "call super with arguments Child and self, then call the function altered on whatever it returns." # 4. At this point, the Parent.altered version of the function runs, and that prints out the Parent message. # 5. Finally, this returns from the Parent.altered, and the Child.altered function continues to print out the after message.
true
817632ccf0c151f9df69af3f1360418df122d1a7
pfcperez/DevF_Ram
/Clases/tarea_semana1.py
2,291
4.125
4
# -*- coding: utf-8 -*- """ Kata #1 Crea un programa que le pregunte al usuario su nombre y edad. Imprime un mensaje dirigido a él, que le diga el año en que cumplirá cien anioos """ import datetime # def ask_questions(): # nombre = raw_input("Hola!!!. Cual es tu nombre?: ") # edad = raw_input("Cual es tu edad?: ") # edad_entera = int(edad) # ahora = datetime.datetime.now() # hundred = 100 -edad_entera # print "Hola {} tu cumpliras tu centenario en el año {}".format(nombre, hundred+ahora.year) # ask_questions() """ Kata #2 Pídele un número al usuario. Dependiendo de si el número es par o impar, imprime el mensaje apropiado al usuario """ # def par_impar(): # numero = int(raw_input("Cual es el numero a revisar?: ")) # div = numero % 2 # if div == 0: # print "El {} numero es par".format(numero) # else: # print "El {} numoero es impar".format(numero) # # par_impar() """ Kata #3 Escribe un programa que tome una lista de números (por ejemplo, a = [5, 10, 15, 20, 25]) y haz dos nuevas listas. una que contenga sólo el primer y último número de la lista original y otra que contenga todos los números intermedios """ def nuevas_listas(): lista_original = [] lista1 = [] lista2 = [] #num = int(raw_input( "Cuantos numeros quieres agregar?: ")) for i in range(0,5): temp = raw_input("Ingresa el numero: ") lista_original.append(temp) lista1.append(lista_original[0]) lista1.append(lista_original[-1]) for t in range(1,4): lista2.append(lista_original[t]) print lista1 print lista2 #print lista_original nuevas_listas() """ Kata #4 Escribe una función que tome una lista de números y un número. La función debe checar si el número pertenece a la lista y devolver el booleano correspondiente """ # def chequear_numero(): # lista = [] # # for i in range(0,5): # temp = int(raw_input("Ingresa el numero en lista: ")) # lista.append(temp) # # numero = int(raw_input("Cual es el numero que vas a revisar: ")) # # if numero in lista: # print "El numero {} esta en la lista".format(numero) # else: # print "El numero {} no se encuetra en la lista".format(numero) # # chequear_numero()
false
a5075c949f17236c4898e95e0aab8103bed3b77c
VineeS/Python
/Assignment1/Qudratic Equation.py
372
4.125
4
import cmath # its used for complex number a = float(input("Enter the value of a :")) b = float(input("Enter the value of b : ")) c = float(input("Enter the value of c :")) d = pow(b, 2) - (4*a*c) print(cmath.sqrt(d)) sol1 = (-b - cmath.sqrt(d))/(2*a) sol2 = (-b + cmath.sqrt(d))/(2*a) print(sol1) print(sol2) print("Quadratic equation {0} and {1} ".format(sol1, sol2))
true
7b07b74ab6c2190395c75b5a3d01d76d8187f82c
RockWilliams/travis-python-test
/functions/math_functions_solution.py
347
4.1875
4
""" module math_functions """ import math def area_of_circle(radius): """ determines the area of a circle with a 'radius' input """ return None if radius <= 0 else math.pi * radius ** 2 def surface_area_of_cube(side): """ determines the surface area of a cube with a 'side' input """ return None if side <= 0 else 6 * side ** 2
true
8af27b5edce3484c442ec1c88fa21a97cd6a7a42
teddymcw/pythonds_algos
/linear_data_structures_chap/anagrams.py
520
4.4375
4
def test_anagram(word1, word2): if sorted(word1) == sorted(word2): return True return False """As we will see in a later chapter, sorting is typically either O(n2) or O(nlogn), so the sorting operations dominate the iteration. In the end, this algorithm will have the same order of magnitude as that of the sorting process.""" """to make anagram calls we would need a list of somewhat sorted english words and then compare this word to the words of that length or something, only returning the sorted matches"""
true
f968fad714d3631754caf79215e15707ebd23ef2
teddymcw/pythonds_algos
/searching_sorting/shortbubblesort.py
999
4.1875
4
#best way to go if list is already somewhat sorted #optimization of bubble sort #will stop at certain operations because we already know def shortBubbleSort(alist): exchanges = True passnum = len(alist)-1 while passnum > 0 and exchanges: steps = 0 print("now alist is: {}, {}".format(alist, steps)) exchanges = False for i in range(passnum): print("assessing {0} and {1}".format(alist[i], alist[i+1])) if alist[i]>alist[i+1]: print("switching {0} and {1}".format(alist[i], alist[i+1])) exchanges = True temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp print("now alist is: {}".format(alist)) steps += 1 else: print("skipping {0} and {1}".format(alist[i], alist[i+1])) steps += 1 passnum = passnum-1 alist = [54,26,93,17,77,31,44,55,20] shortBubbleSort(alist) print(alist)
true
b0de4a5be2668d636a43ffffa632e6de235a6b80
pacifiquei/Data-Structures-and-Algorithms-in-Python
/Stacks/stacks.py
1,647
4.15625
4
# Stack Implementation using Array # Create a stack class class Stack(object): # Constructor def __init__(self): self.stack = [] # Initialize the stck by an empty List self.numOfItems = 0 # Initialize the number of items in stack = 0; Stack Index # Check if Stack is empty def isEmpty(self): return self.stack == [] # If empty, return true else false # Push data to Stack def push(self, data): self.stack.insert(self.numOfItems, data) # Insert the data at Index "num of items"; Initially, Index = 0 self.numOfItems += 1 # Increment Index return '{} pushed to Stack'.format(data) # Pop data from Stack def pop(self): self.numOfItems -= 1 # Decrement the Index to point to top of Stack data = self.stack.pop(self.numOfItems) # Pop out the data from that index return '{} removed from Stack'.format(data) # Size of stack def stackSize(self): return len(self.stack) # Length of the List/Array is the size of Stack # Testing if __name__ == '__main__': stack = Stack() # Push data to Stack print(stack.push(10)) print(stack.push(20)) print(stack.push(30)) print(stack.push(40)) # Pop data from Stack print(stack.pop()) print(stack.pop()) print('Stack size: ',stack.stackSize()) print(stack.pop()) print('Stack size: ',stack.stackSize()) # ------------------------------------------ EOC --------------------------------------
true
e739e85d71ac809c0a18fdfa08d5789f3af731ac
shahzina/UCB_PythonModule
/DownToInput.py
723
4.1875
4
name_user = input("What is your name?") name_neighbor = input ("What is your partners's name?") months1 = int(input("How many months have you been coding for?")) months2 = int(input("How many months has your neighbor been coding for?")) print (f" My name is {name_user} and I have been coding for {months1} months. \n My partner's name is {name_neighbor} and she has been coding it for {months2} months. ") ''' OUTPUT What is your name? Shahzina What is your partners's name? Arshia How many months have you been coding for? 8 How many months has your neighbor been coding for? 0 My name is Shahzina and I have been coding for 8 months. My partner's name is Arshia and she has been coding it for 0 months. '''
true
9884ebd35415d45c58fd9fdc96e43bc1fef52cb4
frankye1000/LeetCode
/python/Valid Parentheses.py
873
4.25
4
"""Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true""" s = "()[]}" def Iscorrect(s): dic = { ']':'[', '}':'{', ')':'(' } stack = [None] for i in s: if i in dic and dic[i]==stack[-1]: stack.pop() else: stack.append(i) # print(stack) if len(stack)==1: return True else: return False print(Iscorrect(s))
true
3e76b028cbf126e97d47bc45293a6dc09c94e998
frankye1000/LeetCode
/python/Palindrome Number.py
697
4.125
4
""" Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? """ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ import math if x<0: return False tmp = x y = 0 while tmp: y = y*10 + tmp%10 tmp = math.floor(tmp/10) return x==y
true
b5d05b987bcfdc9c88591ddf23ced9c82a5af786
frankye1000/LeetCode
/python/Palindromic Substrings.py
588
4.1875
4
"""Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".""" s = "abc" temp = [s[i:j] for j in range(len(s) + 1) for i in range(len(s)) if i < j] print(temp) r = len([strin for strin in temp if strin == strin[::-1]]) print(r)
true
20217a1137b8dcf59f91d8dffcbe3b77a1ee9fa1
JasonWu00/cs-master
/127/45_months.py
1,099
4.4375
4
#Modified by: Ze Hong Wu (Jason) #Email: zehong.wu17@myhunter.cuny.edu #Date: November 16, 2020 #Takes in a number and returns a month. def main(): month = int(input("Enter a month, as an integer: ")) while(month < 1 or month > 12): print("You fool, this isn't a proper value!") month = int(input("Enter a month, as an integer: ")) output = monthString(month) print(output) def monthString(month): if (month == 1): output = "January" elif (month == 2): output = "February" elif (month == 3): output = "March" elif (month == 4): output = "April" elif (month == 5): output = "May" elif (month == 6): output = "June" elif (month == 7): output = "July" elif (month == 8): output = "August" elif (month == 9): output = "September" elif (month == 10): output = "October" elif (month == 11): output = "November" elif (month == 12): output = "December" return output if __name__ == "__main__": main()
true