blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7cdaaed456af8a41dd627feb595823b98dd3713e
YutoTakaki0626/My-Python-REVIEW
/basic/dictionary.py
529
4.28125
4
# dictionary:キーと値の組み合わせを複数保持するデータ型 fruits_colors = {'apple':'red', 'lemon': 'yellow', 'grapes': 'purple'} print(fruits_colors['apple']) fruits_colors['peach'] = 'pink' print(fruits_colors) dict_sample = {1: 'one', 'two': 2, 'three': [1, 2, 3], 'four':{'inner': 'dict'}} print(dict_sample) print(dict_sample['four']['inner']) # .keys() .values() for fruit in fruits_colors.keys(): print(fruit) # .items() for fruit, color in fruits_colors.items(): print(f'{fruit} is {color}')
false
b3080fe028e3a62ade5b64a57da7ce9276c650ae
niksm7/March-LeetCoding-Challenge2021
/Palindromic Substrings.py
622
4.15625
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". ''' class Solution: def countSubstrings(self, s: str) -> int: @lru_cache(None) def ispalindrome(i, j): if i >= j: return True return s[i] == s[j] and ispalindrome(i+1, j-1) return sum(ispalindrome(i, j) for i in range(len(s)) for j in range(i, len(s)))
true
77de892bfce5df9d0d5c9bad7cde7b401e1ba38e
TheDarkKnight1939/FirstYearPython
/3.py
539
4.28125
4
#!/usr/bin/python import random #Imports the class random r=random.randint(10,66) #Uses the randint function to choose a number from 10 to 66 print(r) #Prints the random number choosen if r<35: #If loop which checks if the number is lesser than 35 print(r) print(": is less than 35 \n") exit elif r==30:#If loop which checks if the number is equal to 30 print(" 30 is multiple of 10 and 3, both ") elif r>=35:#If loop which checks if the number is lesser than 35 print(r, " is greater than 35") else: print("your number is : ", r)
true
aad35df15da4265e65defc8f609290a342e727f3
gaurav-singh-au16/Online-Judges
/Binary_Search_Problems/nth_fibonacci_no.py
916
4.1875
4
""" Nth Fibonacci Number The Fibonacci sequence goes like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number can be found by adding up the two numbers before it, and the first two numbers are always 1. Write a function that takes an integer n and returns the nth Fibonacci number in the sequence. Constraints n ≤ 30 Example 1 Input n = 1 Output 1 Explanation This is the base case and the first fibonacci number is defined as 1. Example 2 Input n = 6 Output 8 Explanation Since 8 is the 6th fibonacci number: 1, 1, 2, 3, 5, 8. Example 3 Input n = 7 Output 13 Explanation Since 13 is the seventh number: 1, 1, 2, 3, 5, 8, 13 Solved 2,779 Attempted 3,007 Rate 92.42% """ def solve(n): dp = [0]* 10 dp[0] = 0 dp[1] = 1 for i in range(n+1): if i !=0 and i !=1: dp[i] = dp[i-2]+dp[i-1] return dp[n] if __name__ == "__main__": n = 3 print(solve(n))
true
86a7c2270c42fdd3e898d027dac3f0c63d07fbc8
gaurav-singh-au16/Online-Judges
/Leet_Code_problems/69. Sqrt(x).py
543
4.15625
4
""" 69. Sqrt(x) Easy 1657 2143 Add to List Share Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Example 1: Input: x = 4 Output: 2 Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. Constraints: 0 <= x <= 231 - 1 """ class Solution: def mySqrt(x): return int(x**(1/2))
true
d5fee0cdc323a6feca2f3b7cf95cc59f909bbfab
tsakaloss/pycalculator
/calculator.py
2,930
4.375
4
import sys from lib import operations # Manage the operations def mathing_func(a, b, sign): if sign == '+': return operations.Calculations.plus(a, b) elif sign == '-': return operations.Calculations.minus(a, b) elif sign == '*': return operations.Calculations.multiply(a, b) elif sign == '/': return operations.Calculations.divine(a, b) else: print("Wrong sign detected.") sys.exit(1) def calculator(): try: while True: sign_position_counter = 0 position_list_counter = 0 numbers_listed = [] signs_only = [] counter = 1 # For the text to input third+ sign or = for result # Get first user's input. start_quit = input( 'Type \'start\' to start using this calculator or type close to quit: ') if start_quit == 'close': sys.exit(0) if start_quit == 'start': while True: number_for_list = float( input('Enter a number of your choice: ')) numbers_listed.insert( position_list_counter, number_for_list) position_list_counter += 1 if counter == 1: sign_for_operation = input( 'Enter one of the following: + - * or / : ') signs_only.insert(sign_position_counter, sign_for_operation) counter += 1 position_list_counter += 1 sign_position_counter += 1 else: # Can later add it with '+' at the end of the string after one run sign_for_operation = input( 'Enter one of the following: + - * / OR = to do the math : ') if sign_for_operation == '=': amount = len(numbers_listed) amount -= 1 for i in range(amount): result = mathing_func( numbers_listed[i], numbers_listed[i + 1], signs_only[i]) numbers_listed.remove(numbers_listed[i + 1]) numbers_listed.insert(i + 1, result) print("The result is: ", result) break else: signs_only.insert( sign_position_counter, sign_for_operation) sign_position_counter += 1 except KeyboardInterrupt: print("\nExiting...") sys.exit(0) # gracefull exit. if __name__ == '__main__': # Run calculator. calculator()
true
0c3925c9dfd8736a0f5836d2139fdf6d6a259a70
lightdarkx/python-snippets
/LinearSearch.py
513
4.28125
4
# Program to implement linear search in a given array/list def linearSearch(arr,search_item): print(f"search_item: {search_item}") for i in arr: if (i == search_item): return -2,i #print(f"i: {i}") return -1,-1 arr = [1,2,3,4,5] search_item = 4 ans,position = linearSearch(arr, search_item) #print(f"ans: {ans}") if ans == -1: print("Item not in array") elif ans == -2: print(f"Item is in array at position: {position}")
true
e9a6d1c8de9290cf452f81f35df46f9ab2f9e48a
Meeds122/Grokking-Algorthms
/4-quicksort/quicksort.py
1,280
4.21875
4
#!/usr/bin/python3 def quickSort(arr): working_array = arr.copy() working_array_length = len(working_array) if working_array_length <= 1: # Empty element or single element case return working_array elif working_array_length == 2: # only 2 elements case if working_array[0] <= working_array[1]: # already sorted return working_array else: # sort array return [working_array[1], working_array[0]] else: # more than 2 elements # select the last element as the pivot pivot = [working_array[working_array_length - 1]] less_array = [] greater_array = [] for i in range(working_array_length - 1): if working_array[i] > pivot[0]: greater_array.append(working_array[i]) if working_array[i] <= pivot[0]: less_array.append(working_array[i]) return quickSort(less_array) + pivot + quickSort(greater_array) def testing(): import random test_array = [] for i in range(random.randint(1,20)): test_array.append(random.randint(1,30)) print("Unsorted array:") print(test_array) print("Sorted array:") print(quickSort(test_array)) testing()
true
def9cd930313f4fe0e6f5219f51e25e31ff04788
andrewswellie/Python_Rock_Paper_Scissors
/RockPaperScissors.py
1,537
4.15625
4
# Incorporate the random library import random restart = 1 while restart != "x": print("Let's Play Rock Paper Scissors!!!") options = ["r", "p", "s"] computer_choice = random.choice(options) user_choice = input("You are playing against the computer. His choice is completely random. Make your Choice: (r)ock, (p)aper, (s)cissors? ") if (user_choice == "r") and (computer_choice == "p"): print("You Lose.") restart = input("press any key to start again, or x to exit.") elif (user_choice == "p") and (computer_choice == "s"): print("You Lose.") restart = input("press any key to start again, or x to exit.") elif (user_choice == "s") and (computer_choice == "r"): print("You Lose.") restart = input("press any key to start again, or x to exit.") if (user_choice == "s") and (computer_choice == "p"): print("You WIN!!!") restart = input("press any key to start again, or x to exit.") elif (user_choice == "r") and (computer_choice == "s"): print("You WIN!!!") restart = input("press any key to start again, or x to exit.") elif(user_choice == "p") and (computer_choice == "r"): print("You WIN!!!") restart = input("press any key to start again, or x to exit.") if (user_choice == computer_choice): print("TIE! Kind of like kissing your sister. Try again.") restart = input("press any key to start again, or x to exit.")
true
368ec147cd5f547160e88580a4c11783f2f79f98
pani-vishal/String-Manipulation-in-Python
/Problem 7.txt
221
4.21875
4
#Program to count no. of letters in a sentence/word sent=input("Enter a sentence: ") sent=sent.lower() count=0 for x in sent: if (x>='a' and x<='z'): count+=1 print("Number of letters: "+str(count))
true
afa0d3861f350476303935675bd207e08272ce1c
ramalho/propython
/fundamentos/metaprog/atrib_dinamicos.py
814
4.28125
4
#!/usr/bin/env python # coding: utf-8 '''Exemplo de acesso e atribuição dinâmica de atributos de instância. >>> n = Nova() * self.__setattr__('b') >>> print repr(n.a) 1 >>> print repr(n.b) 2 >>> print repr(n.c) * self.__getattr__('c') 'c?' >>> n.a = 10 * self.__setattr__('a') >>> print repr(n.a) 10 >>> n.x = 99 * self.__setattr__('x') >>> print repr(n.x) 99 ''' class Nova(object): a = 1 def __init__(self): self.b = 2 def __getattr__(self, nome): print '* self.__getattr__(%r)' % nome return nome + '?' def __setattr__(self, nome, valor): print '* self.__setattr__(%r)' % nome self.__dict__[nome] = valor if __name__=='__main__': import doctest doctest.testmod()
false
52a811e422306a3919e5c06cb3c2c568c2a31160
ramalho/propython
/fundamentos/funcional/curry.py
989
4.40625
4
#!/usr/bin/env python ''' Exemplo da técnica de currying. A função rectFactory é um "curry" que retorna uma função que realiza o serviço de rect fixando um dos parâmetros para que ele não precise ser fornecidos a cada invocação. Em rectFactory2 temos um exemplo que demonstra a mesma técnica implementada com o comando lambda. Em rectFactory3 o curry fixa ambos argumentos da função rect. ''' def rect(larg, alt): if larg > 0 and alt > 0: print '*' * larg if alt > 1: for i in range(alt-2): print '*' + ' '*(larg-2) + '*' print '*' * larg def rectFactory(larg): def func(alt): return rect(larg, alt) return func def rectFactory2(larg): return lambda alt: rect(larg, alt) def rectFactory3(larg, alt): return lambda: rect(larg, alt) if __name__=='__main__': f = rectFactory(20) f(7) g = rectFactory2(40) g(3) g(5) h = rectFactory3(30,3) h() h()
false
f91a700285537cbbd9f51fb70d8d7ae0559d1709
jeremymatt/DS2FP
/drop_illogical.py
713
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 25 22:59:05 2019 @author: jmatt """ def drop_illogical(df,var1,var2): """ Drops records from the dataframe df is var1 is greater than var2 For example, if var1 is spending on clothing and var2 is total income it is not logical that var1 is greater than var2 """ #Mask the illogical entries mask = df[var1]>df[var2] #Record the number of entries NumRecords = df.shape[0] #drop the illogical entries df = df[df.keys()][~mask] #Notify the user how many records were dropped print('{} records dropped because {} is greater than {}'.format(NumRecords-df.shape[0],var1,var2)) return df
true
051d08ec216fff8651d3a096578c7fa38ba875ed
CLAHRCWessex/math6005-python
/Labs/wk1/if_statement_preview.py
1,884
4.6875
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Week 1 Extra Material: If-then statements A short look ahead at conditionals and if statements. We will cover these in detail in week 2. But feel free to have edit the code below to see how it works. In most Python programmes that you write you will be using if-then statements. These allow you to make conditional choices in your code. To use if-then statements you need to understand a.) boolean comparisons e.g. x > 1 b.) if, elif and else statements c.) Python whitespace and indentation rules @author: tom """ #%% # ============================================================================= # Boolean comparisons - return True or False # ============================================================================= foo = 2 bar = 'spam' print('is foo equal to 2?: {0}'.format(foo == 2)) print('is foo less than or equal to 5?: {0}'.format(foo <= 5)) print('is foo greater than or 100?: {0}'.format(foo > 5)) print("is bar equal to 'eggs': {0}".format(bar == 'eggs')) print("is bar the same type as foo?: {0}".format(type(bar) == type(foo))) #%% # ============================================================================= # We use boolean comparisons in 'if' statements # ============================================================================= foo = 100 # why not try changing the value of foo to 10, 'bar' and 'eric' if foo == 100: #notice that the print statement is indented. #This is mandatory in python. Otherise you get an error! print("Hello! You branched here, because foo == 100 evaluated to 'True'") elif foo == 10: print("Hello again, you branched here because foo equals 10 this time") elif foo == 'bar': print("Gosh, hello. This time foo looked a bit different!") else: print("So foo didn't equal any of the above. I am the default branch") #%%
true
c7d99b39a0557d62a59e5607c9620f2bcfcab248
eshanmherath/neural-networks
/perceptron/simple_perceptron_OR_gate.py
2,098
4.15625
4
import numpy as np class Perceptron: def __init__(self, number_of_inputs, learning_rate): self.weights = np.random.rand(1, number_of_inputs + 1)[0] self.learning_rate = learning_rate """A step function where non-negative values are returned by a 1 and negative values are returned by a -1""" def activate(self, z): if z >= 0: return 1 else: return -1 def feed_forward(self, input_values): inputs = np.array([ input_values[0], input_values[1], -1 ]) z = inputs.dot(self.weights.transpose()) return self.activate(z) def update_weights(self, actual_x, error): x = np.array([ actual_x[0], actual_x[1], -1 ]) self.weights += self.learning_rate*error*x """ Below code simulates a perceptron learning to act as an OR gate. (-1) represents 0 (+1) represents 1 """ if __name__ == "__main__": print("\nPerceptron learning the OR gate functionality\n") np.random.seed(1111) perceptron = Perceptron(2, 0.01) training_x = np.array([[-1, -1], [-1, 1], [1, -1], [1, 1]]) training_y = np.array([[-1], [1], [1], [1]]) for epoch in range(25): total_error = 0 for example in range(len(training_x)): y_predicted = perceptron.feed_forward(training_x[example]) y_expected = training_y[example][0] error = y_expected - y_predicted total_error += error perceptron.update_weights(training_x[example], error) print("epoch " + str(epoch) + " Total Error " + str(total_error)) if total_error == 0: break print("Final Weights : " + str(perceptron.weights)) "Testing final weights" print("\nTesting final weights") print('Input [-1, -1] Output ' + str(perceptron.feed_forward([-1, -1]))) print('Input [-1, +1] Output ' + str(perceptron.feed_forward([-1, +1]))) print('Input [+1, -1] Output ' + str(perceptron.feed_forward([+1, -1]))) print('Input [+1, +1] Output ' + str(perceptron.feed_forward([+1, +1])))
true
c02c02fd344549fc4cda63bba9ea525cdd30c151
mahinhasan56/python-sqlite
/Extract.py
541
4.3125
4
import sqlite3 with sqlite3.connect("users.db") as db: cursor =db.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS user (userID INTEGER PRIMARY KEY,username VARCHAR(20) NOT NULL, firstname VARCHAR(20) NOT NULL, surname VARCHAR (20) NOT NULL, password VARCHAR(20)NOT NULL );''') cursor.execute("""INSERT INTO user (username,firstname,surname,password)VALUES("farukeu@gmail.com","Faruk","khan","12345")""") db.commit() cursor.execute("SELECT firstname , surname FROM user;") print(cursor.fetchall())
false
e347dab6cada8dfd16b370d9f40f3b590b949a2e
tvocoder/learning_python
/python_functional_programming.py
1,191
4.59375
5
# Functional Programming print("---= Functional Programming =---") print("--= Map =--") # Description: Applies function to every item of an iterable and returns a list of the results. # Syntax: map(function,iterable[,...]) # -- function: Required. A function that is used to create a new list. # -- iterable: Required. An iterable object or multiple comma-seperated iterable objects. # Return Value: list # Remarks: If additional iterable arguments are passed, function must take that many arguments and is applied # -- to the items from all iterables in parallel. # If one iterable shorter than another it is assumed to be extended with None items. # If function is None, the identity function is assumed; if there are multiple arguments, # -- map() returns a list consisting of tuples containing the corresponding items from all iterables. # The iterable arguments may be a sequence or any iterable object; the result is always a list. # Example: l = map(lambda x, y, z: x+y+z, [1, 2, 3], [4, 5, 6], [7, 8, 9]) print(list(l)) def addition(n): return n + n numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) l = map(lambda x : x + x, numbers) print(list(l))
true
304598e5e382fad84021f4a95d5a395b957a4456
tvocoder/learning_python
/python_callable_func.py
2,317
4.5
4
print("---= Callables Operators =---") print("-- *(tuple packing) --") # Description: Packs the consecutive function positional arguments into a tuple. # Syntax: def function(*tuple): # -- tuple: A tuple object used for storing the passed in arguments. # All the arguments can be accessed within the function body the same way as with any other tuple. # Remarks: The tuple name *args is used by convention. # Example: def add(*args): total = 0 for arg in args: total += arg return total x = add(1, 2, 3) print(x) print("*************************") print("-- **(dictionary packing) --") # Definition: Packs the consecutive function keyword arguments into a dictionary. # Syntax: def function(**dict): # -- dict: A dictionary object used for storing the passed in arguments. # All the arguments can be accessed within the function body with the same way as with any other dictionary. # Remarks: The dict name **kwargs is used by convention. # Example: def example(**kwargs): return kwargs.keys() d = example(a = 1, b = 20, c = [10, 20, 30]) print(d) print("*************************") print("-- *(tuple unpacking) --") # Definition: Unpacks the contents of a tuple into the function call # Syntax: function(*iterable) # Remarks: # Example: def add(a, b): return a + b t = (2 ,3) print(add(*t)) print(add(*"AD")) print(add(*{1: 1, 2: 2})) print("*************************") print("-- **(dictionary unpacking) --") # Definition: Unpacks the contents of a dictionary into a function call # Syntax: function(**dict) # -- dict: The dictionary containing pairs of keyword arguments and their values. # Remarks: # Example: def add(a=0, b=0): return a + b d = {'a': 2, 'b': 3} print(add(**d)) print("*************************") print("-- @(decorator) --") # Definition: Returns a callable wrapped by another callable. # Syntax: @decorator # def function(): # decorator: A callable that takes another callable as an argument. # Remarks: # Decorator Syntax: def decorator(f): pass @decorator def function(): pass # Is equivalent to: def function(): pass function = decorator(function) # Example: print("*************************") print(" -- ()(call operator --") # Definition: # Syntax: # Remarks: # Example: print("*************************")
true
658c711767cba340196597ba6658f855293cf73e
Python-aryan/Hacktoberfest2020
/Python/leap_year.py
253
4.125
4
def leapyear(year): if year % 4 == 0: print("Its a leap year") elif year % 100 == 0: print("Its a leap year") elif year % 400 == 0: print("Its a leap year") else: print("Its not a leap year") year = int(input("Enter a Year")) leapyear(year)
false
2690b3fb0d1b3339f9b29f8c5c81638c0eefb682
Python-aryan/Hacktoberfest2020
/Python/sum of list-elements.py
287
4.25
4
#Calculates the sum of a list of numbers number = int(input("Enter number of elements: ")) elements = [] for i in range(number): x = int(input("Enter {} number: ".format(i+1))) elements.append(x) sum=0 for i in elements: sum=sum+i print("Sum of the list elements is: ",sum)
true
bb62b6e47c6d5606a253690c003d9b72b6aea79e
docljn/python-self-study
/wesleyan_intro/module_3/name_phone.py
925
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 28 15:48:51 2018 @author: DocLJN """ import sys import csv # open the csv file here filename = sys.argv[1] file = open(filename, 'w') while True: nextname = input("Enter a friend's name, press return to end: ") if nextname == "": break # break jumps out of the loop nextphone = input("Enter the friend's phone number: ") print(nextname) print(nextphone) option = input("Is this correct? y/n ") if option == 'y': entry = [nextname, nextphone] csv.writer(file).writerow(entry) print('Added',nextname, nextphone) else: print('Next: ') # add lines here to build a row (that is, a list) and append these # two pieces of data to it. Write to the csv file # don't forget to close the csv file file.close()
true
910ba7384503ead042945e33c9c1c48160d59003
Lxunrui/python-learn
/python-opp/ch3/list_basic.py
360
4.125
4
# 两种数据结构:列表和元组 # 列表的创建 a = [1,2,3,4] # 列表里面的元素的数据类型可以是任意的。例如 b = [1,'asd',2.0,['a','b','c']] print(a) print(b) # 列表元素的访问 print('a[0]=',a[0],a[1]) # b[a:b] a代表第几个 b-a代表到第几位 c = b[1:3] print(c,type(c)) s = 'asdzxc' print(s[1:2],s[-1]) print(b[-1])
false
4585d9c998c7312a8a2541259970987d700b45ab
Scorch116/PythonProject---Simple-calculator
/Calculator.py
1,261
4.25
4
'''Simple calculator used to perform basic calculator functions such as addition, subtraction,division and multplication''' def Addition(value1, value2): # this function will add the two numbers return value1 + value2 def subtract (value1, value2): return value1 - value2 def Divide(value1, value2): return value1 / value2 def multiply(value1,value2): return value1 * value2 #print statement for selecting function print("please selection function \n > Add \n > Subtract \n > Divide \n > Multiply") #Input form the user to select function FunctionInput = input("Enter option :") Num1 = int(input("Please enter the first number: ")) Num2 = int(input("PLease enter the second number: ")) # If statement done to select function and read in values if FunctionInput == "Add": print("The answer is ",Addition( Num1, Num2)) elif FunctionInput == "Subtract": print("The answer is ",subtract( Num1, Num2)) elif FunctionInput == "Divide": print("The answer is ",Divide( Num1, Num2)) elif FunctionInput == "Multipy": print("The answer is ",multiply( Num1, Num2)) else: print("Error, PLease try again") #else statement with print error - incase something gose wrong you know its working #better that and actual error
true
d6374434fb6c9d67a684c3db37d6bc34e7701fd9
abhinavmittal93/Week1_Circle_Radius
/Week1_coding.py
320
4.1875
4
import math import datetime def calc_radius(): radius = float(input('Enter the radius of the circle: ')) area = math.pi * radius**2 print(f'Area of the circle is: {area:.2f}') def print_date_time(): time = datetime.datetime.now() print(f'Today\'s date: {time}') print_date_time() calc_radius()
true
9b31816c42dc2107fdbe3af38c21992213168768
danel2005/triple-of-da-centry
/Aviel/8.3.3.py
675
4.3125
4
def count_chars(my_str): """ returns a dict that the keys are the letters and the valus are how many of them were in the string :param my_str: the string we want to count every letter :type my_str: str :return: a dict that the keys are the letters and the valus are how many of them were in the string :rtype: dict """ dict = {} my_list = list(my_str.replace(" ", "")) for letter in my_list: if letter in dict.keys(): dict[letter] += 1 else: dict[letter] = 1 return dict def main(): magic_str = "abra cadabra" print(count_chars(magic_str)) if __name__ == "__main__": main()
true
b37418b1873488e4cf3b9397273f344e0768fd7b
danel2005/triple-of-da-centry
/Aviel/7.3.1.py
814
4.125
4
def show_hidden_word(secret_word, old_letters_guessesd): """ Show the player his prograssion in the game :param secret_word: the word the player need to guess :param old_letters_guessesd: the letters that the player is already guessed :type secret_word: str :type old_letters_guessesd: list :return: string of the secret word but only with the letters that was already guessed :rtype: str """ str = "" for letter in secret_word: if letter in old_letters_guessesd: str += letter + " " else: str += "_ " return str[:-1] def main(): secret_word = "mammals" old_letters_guessesd = ['s', 'p', 'j', 'i', 'm', 'k'] print(show_hidden_word(secret_word, old_letters_guessesd)) if __name__ == "__main__": main()
false
1c6125e33f932902b101c449ffd44c5236788bc0
danel2005/triple-of-da-centry
/Aviel/6.4.2.py
876
4.15625
4
def try_update_letter_guessed(letter_guessed, old_letters_guessed): """ Adds the letter guessed to the array of letters that has already been guessed :param letter_guessed: the guess that the user inputing :param old_letters_guessed: all the letters the user already guessed :type letter_guessed: string :type old_letters_guessed: array :return: true or false, the letter is valid or not and if its already been guessed :rtype: bool """ if len(letter_guessed) >= 2 or not (letter_guessed >= "a" and letter_guessed <= "z" or letter_guessed >= "A" and letter_guessed <= "Z") or (letter_guessed.lower() in old_letters_guessed): old_letters_guessed_str = ' -> '.join(sorted(old_letters_guessed)) print("X") print(old_letters_guessed_str) return False old_letters_guessed += letter_guessed return True
true
2c772ed45516775c12da8c4ae9ba0d6330ab5105
danel2005/triple-of-da-centry
/Aviel/6.4.1.py
651
4.1875
4
def check_valid_input(letter_guessed, old_letters_guessed): """ Checks if the guess is valid or not :param letter_guessed: the guess that the user inputing :param old_letters_guessed: all the letters the user already guessed :type letter_guessed: string :type old_letters_guessed: array :return: true or false, the letter is valid or not and if its already been guessed :rtype: bool """ if len(letter_guessed) >= 2 or not (letter_guessed >= "a" and letter_guessed <= "z" or letter_guessed >= "A" and letter_guessed <= "Z") or (letter_guessed.lower() in old_letters_guessed): return False return True
true
c889e0e9d7f44f7c13658bfeaebdb60e6ffaea8c
danel2005/triple-of-da-centry
/Aviel/7.2.2.py
677
4.28125
4
def numbers_letters_count(my_str): """ returns a list that the first number is the numbers count and the second number is the letters count :param my_str: the string we want to check :type my_str: str :return: list that the first number is the numbers count and the second number is the letters count :rtype: list """ count_letters = 0 count_nums = 0 for letter in my_str: if letter >= "0" and letter <= "9": count_nums += 1 else: count_letters += 1 return [count_nums, count_letters] def main(): print(numbers_letters_count("Python 3.6.3")) if __name__ == "__main__": main()
true
76cde6d34c1a99e235e6c828c1aa0495810947ec
mossi1mj/SentenceValidator
/SentenceValidator.py
882
4.21875
4
import string # take in sentence as variable sentence = input("Enter a sentence: ") # take words in sentence and place in array[] with split() function word = sentence.split()[0] # first word in array will be 0 capitalWord = word.capitalize() # capitalize() function puts first character of a string to uppercase # check for capital letter in first word in sentence if word != capitalWord: print("This sentence does not begin with a capital letter.") # make the first word with a capital letter with replace() function sentence = sentence.replace(word, capitalWord) # check for punctuation mark at the end of sentence if not sentence[-1] in string.punctuation: # -1 is the last element in array using the punctuation() function print("This sentence does end with punctuation.") # add punctuation to sentence sentence = sentence + '.' print(sentence)
true
e9cf929eb3f418b403cbebf5b171db97ef597d76
alejogonza/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
316
4.125
4
#!/usr/bin/python3 """ 1-my_list """ class MyList(list): """ prints to stdout list in order """ def print_sorted(self): """ prints the list """ sorted_list = MyList() for item in self: sorted_list.append(item) print(sorted(sorted_list))
true
9ef602b0e1df3f4111037ecd84e1d78d5994fffb
wesenu/COP3035-CGS5935-Introduction-to-Programming-Using-Python
/myPrograms/Chapter_4_exerciseSolution/ex4_14.py
903
4.21875
4
###################################################### # 4.14 # ###################################################### rows = 7 for r in range (rows): for c in range (rows-r): print ('*', end = ' ') print() ##################################################### # end = ' ' means do not print a new line as print # function automatically prints a new line,adds space # at the end and next print will be printed after # this space on the same line..if no end = ' ' then # the cursor moves to next line on the screen ##################################################### # Note that print () at the 4th line is necessary # because it moves the screen to next line..end=' ' # prints a space after every iteration in column # we have c in range (row-r) because we want to ite- # rate this (inner loop) loop 7 times first and decr- #crease gradually
true
15f146f69ea979780ba6d2a9610f064e0c327cc8
wesenu/COP3035-CGS5935-Introduction-to-Programming-Using-Python
/loopExerciseStarter.py
382
4.1875
4
inputPIN = 0 validPIN = False userPIN = 9999 # for example use only ! inputPIN = int(input("Please enter your PIN -> ")) validPIN = (inputPIN == userPIN) while not validPIN: inputPIN = int(input("Please try again. Enter your PIN -> ")) validPIN = (inputPIN == userPIN) # know complement is true after loop exits # therefore the PIN entered is valid here
true
b8465312a69a2fcbe6aff158dbf9ec524b4c4efb
narru888/PythonWork-py37-
/進階/資料結構/Linked_List(鏈表).py
1,588
4.25
4
""" Linked-list的資料則散落在記憶體中各處,加入或是刪除元素只需要改變pointer即可完成, 但是相對的,在資料的讀取上比較適合循序的使用,無法直接取得特定順序的值(比如說沒辦法直接知道list[3]) """ # 節點 class ListNode: def __init__(self, data): # 資料內容 self.data = data # 下一個節點位置 self.next = None # 單向鏈表 class SingleLinkedList: def __init__(self): # 鏈表頭 self.head = None # 鏈表當前指標節點 self.cursor = None # 添加節點 def add_list_item(self, node): # 確認node為一節點對象 if not isinstance(node, ListNode): node = ListNode(node) # 第一個節點進來時,head和cursor都會指向它 if self.head is None: self.head = node else: # 第二之後的節點進來後,因為這時cursor還是指向上一個節點, # 所以cursor.next能指向新進來的節點(1->2, 2->3, ...) self.cursor.next = node # 讓指標節點指向至新節點 self.cursor = node link = SingleLinkedList() link.add_list_item(1) print(link.head.data, link.cursor.data) link.add_list_item(5) print(link.head.data, link.cursor.data) link.add_list_item(10) print(link.head.data, link.cursor.data) link.add_list_item(15) print(link.head.data, link.cursor.data) print("\n") cursor = link.head while cursor: print(cursor.data) cursor = cursor.next if cursor else None
false
783d97d8d3c3586668f7c39bb60093e5e69bbe7a
kuaikang/python3
/基础知识/3.面向对象/class.py
1,263
4.34375
4
class People: name = "我是类变量,所有实例共享" def __init__(self, name, age, phone): # 构造函数,在类被实例化的时候执行 self.name = name # 实例变量,为每个实例所独有 self.__age = age # 在变量前面加__,表明这是私有变量,可以通过方法访问私有变量 self.phone = phone def get_age(self): # 定义一个方法来访问私有变量 return self.__age p = People("tom", 23, "13912345678") # 通过构造函数实例化了一个对象,参数个数要一致 print("name:", p.name, ",phone:", p.phone) # print(p.age) #通过实例.属性的方式访问私有变量是会报错的 AttributeError: 'People' object has no attribute 'age' print(p.get_age()) # 通过调用方法取到私有变量 # 实例化时可以为实例赋予属性,还有在外面为实例添加属性 p.address = "苏州" print(p.address) # 可以删除实例的属性 del p.address # print(p.address) #这时打印p的address属性会报错 AttributeError: 'People' object has no attribute 'address' # 注意在类的内部,使用def关键字可以为类定义一个函数(方法),与一般函数定义不同,类方法必须包含参数self,且为第一个参数!
false
c22167ee72352ce55dfb2b3db6108857776f6c7c
lyannjn/codeInPlaceStanford
/Assignment2/hailstones.py
829
4.5
4
""" File: hailstones.py ------------------- This is a file for the optional Hailstones problem, if you'd like to try solving it. """ def main(): while True: hailstones() def hailstones(): num = int(input("Enter a number: ")) steps = 0 while num != 1: first_num = num # Even number if num % 2 == 0: num = num // 2 print(str(first_num) + " is even, so I take half: " + str(num)) # Odd number else: num = (num * 3) + 1 print(str(first_num) + " is odd, so I make 3n + 1: " + str(num)) steps += 1 print("This process took " + str(steps) + " steps to reach 1") print("") # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
true
83e0cd383f22f7f9483622e7df9acf195e790103
NithinRe/slipting_current_bill
/Power_Bill.py
1,043
4.15625
4
print("----------------Electricity Bill---------------------") x = int(input("what is cost of current : ")) y = int(input("Enter Number of units used : ")) z = x/y print("Each unit is charged as : ",z) print("-----------------------------------------------------") meter1 = int(input("First floor number of units used :")) First_floor = meter1*z print("first floor bill is : ",First_floor) a = int(input("Enter Number of members in First floor :")) c = First_floor/a print("In First floor Each member should pay : ",c) print("-----------------------------------------------------") meter2 = int(input("Second floor number of units used :")) Second_floor = meter2*z print("Second floor bill is : ",Second_floor) b = int(input("Enter Number of members in Second floor :")) d = Second_floor/b print("In Second floor Each member should pay : ",d) print("-----------------------------------------------------") print("Total Bill : ",First_floor+Second_floor) print("-------------THNAK YOU-------------------------------")
true
880b3b158b1f8e2b56d01ac8e6042cbd2d4b484a
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
589
4.40625
4
#!/usr/bin/python3 """ This function will print a square equal to the size given """ def print_square(size): """ This function will raise errors if an integer is not given as well as if the value is equal or less than zero. """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if isinstance(size, float) and size < 0: raise TypeError("size must be an integer") for i in range(size): for j in range(size): print("#", end="") print("")
true
ab396ea8fa83578e55ee4e24db98b4830749cc27
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_square.py
1,879
4.21875
4
#!/usr/bin/python3 """ this is the unittest file for the Base class """ import unittest from models.square import Square class SqrTest(unittest.TestCase): """ These are the unit tests for the base class """ def test_basics2(self): s = Square(1) self.assertEqual(s.width, 1) s = Square(1, 2) self.assertEqual(s.x, 2) def test_basics(self): s = Square(3, 3, 5) self.assertEqual(s.width, 3) self.assertEqual(s.height, 3) self.assertEqual(s.x, 3) self.assertEqual(s.y, 5) def test_negatives(self): """ this method tests for negative numbers in Rectangle """ with self.assertRaises(ValueError): b1 = Square(-1, 2, 3) with self.assertRaises(ValueError): b2 = Square(1, -2, 3) with self.assertRaises(ValueError): b3 = Square(1, 2, -3) def test_strings(self): """ this method tests for strings in Rectangle """ with self.assertRaises(TypeError): b1 = Square("1", 2, 3) with self.assertRaises(TypeError): b2 = Square(1, "2", 3) with self.assertRaises(TypeError): b3 = Square(1, 2, "3") def test_zero(self): """ this method tests if width and height are 0 """ with self.assertRaises(ValueError): b2 = Square(0, 2) def test_update(self): s = Square(1, 0, 0, 1) self.assertEqual(str(s), "[Square] (1) 0/0 - 1") s.update(1, 2) self.assertEqual(str(s), "[Square] (1) 0/0 - 2") s.update(1, 2, 3) self.assertEqual(str(s), "[Square] (1) 3/0 - 2") s.update(1, 2, 3, 4) self.assertEqual(str(s), "[Square] (1) 3/4 - 2") def test_area(self): s = Square(5, 5) self.assertEqual(s.area(), 25) if __name__ == '__main__': unittest.main()
true
4d3a8bef55942c0f3c4142e807f539ac5cfcda46
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
247
4.28125
4
#!/usr/bin/python3 """ This function appends a string to a file! """ def append_write(filename="", text=""): """ apppends to the end of a file then returns character count """ with open(filename, 'a') as f: return f.write(text)
true
978bad038ca358c0515806600ccd6bc92e53dfad
makpe80/Boot-camp
/7 lesson. Модуль 4. Модули и пакеты/code_examples/sphinx/ex_1.py
291
4.125
4
def say(sound:str="My")->None: """Prints what the animal's sound it. If the argument `sound` isn't passed in, the default Animal sound is used. Parameters ---------- sound : str, optional The sound the animal makes (default is My) """ print(sound)
true
0ab0a052a247fbcc29ad44ca7b05740eb65cd1f8
Taranoberoi/Practise
/List Less Than Ten.py
357
4.28125
4
# Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # write a program that prints out all the elements of the list that are less than 10. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [] # for i in a: # print("Value is ",i) # if i <= 10: # b.append(i) # else: # break # print(b)
true
463f9708d9e3cec7047f3541bc8f0b570b5b44dc
Taranoberoi/Practise
/10_LIST OVERLAP COMPREHESIONS.py
690
4.25
4
# This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way. # Take two lists, say for example these two:and write a program that returns a list that contains only the elements that are # common between the lists (without duplicates). Make sure your program works on two lists of different sizes. # Write this in one line of Python using at least one list comprehension. import random a = [] b = [] c = [] for i in range(10): a.append(random.randrange(1,15)) b.append(random.randrange(1,15)) for i in b: if i in a and i not in c: c.append(i) print(a) print(b) print(c)
true
92a0429afb21d39eb64817d068b73f229a608c09
Othielgh/Cisco-python-course
/5.1.11.7 - Palindromes.py
905
4.25
4
# Your task is to write a program which: # asks the user for some text; # checks whether the entered text is a palindrome, and prints result. # Note: # assume that an empty string isn't a palindrome; # treat upper- and lower-case letters as equal; # spaces are not taken into account during the check - treat them as non-existent; # there are more than a few correct solutions - try to find more than one. def paliCheck(): sentence = input('Please enter a text to check if it\'s a palindrome: ').lower() while not sentence: sentence = input('Please enter a text to check if it\'s a palindrome: ').lower() sentence = sentence.replace(' ', '') if str(sentence) == str(sentence)[::-1]: print('It\'s a palindrome!') elif sentence == '': print('Please enter something!') else: print('This is not a palindrome!') paliCheck()
true
a0a00cec203bbaaeee83a82db647317f2db296b3
Othielgh/Cisco-python-course
/5.1.11.11 - Sudoku.py
1,186
4.3125
4
# Scenario # As you probably know, Sudoku is a number-placing puzzle played on a 9x9 board. The player has to fill the board in a very specific way: # each row of the board must contain all digits from 0 to 9 (the order doesn't matter) # each column of the board must contain all digits from 0 to 9 (again, the order doesn't matter) # each of the nine 3x3 "tiles" (we will name them "sub-squares") of the table must contain all digits from 0 to 9. # If you need more details, you can find them here. # Your task is to write a program which: # reads 9 rows of the Sudoku, each containing 9 digits (check carefully if the data entered are valid) # outputs Yes if the Sudoku is valid, and No otherwise. # Test your code using the data we've provided. import random, numpy grid = numpy.zeros(shape=(9,9)) for r in range(0, 9, 1): for c in range(0, 9, 1): while True: x = random.randint(1,9) if x not in grid[r,:] and x not in grid[:,c]: grid[r,c] = x if c == 8: print(grid[r,:]) continue continue else: break
true
bb7cdb1c3423b10371a07d519035b7ddc0ec029f
havardnyboe/ProgModX
/2019/39/Oppgaver Funksjoner/Oppgave 6.py
315
4.125
4
def fibonacci(nummer): fib_liste = [0, 1] for i in range(nummer-1): nytt_nummer = fib_liste[-1]+fib_liste[-2] fib_liste.append(nytt_nummer) i = i+1 return print("Tall nummer", i+1, "er", fib_liste[-1]) tall_nummer = int(input("Hvilket tall nummer vil du se i fibonaccifølgen?: ")) fibonacci(tall_nummer)
false
fff52176408ddc67628b6c3707bc204363824ab8
greenfox-velox/oregzoltan
/week-04/day-3/09.py
476
4.125
4
# create a 300x300 canvas. # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def draw_square(s): x = 300/2-s/2 blue_box = canvas.create_rectangle(x, x, x+s, x+s, fill='blue') draw_square(80) draw_square(44) draw_square(10) root.mainloop()
true
38bf2fa152fbe028217728b502544ce1f5732432
greenfox-velox/oregzoltan
/week-04/day-3/11.py
751
4.125
4
# create a 300x300 canvas. # create a square drawing function that takes 2 parameters: # the square size, and the fill color, # and draws a square of that size and color to the center of the canvas. # create a loop that fills the canvas with rainbow colored squares. from tkinter import * import random root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def draw_square(size, color): x = 300/2-size/2 draw_box = canvas.create_rectangle(x, x, x+size, x+size, fill=color) for i in range(300, 1, -1): r1 = random.randrange(150, 255) r2 = random.randrange(16, 255) r3 = random.randrange(16, 150) r = '#' + str(hex(r1)[2:]) + str(hex(r2)[2:]) + str(hex(r3)[2:]) draw_square(i*10, r) root.mainloop()
true
ba4b735ad6b8404b5fd529fdf62be47e237cd33d
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex022.py
649
4.34375
4
''' Crie um programa que leia o nome completo de uma pessoa e mostre: - O nome com todas as letras maiúsculas e minúsculas. - Quantas letras ao todo (sem considerar espaços). - Quantas letras tem o primeiro nome. ''' #Recebendo informações: nome = input('Digite um nome: ') #Declarando variaveis: maiusculas = nome.upper() minusculas = nome.lower() quantidade_letras = len(nome) - nome.count(' ') primeiro_nome = len(nome.split()[0]) #Resultado: print('Seu nome em maiusculas: {}\nSeu nome em minusculas:{}\nSeu nome tem ao todo {} letras\nSeu primeiro nome tem {} letras'.format(maiusculas, minusculas, quantidade_letras, primeiro_nome))
false
532eea4a81fa3151ea92a0f3f00d9b0dc71bccb4
PedroSantana2/curso-python-canal-curso-em-video
/mundo-1/ex008.py
379
4.15625
4
''' Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. ''' #Recebendo valores: metros = float(input('Digite o valor em metros: ')) #Declarando variaveis centimetros = metros * 100 milimetros = metros * 1000 #Informando resultado: print('{} metros é: \n{} centímetros\n{} milímetros'.format(metros, centimetros, milimetros))
false
7a9084979864dc2e1bc3a23b964d8d9790370ee5
haveano/codeacademy-python_v1
/05_Lists and Dictionaries/02_A Day at the Supermarket/13_Lets Check Out.py
1,142
4.3125
4
""" Let's Check Out! Perfect! You've done a great job with lists and dictionaries in this project. You've practiced: Using for loops with lists and dictionaries Writing functions with loops, lists, and dictionaries Updating data in response to changes in the environment (for instance, decreasing the number of bananas in stock by 1 when you sell one). Thanks for shopping at the Codecademy supermarket! Instructions Click Save & Submit Code to finish this course. """ shopping_list = ["banana", "orange", "apple"] stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } # Write your code below! def compute_bill(food): total=0 for x in food: # print x if x in stock and stock[x]>0: print "jest", stock[x], "sztuk", x total=total+prices[x] stock[x]=stock[x]-1 else: print "nie ma",x return total zakupy=["banana","gowno","kupa","apple"] print stock print compute_bill(zakupy),"$" print compute_bill(shopping_list) print stock #print stock.keys()
true
97ce0591bd0ed48a9918db96043117d016f3cc06
haveano/codeacademy-python_v1
/11_Introduction to Classes/02_Classes/08_Modifying member variables.py
1,115
4.375
4
""" Modifying member variables We can modify variables that belong to a class the same way that we initialize those member variables. This can be useful when we want to change the value a variable takes on based on something that happens inside of a class method. Instructions Inside the Car class, add a method drive_car() that sets self.condition to the string "used". Remove the call to my_car.display_car() and instead print only the condition of your car. Then drive your car by calling the drive_car() method. Finally, print the condition of your car again to see how its value changes. """ class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): print "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg) def drive_car(self): self.condition="used" my_car = Car("DeLorean", "silver", 88) #print my_car.condition #print my_car.model #print my_car.color #print my_car.mpg print my_car.condition my_car.drive_car() print my_car.condition
true
d2b8e32208cd60547fb0ce5e786064a1d4a17906
haveano/codeacademy-python_v1
/12_File Input and Output/01_File Input and Output/05_Reading Between the Lines.py
847
4.4375
4
""" Reading Between the Lines What if we want to read from a file line by line, rather than pulling the entire file in at once. Thankfully, Python includes a readline() function that does exactly that. If you open a file and call .readline() on the file object, you'll get the first line of the file; subsequent calls to .readline() will return successive lines. Instructions Declare a new variable my_file and store the result of calling open() on the "text.txt" file in "r"ead-only mode. On three separate lines, print out the result of calling my_file.readline(). See how it gets the next line each time? Don't forget to close() your file when you're done with it!) """ my_file=open("text.txt","r") print my_file.readline() print my_file.readline() print my_file.readline() print my_file.readline() print my_file.readline() my_file.close()
true
e988e9f53a578404a3c6c4b81174c704f395f19c
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/02_Introduction to Bitwise Operators/04_The bin() Function.py
1,150
4.65625
5
""" The bin() Function Excellent! The biggest hurdle you have to jump over in order to understand bitwise operators is learning how to count in base 2. Hopefully the lesson should be easier for you from here on out. There are Python functions that can aid you with bitwise operations. In order to print a number in its binary representation, you can use the bin() function. bin() takes an integer as input and returns the binary representation of that integer in a string. (Keep in mind that after using the bin function, you can no longer operate on the value like a number.) You can also represent numbers in base 8 and base 16 using the oct() and hex() functions. (We won't be dealing with those here, however.) Instructions We've provided an example of the bin function in the editor. Go ahead and use print and bin() to print out the binary representations of the numbers 2 through 5, each on its own line. """ print " ### BINy ### " print bin(1) print bin(2) print bin(3) print bin(4) print bin(5) print bin(6) print bin(7) print " ### HEXy ### " print hex(54) print " ### OCTy ### " print oct(7) print oct(9) print oct(15) print oct(17)
true
572f9b19515b5f46c03ddafedb0f93b37b13a49e
haveano/codeacademy-python_v1
/08_Loops/02_Practice Makes Perfect/03_is_int.py
1,183
4.21875
4
""" is_int An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not). For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0. This means that, for this lesson, you can't just test the input to see if it's of type int. If the difference between a number and that same number rounded down is greater than zero, what does that say about that particular number? Instructions Define a function is_int that takes a number x as an input. Have it return True if the number is an integer (as defined above) and False otherwise. For example: is_int(7.0) # True is_int(7.5) # False is_int(-1) # True """ import math def is_int(x): #if type(x)==int: #if math.floor(x)==x: # też działa, ale math.trunc() lub inc() jest lepsze if math.trunc(x)==x: #if int(x)==x: return True else: return False print is_int(-2.3) print is_int(-2.7) print is_int(1.9999999999999999) # HAHAHA """ print math.trunc(-2.3) print math.trunc(-2.7) print math.floor(-2.3) print math.floor(-2.7) print int(-2.9) print int(-2.1) """
true
6876089ff1413f4e3bc30adecefa91b75a59e006
haveano/codeacademy-python_v1
/07_Lists and Functions/01_Lists and Functions/11_List manipulation in functions.py
594
4.34375
4
""" List manipulation in functions You can also append or delete items of a list inside a function just as if you were manipulating the list outside a function. my_list = [1, 2, 3] my_list.append(4) print my_list # prints [1, 2, 3, 4] The example above is just a reminder of how to append items to a list. Instructions Define a function called list_extender that has one parameter lst. Inside the function, append the number 9 to lst. Then return the modified list. """ n = [3, 5, 7] # Add your function here def list_extender(lst): lst.append(9) return lst print list_extender(n)
true
15f47141d90b1e773ff194272ae57c357f3572b4
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/02_Introduction to Bitwise Operators/09_This XOR That.py
1,487
4.15625
4
""" This XOR That? The XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both. a: 00101010 42 b: 00001111 15 ================ a ^ b: 00100101 37 Keep in mind that if a bit is off in both numbers, it stays off in the result. Note that XOR-ing a number with itself will always result in 0. So remember, for every given bit in a and b: 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 Therefore: 111 (7) ^ 1010 (10) = 1101 (13) Instructions For practice, print the result of using ^ on 0b1110 and 0b101 as a binary string. Try to do it on your own without using the ^ operator. """ #print bin(0b1110 or 0b101) # FIRST METHOD: #print bin(0b1110 ^ 0b101) # SECOND METHOD: def policz_xor (a,b): c=["0","b"] lena=len(list(str(bin(a)))) lenb=len(list(str(bin(b)))) lista=list(str(bin(a))) listb=list(str(bin(b))) lista=lista[2:] listb=listb[2:] diff=abs(lena-lenb) if lena<=lenb: lista=["0"]*diff+lista lenc=len(lista) else: listb=["0"]*diff+listb lenc=len(listb) for x in range(lenc): if (((lista[x]=="1") and (listb[x]=="1")) or ((lista[x]=="0") and (listb[x]=="0"))): c.append("0") else: c.append("1") return "".join(c) print policz_xor(0b1110,0b101) print policz_xor(0b1110,0b10110)
true
4b1a907a1f05d61a2904551c34cfc20e1a733840
haveano/codeacademy-python_v1
/08_Loops/01_Loops/13_For your lists.py
625
4.78125
5
""" For your lists Perhaps the most useful (and most common) use of for loops is to go through a list. On each iteration, the variable num will be the next value in the list. So, the first time through, it will be 7, the second time it will be 9, then 12, 54, 99, and then the loop will exit when there are no more values in the list. Instructions Write a second for loop that goes through the numbers list and prints each element squared, each on its own line. """ numbers = [7, 9, 12, 54, 99] print "This list contains: " for num in numbers: print num # Add your loop below! for x in numbers: print x*x
true
758a91bf1eefd576051c24401423f4c6578180fa
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/06_Pop Quiz.py
603
4.21875
4
""" Pop Quiz! When you finish one part of your program, it's important to test it multiple times, using a variety of inputs. Instructions Take some time to test your current code. Try some inputs that should pass and some that should fail. Enter some strings that contain non-alphabetical characters and an empty string. When you're convinced your code is ready to go, click Save & Submit to move forward! """ print 'Welcome to the Pig Latin Translator!' # Start coding here! original = raw_input("enter a word:") if len(original)>0 and original.isalpha(): print original else: print "empty"
true
6efae81bdbee61a5e960c0bce1039a31a48c3bb2
haveano/codeacademy-python_v1
/11_Introduction to Classes/01_Introduction to Classes/03_Classier Classes.py
967
4.46875
4
""" Classier Classes We'd like our classes to do more than... well, nothing, so we'll have to replace our pass with something else. You may have noticed in our example back in the first exercise that we started our class definition off with an odd-looking function: __init__(). This function is required for classes, and it's used to initialize the objects it creates. __init__() always takes at least one argument, self, that refers to the object being created. You can think of __init__() as the function that "boots up" each object the class creates. Instructions Remove the pass statement in your class definition, then go ahead and define an __init__() function for your Animal class. Pass it the argument self for now; we'll explain how this works in greater detail in the next section. Finally, put the pass into the body of the __init__() definition, since it will expect an indented block. """ class Animal(object): def __init__(self): pass
true
3c6f0c6039e2a9d52e415b7b235adda8f27bb3e6
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/01_Break It Down.py
677
4.25
4
""" Break It Down Now let's take what we've learned so far and write a Pig Latin translator. Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes "ythonpay." To write a Pig Latin translator in Python, here are the steps we'll need to take: Ask the user to input a word in English. Make sure the user entered a valid word. Convert the word from English to Pig Latin. Display the translation result. Instructions When you're ready to get coding, click Save and Submit. Since we took the time to write out the steps for our solution, you'll know what's coming next! """ raw_input("Wpisz text po andgielsku: ")
true
26c8ad332a82464bb4e423fc0f801e8f709297f0
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/09_Move it on Back.py
672
4.21875
4
""" Move it on Back Now that we have the first letter stored, we need to add both the letter and the string stored in pyg to the end of the original string. Remember how to concatenate (i.e. add) strings together? greeting = "Hello " name = "D. Y." welcome = greeting + name Instructions On a new line after where you created the first variable: Create a new variable called new_word and set it equal to the concatenation of word, first, and pyg. """ pyg = 'ay' original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): print original word=original.lower() first=word[0] new_word=word+first+pyg else: print 'empty'
true
ed920d881c1a5fa00c6137a741e648894730e987
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/01_Advanced Topics in Python/04_Building Lists.py
672
4.625
5
""" Building Lists Let's say you wanted to build a list of the numbers from 0 to 50 (inclusive). We could do this pretty easily: my_list = range(51) But what if we wanted to generate a list according to some logic—for example, a list of all the even numbers from 0 to 50? Python's answer to this is the list comprehension. List comprehensions are a powerful way to generate lists using the for/in and if keywords we've learned. Instructions Check out the list comprehension example in the editor. When you're pretty sure you know what it'll do, click Save & Submit Code to see it in action. """ evens_to_50 = [i for i in range(51) if i % 2 == 0] print evens_to_50
true
87476d33bbd28688c9eca22541842eda77c5cf44
Akash2918/PPL
/Assignment1/q9.py
903
4.28125
4
print("\nFinding first 10 Harmonic Divisor Numbers :\n") """def floating(n) : x = 1 s = 0 for i in n : x = x * i for i in n: s = s + x/i print("The value of s is : ", s) return s/x """ def calculate(n) : # function that calculates harmonic sum and returns its division with total number of divisors s = 0 x = 0 for i in n : x = x + 1 s = s + 1.0/ i #s = floating(n) #print(s) s = x/s #print(s) return s def harmonic(x) : # function which calculates divisors of numbers and stores into list m = [] i = 1 while i <=x : if x % i == 0 : m.append(i) i = i + 1 #print(m) y = calculate(m) #print('The value of y is :', y) # the type of y is float #print(y) y = y * 10 # converting y into int if y % 10 == 0 : return True else : return False x = 1 n = 1 while n <= 10 : if harmonic(x) : print(x) n = n + 1 x = x + 1 else : x = x + 1
false
e0b4e15b11963d9db6e8640a210f4740888bc11b
liuleee/python_base
/day02/10-for循环的使用.py
982
4.3125
4
# -*- coding:utf-8 -*- #获取容器类型(字符串,列表,元组,字典,set)中每个数据使用for循环最简单 # my_str = 'abc' # for value in my_str: # print(value) # my_list = ['apple','peach','banana','pearl'] # for value in my_list: # print(value) #循环遍历的时候下标和数据都需要,可以使用enumerate my_list = enumerate(['apple','peach','banana','pearl']) # for value in my_list: # print(value[0],value[1]) #index,value获取的是列表中的每一个值,就是拆包 for index,value in my_list: print(index,value) #取下标神器enumerate for value in enumerate((1,5)): print(value) #遍历数据的时候需要下标可以通过enumerate #默认遍历是key my_dict = {'name':'zhang','age':18} # for key in my_dict: # print(key,my_dict[key]) #其实遍历的是每一项字典中的键值对 for key,value in my_dict.items(): print(key,value) my_set = {1,5,7} for value in my_set: print(value)
false
eba7e07b2ee51b4c70ed829acde256362afc7494
liuleee/python_base
/day01/06-数据类型转换.py
556
4.21875
4
# -*- coding: utf-8 -*- num = 10 my_str = '10' # 把字符串转为int类型 num2 = int(my_str) # print(type(num2)) s = num + num2 # print(s) my_float_str = '3.14' print(type(my_float_str)) num3 = float(my_float_str) print(type(num3)) num4 = 4.55 # 浮点数转int型时,只取整数 num5 = int(num4) print(num5) # eval:获取字符串中的 原始 数据 my_str = '5' value = eval(my_str) print(value) print(type(value)) #int类型和float类型计算时int类型会转换成float类型 result = num + num3 print(result) ''' day01 : 55:09 '''
false
2b229803bcb9a175dac4b1b85e2b712c77adba7c
ankitandel/function.py
/4h.py
311
4.1875
4
# write a python program to print the even numbers from a given list.[1,2,3,4,5,6,7,8,9] def is_even_num(b): i=0 while i<=len(b): if i%2==0: print("even number",i,end="") else: print("odd number",i) i=i+1 b=[1,2,3,4,5,6,7,8,9] is_even_num(b)
true
21cced07ce4cf5abbcf22728b0a885585101320c
kavisha-nethmini/Hacktoberfest2020
/python codes/DoubleBasePalindrome.py
733
4.15625
4
#Problem statement: The decimal number, 585 is equal to 1001001001 in binary. #And both are palindromes. Such a number is called a double-base palindrome. #Write a function that takes a decimal number n and checks if it's binary equivalent and itself are palindromes. #The function should return True if n is a double-base palindrome or else it should return False. #Input: Integer #Output: Boolean value #Sample Input: 585 #Sample Output: True #code starts from here def check_Palindrome(n): n = str(n) rev = n[::-1] if n == rev: return True return False def isDoubleBasePalindrome(n): b = str(bin(n)[2:]) if check_Palindrome(n) and check_Palindrome(b): return True return False
true
c62b24ca62cf6b7a6ef94b4a774b00c2c07b3561
wancongji/python-learning
/lesson/26/duixiang.py
739
4.46875
4
class MyClass: """ A example class """ x = 'abc' # 类属性 def __init__(self): # 初始化 print('init') def foo(self): # 类属性foo,也是方法 return "foo = {}".format(self.x) class Person: x = 'abc' def __init__(self, name, age=18): self.name = name self.y = age def show(self, x, y): self.x = x self.y = y return self.x, self.y # mycls = MyClass() # 实例化,初始化 a = Person('tom') b = Person('jerry', 20) print(a.__class__, b.__class__) print(a.__class__.__qualname__, b.__class__.__name__) print(sorted(Person.__dict__.items()), end='\n\n') print(a.__dict__) print(b.__dict__) print(isinstance(b, a.__class__))
false
5e94315bfe25f3afe469c6baacb18f0d123decde
piupom/Python
/tuplePersonsEsim.py
2,212
4.71875
5
# It is often convenient to bundle several pieces of data together. E.g. if the code processes information about people, then each person's information (name, age, etc.) could be bundled. This can be done in a naive manner with e.g. a tuple (also shown below), but classes provide a more convenient way. A class definition defines a new data type that can have several attributes (named pieces of data) and/or member functions. A variable whose type is a class is called an object. If x is an object, then the notation x.y refers to the attribute y (or member function) of x. # A tuple that represents a person's name, age and height. personTuple = ("John Doe", 45, 180) # A class meant for representing a person. This is a minimal class: # the body is left empty (the pass-statetement is a place-holder that # does not do anything; Python syntax does not allow a literally empty body). class Person: pass # An object of class X can be created with the notation X(parameters), # where parameters may or may not be required (depends on the class). # Python classes by default allow to "define" new attributes on-the-fly, # that is, attributes do not need to be predefined by the class definition. # Below we set values into the attributes name, age and height of personObject. personObject = Person() personObject.name = "Tom Cruise" personObject.age = 50 personObject.height = 165 personObject.weight = 75 # Printing out the type of personObject reveals that it is of type # class Person. print(type(personObject)) # One of the reasons why the naive tuple-representation of a person # is awkward: we need to remember which index corresponds to which # attribute, which is prone to accidental programming errors. # As an example, this function prints out a person's attributes. def printPersonTuple(person): print("Name is", person[0]) print("Age is", person[1]) print("Height is", person[2]) # A similar function as above, but using the Person-class. Named # attribute references are much more readable. def printPersonObject(person): print("Name is", person.name) print("Age is", person.age) print("Height is", person.height) printPersonTuple(personTuple) print() printPersonObject(personObject)
true
e8b3807b0f9d38fe7b554e73c91797fd8e13b062
piupom/Python
/classFunctionsPersonsEsim.py
1,538
4.40625
4
# Classes have also other "special" functions. One common is __str__, which defines how to represent the object in string format (e.g. what is printed out if the object is passed to the print-function). Here we transform the printPersonObject-function from above into a __str__-member function. Now Person-objects can be printed directly with print. class Person: def __init__(self, name="", age=0, height=0, weight=0): self.name = name self.age = age self.height = height self.weight = weight def bmi(self): return self.weight/((self.height/100) ** 2) # If p is a Person-object, then the string-transformation call str(p) # will result in calling this __str__ -function. The function implementation # should return a string. Here we use also string formatting to set the # number of printed decimals. # Note: the way the string is split on several lines here works because the # strings are enclosed within parentheses. def __str__(self): return ("Name is {:s}\n" "Age is {:d}\n" "Height is {:.1f}\n" "Weight is {:.1f}\n" "BMI is {:.2f}").format( self.name, self.age, self.height, self.weight, self.bmi()) tc = Person(weight=67, name="Tom Cruise", age=56, height=170) dt = Person("Donald Trump", 72, 188, 105) # These print-calls will print the strings returned by tc.__str__() and # dt.__str__(), respectively. print(tc) print() print(dt) # A side-note: the dir-function lists all attributes/functions of a class object. print(dir(dt))
true
8b746ca827fa6e652e2d5bc47eb897abe74a0cd0
projectsMuiscas/avangers
/funcionesTuplas.py
1,604
4.21875
4
# devolviendo varios valores desde una funcion def estadisticas_basicas (operado , operando): suma = operado + operando resta = operado - operando multi = operado * operando res = (suma,resta,multi) return res mysuma , myresta , mymulti = estadisticas_basicas (2 ,2) print (mysuma , ';' , myresta , ';' , mymulti) # funciones anidadas def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner con esto nos ahorramos procesamiento de computo ya que a word1,2,3 los operamos en #una funcion interna def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2),inner(word3)) # Call three_shouts() and print print(three_shouts('a', 'b', 'c')) '''""" RETORNAR FUNCIONES """''' # Define echo def echo(n): """Return the inner_echo function.""" # Define inner_echo def inner_echo(word1): """Concatenate n copies of word1.""" echo_word = word1 * n return echo_word # Return inner_echo return (inner_echo) # ESTAMOS RETORNANDO LA FUNCION # Call echo: twice twice = echo(2) # ASIGNAMOS A ESTE OBJ LA FUNCION PRINCIPAL # Call echo: thrice thrice = echo(3) # Call twice() and thrice() then print print(twice('hello'), thrice('hello')) ##INTERESNATE LE MANDAMOS A LAS VAR ES EL ARGUMENTO DE LA FUNCION HIJA ## VARIABLES NONLOCAL Y GLOBAL IMPORTANTE APRENDER PARA EL SCPOE DE LA VARIABLE
false
923a822bb263814d9af788e325e228cfba233894
roblivesinottawa/intermediate_100_days
/day_twentythree/turtle_crossing/carmanager.py
1,631
4.21875
4
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 # create a class and methods to manage the movement of the cars class CarManager: def __init__(self): # create a variable to store all cars and set it to an empty list self.all_cars = [] # create a varaible that will set the starting speed of the cars self.car_speed = STARTING_MOVE_DISTANCE # this method will create cars along the y line # and set the properties for the cars def create_car(self): # create less cars random_chance = random.randint(1, 6) if random_chance == 1: new_car = Turtle("square") # this will stretch the turtle new_car.shapesize(stretch_wid=1, stretch_len=2) new_car.penup() new_car.color(random.choice(COLORS)) # define where it's going to go on the screen yrandom = random.randint(-250, 250) # cars will go to the very edge of the screen new_car.goto(300, yrandom) # then it will be added to the list of all cars self.all_cars.append(new_car) # create a new method to move all cars def move_cars(self): # FOR EACH OF THE CARS IN THE LIST for car in self.all_cars: # each car will be moved by the distance stored in the variable car.backward(self.car_speed) # create a method that will increase the speed of the cars by 10 once at the end line def level_up(self): self.car_speed += MOVE_INCREMENT
true
690574f888f0c7a65aef7402f12c56e5a928e7dd
twopiharris/230-Examples
/python/basic3/nameGame.py
533
4.25
4
""" nameGame.py illustrate basic string functions Andy Harris """ userName = input("Please tell me your name: ") print ("I will shout your name: ", userName.upper()) print ("Now all in lowercase: ", userName.lower()) print ("How about inverting the case? ", userName.swapcase()) numChars = len(userName) print ("Your name has", numChars, "characters") print ("Now I'll pronounce your name like a cartoon character:") userName = userName.upper() userName = userName.replace("R", "W") userName = userName.title() print (userName)
true
7d88f2a2dff5286c80d7fcf9a03fd70b9162f42f
twopiharris/230-Examples
/python/basic3/intDiv.py
443
4.53125
5
""" integer division explains integer division in Python 3 """ #by default, dividing integers produces a floating value print("{} / {} = {}".format(10, 3, 10 / 3)) #but sometimes you really want an integer result... #use the // to force integer division: print("{} // {} = {}".format(10, 3, 10 // 3)) #integer division is incomplete. Use modulus (%) for remainder print("{} / {} = {} remainder {}".format(10, 3, 10 // 3, 10 % 3))
true
172bca8ed49127e5baa1a23dd7795a19c3c7d984
willl4/mathproject
/functionAnalysisProgram.py
2,532
4.15625
4
""" function = input('Enter a function: ') func = function.split('x^') for temp in func: print(temp) """ if __name__ == '__main__': data = {} data['coefficients'] = '' data['derivative'] = '' function = int(input('Choose highest power in function: ')) power = function while function >= 0: coefficient = int(input('Enter the coefficient for the x^'+str(function)+' term: ')) data['coefficients'] = data['coefficients']+str(coefficient) function = function-1 list1 = data['coefficients'].split() for i in range(0,len(data['coefficients'])): derivativecoeff = int(data['coefficients'][i])*power while power > 1: data['derivative'] = data['derivative']+str(derivative) if power = 1: data['derivative'] = data['derivative'] + derivative = str(derivativecoeff)+'x^'+str(power-1)+'+' power+=-1 data['derivative'] = data['derivative']+str(derivative) print(data['derivative']) """ function = int(input('Choose highest power in function: ')) if function == 1: coefficient1 = int(input('Enter the coeffecient for the x^1 term: ')) coefficient = int(input('Enter the constant: ')) elif function == 2: coefficient2 = int(input('Enter the coeffecient for the x^2 term: ')) coefficient1 = int(input('Enter the coeffecient for the x^1 term: ')) coefficient = int(input('Enter the constant: ')) elif function == 3: coefficient3 = int(input('Enter the coeffecient for the x^3 term: ')) coefficient2 = int(input('Enter the coeffecient for the x^2 term: ')) coefficient1 = int(input('Enter the coeffecient for the x^1 term: ')) coefficient = int(input('Enter the constant: ')) elif function == 4: coefficient4 = int(input('Enter the coeffecient for the x^4 term: ')) coefficient3 = int(input('Enter the coeffecient for the x^3 term: ')) coefficient2 = int(input('Enter the coeffecient for the x^2 term: ')) coefficient1 = int(input('Enter the coeffecient for the x^1 term: ')) coefficient = int(input('Enter the constant: ')) elif function == 5: coefficient5 = int(input('Enter the coeffecient for the x^5 term: ')) coefficient4 = int(input('Enter the coeffecient for the x^4 term: ')) coefficient3 = int(input('Enter the coeffecient for the x^3 term: ')) coefficient2 = int(input('Enter the coeffecient for the x^2 term: ')) coefficient1 = int(input('Enter the coeffecient for the x^1 term: ')) coefficient = int(input('Enter the constant: ')) """
false
92fc4e3107ecedca5a04673bd9b62e2c03a336e7
davidtscott/CMEECoursework
/Week2/Code/tuple.py
1,329
4.53125
5
#!/usr/bin/env python3 # Date: October 2018 """ Extracts tuples from within a tuple and outputs as seperate lines """ __appname__ = '[tuple.py]' __author__ = 'David Scott (david.scott18@imperial.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code/program" birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) # Birds is a tuple of tuples of length three: latin name, common name, mass. # write a (short) script to print these on a separate line or output block by species # Hints: use the "print" command! You can use list comprehension! # ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING! # ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT # SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS # for every tuple in object birds, print # for tuple in birds: # print(tuple) # print("") birdlist = [print(i,"\n") for i in birds] # this prints each tuple seperately, seperated by blank line as opposed to # printing entire block as would happen just used 'birds' # OR #for tuple in birds: # print(tuple[0]) # print(tuple[1]) # print(tuple[2]) # print(" ")
true
2ee1ecec1a2b53884a259649b6f59281ffd118cc
MurilloFagundesAS/Exercicios-Resolvidos-Curso-em-Video
/Aula17-Listas1.py
1,541
4.34375
4
lista = [1,2,3] # lista vazia : lista = [] ou lista = list() print(lista) i = 1 lista2 = [] while i <= len(lista): lista2.append(lista.index(i)) lista2.append(lista[i]) i+=1 print(lista2) # lista.append('append') # Adiciona no final da lista # # print(lista) # # # # lista.insert(1,'insert') # Adiciona entre os elementos da lista # # print(lista) # # # # # Todos os casos reposicionam o indice da lista # # del lista[3] # Deleta # # print(lista) # # # # lista.pop(3) # Deleta, usado normalmente para eliminar o último elemento # # print(lista) # # lista.pop() # # print(lista) # # # # lista.remove(1) # Deleta o elemento indicado, mas só a primeira ocorrência # # print(lista) # # # # # list é função pra declarar lista # # lista = list(range(1,11)) # # print(lista) # # # # lista.sort(reverse=True) # parametro reverse inverte # # print(lista) # # # # lista.sort() # sort organiza a lista por ordem alfabetica/númerica crescente # # print(lista) # # # # print(len(lista)) # a função len dá a quantidade de itens numa lista # # # # for posicao, valor in enumerate(lista): # enumerate dá o indice e o elemento da lista # # print(f'Na posição {posicao} encontra-se o valor {valor}!') # # # # for num in range(0,4): # # lista.append(int(input('Digite um valor: '))) # # print(lista) # # # listaB = lista # no Python, listas estão interligadas se forem igualadas # print(listaB) # # listaC = lista[:] # no Python, nesse caso, só copiei a lista e seus elementos # listaC[7] = 1010 # print(listaC)
false
c88471e4498d8ee9343434e29b1a58d1e1732715
MurilloFagundesAS/Exercicios-Resolvidos-Curso-em-Video
/Ex025-FindSilva.py
237
4.1875
4
nome = str(input("Qual o Seu nome? ")) teste = nome.find('Silva') if teste != -1: print('Você tem Silva no nome!') else: print('Você não tem Silva no nome!') #print('Você tem Silva no nome? '.format('SILVA' in nome.upper))
false
873879f49529cc6abfb81cb3258aa8fb431b1ca5
Sahana-Chandrashekar/infytq
/prg23.py
493
4.25
4
''' Write a python function to find out whether a number is divisible by the sum of its digits. If so return True,else return False. Sample Input Expected Output 42 True 66 False ''' #PF-Prac-23 def divisible_by_sum(number): temp = number s = 0 while number != 0: rem = number%10 s += rem number = number//10 if temp%s == 0: return True else: return False number=25 print(divisible_by_sum(number))
true
ab049e9c3ef3aeba3146f3e2ee2072b9e9422353
xiaoloinzi/worksplace
/GR1/meiriyilian/day_0818.py
2,704
4.1875
4
# encoding=utf-8 # 【python每日一练】实现一个购物车功能,商品属性只需要包括名称,数量,价格, # 要求实现添加一个商品,删除一个商品,最终打印订单详情和总价格 ''' 1、写一个购物车的类,属性有商品名称,数量,价格,然后实现添加商品,删除商品、打印订单详情的方法 2、定义一个字典的数据结构进行存储数据,要判断输入的商品是否存在,存在则提示并不保存 ''' dict1 = {} class Shopping(object): def __init__(self,product_name= None,price= None,quantity= None): self.product_name = product_name self.price = price self.quantity = quantity def addProduct(self): if self.product_name == None or self.price == None or self.quantity == None: return "product_name or price or quantity can not be empty not be empty!" if dict1.has_key(self.product_name): num = raw_input("The goods you have entered have been added to the shopping cart, whether to modify!(Y/N)") if num == "Y" or num == "y": dict1[self.product_name] = [self.price,self.quantity] else: dict1[self.product_name] = [self.price,self.quantity] def deleteProduct(self): if self.product_name == None or self.price == None or self.quantity == None: return "product_name or price or quantity can not be empty not be empty!" if not self.price.isdigit() and not self.quantity.isdigit(): return "Price or quantity entered incorrectly" if dict1.has_key(self.product_name): del dict1[self.product_name] else: num = raw_input("The item you entered does not exist") if __name__=="__main__": stration = "" while True: stration = raw_input("Please enter the goods you want to buy and the price and quantity, separated by commas") if stration == "quit": break num = int(raw_input("Do you need to add a product or delete a product?(1-add;2--delete)")) stration = stration.split(',') if len(stration) == 3: product = Shopping(stration[0],stration[1],stration[2]) if num == 1: product.addProduct() elif num == 2: product.deleteProduct() elif num != 1 and num != 2: print "Sorry, the operation you entered does not exist, please start from scratch" else: print "The information you entered is incomplete" print u'商品名称'+'\t'+u'价格'+'\t'+u'数量' for i,j in dict1.items(): print i+'\t\t'+j[0]+'\t\t'+j[1]
false
88ab6d0234b210119fda15fe508a7fc65d0b94ab
Brijesh739837/Mtechmmm
/arrayinput.py
242
4.125
4
from array import * arr=array('i',[]) # creates an empty array length = int(input("enter the no of students")) for i in range(length): n = int(input("enter the marks of students")) arr.append(n) for maria in arr: print(maria)
true
8b744ce1431081f48d0e6cdddd414d8a6ec1604a
Brijesh739837/Mtechmmm
/numpyoperation.py
1,016
4.15625
4
from numpy import * import time arr = array([1,2,3,4,5]) arr = arr+10 print(arr) arr =arr *5 print(arr) arr1 = array([1,2,3,4,5]) arr2 = array([1, 2, 3, 4, 5]) arr3 = arr1 + arr2 print(arr3) print(concatenate([arr1,arr2])) ''' copy an array to another arrray''' ''' aliasing ''' arr4 = arr1 print(arr4) print(id(arr4)) print(id(arr1)) ''' copy ''' ''' what if you want to create a different array with same content''' print('what if you want to create a different array with same content') arr5= arr1.view() print(arr5) print(id(arr5)) print(id(arr1)) ''' shallow copy exp''' arr5[4]=50000 print(arr5) print(arr1) ''' shallow copy''' print('shallow copy') arr1[1] =500 print(arr1) print(arr4) ''' "if we change in another then change occurs in both"''' arr4[0]=6000 print(arr4) print(arr1) ''' deep copy''' print('Deep copy') arr6= array([4,5,8,9,7,8]) arr7 = arr6.copy() print(arr7) print(arr6) print(id(arr6)) print(id(arr7)) arr6[3]=45555 print(arr6) print(arr7) print('aa') print(min([arr6]))
false
940c2f06be34dad6d306f1ca73f664f0d496bbc0
Brijesh739837/Mtechmmm
/stringmaniexp.py
797
4.28125
4
'''x= input("enter your name") name= x a= len(name) print(a) print(name.capitalize()) print(name.lower()) print(name.upper()) print(name.swapcase()) print(name.title()) print(name.isdigit()) print(name.isalpha()) print(name.islower()) print(name.isupper()) print(name.isalnum()) str = input("enter a string") print(str) find=input("enter the string u want to find") print(find) print(str.find('a')) rep=input("enter the string u want to replace") print(rep) print(str.replace(find,rep)) str1="hello how r u" print(str1) print(str1.count('h')) print(str1.endswith('ufd')) print(str1.replace('r','are'))''' x= input("enter your name") print(x) print(x.split(',')) str3=" Ram " print(str3) print(str3.lstrip(),"fdfdfd") print(str3.rstrip(),"fdfdfd") print(str3.strip(),"fdfdfd")
false
56dfa6e4d1b0ef316cac9de3ad21287f69d0e854
omostic21/personal-dev-repo
/guesser_game.py
1,433
4.1875
4
#I wrote this code just to play around and test my skils #Author: Omolola O. Okesanjo #Creation date: December 10, 2019 print("Welcome to the Number Guessing game!!") x = input('Press 1 to play, press 2 for instructions, press 3 to exit') x = int(x) if x == 2: print("The computer will pick a number within the specified range that you give it. Try to predict the computer's number. If you didn't get the number but you are close to getting it, the computer will give you a second try; If not, you fail!") y = input("Preass 1 to play or 3 to exit") x = int(y) if x == 3: exit if x == 1: num_range = int(input("What is the range you want to guess from?")) #To import random module import random rnumb = random.randrange(num_range) your_numb = int(input('Please type a number from 0 to ' + str(num_range))) diff = your_numb - rnumb diff = abs(diff) tolerance = int(num_range * 0.45) if diff == 0: print('Hooray!! You Win; The number was ' + str(rnumb)) elif diff <= tolerance: print("You're within range, I'll give you one last chance") last_chance = int(input()) diff2 = last_chance - rnumb if abs(diff2) == 0: print('Hooray!! You Win') else: print("Sorry, Better luck next time! " + "The number was " + str(rnumb)) else: a= "You fail!!! The number was {}" print(a.format(str(rnumb)))
true
24a0066c1f6d87c37cf15b81eb59f28c199997f8
cgarey2014/school_python_projects
/garey3/program3_3.py
1,175
4.21875
4
# Chris Garey #2417512 # This is original work by me, there are no other collaborators. # Begin Prog # Set the initial answer counter to zero # Ask the first question, count one point if correct and no points if wrong. # Ask the second question, count one point if correct and no points if wrong. # Ask the third question, count one point if correct and no points if wrong. # Calculate the total points # Sets answer counter to zero correct_answers = 0 #Starts the quiz with the first question ounces = int(input('How many ounces are in 1 measuring cup? ')) if ounces == 8: correct_answers += 1 print('Correct. Good job!') else: print('Sorry, the answer is 8') # Asks the second question flower = input('What is the state flower of Texas? ').lower() if flower == "bluebonnet": correct_answers += 1 print('Awesome! Well done.') else: print('Sorry, the answer is Bluebonnet.') # Asks the third question points = float(input('How many points does a octagon have? ')) if points == 8: correct_answers += 1 print('Nice! That is correct.') else: print('Sorry, the answer is 8') print("Good job. Your final score was: ", correct_answers)
true
44a981d0bb30cc57c6fd15ed98e02993129563cd
sprksh/quest
/recursion/backtracking/backtracking.py
1,657
4.34375
4
""" Backtracking is when you backtrack after recursion Examples in n_queens in the bottom section """ class newNode: # Construct to create a new node def __init__(self, key): self.key = key self.left = None self.right = None self.parent = None def __repr__(self): return str(self.key) def tree_sum(root): if root is None: return 0 return root.key + tree_sum(root.left) + tree_sum(root.right) # this is plain recursion def max_path_sum(root): def sub_tree_sum(node): # base case if node is None: return 0 l = sub_tree_sum(node.left) r = sub_tree_sum(node.right) return node.key + l if l > r else node.key + r max_path_sum = sub_tree_sum(root) return max_path_sum def max_sum_path(root): actual_path = [] def sub_tree_sum(node): if node is None: return 0 l = sub_tree_sum(node.left) r = sub_tree_sum(node.right) maximum = node.key + l if l > r else node.key + r actual_path.append(node.left if l > r else node.right) return maximum max_path_sum = sub_tree_sum(root) actual_path = [_ for _ in actual_path if _] actual_path.append(root) return max_path_sum, actual_path if __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.right.left.right = newNode(12) max_sum, path = max_sum_path(root) print(max_sum, path)
true
6a55c9c131b08c9afd042592d7b3b5db8cec153e
insomnia-soft/projecteuler.net
/004/004.py
831
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # def palindrome(n): m = n p = 0 while m > 0: mod = m % 10 m /= 10 p = p * 10 + mod if p == n: return True return False def main(): """ Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ nmax = 0 for i in range(100, 1000): for j in range(100, 1000): n = i * j; if palindrome(n) and n > nmax: nmax = n print nmax return 0 if __name__ == '__main__': main()
true
3b23e311c63ab7ecbc0c2bed101f1a9cddb86971
lbovboe/The-Lab-Python-level-1
/1.06-5.py
331
4.1875
4
age = int(input("Enter your age : ")) if(age >=10 and age <=16): ans = input("Are you a student of the lab? : ").lower() if(ans == "yes"): print("You must be smart! ") else: print("You should join the lab! ") elif(age < 10 or age >16 and age <20 ): print("That's the good age!") else: print("You are a teenager!")
false
31c2019a419a335dba454aefb11f62735df929ae
seokhyun0220/pythonProject1
/Ch04/4_1_ List.py
940
4.21875
4
""" 날짜 : 2021/04/27 이름 : 김철학 내용 : 파이썬 자료구조 리스트 실습 교재 p84 """ #리스트 생성 list1 = [1,2,3,4,5] print('list type :', type(list)) print('list[0] :', list1[0]) print('list[2] :', list1[2]) print('list[3] :', list1[3]) list2 = [5,3.14, True, 'Apple'] print('list2 type :', type('list2')) print('list2[1] :', list2[1]) print('list2[2] :', list2[2]) print('list2[3] :', list2[3]) list3 = [[1,2,3],[4,5,6],[7,8,9]] print('list3 type :',type(list3)) print('list3[0][0] :',list3[0][0]) print('list3[1][1] :',list3[1][1]) print('list3[2][1] :',list3[2][1]) #리스트 덧셈 animal1 = ['사자','호랑이','코끼리'] animal2 = ['곰','기린'] result = animal1 + animal2 print('result :', result) #리스트 수정 , 추가 , 삭제 nums = [1,2,3,4,5] print('nums :', nums) nums[1] = 7 print('nums :',nums) nums[2:4] = [8,9,10] print('nums :', nums) nums[3:5] = [] print('nums :',nums)
false
43be50b95f9781fecb0bcb7a242061af8a8d461c
seokhyun0220/pythonProject1
/Ch05/5_5_FuctionList.py
1,764
4.375
4
""" 날짜 : 2021/04/29 이름 : 김철학 내용 : 파이썬 리스트함수 교재 p88 """ dataset = [1,4,3] print('1.dataset :', dataset) # List 원소 추가 dataset.append(2) dataset.append(5) print('2.dataset :', dataset) # List 정렬 dataset.sort() print('3.dataset :', dataset) # 오름차순 dataset.sort(reverse=True) # 내림차순 print('4.dataset :', dataset) # List 원소 삽입 dataset.insert(2, 6) # 2번에 6를 추가 dataset.insert(1, 7) # 1번에 7를 추가 print('5.dataset :', dataset) # List 원소 삭제 dataset.remove(6) print('6.dataset :', dataset) # map 함수 # - 리스트 원소를 지정된 함수로 일괄 처리해주는 함수 # - 여러 개의 데이터를 한번에 다른 형태로 변환할 때 많이 사용 def plus10(n): return n+10 list1 = [1,2,3,4,5] list1_map_list = list(map(plus10, list1)) print('list1_map_list :', list1_map_list) # 실수 -> 정수 list2 = [1.1, 2.2, 3.3, 4.4, 5.5] list2_map_list = list(map(int, list2)) print('list2_map_list :', list2_map_list) list3 = [1,2,3,4,5] list3_map_list = list(map(lambda x:x*2, list3)) print('list3_map_list :', list3_map_list) # 문자 숫자로 변환 list4 = ['1', '2', '3', '4', '5'] list4_map_list = list(map(int, list4)) print('list4_map_list :', list4_map_list) # input 함수 확장 a = input('입력 :') print('a :', a) var1, var2, var3 = input('3개 숫자 입력(띄어쓰기 구분) :').split() print('var1 : {}, var2 : {}, var3 : {}'.format(var1, var2 ,var3)) print('var1+var2+var3 = ', var1+var2+var3) # 숫자로 변환 num1,num2,num3 = map(int, input('3개 숫자 입력(띄어쓰기 구분) :').split()) print('num1 : {}, num2 : {}, num3 : {}'.format(num1, num2 ,num3)) print('num1+num2+num3 = ', num1+num2+num3)
false
19f2142d863f2105fd453b35dd9832bff8ffb9e5
subash319/PythonDepth
/Practice16_Functions/Prac_16_10_count_even_odd.py
374
4.28125
4
# 10. Write a function that takes in a list of integers and returns the number of even and odd numbers from that list. def count_even_odd(list_count): even_count,odd_count = 0,0 for num in list_count: if num%2 == 0: even_count += 1 else: odd_count += 1 return even_count,odd_count print(count_even_odd(list(range(20))))
true
42e99ec5b61f9ea5debb7e192cd83ff4f47cc7cc
subash319/PythonDepth
/Practice10_Loops/Practice10_1_sum_n_numbers.py
635
4.375
4
# 1. Write code to find sum of first n natural numbers using a # # (a) while loop # # (b) for loop # # (c) without any loop # a while loop n = int(input("Enter the 'n' value to find sum of n natural numbers:")) initial_n = n sum = 0 while n: sum += n n -= 1 print(f"sum of {initial_n} natural numbers:{sum}") n_for = initial_n sum_for = 0 for x in range(1, n_for+1): sum_for += x print(f'The sum of {initial_n} natural numbers using for loop:{sum_for}') sum_without_loop = 0 if initial_n: sum_without_loop = (initial_n*(initial_n+1))/2 print(f"Sum of {initial_n} numbers without using loop is {sum_without_loop}")
false
4410eadec793e5cfb189305a350f91052cc822e6
subash319/PythonDepth
/Practice14_List_Comprhensions/Prac_14_6_cubes_all_odd.py
292
4.53125
5
# 6. This list comprehension creates a list of cubes of all odd numbers. # # cubes = [ n**3 for n in range(5,21) if n%2!=0] # Can you write it without the if clause. cubes = [n**3 for n in range(5, 21, 2)] cubes_2 = [ n**3 for n in range(5,21) if n%2!=0] print(cubes) print(cubes_2)
true
3687ac68a5e5a98d1972ae671b90d598f2055e84
subash319/PythonDepth
/Practice17_Functions_2/Prac_17_6_kwargs.py
493
4.125
4
# def display(L, start='', end=''): # for i in L: # if i.startswith(start) and i.endswith(end): # print(i, end=' ') # # display(dir(str), 'is', 'r') # In the function definition of the function display(), # make changes such that the user is forced to send keyword arguments for the last two parameters. def display(L, *, start='', end=''): for i in L: if i.startswith(start) and i.endswith(end): print(i, end=' ') display(dir(str), start = 'is', end = 'r')
true
8a8e5cc2188d84672aa8f3502c459f5a622e956b
subash319/PythonDepth
/Practice11_Loops/Prac_11_6_Insert_list.py
469
4.3125
4
# L1 = ['China', 'Brazil', 'India', 'Iran', 'Iraq', 'Russia'] # L2 = ['Italy', 'Japan', 'China', 'Russia', 'Nepal', 'France'] # Write a program that inserts all common items of these 2 lists into a third list L3. L1 = ['China', 'Brazil', 'India', 'Iran', 'Iraq', 'Russia'] L2 = ['Italy', 'Japan', 'China', 'Russia', 'Nepal', 'France'] L3 = list() for country1 in L1: for country2 in L2: if country1 == country2: L3.append(country1) print(L3)
false
11506ebc9da92d469b83fbe2f261e4a4ce412716
subash319/PythonDepth
/Practice13_LoopingTechniques/Prac_13_15_zip.py
1,721
4.21875
4
# 15.Write a program that displays the following output from the above data. Use zip in for loop to iterate over the # lists. # # # # John # # -------------------------------------------------- # # Physics 100 40 90 # # Chemistry 80 25 78 # # Maths 100 40 87 # # Biology 75 20 67 # # Total = 322 # # Percentage = 90.70 # # -------------------------------------------------- # # Sam # # -------------------------------------------------- # # Physics 100 40 95 # # Chemistry 80 25 76 # # Maths 100 40 78 # # Biology 75 20 57 # # Total = 306 # # Percentage = 86.20 # # -------------------------------------------------- # # Dev # # -------------------------------------------------- # # Physics 100 40 80 # # Chemistry 80 25 69 # # Maths 100 40 59 # # Biology 75 20 45 # # Total = 253 # # Percentage = 71.27 # # -------------------------------------------------- D = { 'John' : [90,78,87,67] , 'Sam' : [95,76,78,57] , 'Dev' : [80,69,59,45] } subjects = ['Physics', 'Chemistry', 'Maths', 'Biology'] max_marks = [100, 80, 100, 75] pass_marks = [40, 25, 40, 20] # print(list(zip(D.items(),subjects,max_marks,pass_marks))) for (name,marks) in D.items(): print(name) print('-' * 50) total,sum_max_marks = 0,0 for mark,subject,max_mark,pass_mark in zip(marks,subjects,max_marks,pass_marks): print(f'{subject:10} {max_mark:4} {pass_mark:4} {mark:5}') total += mark sum_max_marks += max_mark per = (total/sum_max_marks)*100 print(f'Total = {total:3}') print(f'Max Marks = {sum_max_marks:3}') print(f'Percentage = {per:4.2f}') print('-' * 50)
false
2b44c016feeed5be184877be0e84ba5ff8e7f38c
VishalSinghRana/Basics_Program_Python
/Squareroot_of_Number.py
284
4.34375
4
y="Y" while(y=="y" or y=="Y"): number = int(input("Enter the number")) if number < 0: print("Please Enter a postive number") else: sqrt= number**(1/2) print("The squareroot of the numebr is ",sqrt) y=input("Do you want to continue Y/N?")
true
429a1a5a27ce1a2d1166d16de7b33bfc2b947008
patiregina89/Desafios-Prof_Guanabara
/Desafio59.py
1,191
4.34375
4
'''Crie um programa que leia dois valores e mostre um menu na tela. 1 - somar 2 - multiplicar 3 - maior 4 - novos números 5 - sair do programa O programa deverá realizar a operação solicitada em cada caso''' num1 = int(input('Informe um número: ')) num2 = int(input('Informe outro número: ')) maior = num1 opcao = 0 while opcao != 5: print('[1] Somar \n[2] Multiplicar \n[3] Maior \n[4] Novos números \n[5] Sair do programa') opcao = int(input('Qual opcão deseja? ')) if opcao == 1: print('{} + {} = {}'.format(num1, num2, num1+num2)) elif opcao == 2: print('{} x {} = {}'.format(num1, num2, num1*num2)) elif opcao == 3: if num2 > maior: maior = num2 print('O número {} é maior.'.format(maior)) else: maior = num1 print('O número {} é maior.'.format(maior)) elif opcao == 4: num1 = int(input('Informe um número: ')) num2 = int(input('Informe outro número: ')) elif opcao == 5: break print('Você saiu do programa') else: print('Opcão inválida. tente novamnete.') print('Fim do programa!')
false
b81bf5104838515302768a79df37c945fa7a4f5a
kcwebers/Python_Fundametnals
/fundamentals/insertion.py
2,060
4.3125
4
# Build an algorithm for insertion sort. Please watch the video here to understand how insertion sort works and implement the code. # Basically, this sort works by starting at index 1, shifting that value to the left until it is sorted relative to all values to the # left, and then moving on to the next index position and performing the same shifts until the end of the list is reached. The following # animation also shows how insertion sort is done. # Some Tips! # Don't forget to write your plan in a non-programming language first (pseudocode!) and test your base cases before you build your code. # Please refrain from checking other people's code. If your code does NOT work as intended make sure # you are writing up your plan first, # your plan solves your base case, and # your plan solves other base cases you have specified. # Sometimes if you are stuck for too long, you need to just start all over as this can be more efficient to do than dwelling on old code # with bugs that are hard to trace. def insertionSort(li): for x in range(len(li)): # loop through initial list to access each element for y in range(x + 1, len(li)): # loop through same array starting at index +1 ahead of x if(li[x] > li[y]): # if element (li[y]) is greater than the one before it (li[x], which is set to be one index behind always) tmp = li[x] # swap the smaller element with the with the original element li[x] = li[y] li[y] = tmp return li # return final array # this is the answer per online looking ... I think I am a bit confused about what an insertion sort is def insertionSort(li): for i in range(1, len(li)): # loop through array starting at the first index key = li[i] j = i - 1 # Move elements that are greater than key to one position ahead of their current position while j >= 0 and key < li[j] : li[j + 1] = li[j] j -= 1 li[j + 1] = key print(insertionSort(arr))
true