blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
12bfdf8a61a8cacf952be845fb1a449e480d7f9c | tobitech/code-labs | /machine learning/complete_python_programming_for_beginners/data structures/finding_items.py | 347 | 4.15625 | 4 | letters = ["a", "b", "c"]
print(letters.index("a")) # get the index of an object in a list
# print(letters.index("d")) # you get a ValueError for object not in list
if "d" in letters: # `in` operator to check if object is in list
print(letters("d"))
# returns the number of occurences of a given item in a list
print(letters.count("a"))
| true |
6165a1189d01bd464652660b70ee618906a6a53a | tobitech/code-labs | /machine learning/complete_python_programming_for_beginners/control flow/infinite_loops.py | 381 | 4.25 | 4 | # this program is the same as the one we did in the while_loop lesson
# while True:
# command = input("> ")
# print("ECHO", command)
# if command.lower() == "quit":
# break
# Exercise: dispaly even numbers between 1 to 10
count = 0
for x in range(1, 10):
if x % 2 == 0:
print(x)
count += 1
else:
print(f"We have {count} even numbers")
| true |
76c76d7de9ea0086277091f516bf37460301c664 | tobitech/code-labs | /machine learning/complete_python_programming_for_beginners/classes/constructors.py | 670 | 4.25 | 4 | class Point:
# `self` is a reference to the current object
def __init__(self, x, y):
# `x` and `y` are new attributes we are adding to the object
# using the passed values to set them
self.x = x
self.y = y
# we have a reference to the current object here with `self`
# with that we can read the current values for `x` and `y`
# defined in the constructor
def draw(self):
# using self we can read attributes in the object
# or also call other methods in this object
print(f"Point ({self.x}, {self.y})")
point = Point(1, 2)
# print(point.x) # `x` not available to the object
point.draw()
| true |
a9c7e3106ad820fa80cf9895a3a6d77d7ddf92bd | richardcsuwandi/data-structures-and-algorithms | /Recursive Algorithms/fibonacci.py | 547 | 4.1875 | 4 | # Create an empty dict to store cached values
fibonacci_cache = {}
def fibonacci(n):
# If the value is cached, return the value
if n in fibonacci_cache:
return fibonacci_cache[n]
# Compute the nth term
if n == 1:
value = 1
elif n == 2:
value = 1
else:
value = fibonacci(n-1) + fibonacci(n-2)
# Cache the value and return
fibonacci_cache[n] = value
return value
def main():
for n in range(1, 101):
print(f'{n}: {fibonacci(n)}')
if __name__ == "__main__":
main() | true |
2eb9ef055524934cb078711a5faf5a4028f2b926 | keshavgbpecdelhi/Algorithmic-Toolbox | /Algorithmic Toolbox/5.1 money change.py | 1,201 | 4.21875 | 4 | # -------------------------Money Change Again----------------------------
# As we already know, a natural greedy strategy for the change problem does not work correctly for any
# set of denominations. For example, if the available denominations are 1, 3, and 4, the greedy
# algorithm will change 6 cents using three coins (4 + 1 + 1) while it can be changed using just two coins (3 + 3).
# Your goal now is to apply dynamic programming for solving the Money Change Problem for
# denominations 1, 3, and 4.
# Problem Description
# Input Format. Integer money.
# Output Format. The minimum number of coins with denominations 1, 3, 4 that changes money.
# Constraints. 1 ≤ money ≤ 103
# .
# Sample 1.
# Input:
# 2
# Output:
# 2
# 2 = 1 + 1.
# Sample 2.
# Input:
# 34
# Output:
# 9
# 34 = 3 + 3 + 4 + 4 + 4 + 4 + 4 + 4 + 4.
#-------------------------Solution using python3--------------------------
import math
values = [1, 3, 4]
m = int(input())
minimum_coins = [0] + [math.inf]*m
for i in range(1, m+1):
for j in values:
if i>=j:
coins = minimum_coins[i-j]+1
if coins < minimum_coins[i]:
minimum_coins[i] = coins
print(minimum_coins[m]) | true |
a65fb8222c63c2d94701bea3363d705b209757ca | alexander-fraser/learn-python | /Python_010_Reverse_Words.py | 791 | 4.40625 | 4 | # Reverse Words
# Alexander Fraser
# 28 Febuary 2020
"""
Write a program (using functions!) that asks the user
for a long string containing multiple words. Print back
to the user the same string, except with the words in
backwards order.
"""
def collect_input():
# Get the input from the user.
input_string = input("Input a string of words: ")
return input_string
def reverse_order(input_string):
# Split the string into words (based on spaces)
# then print out the words in reverse order
split_string = input_string.split(" ")
length = len(split_string)
for i in range(0, length):
print('{} '.format(split_string[length - i - 1], ))
def main():
input_string = collect_input()
reverse_order(input_string)
if __name__ == "__main__":
main() | true |
d398fdbb843796180ac067a16217743a43bbc0a1 | alexander-fraser/learn-python | /Python_002_Primes.py | 1,304 | 4.5 | 4 | # Primes
# Alexander Fraser
# 8 Febuary 2020
# This program outputs all the prime numbers up to the
# integer specified by the user.
def collect_stop_value():
# This function prompts the user for an integer.
# It loops until an integer is entered by the user.
while True:
try:
user_input = input("What upper limit would you like to set?\n")
limit_value = int(user_input)
except:
print("That was not a valid integer. Please try again.")
else:
if limit_value >= 2:
break
print("The integer entered was less than 2. Please try again.")
return limit_value
def determine_prime(candidate_value):
for i in range(2, candidate_value):
if (candidate_value % i) == 0:
return False
return True
def loop_through_candidates(limit_value):
primes_list = []
for i in range(2, limit_value + 1):
is_prime = determine_prime(i)
if is_prime == True:
primes_list.append(i)
return primes_list
def main():
print("This program will output all primes up to the number specified.")
limit_value = collect_stop_value()
primes_list = loop_through_candidates(limit_value)
print(primes_list)
if __name__ == "__main__":
main()
| true |
1d856ff4c9c072949c50cf8631b87e6ad90ab87c | vinaykath/PD008bootcamp | /Dev's Work/palindrome.py | 260 | 4.3125 | 4 | def palindrome_check(str):
str = str.replace(" ", "")
print(str)
return str == str[::-1]
str = input("Enter a string:" )
result = palindrome_check(str)
if result:
print("String is a palindrome!")
else:
print("String is not a palindrome")
| true |
5f4614126867e84ce2d94239b0c07adb32daaddb | Gokul-Venugopal/Python_Basics | /python4.py | 1,357 | 4.15625 | 4 | #using slicing
my_list=['a','b','c','d','e','f']
for i in my_list[::2]: ###2 steps printing
print(i)
### appending a string
msg="hello"
my_list=[]
for i in msg:
my_list.append(i)
print(my_list)
my_list1=[char for char in msg]
print(my_list1)
for i in range(0,5): ###squares from 0 to 5
print(i**2)
square_val=[i**2 for i in range(0,5) ] ###Alternate way [0, 1, 4, 9, 16]
print(square_val)
###Similarly calculating odd numbers from 1 to 10
my_even=[i for i in range(1,11) if i%2!=0 ]
print(my_even)
#list comprehension with nested for loop
for i in [4,5,6]:
for j in [1,2,3]:
print(i**j)
#Alternate way
res=[i**j for i in [4,5,6] for j in [1,2,3] ]
##################################################################################################################
#functions
name="function"
def sample_fun(self):
print(f'This is a sample {name}')
sample_fun(name)
def sum_1(a,b):
print(f'Sum is {a+b}')
sum_1(10,100)
num=[1,2,3,6,7]
def even_odd(num): #checks the number in num if first number is even it returns true else false
for i in num:
if i % 2==0:
return True
else:
return False
print(even_odd(num))
################################################################################################################# | false |
0da05c32e114f858801b3323c36a16633872ba25 | ecxr/matrix | /hw0/hw0.py | 2,632 | 4.1875 | 4 | # Please fill out this stencil and submit using the provided submission script.
## Problem 1
def myFilter(L, num):
"""
input: list of numbers and a number.
output: list of numbers not containing a multiple of num.
>>> myFilter([1,2,4,5,7], 2)
[1, 5, 7]
"""
return [ x for x in L if x % num != 0 ]
## Problem 2
def myLists(L):
"""
input: list L of non-negative integers.
output: output: a list of lists: for every element x in L create a
list containing 1; 2; : : : ; x.
>>> myLists([1,2,4])
[[1], [1, 2], [1, 2, 3, 4]]
"""
return [ [x for x in range(1, y+1)] for y in L ]
## Problem 3
def myFunctionComposition(f, g):
"""
input: two functions f and g, represented as dictionaries, such that g o f
exists.
output: dictionary that represents a function g o f
>>> g = {'a':'apple', 'b':'banana'}
>>> f = {0:'a', 1:'b'}
>>> myFunctionComposition(f,g)
{0: 'apple', 1: 'banana'}
"""
return { k : g[f[k]] for k in f.keys() }
## Problem 4
# Please only enter your numerical solution.
complex_addition_a = (5+3j)
complex_addition_b = 1j
complex_addition_c = (-1+0.001j)
complex_addition_d = (0.001+9j)
## Problem 5
GF2_sum_1 = 1
GF2_sum_2 = 0
GF2_sum_3 = 0
## Problem 6
def mySum(L):
"""
Input: list of numbers
Output: sum of numbers in the list
>>> mySum([])
0
>>> mySum([1,2,3])
6
"""
current = 0
for x in L:
current += x
return current
## Problem 7
def myProduct(L):
"""
Input: list of numbers
Output: product of numbers in the list
>>> myProduct([])
1
>>> myProduct([2,4,4])
32
"""
current = 1
for x in L:
current = current * x
return current
## Problem 8
def myMin(L):
"""
Input: list of numbers
Output: minimum number in the list
>>> myMin([2, -1, 4])
-1
"""
current = float('Inf')
for x in L:
if (x < current):
current = x
return current
## Problem 9
def myConcat(L):
"""
Input: list of strings
Output: concatenation of all the strings in L
>>> myConcat(["foo", "bar", "baz"])
'foobarbaz'
"""
current = ''
for x in L:
current += x
return current
## Problem 10
def myUnion(L):
"""
Input: list of sets
Output: the union of all sets in L
>>> myUnion([{1,2},{3,4},{5,6}])
{1, 2, 3, 4, 5, 6}
"""
current = set()
for x in L:
current |= x
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
print("Tests done")
| true |
c90cbb758d1b0caf0bacbea3c8ea36a9cac55138 | mandaltu123/learnpythonthehardway | /basics/few_more_commandlines.py | 286 | 4.21875 | 4 | # some more tests on commanline args
from sys import argv
if len(argv) == 3:
num1 = int(argv[1])
num2 = int(argv[2])
else:
num1 = int(input("Enter number 1 : "))
num2 = int(input("Enter number 2 : "))
print("the sum of number1 and number2 is {}".format(num1 + num2)) | true |
00a5e7ffa38f1cb9e296ab0e82765bcf6a76a7f9 | mandaltu123/learnpythonthehardway | /basics/dictionaries.py | 1,052 | 4.25 | 4 | # Dictionaries are the most commonly used datastructure in python
# They are key value pairs
dic = {1: 'one', 2: 'two', 3: 'three'}
print("print my first dictionary {}".format(dic)) # I did not write dick
# it has keys and values
keys = dic.keys()
values = dic.values()
print("keys are {}".format(keys))
print("values are {}".format(values))
# one way of iteration over dictionary is :
for key in keys:
print("key = {} and value = {}".format(key, dic.get(key)))
# item() function in dictionary
items = dic.items()
for item, data in dic.items():
print("the key is {} and the value is {}".format(item, data))
# adding a new item to dictionary
dic[4] = 'four'
print("new dictionary is {} ".format(dic))
# adding a new item with same key
dic[4] = 'iv'
print("adding another item with same key 4 {}".format(dic)) # if you are coming from java background it does the same
# same as like hash table or hashmap it overwrites the old item with the new one
# del operator
del dic[4]
print("dictionary after deleting 4 {}".format(dic))
| true |
2cff4e9e9ff1b7a3df2937541795ea7f8356f07a | nyxgear/TIS-diversity-algorithms | /diversity/default_diversity_functions.py | 1,248 | 4.6875 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The functions below are used as a default by algorithms to compute a set of diverse elements.
"""
def diversity_element_element(e1, e2):
"""
Default diversity function to compare an ELEMENT against another ELEMENT
:param e1: element
:param e2: element
:return: diversity value
"""
return abs(e1 - e2)
def diversity_element_set(element, sett):
"""
Default diversity function to compare an ELEMENT against a SET
:param element: element
:param sett: set against which calculate diversity
:return: diversity value
"""
if len(sett) == 0:
raise Exception("Set into element-set diversity function is empty.")
return sum([abs(element - x) for x in sett]) / len(sett)
def diversity_set(sett):
"""
Default diversity function to compute the diversity "amount" of a SET.
:param sett: set for which calculate the diversity
:return: diversity value
"""
if len(sett) == 0:
raise Exception("Set into set diversity function is empty.")
diversity = 0
for i in range(len(sett)):
for j in range(i, len(sett)):
diversity += abs(sett[i] - sett[j])
return diversity
| true |
4c5f7e6130818e5090568713c75f357e39fe09eb | ronaldvilchez98/Santotomas_estructuras_programacion | /python_3/guia4/Ejercicio_12.py | 795 | 4.1875 | 4 | '''
::::::::::::::::::::::::::::::::::::::::::::::
:: @github: adrian273 ::
:: @email: adrianverdugo273@gmail.com ::
::::::::::::::::::::::::::::::::::::::::::::::
12@ Leer dos números, si el número uno es mayor que el número dos calcule
Número1*Número2, si el número dos es mayor y además es distinto d cero calcule Número1/Número2, si el número dos es cero muestre “no se puede calcular”.
'''
number1 = int(input('Ingrese un numero \n'))
number2 = int(input('Ingrese un numero \n'))
if number1 > number2:
result = number1 * number2
print('El resultado es ' + str(result))
if number2 > number1 and number2 != 0:
result = number1 / number2
print('El resultado es ' + str(result))
if number2 == 0:
print('No se puede calcular')
| false |
aed564b67fbbfa7d1cb804f859c9ba29499bd0ab | ronaldvilchez98/Santotomas_estructuras_programacion | /python_3/guia4/Ejercicio_2.py | 820 | 4.3125 | 4 | '''
::::::::::::::::::::::::::::::::::::::::::::::
:: @github: adrian273 ::
:: @email: adrianverdugo273@gmail.com ::
::::::::::::::::::::::::::::::::::::::::::::::
2@ Lea tres números y calcule:
a. Numero1 + numero2
b. (numero1 + numero3) / numero2
c. Numero1 ^ numero2 / numero3
d. Numero1 MOD numero2
'''
number1 = int(input('Ingrese numero \n'))
number2 = int(input('Ingrese numero \n'))
number3 = int(input('Ingrese numero \n'))
result = number1 + number2
print('El primer resultado es ' + str(result))
result = (number1 + number3) / 2
print('El segundo resultado es ' + str(result))
result = number1 ** number2 / number3
print('El tercer resultado es ' + str(result))
result = number1 % number2
print('El cuarto resultado es ', result)
| false |
3eec349bfcca6bb0a154d7cf22d46568a6ad3ba6 | SolutionsDigital/Yr10_Activities | /Activity06/Act06_proj5.py | 1,956 | 4.1875 | 4 | # File : Act06_proj5.py
# Name :Michael Mathews
# Date :1/4/19
""" Program Purpose : Deleting items using
Del index or Remove for item Name
"""
myCountriesList=["Greenland", "Russia", "Brazil", "England", "Australia", "Japan", "France"]
userSelection ="y"
def showOptions():
print("----------------------------------")
print("Press D - To delete a Country by Number ")
print("Press R - To remove a Country by Name")
print("Press X - To EXIT")
print("----------------------------------")
print()
def Report():
print()
print("There are",len(myCountriesList), "Countries in this list. ",)
print()
for i in range (len(myCountriesList)):
print(i+1, " - ", myCountriesList[i])
print()
def removeCountry():
print()
removeThisCountry=input("Type the Name of the Country to remove: ")
myCountriesList.remove(removeThisCountry)
print()
print(removeThisCountry, "has been removed")
print("-------------------------------")
def popCountry():
print()
popThisCountry=int(input("Type the Number of the Country to deleted: "))
popThisCountry=popThisCountry-1
if popThisCountry < 0:
print("Selected Number out of range")
elif popThisCountry > len(myCountriesList):
print("Selected Number out of range")
else:
print()
print(popThisCountry+1, '-', myCountriesList[popThisCountry], "has been Deleted")
myCountriesList.pop(popThisCountry)
print("-------------------------------")
while userSelection != "X" or "x":
Report()
showOptions()
userSelection=input("Select the Letter Option :")
if userSelection in ("D","d"):
popCountry()
elif userSelection in ("R","r"):
removeCountry()
elif userSelection in ("S","s"):
sortCountries()
elif userSelection in ("X","x"):
break
else:(" Try a valid Character of D R S or X ")
print("See you next time")
| true |
2cb7fcb58a5f39cf15526035a37475eb1928e1d1 | SolutionsDigital/Yr10_Activities | /Activity02/Act02_proj1.py | 1,289 | 4.15625 | 4 | """
File : Act02_Py_p1.py
Name : Michael Mathews Date : 25/01/2020
This program will accept the score from the user and find the Average
The average is used in a selection Construct to
check on PASS or Fail - Pass reuires >= 65
"""
# Welcomes the user
print("Welcome to the Pass Fail Calculator")
# Puts a line break in after the welcome
print()
# makes the program loop until x is entered
while quit !='x':
# three marks entered as converted to float (from input default string)
mark1= float(input('Please enter your first mark out of 100 - mark1:'))
mark2= float(input('Please enter your Second mark out of 100 - mark2:'))
mark3= float(input('Please enter your Third mark out of 100 - mark3:'))
# Average mark calculated with equation
AvMark = (mark1+mark2+mark3)/3
print("Your Average mark is ", round(AvMark,1))
# checks if average is above or equal to 65
if AvMark >=65:
print ('well done you passed') # Congratulations message printed
else:
print ('bugger you failed this time')# bugger message printed
print()
# Puts a line break in before Option to quit with quit offering
quit = input('Press ''x'' to quit or Any key to try again ')
# Farewell to the uer
print(" Thanks for using the Pass Fail Calculator")
| true |
bea55b3e79ea96b209624c982c38e18e618e573e | SolutionsDigital/Yr10_Activities | /Activity04/Act04_proj5.py | 1,857 | 4.15625 | 4 | # File : Act04_proj5.py
# Name : Michael Mathews Date : 1/4/19
# Program Purpose : Convert Temperature
# Farenheit to Celsius,Celsius to Farenheit
# Show Boiling and Freezing Points for both
def fahr_to_Celsius():
far = float(input("Please enter the temperature in Farenheit: "))
cels = ((far-32)*(5/9))
print (far,"Farenheit in Celsius is",cels,"degrees.")
print()
def Celsius_to_Fahr():
cel = float(input("Please enter the temperature in Celsius: "))
farh = ((cel*(9/5)+32))
print (cel,"Celsius in Farenheit is",farh,"degrees.")
print()
def FreezeBoil():
print ("The boling temperature is 100.0 C and 212 F.")
print ("The freezing temperatures are 0.0 C and 32 F.")
print()
menu = {} # sets options for menu
menu['1']="- Convert Farenheit to Celsius"
menu['2']="- Convert Celsius to Farenheit"
menu['3']="- Display the freezing and boiling points"
menu['0']="- Exit"
print(" Welcome to the Temperature Converter") # Welcomes User
print() # Leaves a 1 line space
while True:
options=menu.keys()
for entry in options: # Displays Menu options
print(entry, menu[entry])
print() # Leaves a 1 line space
selection=input("Please Select:") # Prompts user to select
print() # Leaves a 1 line space
if selection =='1':
fahr_to_Celsius() # 1 select runs F to C
elif selection == '2':
Celsius_to_Fahr() # 2 select runs C to F
elif selection == '3':
FreezeBoil() # 3 Freezing-Boiling Display
elif selection == '0': # 0 Farewell User
print("Thanks for use the Temperature convertor. Stay Cool !")
break
else: # User Proofing
print ("Unknown Option Selected!" )
| true |
e508ebb8eea7327116e450eebb7684a3c31cd43c | SolutionsDigital/Yr10_Activities | /Activity01/Act01_proj3.py | 695 | 4.28125 | 4 | """
File : Act01_proj3.py
Name : Michael Mathews
Date :25/01/2020
Program Purpose: The user enters the Name, Address and Age
This info will be displayed on the screen including age next year.
"""
# request for user to enter their first name
FName= input("Enter your first name : ")
# request for user to enter their Surname
Surname= input("Enter your surname : ")
# request for user to enter their Suburb
Suburb = input("Enter your suburb :")
# request for user to enter their age
# note use of int to change user entry to integer
Age = int(input("Enter your age :"))
# print function used to output message to screen
print (FName+" " + Surname + " from " + Suburb +" will be ", Age+1, "next year")
| true |
634a09a2b56eb7b564c56de6546297150b2af7f5 | sholatransforma/hello-transforma | /cylinder.py | 332 | 4.25 | 4 | #program to find the area of a cylinder
pi = 20/6
height = float(input(' what is height of cylinder'))
radius = float(input('what is radius of cylinder'))
volume = pi * radius * radius * height
surfacearea = (height * (2 * pi * radius)) + (2 * (pi * radius**2))
print('volume is', volume)
print('surface area', surfacearea)
| true |
6e858df9b2a8fa0f0e1ccbc42e9a17aa14eec066 | lkfken/python_assignments | /assn-4-6.py | 1,272 | 4.53125 | 5 | __author__ = 'kleung'
# 4.6 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay.
# Award time-and-a-half for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of time-and-a-half in a function called computepay() and
# use the function to do the computation. The function should return a value.
# Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
# You should use raw_input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input unless you want to -
# you can assume the user types numbers properly.
OVERTIME_RATE = 1.5
MAX_REGULAR_HOURS = 40
def computepay(total_work_hours, hourly_rate):
if total_work_hours > MAX_REGULAR_HOURS:
ovetime_pay = (total_work_hours - MAX_REGULAR_HOURS) * (hourly_rate * OVERTIME_RATE)
regular_pay = MAX_REGULAR_HOURS * hourly_rate
else:
ovetime_pay = 0.0
regular_pay = total_work_hours * hourly_rate
return ovetime_pay + regular_pay
total_work_hours = int(raw_input("Enter hours: "))
hourly_rate = float(raw_input("Enter rate: "))
total_pay = computepay(total_work_hours, hourly_rate)
print total_pay | true |
eb7bac332ef99d88940b266c62db3015592268ed | sudhanshu-jha/python | /python3/Python-algorithm/Bits/drawLine/drawLine.py | 1,420 | 4.125 | 4 | # A monochrome screen is stored as a single array of bytes, allowing
# eight consecutive pixels to be stored in one byte. The screen has
# width w, where w is divisible by 8(that is no byte will be split
# across rows). Height of screen can be derived from the length of the
# array and the width. Implement a function that draws a horizontal
# line from (x1,y) to (x2,y).
# The method signature should look something like:
# drawLine(byte[] screen, int width, int x1, int x2, int y)
def drawLine(screen, width, x1, x2, y):
start_offset = x1 % 8
first_full_byte = x1 / 8
if start_offset != 0:
first_full_byte += 1
end_offset = x2 % 8
last_full_byte = x2 / 8
if end_offset != 7:
last_full_byte -= 1
# set full bytes
for b in range(first_full_byte, last_full_byte + 1):
screen[(width / 8) * y + b] = 255
# create masks for start and end line
start_mask = 255 >> start_offset
end_mask = ~(255 >> (end_offset + 1))
# set start and end of line
if (x1 / 8) == (x2 / 8):
mask = start_mask & end_mask
screen[(width / 8) * y + b] |= mask
else:
if start_offset != 0:
byte_number = (width / 8) * y + first_full_byte - 1
screen[byte_number] |= start_mask
if end_offset != 7:
byte_number = (width / 8) * y + last_full_byte + 1
screen[byte_number] |= end_mask
| true |
3d1ccaceeee56c703069c90028669e6dc37ef5c0 | sudhanshu-jha/python | /python3/Python-algorithm/ArraysAndStrings/isRotation/isRotation.py | 294 | 4.1875 | 4 | # Accepts two strings and returns if one is rotation of another
# EXAMPLE "waterbottle" is rotation of "erbottlewat"
def isRotation(str1, str2):
if len(str1) == len(str2) and len(str1) > 0:
str1str1 = "".join([str1, str1])
return str1str1.find(str2) >= 0
return False
| true |
a484920a839689704cd09da05cb6a327b65fc5a2 | jdangerx/internet | /bits.py | 2,119 | 4.125 | 4 | import itertools
def bytes_to_ints(bs):
"""
Convert a list of bytes to a list of integers.
>>> bytes_to_ints([1, 0, 2, 1])
[256, 513]
>>> bytes_to_ints([1, 0, 1])
Traceback (most recent call last):
...
ValueError: Odd number of bytes.
>>> bytes_to_ints([])
[]
"""
if len(bs) % 2 != 0:
raise ValueError("Odd number of bytes.")
pairs = zip(bs[::2], bs[1::2])
return [(a << 8) + b for a, b in pairs]
def short_to_chars(xs):
"""
Convert a list of integers to a list of bytes.
>>> short_to_chars([256, 513])
[1, 0, 2, 1]
>>> short_to_chars([])
[]
"""
arr = itertools.chain.from_iterable((x >> 8, x & 255) for x in xs)
return list(arr)
def ones_complement_addition(x, y, bitsize=16):
"""
Add two numbers of any bitsize and carry the carry around.
11 + 10 = 101 => 10:
>>> ones_complement_addition(3, 2, 2)
2
11 + 11 = 110 => 11:
>>> ones_complement_addition(3, 3, 2)
3
00 + 10 = 10 => 10:
>>> ones_complement_addition(0, 2, 2)
2
"""
cap = 2 ** bitsize - 1
total = x + y
if total > cap:
total -= cap
return total
def ones_complement_sum(xs, bitsize=16):
"""
Sum across a bunch of integers with one's complement.
[11, 10, 10] -> [10, 10] -> [01]:
>>> ones_complement_sum([3, 2, 2], 2)
1
[10, 10, 10] -> [01, 10] -> [11]:
>>> ones_complement_sum([2, 2, 2], 2)
3
[]:
>>> ones_complement_sum([], 2)
0
"""
sum = 0
for x in xs:
sum = ones_complement_addition(sum, x, bitsize)
return sum
def ones_complement(x, bitsize=16):
"""
Swap all 1s and 0s.
01 -> 10
>>> ones_complement(1, bitsize=2)
2
>>> ones_complement(7, bitsize=3)
0
>>> ones_complement((ones_complement(15232)))
15232
"""
return ((1 << bitsize) - 1) ^ x
def checksum(bs):
ints = bytes_to_ints(bs)
ones_comp_sum = ones_complement_sum(ints)
return ones_complement(ones_comp_sum)
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
eb7d1d9f48e4f2079232d0f05f76d8bd82b513b5 | ma7modsidky/data_structures_python | /Queue/queue.py | 1,121 | 4.28125 | 4 | from collections import deque
class Queue:
def __init__(self):
self.buffer = deque()
def enqueue(self, val):
self.buffer.appendleft(val)
def dequeue(self):
return self.buffer.pop()
def is_empty(self):
return len(self.buffer) == 0
def size(self):
return len(self.buffer)
#Like stack, queue is a linear data structure that stores items in First In First Out (FIFO) manner. With a queue the least recently added item is removed first. A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.
# Operations associated with queue are:
#Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity : O(1)
#Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity : O(1)
#Front: Get the front item from queue – Time Complexity : O(1)
#Rear: Get the last item from queue – Time Complexity : O(1)
| true |
0ab91bf2df821543954022ea9788a884841e66e8 | vivibruce/dailycodingproblem | /serialize_deserialize/serialize_deserialize.py | 1,487 | 4.21875 | 4 | '''
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
The following test should pass:
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
'''
class Node:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def serialiaze(self):
if self:
l=[]
l.append(self.data)
if self.left:
l.append(self.left.serialiaze())
else:
l.append(-1)
if self.right:
l.append(self.right.serialiaze())
else:
l.append(-1)
return l
else:
l.append(-1)
return l
def deserialize(lst):
if lst:
node = Node(lst[0])
if type(lst[1]) is list:
node.left = deserialize(lst[1])
else:
node.left = None
if type(lst[2]) is list:
node.right = deserialize(lst[2])
else:
node.right = None
return node
def count_nodes(node):
return count_nodes(node.left) + count_nodes(node.right) + 1 if node else 0
node = Node('root', Node('left', Node('left.left')), Node('right'))
print(deserialize(node.serialiaze()).left.left.data == 'left.left')
print(count_nodes(node))
# [1, [2, -1, -1], [3, [4, -1, -1], -1]] | false |
b171bb9dc81ec1e100edc31c61bbc05a13e9a8cf | bhavikjadav/Python_Crash_Course_Eric_Matthes_Chapter_5 | /5.11_Ordinal Numbers.py | 808 | 4.59375 | 5 | #!/usr/bin/env python
# coding: utf-8
# # 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
# # • Store the numbers 1 through 9 in a list.
# # • Loop through the list.
# # • Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th", and each result should be on a separate line.
# In[14]:
ordinal_numbers = list(range(1, 10))
# In[15]:
for ordinal_number in ordinal_numbers:
if str(ordinal_number) == "1":
print("1st")
elif str(ordinal_number) == "2":
print("2nd")
elif str(ordinal_number) == "3":
print("3rd")
else:
print(str(ordinal_number) + "th")
| true |
5662b37a922038c74948d92ccad0319f39aee4f6 | artificialbridge/hello-world | /BillCalculator.py | 1,018 | 4.125 | 4 | def tip(bill, percentage):
total = bill*percentage*0.01
return total
def total_bill(bill,percentage):
total = bill+tip(bill, percentage)
return total
def split_bill(bill,people):
total = float(bill)/people
return total
def main():
choice = raw_input("Enter 1 to calculate tip or 2 to split bill ")
if choice == "1":
bill = float(raw_input("original bill amount: "))
percentage = float(raw_input("tip percentage: "))
print tip(bill, percentage)
total = total_bill(bill, percentage)
print total
if raw_input("Would you like to split the bill? (yes/no) ")=='yes':
people = int(raw_input("How many ways would you like to split the bill? "))
print split_bill(total, people)
if choice=='2':
bill = float(raw_input("total bill amount: "))
people = int(raw_input("How many ways would you like to split the bill? "))
print split_bill(bill, people)
if __name__ == '__main__':
main()
| true |
bccf02c621aafa681f2303f24442eabf6e3a5a57 | roshsundar/Code_Archive | /Python_programs/LookForCharac.py | 300 | 4.15625 | 4 |
occurences=0
print "Please enter a group of words"
userPut=raw_input()
print "Now enter a character that you want me to find in it"
charac=raw_input()
for letter in userPut:
if letter == charac:
occurences += 1
print "I found",occurences,"ocurrences of your character in the words"
| true |
5f7a811381b65512f224a43ec09bd94ebbddeb14 | activehuahua/python | /pythonProject/exercise/8/8.2.py | 265 | 4.28125 | 4 | list1=[]
for i in range(2,30,4):
list1.append(i)
print(list1)
list1=[]
for i in range(0,10):
list1.append(i)
print(list1)
list1=[]
for i in range(3,19,3):
list1.append(i)
print(list1)
list1=[]
for i in range(-20,861,220):
list1.append(i)
print(list1) | false |
e3d017f081d9b76417b13ba725de6910a91f1742 | aribajahan/Projects | /learnPTHW/ex31.py | 1,360 | 4.28125 | 4 | print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input(">>> ")
if door == "1":
print "There's a huge bear here eating a cheesecake. What do you do now?"
print "1. Take the damn cheesecake."
print "2. Scream at the bear"
print "3. Call Batman"
bear =raw_input("---> ")
#the ---> is what appears on the console where the answer has to be given
if bear == "1":
print "The bear just ate your face off. Cocky, eh?"
elif bear == "2":
print "Foolishness. You just got eaten."
elif bear == "3":
print "Nice....Let's see how long he takes."
else :
print " Well, I guess doing %s is probably better. Bear runs away" % bear
#the more options there are, the more elif you should add
#each one has to have a colon
elif door == "2":
print "You are welcomed by Chris O'Donell. But now there's Grey's Jesse Williams and Wentworth Miller. Which one do you choose?"
print "1. Chris O'Donell"
print "2. Grey's Jesse Williams"
print "3. Wentworth Miller"
boy = raw_input(">> ")
if boy == "1":
print "booooo! Weak Choice."
elif boy == "2":
print "Well obviously.... Nice choice. Man I love that man. #Bowchicawowow"
elif boy == "3":
print "Amen. Wish he still did movies or TV"
else:
print "It's not that hard of a choice. But I guess %s is ok too." % boy
else:
print "Man you suck at making choices. Did you really have to suggest %r . Ay dios mio." % door | true |
d7af5f75c15b02c9a1bc839f1f6ee9c32942e53d | mochimasterman/hello-world | /mathtime.py | 1,231 | 4.1875 | 4 | print("hello!")
print("lets do math!")
score = 0
streak = 0
answer1 = input("What is 1 + 1?")
if answer1 == "2":
print("Correct!")
score = score+1
streak += 1
else:
print("Incorrect!")
streak = 0
print("Your score is", answer1)
#start level 2
print("To level 2!")
answer2 = input("what is 7 plus 2?")
if answer2 == "9":
print("correct!")
score += 1
streak += 1
else:
print("Incorrect!")
streak = 0
print("its getting harder!")
if answer2 == "9" and answer1 == "2":
print("If you get this question correct you will get double points!")
answer3 = input("What is 10 - 6?")
if answer3 == "4":
streak += 1
if answer2 == "9" and answer1 == "2":
print("yay! you got all three questions correct. You have acheived a streak of 3. Keep on going for more prizes! :)")
score += 2
else:
print("you got it right!")
score += 1
else:
print("wrong! good try!")
print("Your score is ", score)
answer4 = input("What is 20 - 18?")
if answer4 == "2":
print("Correct!")
streak += 1
score += 1
else:
print("Incorrect")
streak = 0
print("This is the end for now! Your score was " ,score, "! I update this a few times too! so don't worry!")
| true |
dfbdf41e70262819171d78dfebe7fe44d8b8b52e | Alex7lav81/Group_22 | /Python_HW/HW_2_script_9.py | 2,226 | 4.53125 | 5 | """ Задание 9
Написать скрипт используя функцию input().
1. Функция должна на вход принимать целое число.
2. Внутри функции должно сгенерироваться рандомное целое число (import random)...(random.randint(1, 100))
3. Выводить должна "Вы вели число = (введённое число), которое (меньше/больше/равно и меньше/больше/равно)
сгенерированному числу"
"""
import random
print("Введите целое число:")
var_int = int(input())
var_rand_1 = random.randint(1, 100)
var_rand_2 = random.randint(1, 100)
if var_int > var_rand_1:
if var_int > var_rand_2:
print("Вы ввели чмсло = ", var_int, ", которое больше ", var_rand_1, " и больше ", var_rand_2)
elif var_int < var_rand_2:
print("Вы ввели чмсло = ", var_int, ", которое больше ", var_rand_1, " и меньше ", var_rand_2)
else:
print("Вы ввели чмсло = ", var_int, ", которое больше ", var_rand_1, " и равно ", var_rand_2)
elif var_int < var_rand_1:
if var_int > var_rand_2:
print("Вы ввели чмсло = ", var_int, ", которое меньше ", var_rand_1, " и больше ", var_rand_2)
elif var_int < var_rand_2:
print("Вы ввели чмсло = ", var_int, ", которое меньше ", var_rand_1, " и меньше ", var_rand_2)
else:
print("Вы ввели чмсло = ", var_int, ", которое меньше ", var_rand_1, " и равно ", var_rand_2)
else:
if var_int > var_rand_2:
print("Вы ввели чмсло = ", var_int, ", которое равно ", var_rand_1, " и больше ", var_rand_2)
elif var_int < var_rand_2:
print("Вы ввели чмсло = ", var_int, ", которое равно ", var_rand_1, " и меньше ", var_rand_2)
else:
print("Вы ввели чмсло = ", var_int, ", которое равно ", var_rand_1, " и равно ", var_rand_2) | false |
6f2c1d479982891bd6900b0c4b00ed30144f62c8 | Requinard/merge-sort | /sqrt.py | 1,189 | 4.125 | 4 | """
Try to find the square root of a number through approximation
Estimated operational time: O((number * 10)*precision)
"""
def brute_sqrt(number, power=2, precision=13):
var = 1.0
mod = 1.0
# 13 is the max amount of numbers we can actually count with floats, going above 13 is useless
if precision > 13:
precision = 13
# Loop throught the precision, each precision is a number behind the dot
for i in range(0, precision):
while True:
guess = var**power
if guess > number:
var -= mod
mod /= 10
break
elif guess == number:
return number
else:
var += mod
return var
def newton_sqrt(num, power=2, initial_guess= 10.0, depth=10):
if depth is 1:
return initial_guess
else:
new_guess = initial_guess-((initial_guess**power-num)/(power*initial_guess))
if initial_guess is new_guess:
return initial_guess
return newton_sqrt(num, power, new_guess, depth - 1)
print brute_sqrt(520, 3)
print brute_sqrt(13.928)
print newton_sqrt(612)
print newton_sqrt(13.928) | true |
82a2e068371c6790528cb4319a3b5f36788263a9 | sprajjwal/spd1.4-interview-practice | /problem2.py | 1,199 | 4.125 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
# Example:
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Solution
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
dummyHead = ListNode(0)
l3 = dummyHead
while l1 != None or l2 != None:
if l2 == None:
l3.next = ListNode(l1.val)
l1 = l1.next
elif l1 == None:
l3.next = ListNode(l2.val)
l2 = l2.next
elif l1.val < l2.val:
l3.next = ListNode(l1.val)
l1 = l1.next
else:
l3.next = ListNode(l2.val)
l2 = l2.next
l3 = l3.next
l3 = dummyHead.next
return l3
# Testing
if __name__ == "__main__":
l1 = ListNode(2)
l1.next = ListNode(5)
l1.next.next = ListNode(9)
l2 = ListNode(1)
l2.next = ListNode(9)
l2.next.next = ListNode(23)
l3 = mergeTwoLists(l1, l2)
while l3 != None:
print(f"{l3.val} ->", end="")
if l3.next != None:
l3 = l3.next
else:
break | true |
1c23fbe547cc8215f459b8f890f28c7aed978e04 | Dsblima/python_e_mysql | /strings.py | 402 | 4.21875 | 4 | nome = "danilo lima\n"
print(nome[0:3])
"""
string = 'string'
string[a:b] retorna uma substring que inicia em a e tem tamanho b
"""
print(nome.lower())
print(nome.upper())
print(nome.strip()) #retira espaços e caractéres especiais do final da string
print(nome)
print(nome.split("l"))
print(nome.find("l")) # retorna em que posição começa a string pesquisada
print(nome.replace("lima","silva")) | false |
00eaa267b38e765580f2dfa24a11e2f7b2538559 | ansh8tu/Programming-with-python-Course | /Tetrahedron.py | 236 | 4.3125 | 4 | # This is a Python Program to find the volume of a tetrahedron.
import math
def vol_tetra(side):
volume = (side ** 3 / (6 * math.sqrt(2)))
return round(volume, 2)
# Driver Code
side = 3
vol = vol_tetra(side)
print(vol)
| true |
d76f3007f958af60010f9cfd25a500507930d954 | depth221/python | /Score2.py | 1,022 | 4.15625 | 4 | while True:
try:
num = input("num: ")
if num == "½":
num = 1/2
elif num == "⅓":
num = 1/3
elif num == "⅔":
num = 2/3
elif num == "¼":
num = 1/4
elif num == "¾":
num = 3/4
elif num == "⅛":
num = 1/8
elif num == "⅜":
num = 3/8
elif num == "⅝":
num = 5/8
elif num == "⅞":
num = 7/8
num = float(num)
if num > 1.0 or num < 0.0:
print("0과 1 사이의 숫자를 입력해 주세요")
elif num >= 0.9:
print("A")
elif num >= 0.8:
print("B")
elif num >= 0.7:
print("C")
elif num >= 0.6:
print("D")
elif num >= 0.0:
print("F")
else:
print("Bad score")
except:
print("숫자를 입력해 주세요")
| false |
8370e8d257bab5bfeedafbfe6307682dffd916f9 | hraf-eng/coding-challenge | /question03.py | 1,473 | 4.3125 | 4 | # 3. Check words with typos:
# There are three types of typos that can be performed on strings: insert a character,
# remove a character, or replace a character. Given two strings, write a function to
# check if they are one typo (or zero typos) away.
# Examples:
# pale, ple > true
# pales, pale > true
# pale, bale > true
# pale, bake > false
# Function for building a dictionary with the count for each letter in word
def get_letter_count(word):
letter_count = dict()
for letter in word:
# If dictionary has letter, increase count
if letter_count.get(letter):
letter_count[letter] += 1
else: # If not, start count
letter_count[letter] = 1
return letter_count
def is_typo(word1, word2):
letter_count1 = get_letter_count(word1)
letter_count2 = get_letter_count(word2)
size1 = len(word1)
matching_letters = 0
# Check each letter present on first word
for key in letter_count1.keys():
# Verify if it is present on the second dictionary
if letter_count2.get(key):
# Increment matching letter count
matching_letters += 1
# Calculate the difference in matching letters
difference = abs(size1 - matching_letters)
return difference <= 1
print("pale, ple ->", is_typo("pale", "ple"))
print("pales, pale ->", is_typo("pales", "pale"))
print("pale, bale ->", is_typo("pale", "bale"))
print("pale, bake ->", is_typo("pale", "bake"))
| true |
3d99c11bd5d21fa09e7f9bacedcb2da703477599 | meta3-s/K-Nearest-Neighbors-Python | /KNN.py | 1,753 | 4.21875 | 4 | ## Tutorial on the implementation of K-NN on the MNIST dataset for the recognition of handwritten numbers.
from sklearn.datasets import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# DisplayImage method to display image data (optional method)
def displayImage(i):
plt.imshow(digit['images'][i], cmap='Greys_r')
plt.show()
#Display of dataset
digit = load_digits() # loading the MNIST dataset
dig = pd.DataFrame(digit['data'][0:1700]) # Creation of a Panda dataframe
dig.head() # show the table below
# ## Let's display an image from the MNIST dataset!
displayImage(0) # display of the first image of the MNIST dataset
digit.keys()
train_x = digit.data
train_y = digit.target
# ### Splitting of the MNIST data set into Training set and Testing Set. With:
# * 75% in Training set
# * 25% in Testing set
x_train,x_test,y_train,y_test=train_test_split(train_x,train_y,test_size=0.25)
# ## Instantiation and training of a K-NN classifier with K = 7
KNN = KNeighborsClassifier(7)
KNN.fit(x_train, y_train)
# ## Calculation of the performance scoring of our 7-NN model
# Accuracy compared to test data
print(KNN.score(x_test,y_test))
# ## Prediction test of our model on a figure not yet seen
# Display an element of the image format matrix
test = np.array(digit['data'][1726])
test1 = test.reshape(1,-1)
displayImage(1726)
#Predicition Result : 3
#test = np.array(digit['data'][1720])
#test1 = test.reshape(1,-1)
#displayImage(1720)
#Predicition Result : 8
# Print Prediction
print("Predicted Number:", KNN.predict(test1))
| true |
f0a55ad1564a3bf36db8bb0206d9cab022effa6a | PacktPublishing/Python-for-the-.NET-Developer | /Ch05/05_01/Begin/Python_VSC/Ch2/Program.py | 1,776 | 4.34375 | 4 | import math
# This is a single-line comment
''' This is an
example of a
multi-line comment
'''
def demo_print_greeting():
print("Rise & Shine!!")
def demo_local_variable():
a_variable = 7
a_variable ="The name is 007"
print(a_variable)
name = "Unknown"
def demo_global_variable():
global name
name = "Paul"
print(name + "y")
def demo_arithmetic():
print("\nDemo Arithmetic\n")
print("7 + 2 =", 7+2)
print("7 - 2 =", 7-2)
print("7 * 2 =", 7*2)
print("7 / 2 =", 7/2)
print("7 % 2 =", 7%2)
print("7 ** 2 =", 7**2) #Power
print("7 // 2 =", 7//2) #Floor
print("math.floor(7/2) =", math.floor(7/2))
print("math.ceil(7/2) =", math.ceil(7/2))
def demo_order_of_operations():
print("\nDemo Order of Operations\n")
print("5+7-3*2 =", 5+7-3*2)
print("5+(7-3)*2 =", 5+(7-3)*2)
def demo_function_params(first,last):
print("The name is " + first + " " + last)
def demo_function_return(first, last):
full_name = first + " " + last
return "The full name is " + full_name
def demo_function_default(first = "Someone", last = "UnknownLast"):
full_name = first + " " + last
return "The full name is " + full_name
def demo_function_calls():
demo_function_params("James", "Bond") # executes function
print(demo_function_return("James", "Bond")) # prints returned value
print(demo_function_default(last="Bond")) # uses default value for 'first'
print(demo_function_return) # print object
def main():
#demo_print_greeting()
#demo_local_variable()
#demo_global_variable(); print(name)
#demo_arithmetic()
#demo_order_of_operations()
demo_function_calls()
if __name__ =="__main__":
main() | false |
34aeb29e9f40139d27530f54a7d595984a88974a | SurajKakde/Blockchain | /assignments/Assignment_Suraj.py | 657 | 4.25 | 4 | # collecting input from the user for name and age
name=input('Please enter your name: ')
age=input('Please enter your age: ')
def my_intro(name, age):
""" Concatenate the name and age and print"""
print('Hello! My name is '+name+' and my age is ' +age)
def add_strings(string1, string2):
"""concatenates two random strings
"""
print(string1 + ' ' + string2)
def decades_lived(age):
"""returns the number of decades lived
Arguments:
:age: Age fo the person
"""
return int(age) // 10
my_intro(name, age)
add_strings('hello', 'world')
print(name + ' already lived '+ str(decades_lived(age)) + ' decades.')
| true |
5470a958b10403c6a2c90bc068ec1193503632de | eevan7a9/playground-python3 | /dict.py | 540 | 4.40625 | 4 | # a dictionay of hero
hero = {
"name": "saitama",
"age": 25,
"email": "saitama@yahoo.com",
"purchase": [
"bannana",
"apple",
"pai"
]
}
# we print the hero name
print(hero["name"])
# we print the entire hero dictionary
print(hero)
# we change the hero name to 'master saitama'
hero["name"] = "master saitama"
# we now print the hero name; it's now changed
print(hero["name"])
# we loop through the dictionary hero to get its key and value
for key, value in hero.items():
print(key + " : " + str(value))
| false |
96938389c82a3f91cf88dd8e670faf540fcbff7c | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day17/review.py | 1,030 | 4.28125 | 4 | """
迭代
可迭代对象
迭代器
生成器
class 可迭代对象:
def __iter__():
创建迭代器对象
class 迭代器:
def __next__():
返回一个元素
如果没有元素,则抛出一个StopIteration异常
for 变量 in 可迭代对象:
变量得到的就是__next__方法返回值
原理:
iterator = 可迭代对象.__iter__()
while True:
try:
变量 = iterator.__next__()
print(变量)
except:
break
启发:调用next执行一次,计算一次,返回一次
生成器函数:
def 函数名():
yield 数据
# 调用方法不执行
生成器 = 函数名()
# for 生成器才执行函数体
for item in 生成器:
print(item)
优势:延迟/惰性操作
生成器源码
class 生成器:
def __iter__():
return self
def __next__():
定义着yield以前的代码
返回yield后面的数据
"""
| false |
ff185c8381ab3c89e9b6c7a5cf982a432a2b1940 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day08/day07_exercise/exercise01.py | 518 | 4.34375 | 4 | """
定义在控制台打印二维列表的函数
[
[1,2,3,44],
[4,5,5,5,65,6,87],
[7,5]
]
1 2 3 44
4 5 5 5 65 6 87
7 5
"""
def print_double_list(double_list):
"""
打印二维列表
:param double_list: 需要打印的二维列表
:return:
"""
for line in double_list:
for item in line:
print(item, end=" ")
print()
list01 = [
[1, 2, 3, 44],
[4, 5, 5, 5, 65, 6, 87],
[7, 5]
]
print_double_list(list01)
| false |
24b9f2bf9125b6469bb3b58d045b655e8b1e2e43 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day04/sort.py | 1,875 | 4.125 | 4 | """
sort.py 排序算法训练
"""
# 冒泡排序
def bubble(list_):
# 外层表示比较多少轮
for i in range(len(list_)-1):
# 内从循环表示每轮两两比较的次数
for j in range(len(list_)-1-i):
# 从大到小排序
if list_[j] < list_[j+1]:
list_[j],list_[j+1] = list_[j+1],list_[j]
# 完成一轮排序
def sub_sort(list_,low,high):
# 选定基准
x = list_[low]
# low向后,high向前
while low < high:
# 后面的数往前放
while list_[high] >= x and high > low:
high -= 1
list_[low] = list_[high]
# 前面的数往后放
while list_[low] < x and low < high:
low += 1
list_[high] = list_[low]
list_[low] = x
return low
# 快速排序
def quick(list_,low,high):
# low表示列表第一个元素索引,high表示最后一个元素索引
if low < high:
key = sub_sort(list_,low,high)
quick(list_,low,key-1)
quick(list_,key+1,high)
# 选择排序
def select(list_):
# 每轮选择最小值,需要len(list_)-1轮
for i in range(len(list_)-1):
min = i # 假设list_[i]为最小值
for j in range(i+1,len(list_)):
if list_[min] > list_[j]:
min = j # 擂主换人
# 进行交换,将最小值换到了应该在的位置
if min != i:
list_[i],list_[min] = list_[min],list_[i]
# 插入排序
def insert(list_):
# 判断每次比较的数是谁,从第二个数开始
for i in range(1,len(list_)):
x = list_[i] # 空出list_[i]的位置
j = i - 1
while j >= 0 and list_[j] > x:
list_[j+1] = list_[j]
j -= 1
list_[j+1]=x
l = [4,9,3,1,5,2,8,4]
# bubble(l)
# quick(l,0,len(l)-1)
# select(l)
insert(l)
print(l)
| false |
32c2314acb5f39e11e68401da3e1ec41624da7a6 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day14/demo2.py | 727 | 4.125 | 4 | """
运算符重载
"""
class Vector1:
def __init__(self,x):
self.x = x
def __str__(self):
return str(self.x)
def __add__(self, other):
return Vector1(self.x+other)
def __radd__(self, other):
return Vector1(self.x + other)
def __iadd__(self, other):
self.x += other
return self
v01 = Vector1(10)
print(v01+2)
print(2+v01)
print(id(v01))
# 重写 __iadd__,实现在原对象基础上的变化
# 如果不重写 __iadd__,默认使用 __add__,一般产生新对象
v01 += 2
print(v01,id(v01))
# list01 = [1]
# print(id(list01))
# # 生成新对象
# re = list01 + [2]
# print(re)
# # 在原有基础上累加
# list01 += [2]
# print(list01,id(list01))
| false |
4982fc5b669850922cfa4eb256eb81d10d6d0a91 | AnilNITK/Pycharm | /Greatest_number.py | 281 | 4.125 | 4 | x1=int(input("enter first number"))
x2=int(input("enter second number"))
x3=int(input("enter third number"))
if x1>x2 and x1>x3:
print(str(x1)+" is grteatest number")
elif x2>x3 and x2>x1:
print(str(x2)+" is greatest number")
else:
print(str(x3)+" is greatest number")
| false |
e6763855509e00ddf98426472a37c79d1f464df8 | vibhor-vibhav-au6/APJKalam | /week8/day03.py | 570 | 4.15625 | 4 | '''
Tell space complexity of following piece of code: (5 marks)
for i in range(n):
for j in range(n):
print(“Space complexity”)
'''
# O(N) = o(n) * o(n) = o(n^2)
'''
Reverse an array of integers and do not use inbuilt functions like “reverse”, don’t use shorts hands like “arr[::-1]”. Only use following approach:
swap first and last element,
then second and second last element,
till middle.
'''
def rev(arr):
l = len(arr)
for i in range(l//2):
arr[i], arr[l-i-1] = arr[l-i-1], arr[i]
return arr
print(rev([1,2,3,4,5,6,7,8,9])) | true |
844d4449de7f4571ba39ee86dd2d65a3edcf449a | vibhor-vibhav-au6/APJKalam | /week8/day01.py | 1,655 | 4.125 | 4 | '''
Recursive implementation of atoi() function:(5 marks)'''
def myAtoiRecursive(st):
if st == '':
return
if len(st) == 1:
return ord(st)-48
return ((ord(st[0])-48)*10**(len(st)-1)) + myAtoiRecursive(st[1:])
# '1234' = 1234 = 1*len(st)-1 **10
# 1*10**3 = 1000
# 2*10**2 = 200
# (ord('1')-48)*10**(len('1234')-1) + myAtoiRecursive('234')
# (ord('2')-48)*10**(len('234')-1) + myAtoiRecursive('34')
# '3' + myAtoiRecursive('4')
# '4' + myAtoiRecursive('')
# print(chr(48))
# print(myAtoiRecursive('1239'))
'''
Write a function that prints digits of a number from left to right , using
recursion
'''
# printRecursive(1234)
# printRecursive(1234//10)
# printRecursive(123//10)
# printRecursive(12//10)
# printRecursive(1//10)
# 1
# 2
# 3
# 4
def printRecursive(num):
if num < 10:
print(num)
else:
printRecursive(num // 10)
print(num % 10)
# printRecursive(1234)
'''Reverse a string using recursion'''
'abcd'
def reverseString(st):
if st == '':
return st
return st[-1]+ reverseString(st[:-1])
# print(reverseString('abcd'))
'''Recursive implementation of binary search'''
def binarySearch(array, target):
return binarySearchHelper(array, target, 0, len(array) - 1)
def binarySearchHelper(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
potentialMatch = array[middle]
if target == potentialMatch:
return middle
elif target < potentialMatch:
return binarySearchHelper(array, target, left, middle - 1)
else:
return binarySearchHelper(array, target, middle + 1, right)
# print(binarySearch([1,2,3,4,5,6], 4))
| false |
5e48f5bb5cffdf1bd49a9ca6f026ae06bbf7f1e4 | isemona/codingchallenges | /18-SwapCase.py | 1,476 | 4.1875 | 4 | #https://www.coderbyte.com/editor/Swap%20Case:Python
#Difficulty easy
#Implemented built in function .swapcase()
def SwapCase(str):
# code goes here
# swap letters small for cap, i/o str-str mutation; symbols stay as is, refactor
new_str = []
for i in str:
if i == i.lower():
new_str.append(i.upper())
else:
new_str.append(i.lower())
return(''.join(new_str))
# keep this function call here
print SwapCase(raw_input())
Using range
def SwapCase(str):
# in Python there is also a built-in function
# that swaps character cases for you
# return str.swapcase()
# turn the string into a list of characters
chars = list(str)
# loop through the array swapping letter cases
# uppercase -> lowercase
# lowercase -> uppercase
for i in range(0, len(chars)):
if chars[i] == chars[i].upper():
chars[i] = chars[i].lower()
elif chars[i] == chars[i].lower():
chars[i] = chars[i].upper()
# return the modified list of characters joined as a string
return ''.join(chars)
print SwapCase("Hello World")
Refactored
def SwapCase(s):
a = ''
for i in s:
if i == i.lower():
a += i.upper()
elif i == i.upper():
a += i.lower()
else:
a += i
return a
print SwapCase(raw_input())
Simplified
def SwapCase(s):
return(s.swapcase())
print SwapCase(raw_input())
| true |
2b9cfd9a36063e0a54b666afd4351e72d0cb3636 | PhuongBui27/python_ex | /LoopIfThenElse.py | 597 | 4.125 | 4 | '''number=int(input('Input an odd number: '))
if number %2==0:
print('Sorry, the number you enter is even number')
number=int(input('Input an odd number: '))
if number%2==1:
for i in range(number,0,-2):
for j in range(1,(number+1)//2):
print('',end='')
for k in range(number-i, number):
print(i,end='')
print('')
# Bài 2:
for i in range(1,100):
if i%3==0:
print('%3d' % (i),end='')
'''
numbers=[1,3,5,7,9,11,14,15]
for i in numbers:
if i%2==0:
print('Found even')
break
print('All are odd numbers')
| false |
988dd42a48919561214433608e085431fc0fac80 | obebode/EulerChallenges | /EulerChallenge/Euler4.py | 685 | 4.25 | 4 | def checkpalindrome(nums):
# return the palindrome numbers i.e original num equals to the same number in reverse form
return nums == nums[::-1]
def largestpalindrome():
# Initial largest to zero
largest = 0
# Nested for loop to generate three digit numbers for 100-999
# Check if product is higher than largest and is palindrome
# Assign largest to product and return largest
for i in range(100, 1000):
for j in range(100, 1000):
product = i*j
if product > largest and checkpalindrome(str(product)):
largest = product
return largest
# The correct answer is 906609
print(largestpalindrome())
| true |
1a474a4d6ccfdbe6c954766fa96ebaef9fb1c7c3 | arajitsamanta/google-dev-tech-guide | /python-basics/fundamentals/repition-statements.py | 2,738 | 4.15625 | 4 |
def whileLoop():
theSum = 0
i = 1
while i <= 100:
theSum = theSum + i
i = i + 1
print("The sum = ", theSum)
# The while loop is a compound statement and thus requires a statement block even if there is only a single statement to be executed. Consider the user of
# the while loop for user input validation
value = 0
while value < 0:
value = int(input("Enter a postive integer: "))
# The for loop in Python is more than a simple construct for creating general count-controlled loops as in Java. Instead, it is a generic sequence iterator that can
# step through the items of any ordered sequence object. The general syntax of the for loop is as follows
# for <loop-var> in <object> :
# <statement-block>
# The body of the loop (statement-block) is executed once for each item in the ordered sequence. Before beginning each iteration, the current item of the ordered
# sequence is assigned to the loop variable (loop-var).
def forLoop():
# single step iteration
for i in range(1, 11):
print(i)
# variable step increments
# Instead of stepping or counting by 1, a third argument can be provided to the xrange() function to indicate the step value.
for i in range(0, 51, 5):
print(i)
# Iterationg from zero
# Incrementing loops which start with an index of 0 are very common. Therefore, the xrange() function has a special version which starts at 0 and iterates a
# specified number of times. In the following example,
for i in range(20):
print(i)
# Reads a group of positive integer values from the user,
# one at a time, until a negative value is entered. The average
# value is then computed and displayed.
def avgValue():
# Initlize the counting variables.
total = 0
count = 0
# Extract the values.
value = int(input("Enter an integer value (< 0 to quit): "))
while value >= 0:
total = total + value
count = count + 1
value = int(input("Enter an integer value (< 0 to quit): "))
# Compute the average.
avg = float(total) / count
# Print the results.
print("The average of the", count, "values you entered is", avg)
# This program iterates through a string and counts the number of vowels it contains.
def countVowels():
# Extract a string from the user.
text = input("Enter a string to be evaluated: ")
# Iterate through the string.
numVowels = 0
vowels = "aeiou"
for ch in text:
if ch in vowels:
numVowels = numVowels + 1
# Print the results.
print("There are " + str(numVowels) + " vowels in the string.")
# invoke test functions
whileLoop()
forLoop()
avgValue()
countVowels()
| true |
3a2b69e1e977c7de04dd12b6b0d7d3f78b5e6efe | justien/lpthw | /ex_11xtnsn.py | 1,186 | 4.4375 | 4 | # -*- coding: utf8 -*-
# Exercise 11: Asking Questions
print "=================================================="
print "Exercise 11: Asking Questions"
print
print
# With this formulation, I can combine the string name with the question
# and the raw_input all at once.
name = raw_input("What is your name? ")
#^-- variable name
# ^---the type of input
# raw_input takes arguments; here, something to be
# printed to tty, and the implicit wait for input
# ^---variable declaration takes an input. arguments (?)
print "Hello, %s." % name
# ^---python prepares to display output as a string
# ^--- this variable is displayed as a string
# Wrapping raw_input() in int() converts the raw input into an integer
print "How old are you, in years?",
age = int(raw_input())
print "How tall are you, in centimetres?",
height = int(raw_input())
print "How much do you weigh, in kilos?",
weight = int(raw_input())
print
print "So %st, you're %r years old, %r centimetres tall, and you weigh %r kilos." %(
name, age, height, weight)
print
print
print "==================================================" | true |
de4a884792759d26a039007727f5387d802bafba | justien/lpthw | /ex8.py | 1,364 | 4.4375 | 4 | # -*- coding: utf-8 -*-
# Exercise 8: Printing, Printing
print "=================================================="
print "Printing, Printing"
print
print
# Formatter is a string, which text can be used as four values.
# It is a string that's made up of four raw inputs.
formatter = "%r %r %r %r"
# We now demonstrate that the value of the string conforms to python syntax.
# And by printing out exactly what is in the brackets (the supplied values),
# we can see that it is parsing the input as raw input.
# And that it can be used as a text source.
print formatter % (1, 2, 3, 4)
print
print formatter % ("one,", "two", "three", "four")
print
print formatter % (True, False, False, True)
print
print formatter % (formatter, formatter, formatter, formatter)
print
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
print
# The last item of the following will be printed out with double-quotes,
# whereas the first 3 lines will print out with single quotes.
# I think this is because it contains a single quote, so the representation
# is shown in double quotes to (somehow) escape the single-quote.
print formatter % (
"But it did not sing.",
"But it did not sing.",
"Nnn nn nnnnn nnnn.",
"Nnn nn nnnn'n nnnn."
)
print "=================================================="
| true |
a61b900e548eb869c5470b35139674bca31bcd3b | justien/lpthw | /ex10_formatting_cats.py | 1,005 | 4.1875 | 4 | # -*- coding: utf8 -*-
# Exercise 10: What was that?
print "=================================================="
print "Exercise 10: What was that?"
print
print
# here are the defined strings, including:
# * the use of \t to show a tab indentation
# * the use of \n to show a new line
# * the use of \ to escape the following '\' so it is printed
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat"
furry = "cat brush"
# fat_cat is a multi-line string, and uses \t to have nice formatting
fat_cat = '''
I'll do a list:
\t* Cat food
\t* Fishies (cat's favourite!)
\t* Catnip
\t* Grass\n\t* Grackle
'''
# furry_cat shows you how to escape the percentage sign so it can be printed
furry_cat = """
furry_cat needs 10%% time with\n\t* %s
""" % furry
print tabby_cat
print
print persian_cat
print
print backslash_cat
print
print fat_cat
print
print furry_cat
print
print
print "=================================================="
| true |
7136768c1f9c5aa645fc47517444c423d59e3989 | justien/lpthw | /ex11.py | 810 | 4.3125 | 4 | # -*- coding: utf8 -*-
# Exercise 11: Asking Questions
print "=================================================="
print "Exercise 11: Asking Questions"
print
print
# With this formulation, I can combine the string name with the question
# and the raw_input all at once.
name = raw_input("What is your name? ")
print "Hello, %s." % name
# Wrapping raw_input() in int() converts the raw input into an integer
print "How old are you, in years?",
age = int(raw_input())
print "How tall are you, in centimetres?",
height = int(raw_input())
print "How much do you weigh, in kilos?",
weight = int(raw_input())
print
print "So %s, you're %r years old, %r centimetres tall, and you weigh %r kilos." %(
name, age, height, weight)
print
print
print "=================================================="
| true |
3e84b12be6d6b54fabb5bfc379f4d84561fb54b6 | justien/lpthw | /ex34_Lists.py | 1,218 | 4.3125 | 4 | # -*- coding: utf8 -*-
# Exercise 34: Accessing Elements of Lists
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 34: Accessing Elements of Lists"
print
print
print "Here we're gonna understand CARDINALITY"
print
print "Let's practice cardinals with the following list:"
print "bear, python, peacock, kangaroo, whale, platypus"
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
raw_input("Which animal is at 1? ")
print animals[1]
print animals
raw_input("Which is the 3rd animal? ")
print animals[2]
print
print animals
raw_input("Which is the 1st animal? ")
print animals[0]
print
print animals
raw_input("Which is the animal at 3? ")
print animals[3]
print
print animals
raw_input("Which is the fifth animal? ")
print animals[4]
print
print animals
raw_input("Which is the animal at 2? ")
print animals[2]
print
print animals
raw_input("Which is the 6th animal? ")
print animals[5]
print
print animals
raw_input("Which is the animal at 4? ")
print animals[4]
print
print
print "=======================================================================" | false |
0309187a186d97e4656d0182e37a1c2be64fae16 | savva-kotov/python-intro-practise | /3-2-6.py | 943 | 4.125 | 4 | '''
Вспомните трюк с чтением последовательности с прошлого занятия. Вам подается на вход последовательность целых чисел,
в которой каждое число идет на новой строке. Заканчивается последовательность точкой.
Прочитайте такую последовательность и выведите список, содержащий её элементы.
Теперь Вы знаете про break и continue. Поэтому попробуйте решить эту задачу, использовав только один вызов функции input().
Sample Input 1:
1
2
3
.
Sample Output 1:
[1, 2, 3]
Sample Input 2:
.
Sample Output 2:
[]
'''
a = input()
res = []
if a != '.':
while a != '.':
res.append(int(a))
a = input()
print(res)
| false |
448bc46010c439ef8bbb4682dd71f4182799c994 | himynameismoose/Printing-Variables | /main.py | 2,048 | 4.4375 | 4 | # Lab 1.3: Printing & Variables
# Part 1: Printing Practice
# There are five lines of code provided to you in the Google Document.
# Enter the five lines of Python code below, and run it to see what happens.
# Make sure to respond to the prompts in the Google Document.
# /ghttps://docs.google.com/document/d/1Wt4zeX6yIoUBUqEyevYytRpU4yjKUwGLn4bxDqt8YPg/edit?usp=sharing
print("Part 1")
print()
print("1")
# Expected output: 1
print(1)
# Expected output: 1
print(1 + 2)
# Expected output: 3
print("1" + "2")
# Expected output: 12
print("this" + " " + "is" + " " + "a" + " " + "sentence" + ".")
# Expected output: this is a sentence.
print("-----------------------------------------------")
# Part 2: Variables Practice
# There are two lines of code provided to you in the Google Document.
# Enter the two lines of Python code below, and run it to see what happens.
# Make sure to respond to the prompts in the Google Document.
print("Part 2")
print()
animal = "dogs"
print(animal + "are really cool.")
print("-----------------------------------------------")
# What happens?
# The output is: dogsare really cool.
# How would you make the program print out "cats are really cool" instead?
# Reassign the variable 'animal' to string 'cats' and add a space before the word 'are' in the print statement.
# Part 3: From Snap to Python
# There is an image of some Snap code provided to you in the Google Document.
# Re-write the Snap code in Python below. Run it to make sure it works.
print("Part 3")
print()
number = 100
print(number)
number_2 = 100 + number
print(number_2)
print("-----------------------------------------------")
# Part 4: Four Fours
# Please see the Google Document for instruction.
# Write your code below. Run it to make sure it works.
print("Part 4")
print()
print("Zero is", 44 - 44)
print("One is", 44 / 44)
print("Two is", 4 * 4 / (4 + 4))
print("Three is", (4 + 4 + 4) / 3)
print("Four is", (4 - 4) / 4 + 4 )
print()
print("Extra Credit:")
print("Five is", ((4 * 4) + 4) / 4)
print("Six is", (4 + 4) / 4 + 4) | true |
9923a57fb40e19f65c5890625f31c3837413db4f | Agskvortsov/New_python_hw | /home_work_35.py | 2,065 | 4.28125 | 4 | # 35. Создать два класса: Окружность и Точка. Создать в классе окружности метод,
# который принимает в качестве параметра точку и проверяет находится ли данная точка внутри окружности.
class Point:
def __init__(self, name, coord_x, coord_y):
self.name = name
self.coord_x = coord_x
self.coord_y = coord_y
print("New point %s with coordinates x=%d, y=%d added" % (self.name, self.coord_x, self.coord_y))
class Circle:
def __init__(self, name, radius, coord_x, coord_y):
self.name = name
self.radius = radius
self.coord_x = coord_x
self.coord_y = coord_y
print("New circle %s with radius=%d and coordinates x=%d, y=%d added" % (self.name, self.radius, self.coord_y, self.coord_y))
def check(self, Point):
import math
x1 = self.coord_x
y1 = self.coord_y
r = self.radius
x2 = Point.coord_x
y2 = Point.coord_y
cat1 = abs(x2 - x1)
cat2 = abs(y2 - y1)
gippotenuse = math.sqrt(cat1**2 + cat2**2)
if cat1 == 0 or cat2 == 0:
if cat1 + cat2 <= r:
print("point is in circle1")
else:
print("point is not in circle1")
elif gippotenuse <= r:
print("point is in circle")
else:
print("point is not in circle2")
print(cat1, cat2)
A = Circle("Circle A", 3, 1, 2)
b = Point("Point -2,1", -3, 2)
Circle.check(A, b)
# def fill_truck(weight_limit, box_weight):
# qtty_of_box_loaded = weight_limit // box_weight # применено целочисленно деление
# total_weight = 0
# for i in range(1, qtty_of_box_loaded+1):
# total_weight = total_weight + box_weight
# print(("Ttl wght = %d , Ttl qtty of boxes = %d, last box weight = %d") %
# (total_weight, i, box_weight))
# fill_truck(2000, 500) | false |
bffc4b4dd0c997c57a348360d052283d95409dad | 4rude/WGUPS_Delivery_Program_C950 | /dsa_2/Truck.py | 754 | 4.21875 | 4 | class Truck:
"""
The Truck class is used to hold packages to delivery, hold location data about where the truck is at and where
it should go next, time data about the current time of the truck/driver, and the total mileage of the truck
objet.
"""
# Set the init method for the Truck class so a Truck class can be used to hold truck data, packages, current and
# future addresses that must be visited, and the amount of miles traveled by the truck.
def __init__(self, truck_id, time, package_list):
self.truck_id = truck_id
self.package_list = package_list
self.time = time
self.return_time = None
self.miles = 0.0
self.current_location = ""
self.next_location = ""
| true |
7a89f3ce8e82e16430e307a7647e84053b1c84b5 | Anjalibhardwaj1/Hackerrank-Solutions-Python | /Basics/Write_a_func.py | 1,243 | 4.1875 | 4 | #An extra day is added to the calendar almost every four years as February 29,
# and the day is called a leap day. It corrects the calendar for the fact that
# our planet takes approximately 365.25 days to orbit the sun. A leap year
# contains a leap day.
#In the Gregorian calendar, 3 conditions are used to identify leap years:
# -The year can be evenly divided by 4, is a leap year, unless:
# - The year can be evenly divided by 100, it is NOT a leap year, unless:
# - The year is also evenly divisible by 400. Then it is a leap year.
#This means that in the Gregorian calendar, the years 2000 and 2400 are leap
#years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.
#Task:
# Given a year, determine whether it is a leap year. If it is a leap year,
#return the Boolean True, otherwise return False.
#leap year function
def is_leap(year):
if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
leap = True
elif year % 4 == 0 and not year % 100 == 0 and not year % 400 == 0:
leap = True
else:
leap = False
return(leap)
#User year input
year = int(input('Enter a year to check if it is a leap year: '))
is_leap(year)
| true |
45741e375f049b22566ca98b54f966a531d18178 | sonalinegi/Training-With-Acadview | /thread.py | 1,039 | 4.21875 | 4 | #Create a threading process such that it sleeps for 5 seconds and then prints out a message.
import threading
import time
import math
def mythread() :
print('thread is starting')
time.sleep(5)
print('thread is ending')
t=threading.Thread(target=mythread)
t.start()
#Make a thread that prints numbers from 1-10, waits for 1 sec between
def mythread2():
for i in range(0,11):
print(threading.Thread,i)
time.sleep(1)
t=threading.Thread(target=mythread2)
t.start()
# Make a list that has 5 elements.
#Create a threading process that prints the 5 elements of the list with a delay of multiple of 2 sec between each display.
#Delay goes like 2sec-4sec-6sec-8sec-10sec
list=[1,2,3,4,5]
def mythread3(delay=1):
for i in list :
delay=delay*2
time.sleep(delay)
print(i)
t=threading.Thread(target=mythread3)
t.start()
#Call factorial function using thread.
def fact() :
no=int(input('enter a no'))
res=math.factorial(no)
print(res)
threading.Thread(target=fact).start()
| true |
805d046c0b89d814faafebef53c44e37eb23b69a | onc-healthit/SPD | /SPD Data Generator/nppes_data_generators/npis/utils.py | 860 | 4.25 | 4 | import operator
from fn.func import curried
def backward_digit_generator(number):
'''
Given a number, produces its digits one at a time starting from the right
:param number:
:return:
'''
if number == 0:
return
yield number % 10
yield from backward_digit_generator(number // 10)
def double_to_digit(d):
'''
Doubles a digit. If the result is a 2-digit number subtract 9 i.e. sum thw 2 digits
:param d:
:return:
'''
assert 0 <= d <= 18, "Expected a positive 1 or 2-digit number maxed at 18. Got %.0f" % d
dd = d * 2
return dd if dd < 10 else dd - 9
@curried
def add(x, y):
return operator.add(x, y)
@curried
def append_digit(number, digit):
'''
Appends a digit to a given number.
:param number:
:param digit:
:return:
'''
return number * 10 + digit
| true |
0e641db8d691a96cc7ea8a2336bc336c59330a4f | solomonli/PycharmProjects | /CodingBat/Logic-1/love6.py | 530 | 4.125 | 4 | def love6(a, b):
"""
The number 6 is a truly great number. Given two int values, a and b,
return True if either one is 6. Or if their sum or difference is 6.
Note: the function abs(num) computes the absolute value of a number.
love6(6, 4) → True
love6(4, 5) → False
love6(1, 5) → True
:param a: int
:param b: int
:return: boolean
"""
s = a + b
diff = abs(a - b)
return a == 6 | b == 6 | s == 6 | diff == 6
print(love6(6, 4))
print(love6(4, 5))
print(love6(1, 5))
| true |
0cfc99ea3265b2f6e04e1378e2730dff56e9bc02 | solomonli/PycharmProjects | /Stanford/Python Numpy Tutorial.py | 1,237 | 4.1875 | 4 | def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
small = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
big = [x for x in arr if x > pivot]
print(small, " AND ", mid, " AND ", big)
return quicksort(small) + mid + quicksort(big)
print(quicksort([3, 6, 8, 10, 100, 1, 2, 1]))
'''
WOW, WHAT A COOL,ELEGENT CODE!
'''
'''
1. Pick an element, called a pivot, from the array.
2. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot,
while all elements with values greater than the pivot come after it (equal values can go either way).
3. After this partitioning, the pivot is in its final position. This is called the partition operation.
Recursively apply the above steps to the sub-array of elements with smaller values
and separately to the sub-array of elements with greater values.
The base case of the recursion is arrays of size zero or one, which are in order by definition,
so they never need to be sorted.
The pivot selection and partitioning steps can be done in several different ways;
the choice of specific implementation schemes greatly affects the algorithm's performance.
'''
| true |
69f79ee16e480e49518c42354e0a5cae79d33c90 | solomonli/PycharmProjects | /The Absolute Basics/Chapter 3/Section 1.py | 1,112 | 4.28125 | 4 | __author__ = 'phil'
# Basic prompt
input("Prompt")
# Feeding the entered data from the prompt into a String variable
inputString = input("Enter something: ")
# Now output the String
print("You entered:", inputString)
# Assigning to a variable, and performing a calculation
mathsInt = (input("Enter an integer: ") / 2)
# Basic assigning
string = "I hate Python"
# Output the original
print(string)
# Replacing the contents of the string variable
string.replace("hate", "love")
# Output the new version
print(string)
# Basic assigning
phrase = "These are the strings you are looking for"
# Output the original
print(phrase)
# Replacing the contents
phrase.replace("the strings", "not the droids")
# Print the new version
print(phrase)
# Basic assigning
messyString = "tHis sTRinG is A MEss"
# Print the original
print(messyString)
# Change the case of messyString to Title Case, and assign it to titleString
titleString = messyString.title() # Remember that title() and other case changers often do not affect the original string
# Print out both messyString and titleString
print(messyString, titleString)
| true |
3d83a21171ae14b33c7ce1bf1fab9a2f8a2575d9 | Zak-Kent/Hack_O_class | /wk1/names_challenge.py | 835 | 4.21875 | 4 | """
The goal of this challenge is to create a function that will take a list of
names and a bin size and then shuffle those names and return them in a
list of lists where the length of the inner lists match the bin size.
For example calling the function with a list of names and size 2 should return
a list of lists where each inner list has 2 random names. If the the number
of names provided doesn't divide evenly into the bin size and only one name is
remaining add that name to another inner list.
"""
def names_func(a_list, size):
"""
This func should take a list and size, break the list into lists of the
size and return a list of lists.
"""
return None
if __name__ == '__main__':
# Any code here will run when the file is called by name on the command line
print(names_func([1,], 2))
| true |
da632a41ed0b9cd24276ccde14c70b2080fe2bdd | akyerr/Codewars-Examples | /facebook_likes.py | 823 | 4.1875 | 4 | """
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:
"""
def likes(names):
if len(names) == 0:
return "no one likes this"
elif len(names) == 1:
return "{} likes this".format(names[0])
elif len(names) == 2:
return "{} and {} like this".format(names[0], names[1])
elif len(names) == 3:
return "{}, {} and {} like this".format(names[0], names[1], names[2])
else:
return "{}, {} and {} others like this".format(names[0], names[1], (len(names)-2))
print(likes(['Peter'])) | true |
64a1ce15b855819cf6b3456f95bb87c4ee592052 | akyerr/Codewars-Examples | /add_and_convert_to_Binary.py | 284 | 4.40625 | 4 | """
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.
The binary number returned should be a string.
"""
def add_binary(a,b):
result = bin(a+b)
return result[2:]
print(add_binary(1,1)) | true |
c687037d35ef6aacc65d171c1d87ae2f7367a972 | karar-vir/python | /difference_between_sort_and_sorted.py | 375 | 4.34375 | 4 | langs = ["haskell", "clojure", "apl"]
print(sorted(langs)) #sorted(langs) will return the new list bt it will not effect the original list
print('original list : ',langs)
langs.sort() #langs.sort() will return the new sorted list placed at the previous list
print(langs)
#Reverse() funtion
print('original list : ',langs)
langs.reverse()
print(langs)
| true |
56925000eaeb4f5f51574302ac5aada4e9657783 | Adrncalel/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 893 | 4.5 | 4 | #!/usr/bin/python3
class Square:
"""An empty class that defines a square"""
def __init__(self, size=0):
"""inizialization and conditioning input only to be integer"""
'''
if isinstance(size, int) == False:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
'''
self.__size = size
def area(self):
"""returns the area of the Square object"""
return (self.__size * self.__size)
@property
def size(self):
"""Setting of getter that will get the private attribute"""
return self.__size
@size.setter
def size(self, value):
if isinstance(value, int) is False:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
| true |
dd0cc39c574724db9e894830f1b60b788a8f95f6 | Adrncalel/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 475 | 4.28125 | 4 | #!/usr/bin/python3
"""
This is the add_integer module
The function adds two integers or floats
"""
def add_integer(a, b=98):
"""This function adds to variables 'a' and 'b' which
can be either float or int and returns the value
casted to int"""
if isinstance(a, (float, int)) is False:
raise TypeError("a must be an integer")
if isinstance(b, (float, int)) is False:
raise TypeError("b must be an integer")
return (int(a) + int(b))
| true |
f41270ab8de5dcb8b5405ae7c5c6b163021a1906 | ngupta10/Python_Learnings | /Basic Python Scripts/List&Functions.py | 2,416 | 4.625 | 5 | """
0.Setup:
a.create a list of integers and assign it to a variable
b.create a list of strings and assign it to a variable
c.create a list of floats and assign it to a variable
1.Passing A List to A Function:
a.create a function that takes and returns an input
b.print a call of the function you created in step 1.a. with the list of integers from step 0.a. as the input
c.print a call of the function you created in step 1.a. with the list of strings from step 0.b. as the input
d.print a call of the function you created in step 1.a. with the list of floats from step 0.c. as the input
2.Accessing An Element In A list using A Function:
a.create a function that takes a list as an input and returns one of that lists elements
b.print a call of the function you created in step 2.a. with the list of integers from step 0.a. as the input
c.print a call of the function you created in step 2.a. with the list of strings from step 0.b. as the input
d.print a call of the function you created in step 2.a. with the list of floats from step 0.c. as the input
3.Modifying A List Element Within A Function:
a.create and call a function that prints the product of all the integers from the list you created in step 0.a.
b.create and call a function that concatenates all the strings from the list you create in step 0.b and prints the
result
c.create and call a function that prints the quotient of all the floats from the list you created in step 0.c.
4.Manipulating Lists Within Functions:
a.create a list that uses 3 of the following functions on one of the lists you created in part 0 of
this problem set: .index(), .append(), .remove(), .insert, or .pop().
Also, make sure that the function prints the resulting list
b.call the function from part
4.a. using one of the lists you made in part 0 of this problem set.
"""
li1 = [1,2,3,4,5]
li2 = ["aaaa","bbbb","ccccc","dddddd","eeeeee"]
li3 = [1.1,2.2,3.3,4.4,5.5]
def ex1(li):
return li[0]
print(ex1(li1))
print(ex1(li2))
print(ex1(li3))
def ex2(li):
total =1
for nums in li:
total *= nums
return total
print(ex2(li1))
def ex3(li):
str =""
for st in li:
str += st
return str
print(ex3(li2))
def ex4(li):
print(li[2]/li[1])
ex4(li3)
def ex5(li):
li.append(6)
li.pop(3)
li.insert(0,10)
return li
print(ex5(li1)) | true |
025c7bf7c4ab66a8aa5e826964f7a68ca0245b88 | ngupta10/Python_Learnings | /Basic Python Scripts/commentsAndMathOperators.py | 1,538 | 4.1875 | 4 | """
comments practice:
1.create a single line comment 2.create a multiple line comment
"""
# enter your code for "comments practice" between this line and the line below it---------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
"""
basic mathematical operators practice: 1.create a variable called add and assign it the sum of two numbers
2.create a variable called sub and assign it the difference of two numbers
3.create a variable called mult and assign it the product of two numbers
4.create a variable called div and assign it the quotient of two numbers
5.create a variable called power and assign it the value of a number raised to a power
6.create a variable called mod and assign it the emainder of a quotient
"""
add = 1+2
sub = 2 -1
mult = 3 * 2
div = 10 / 5
power = 2**2
mod = 10 % 7
""" modulo practice: 1.create a variable called mod1 and assign it the result of 7 % 5
2.create a variable called mod2 and assign it the result of 16 % 6
3.create a variable called mod3 and assign it the result of 4 % 3
"""
mod1 = 7 % 5
mod2 = 16 % 6
mod3 = 4 % 3
""" order of operations practice:
1.create and assign a variable called ordOp1 the result of 7 + 6 + 9 - 4 * ((9 - 2) ** 2) / 7
2.create and assign a variable called ordOp2 the result of (6 % 4 * (7 + (7 + 2) * 3)) ** 2 """
ordOp1 = 7 + 6 + 9 - 4 * ((9 - 2) ** 2) / 7
ordOp2 = (6 % 4 * (7 + (7 + 2) * 3))
| true |
399818ed5f45d6d9a0c5756ad3a9121742709f1a | Junghyo/pycharm | /data_science/basic/01_data_type/practice02_operator.py | 1,670 | 4.15625 | 4 | """
# 연산자
1. 산술연산자
+, -, *, /
제곱 : **
나머지를 산출 : %
몫 : //
"""
print("plus", 5 + 2) # 7
print("minus", 5 - 2) # 3
print("multiple", 5 * 2) # 10
print("divide", 5 / 2) # 2.5
print("square", 5 ** 2) # 25
print("reminder", 5 % 2) # 1
print("quotient", 5//2) # 2
"""
2. 비교 연산자
==, !=, <, >, <=, >=
"""
num = 10
if num == 1:
print("num is 1")
else:
print("num is not 1")
if num >= 1:
print("num is more then 1")
else:
print("num is less than 1")
"""
3. 할당연산자
+=, -=, *=, /=, %=, //=
"""
print(num * 10) # 100
num *= 10
print(num) # 100
"""
4. 논리연산자
and, or, not
and : 양쪽 모두 참
or : 둘중 하나만 참
not : 참이면 거짓, 거짓이면 참
"""
x = True
y = False
if x and y:
print("yes")
else:
print("no")
if x or y:
print("yes")
else:
print("no")
"""
5. Bitwise 연산자
&(AND), |(OR), ^(XOR), ~(Complement), <<, >>(Shift)
비트단위의 연산을 하는데 사용
"""
a = 8
b = 11
c = a & b
d = a ^ b
e = a >> b
f = a << b
g = ~ b
h = ~ a
print(c) # 8
print(d) # 3
print(e) # 0
print(f) # 16384
print(g) # -12
print(h) # -9
"""
6. 멤버쉽 연산자
in, not in
좌측 Operand가 우측 Collection(List)에 속해 있는지 Check
"""
a = [1, 2, 3, 4]
if 3 in a:
print("3 is in", a)
else:
print("3 is not in", a)
if 10 not in a:
print("10 is not in", a)
else:
print("10 is in", a)
"""
7. Identify 연산자
is, is not
양쪽 Operand가 동이한 Object인지 아닌지 Check
"""
a = "ABC"
b = a
print(a is b) # True
b = "abc"
print(a is b) # False
print(a is not b) # True | false |
2567d02810607eb8e12826e5aceb419dfedf2a9d | fs412/codingsamples | /HW01fransabetpour-1.py | 2,090 | 4.25 | 4 | """ My name is Fran Sabetpour and here is my script for the classic "Rock, Paper, Scissors" game! """
def startover():
# User gets to input their choice between rock, paper, scissors.
game = input("Let's play some Rock, Paper, Scissors! R = rock, S = scissors, P = paper. Press Q if you would like to quit. Now let's begin! Rock, paper, scissors, shoot! (Enter your answer): ")
if game == "R":
print("You have drawn rock!")
elif game == "S":
print("You have drawn scissors!")
elif game == "P":
print("You have drawn paper!")
# Here's an option for the user to quit the game.
elif game == "Q":
import sys
sys.exit()
# Now, it is the computer's turn to make a random choice.
play = ["rock", "paper", "scissors"]
import random
player = random.choice(play)
# This determines whether the user has lost, won, or got a tie.
if game == "R" and player == "scissors":
print("Computer draws scissors. You win!")
elif game == "R" and player == "rock":
print("Computer draws rock. We have a tie!")
elif game == "R" and player == "paper":
print("Computer draws paper. You lose!")
if game == "P" and player == "scissors":
print("Computer draws scissors. You lose!")
elif game == "P" and player == "rock":
print("Computer draws rock. You win!")
elif game == "P" and player == "paper":
print("Computer draws paper. We have a tie!")
if game == "S" and player == "scissors":
print("Computer draws scissors. We have a tie!")
elif game == "S" and player == "paper":
print("Computer draws paper. You lose!")
elif game == "S" and player == "rock":
print("Computer draws rock. You win!")
# Here is an option for the player to quit the game or try again.
answer = input("Would you like to play again? Enter 'Y' for yes or 'N' for no. ")
if answer == "N":
import sys
sys.exit()
if answer == "Y":
print("Alright! Let's play again!")
while True:
startover() | true |
abe82b0d19fc671d7fc82e3d449324369accc2c6 | JayChenFE/python | /fundamental/automate_the_boring_stuff_with_python/exercise/ch7/7.18.1_强口令检测.py | 965 | 4.125 | 4 | '''
写一个函数,它使用正则表达式,确保传入的口令字符串是强口令。
强口令的定义是:
长度不少于8 个字符,同时包含大写和小写字符,至少有一位数字。
你可能需要用多个正则表达式来测试该字符串,以保证它的强度。
'''
import re
def passStrengthTest(passWord):
lowerRegex = re.compile(r'[a-z]')
upperRegex = re.compile(r'[A-Z]')
numRegex = re.compile(r'[0-9]')
moLower = lowerRegex.search(passWord)
moUpper = upperRegex.search(passWord)
moNum = numRegex.search(passWord)
if len(passWord) < 8:
print('Your password is less than 8 characters which is too short.')
elif not moLower:
print('You need at least one lower case letter.')
elif not moUpper:
print('You need at least one upper case letter.')
elif not moNum:
print('You need at least one number.')
else:
print('Your password is strong!')
| false |
7ffb535c242ea256f5c6c989805d1eb17f8adb1a | JayChenFE/python | /fundamental/python_crash_course/exercise/ch04/4-11.py | 827 | 4.21875 | 4 | # 4-11
# 你的比萨和我的比萨 :在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friend_pizzas 中,再完成如下任务。
# 在原来的比萨列表中添加一种比萨。
# 在列表friend_pizzas 中添加另一种比萨。
# 核实你有两个不同的列表。为此,打印消息“My favorite pizzas are:”,
# 再使用一个for 循环来打印第一个列表;打印消息“My friend's favorite pizzas are:”,
# 再使用一个for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
my_pizzas = ['a','b','c','d']
friend_pizzas = my_pizzas[:]
my_pizzas.append('e')
friend_pizzas.append('f')
print('My favorite pizzas are:')
print(my_pizzas)
print("\nMy friend's favorite pizzas are:")
print(friend_pizzas)
| false |
b35390238fc7717476eb6ef747b737c6ef8b8f21 | JayChenFE/python | /fundamental/python_crash_course/exercise/ch04/4-10.py | 753 | 4.3125 | 4 | # 4-10
# 切片 :
# 选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
# 打印消息“The first three items in the list are:”,再使用切片来打印列表的前三个元素。
# 打印消息“Three items from the middle of the list are:”,再使用切片来打印列表中间的三个元素。
# 打印消息“The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。
num = [1,2,3,4,5,6,7]
print('The first three items in the list are:')
print(num[:3])
print('The middle three items in the list are:')
start_index = int((len(num) - 3) / 2)
print(num[start_index:start_index + 3])
print('The last three items in the list are:')
print(num[-3:])
| false |
465371a901d073b4430231511a41d860c180dc4f | learnpi/codepy | /Day3/if_4.py | 597 | 4.1875 | 4 | lst_edible_fruits = ['apple','gauva','raspberry', 'cherry', 'jackfruit']
lst_non_edible_fruits = ['grapes','orange','banana','watermelon','mango']
dict_fruits = {'edible_fruits': lst_edible_fruits,
'non_edible_fruits':lst_non_edible_fruits}
choice_fruit_str = input('Enter a fruit name to check : ')
if choice_fruit_str in dict_fruits['edible_fruits']:
print('You can have the fruit',choice_fruit_str)
elif choice_fruit_str in dict_fruits['non_edible_fruits']:
print('You are forbidden to have this fruit')
else:
print('Fruit not listed , Please consult the doctor')
| false |
3e340a8d4c5f63d1becbb2bef3755e59c71213b4 | jefersonlima/Courses | /Cursos/UdemyProgramacaoEmPythonDoBasicoAoAvancado/guppe/secao_13_LeituraEEscritaEmArquivos/seek_e_cursors.py | 1,509 | 4.59375 | 5 | """
Seek e Cursors
seek() -> É utilizada para movimentar o cursor pelo arquivo.
arquivo = open('t.txt')
print(arquivo.read())
# seek() -> A função seek() é utilizada para movimentação do cursor pelo arquivo. Ela recebe um
# parâmetro que indica onde queremos colocar o cursor.
# Movimentando o cursor pelo arquivo com a função seek()
arquivo.seek(0)
print(arquivo.read())
arquivo.seek(22)
print(arquivo.read())
arquivo = open('t.txt')
# readline() -> função que lê o arquivo linha a linha
ret = arquivo.readline()
print(type(ret))
print(ret)
print(ret.split(' '))
arquivo = open('t.txt')
# readlines() -> retorna uma lista das linhas
linhas = arquivo.readlines()
print(len(linhas))
# OBS: Quando abrimos um arquivo com a função open() é criada uma conexão entre o arquivo
no disco do computador e o nosso programa. Essa conexão de streaming. Ao finalizar
os trabalhos com o arquivo devemos fechar essa conexão. para isso utilizamos a função close()
Passo para se trabalhar com um arquivo:
1 - Abrir o arquivo:
2 - trabalhar o arquivo:
3 - Fechar o Arquivo:
"""
# 1 - Abrir o arquivo:
arquivo = open('texto.txt')
# 2 - trabalhar o arquivo:
print(arquivo.read())
print(arquivo.closed) # Verifica se o arquivo está aberto ou fechado
# 3 - Fechar o Arquivo:
arquivo.close()
print(arquivo.closed) # Verifica se o arquivo está aberto ou fechado
# OBS: Se tentarmos manipular o arquivo após seu fechamento, termos um ValueError
# print(arquivo.read())
| false |
7b7337c7736073bc8d95807d99c4164012a65b8d | jefersonlima/Courses | /Cursos/UdemyProgramacaoEmPythonDoBasicoAoAvancado/guppe/secao_12_TrabalhandoComModulosEPacotesEmPython/modulos_customizados.py | 949 | 4.34375 | 4 | """
Módulos Customizados
Como módulos Python nada mais são do que arquivos Python, Então TODOS os arquivos que criamos
neste curso são módulos Python prontos para serem utilizados.
# ### CORRIGIDO ###
# Resolver isso no futuro devido eu ter organizado por diretórios e o professor nao fez isso por isso não consigo
# Importar igual o exemplo dessa aula
from guppe.secao_8_FuncoesEmPython import funcoes_com_parametros as fcp
print(fcp.soma_impares([1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(soma_impares([1, 2, 3, 4, 5, 6, 7, 8, 9]))
# Importando todo o módulo (Temos acesso a TODOS os elementos do módulo)
from guppe.secao_8_FuncoesEmPython import funcoes_com_parametros as fcp
# Estamos acessando e imprimindo uma variável contida no módulo
print(fcp.lista)
print(fcp.tupla)
print(fcp.soma_impares(fcp.lista))
from guppe.secao_10_ExpressoesLambdasEFuncoesIntegradas import map as m
print(list(map(m.c_para_f, m.cidades)))
"""
| false |
592211d0a479a900ec1abf5d0106224c421fc630 | jefersonlima/Courses | /Cursos/UdemyProgramacaoEmPythonDoBasicoAoAvancado/guppe/secao_12_TrabalhandoComModulosEPacotesEmPython/modulos_builtin.py | 1,199 | 4.21875 | 4 | """
Trabalhando com Módulos Builtin (módulos integrados, que já vem instalados no Python)
httos://docs.python.org/3/py-modindex.html
________________________
|Python|Módulos Builtin|
------------------------
# utilizando alias (apelidos) para módulos/funções
# Apelido no Módulo
import random as rdm
# print(rdm.random())
# Apelido na função
from random import randint as rdi, random as rdm
print(rdi(5,89))
print(rdm())
print(rdm.random())
# from random import random
# Podemos importar todas as funções de um módulo utilizando o *
# import random # está importando tudo mas para usar precisa chamar o módulo seguido de ponto + o nome da funçao
# print(random.random())
# Importando t'odo o modulo
from random import * # assim é só usar a função sem precisar charmar com o modulo
print(random())
# Costumamos utilizar tuple para colocar multiplos imports de um mesmo módulo
# errado
from random import random, randint, shuffle, choice
# Correto
from random import (
random,
randint,
shuffle,
choice
)
print(random())
print(randint(3, 7))
lista = ['Geek', 'University', 'Python']
shuffle(lista)
print(lista)
print(choice('University'))
"""
| false |
a2cee6b8c3239bb858b4fd50dd64027b58b8c027 | jefersonlima/Courses | /Cursos/UdemyProgramacaoEmPythonDoBasicoAoAvancado/guppe/secao_9_ComprehensionsEmPython/list_comprehension_p1.py | 1,481 | 4.6875 | 5 | """
List Comprehension (*Compreenção de listas)
- Utilizando list Comprehension nós podemos gerar novas listas com dados processados a partir de outro
interável
# Sintaxe da List Comprehension
[ dado for dado in interável ]
# Exemplos
numeros = [1, 2, 3, 4, 5]
res = [numero * 10 for numero in numeros]
print(res)
# Para entender melhor o que está acontecendo devemos dividir a expressão em duas partes:
# - A primeira parte: for numero in numeros
# - A segunda parte: numero * 10
res = [numero / 2 for numero in numeros]
print(res)
def funcao(valor):
return valor * valor
res = [funcao(numero) for numero in numeros]
print(res)
# List Comprehension versus Loop
# Loop
numeros = [1, 2, 3, 4, 5]
numeros_doblados = []
for numero in numeros:
numero_doblado = numero * 2
numeros_doblados.append(numero_doblado)
print(numeros_doblados)
# Loop Mehorado
numeros = [1, 2, 3, 4, 5]
numeros_doblados = []
for numero in numeros:
numeros_doblados.append(numero * 2)
print(numeros_doblados)
# List Comprehension
print([numero * 2 for numero in numeros])
# Outros exemplos
# 1
nome = 'Geek University'
print([letra.upper() for letra in nome])
# 2
amigos = ['maria', 'julia', 'pedro', 'guilherme', 'vanessa']
print([amigo.title() for amigo in amigos])
# 3
print([numero *3 for numero in range(1, 10)])
# 4
print([bool(valor) for valor in [0, [], '', True, 1, 3.14]])
# 5
print([str(numero) for numero in [1, 2, 3, 4, 5]])
"""
| false |
c8fc402ee1dcba95dc7b9e3d5bc1f408fb66e418 | JohnJGreen/1310Python | /hw01/hw01_task4.py | 786 | 4.125 | 4 | # John Green
# UT ID 1001011958
# 9/01/13
# Write a program that asks the user to enter two real numbers (not integers) and
# computes and displays the following opertations between the two:
# multiplication, division, integer division, modulo , exponentiation
# hw01_task4
# First number
first_flt = float(input("Enter the first number: "))
# Second number
second_flt = float(input("Enter the second number: "))
# multiply
print(first_flt, "*", second_flt, "=", first_flt*second_flt)
# divide
print(first_flt, "/", second_flt, "=", first_flt/second_flt)
# int divition
print(first_flt, "//", second_flt, "=", first_flt//second_flt)
# modulis
print(first_flt, "%", second_flt, "=", first_flt%second_flt)
# exponetial
print(first_flt, "**", second_flt, "=", first_flt**second_flt)
| true |
c2eb184d8c3088aeb4adf1f491ae54be853fbb1f | ABROLAB/Basecamp-Technical-Tasks | /Task_7.py | 883 | 4.1875 | 4 | '''
Write a function that takes an array of positive
integers and calculates the standard deviation of
the numbers. The function should return the standard deviation.
'''
def Calc_Standard_Dev(int_array):
standard_deviation = 0
sqr_mean = 0
sqr_array = []
# step 1: calculate the mean
mean = sum(int_array)/len(int_array)
# Step 2: subtract each integer from mean then square
for element in int_array:
sqr = pow((mean - element),2)
sqr_array.append(sqr)
# step 3: calculate mean of integers gotten from step 2
sqr_mean = sum(sqr_array)/len(sqr_array)
# Step 4: Take the square root of the result in step 3
standard_deviation = pow(sqr_mean,0.5)
return standard_deviation
Result = Calc_Standard_Dev([9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4])
print(Result)
| true |
5cbd32acc84eec60397e0adf2ee48a05cfbfc371 | ProjitB/StoreHouse | /bomberman/Assignment1_20161014/brick.py | 582 | 4.21875 | 4 | import random
from random import randint
class Brick(object):
def __init__(self, board):
'''Initializes the board
'''
self.board = board.board
#Random initial location for Brick
x = randint(3, board.size)
y = randint(3, board.size - 1)
#If original position not allowed:
while board.board[x][y] != "Empty":
x = randint(3, board.size - 1)
y = randint(3, board.size - 1)
#Printing brick position on the board
board.board[x][y] = "Brick"
self.x = x
self.y = y
| true |
403a7797feb8891f815fcb5ef602a87349ef42eb | Aalukis1/Basic-Python-programming | /second.py | 293 | 4.25 | 4 | #FOR AND WHILE LOOP
# for a in range(1,10):
# print(a)
# if a == 5:
# break
# for odd in range(1,36,2):
# print ("odd numbers are: ", odd)
# for even in range(2,35,2):
# print ("even numbers are: ", even)
x = 2
while x >= 1 and x <= 35):
print (x)
x = x + 2 | false |
d39052ddac2e15a63ff8e3c956c7628ad7e6bea8 | eduardoprograma/linguagem_Python | /Introdução à Programação com Python/Do autor/Códigi fonte e listagem/listagem/capitulo 03/03.27 - Erro de conversão vírgula no lugar de ponto.py | 1,151 | 4.15625 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem\capitulo 03\03.27 - Erro de conversão vírgula no lugar de ponto.py
##############################################################################
# Na tela:
"""
Digite seu nome: Mary
Digite sua idade: 25
Digite o saldo da sua conta bancária: 17,4
Traceback (most recent call last):
File "input/input2.py", line 3, in <module>
saldo = float(input("Digite o saldo da sua conta bancária: "))
ValueError: invalid literal for float(): 17,4
"""
| false |
a28d84c47f416b1da64d07ebd1b9ed89d387c451 | eduardoprograma/linguagem_Python | /Introdução à Programação com Python/Do autor/Exercícios resolvidos/exercicios/capitulo 05/exercicio-05-12.py | 1,227 | 4.4375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 05\exercicio-05-12.py
##############################################################################
depósito = float(input("Depósito inicial: "))
taxa = float(input("Taxa de juros (Ex.: 3 para 3%): "))
investimento = float(input("Depósito mensal:"))
mês = 1
saldo = depósito
while mês <= 24:
saldo = saldo + (saldo * (taxa / 100)) + investimento
print ("Saldo do mês %d é de R$%5.2f." % (mês, saldo))
mês = mês + 1
print ("O ganho obtido com os juros foi de R$%8.2f." % (saldo-depósito))
| false |
23575e3b315bfbb17f59e7581610b1f87f75c5e6 | eduardoprograma/linguagem_Python | /Introdução à Programação com Python/Do autor/Exercícios resolvidos/exercicios/capitulo 04/exercicio-04-10.py | 1,326 | 4.3125 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 04\exercicio-04-10.py
##############################################################################
consumo=int(input("Consumo em kWh:"))
tipo=input("Tipo da instalação (R,C ou I):")
if tipo == "R":
if consumo <= 500:
preço = 0.40
else:
preço = 0.65
elif tipo == "I":
if consumo <= 5000:
preço = 0.55
else:
preço = 0.60
elif tipo == "C":
if consumo <=1000:
preço = 0.55
else:
preço = 0.60
else:
preço = 0
print("Erro ! Tipo de instalação desconhecido!")
custo = consumo * preço
print("Valor a pagar: R$ %7.2f" % custo)
| false |
0e09b97438dc5ee7674acb8828162530dd5cfb18 | eduardoprograma/linguagem_Python | /Introdução à Programação com Python/Do autor/Exercícios resolvidos/exercicios/capitulo 03/exercicio-03-15.py | 1,151 | 4.375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 03\exercicio-03-15.py
##############################################################################
cigarros_por_dia=int(input("Quantidade de cigarros por dia:"))
anos_fumando=float(input("Quantidade de anos fumando:"))
redução_em_minutos = anos_fumando * 365 * cigarros_por_dia * 10
# Um dia tem 24 x 60 minutos
redução_em_dias = redução_em_minutos / (24 * 60)
print("Redução do tempo de vida %8.2f dias." % redução_em_dias)
| false |
cf50da36792edbb6f338c6cff1c1fe4001b556f0 | eduardoprograma/linguagem_Python | /Introdução à Programação com Python/Do autor/Exercícios resolvidos/exercicios/capitulo 06/exercicio-06-07.py | 1,228 | 4.3125 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 06\exercicio-06-07.py
##############################################################################
expressão = input("Digite a sequência de parênteses a validar:")
x=0
pilha = []
while x<len(expressão):
if(expressão[x] == "("):
pilha.append("(")
if(expressão[x] == ")"):
if(len(pilha)>0):
topo = pilha.pop(-1)
else:
pilha.append(")") # Força a mensagem de erro
break
x=x+1
if(len(pilha)==0):
print("OK")
else:
print("Erro")
| false |
fe6a6f701407eff698c2c42b4033715d1cf4537b | eduardoprograma/linguagem_Python | /Introdução à Programação com Python/Do autor/Exercícios resolvidos/exercicios/capitulo 06/exercicio-06-13.py | 1,226 | 4.375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 06\exercicio-06-13.py
##############################################################################
T=[-10,-8,0,1,2,5,-2,-4]
mínima = T[0] # A escolha do primeiro elemento é arbitrária, poderia ser qualquer elemento válido
máxima = T[0]
soma = 0
for e in T:
if e < mínima:
mínima = e
if e > máxima:
máxima = e
soma = soma + e
print("Temperatura máxima: %d °C" % máxima)
print("Temperatura mínima: %d °C" % mínima)
print("Temperatura média: %d °C" % (soma / len(T)))
| false |
76bf387637e4e51f639f00d9e7297acc297114ca | sjay05/CCC-Solutions | /2007/J4.py | 305 | 4.21875 | 4 | """
author: sjay05
"""
word1 = raw_input()
word2 = raw_input()
if len(word1) != len(word2):
print "It is not a anagram."
else:
w1l = sorted([c for c in word1])
w2l = sorted([c for c in word2])
if w1l == w2l:
print "It is a anagram."
else:
print "It is not a anagram."
| false |
3f5345a8ed48cbdcb9f72d4a7d3df7ffdb2277c4 | thessaly/python_boringstuff | /2.py | 1,069 | 4.25 | 4 |
name = ''
# Example of infinite loop
#while name != 'your name':
# print('Please type your name.')
# name = input()
#print('Thanks!')
# When used in conditions, 0, 0.0 and ' ' are considered False
# name = ''
# while not name:
# print('Enter your name:')
# name = input()
# print('How many guests will you have?')
# numOfGuests = int(input())
# if numOfGuests:
# print('Be sure to have enough room for all your guests.')
# print('Done')
# # Gauss counter
# total = 0
# for num in range(101):
# total = total + num
# print(total)
# Range can take three arguments: start, stop, step
# for i in range(0,10,2):
# print(i)
# Steps can be negative
# for i in range(5,-1,-1):
# print(i)
# Importing modules
# import random
# for i in range(5):
# print(random.randint(1, 10))
# Can import multiple modules
# import random, sys, os, math
# Terminating a program
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed: ' + str(response) + '.')
| true |
932a5f8d571d30fb08e416aa450b224373b3c750 | AssiaHristova/SoftUni-Software-Engineering | /Programming Basics/nested_loops/train_the_trainers.py | 477 | 4.125 | 4 | n = int(input())
presentation = input()
sum_all_grades = 0
all_grades = 0
while presentation != 'Finish':
sum_grades = 0
avg_grade = 0
for i in range(1, n + 1):
grade = float(input())
sum_grades += grade
avg_grade = sum_grades / i
sum_all_grades += grade
all_grades += 1
print(f'{presentation} - {avg_grade:.2f}.')
presentation = input()
print(f"Student's final assessment is {sum_all_grades / all_grades:.2f}.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.