blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
30c609333d0c05412084752982ecfbf9e4239148 | rodumani1012/PythonStudy | /Python/Python04_If/if01.py | 276 | 4.3125 | 4 | # if else 사용하기
# : 은 {} 역할을 한다.
print('< if else >')
a = 3
if a == 1:
print('a == 1')
else:
print('a != 1')
print()
print('< if elif else >')
a = 2
if a == 1:
print('a == 1')
elif a == 2:
print('a == 2')
else:
print('a != 1 & a != 2') | false |
b85ac3dccbb23244c244d88d610b18231b5c7683 | rishi1212/hackerRank | /test/xyz.py | 841 | 4.1875 | 4 | import math
def prime_factorize(n):
factors = []
number = abs(n)
factor = 2
while number > 1:
factor = get_next_prime_factor(number, factor)
factors.append(factor)
number /= factor
if n < -1: # If we'd check for < 0, -1 would give us trouble
factors[0] = -factors[0]
return factors
def get_next_prime_factor(n, f):
if n % 2 == 0:
return 2
# Not 'good' [also] checking non-prime numbers I guess?
# But the alternative, creating a list of prime numbers,
# wouldn't it be more demanding? Process of creating it.
for x in range(max(f, 3), int(math.sqrt(n) + 1), 2):
if n % x == 0:
return x
return n
n=int(input())
for i in range(0,n):
t=int(input())
z=prime_factorize(t)
ans=len(set(z))
print(ans)
'''wrong''' | true |
c9be9ac549376075277dc82e55f6b36b3bf7525b | DeveloperTinoco/SDEV-220 | /Chapter 15 - Exercise 15.13.py | 1,047 | 4.3125 | 4 |
# Creates a function that takes one argument
def countUppercase(inputString):
# If there is no string entered by the user, then the 0 value is returned since no letters are present
if not inputString:
return 0
# When a string is entered, this function recursively calls itself to see how many uppercase letters are present
else:
upper = countUppercase(inputString[1:])
# Goes through the string and increments the counter if an uppercase letter is encountered
if inputString[0].isupper():
return upper + 1
else:
return upper
# Asks user for input
inputString = input(
"Enter a string to see how many uppercase letters it contains: ")
# Passes the user's string input into the function
countUppercase(str(inputString))
# Shows the user how many uppercase letters are present in the string they entered
print("The amount of uppercase letters in the string that you entered is " +
str(countUppercase(inputString)) + ".")
| true |
f7cbdd7f6fee779418ae5ebaef9553b7041b45e7 | olafurs17/Python-files | /assignment4_5.py | 714 | 4.25 | 4 | '''
Write a Python program using for loops that, given an integer n as input, prints all consecutive sums from 1 to n.
For example, if 5 is entered, the program will print five sums of consecutive numbers:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
Print only each sum, not the arithmetic expression.
number = input("Please input an integer: ")
number = int(number)
for i in range(1, number + 1):
nums = range(1, i + 1)
print(' + '.join(map(str, nums)), '=', sum(nums))
'''
num = int(input("Input an int: ")) # Do not change this line
num = int(num)
for i in range(1, num + 1):
nums = range(1, i + 1)
for j in nums:
print(1,'+', '=', sum(nums))
| true |
3fe1d609a962d88299adb025aed6f992cfc1bb13 | olafurs17/Python-files | /Practise_1.py | 2,540 | 4.15625 | 4 | '''
sum1 = input('Input for sum1: ')
sum2 = input('Input for sum2: ')
sum = int(sum1) + int(sum2)
print('The SUM: ', (sum))
sum1 = input('Input for sum1: ')
sum2 = input('Input for sum2: ')
sum3 = input('Input for sum3: ')
sum = int(sum1) + int(sum2) + int(sum3)
print('The SUM is :',(sum))
sum1 = input('Input for sum1: ')
sum2 = input('Input for sum2: ')
sum = sum1 + sum2
print('There product: ', (sum))
name_str = input('Name: ')
age_int = input('Age: ')
print('Hello my name is',name_str,'and my age is',age_int,)
firstname = input('What is your Firstname? ')
lastname = input('What is your Lastname? ')
fullname = firstname +' '+ lastname
print('Your fullname is ',fullname)
# Celsius to Fahrenheit
# (degrees in celsius) * 9/5 + 32
celsius_int = int(input('Input the temperatur in celsius: '))
fahrenheit_float = (celsius_int * (9/5)) + 32
fahrenheit_int = int(fahrenheit_float)
print('Celsius scale: ', celsius_int)
print('Fahrenheit scale:', fahrenheit_int)
sum1 = int(input('Punch firstnumber: '))
sum2 = int(input('Punch secondnumber: '))
if sum1 > sum2:
print('The greater integer is Firstnumber =', sum1)
elif sum2 > sum1:
print('The greater integer is Secondnumber =', sum2)
else:
print('The numbers are equal!')
string1 = str(input('Punch firststring: '))
string2 = str(input('Punch secondstring: '))
if len(string1) == len(string2):
print('The strings are at the same lenght !!!')
sum1 = int(input('Punch firstnumber: '))
sum2 = int(input('Punch secondnumber: '))
sum3 = int(input('Punch thirdnumber: '))
if sum1 < sum2 and sum1 < sum3:
print('The smallest integer is the firstnumber =', sum1)
elif sum2 < sum1 and sum2 < sum3:
print('The smallest integer is the secondnumber =', sum2)
elif sum3 < sum1 and sum3 < sum2:
print('The smallest integer is the thirdnumber =', sum3)
number = int(input('Punch the number: '))
if number >= 0 and number < 10:
print('Less than 10')
elif number >= 10 and number < 20:
print('Between 10 and 20')
elif number >= 20:
print('the value is to high!')
elif number <= -1:
print('too low')
a = int(input('Punch number for a: '))
b = int(input('Punch number for b: '))
while True:
choice = int(input('Punch number for choice: '))
if choice == 1:
print('Summa a og b =', (a + b))
elif choice == 2:
print('b dregið frá =', (b - a))
elif choice == 3:
print('margfalda saman a og b =', (a * b))
else:
print('Invalid input!!!')
break
'''
for i in range(-5, 11):
print(i)
| false |
62e4e8317ff03d4899e158c5a9883f41fc68b450 | ferraopam/python_ws | /dice.py | 487 | 4.125 | 4 | import random as rn
num = rn.randint(1 , 6)
count = 0
while True:
inp_num=int(input("enter th number:"))
if inp_num == num:
count += num
print(f"you guessed number in{count} attempts")
break
elif inp_num < num:
print("Guessed number is less than actual number:")
count += 1
else:
print("Guessed number is more than actual number:")
count += 1
if count == 3:
print("Better luck next time")
break | true |
be013612c8a38ac3e499918c38fa27bc2b4af4c4 | santiagodiaz1993/MyPlayground | /data_science/deep_learning/neural_networks_from_scratch/experimentation/test_data_shuffling.py | 627 | 4.28125 | 4 | #!/usr/bin/env python
# coding=utf-8
import numpy as np
array = [[1, 2, 3, 4, 1], [3, 5, 6, 7, 8], [1, 3, 4, 6, 4]]
print(array)
numpy_array = np.array(array)
print(numpy_array)
print("This is how to show ranges")
print(numpy_array[:1])
keys = np.array(range(numpy_array.shape[0]))
print("This is the keys")
print(keys)
print("This is after passing keys in into []")
# When we pass in an array into another array with [] then we are poviding the
# index reassignment
np.random.shuffle(keys)
print(numpy_array[keys[:2]])
print("This is what the reshape function does")
print(numpy_array)
print(numpy_array.reshape(5, 3))
| true |
efaec772a909173601dcc1ff44b812dd5d72df5d | dorabelme/Learn-Python-3-the-Hard-Way | /ex20.py | 1,143 | 4.4375 | 4 | # importing argv from sys module
from sys import argv
# arguments
script, input_file = argv
# function names print_all with file argument
def print_all(f):
# reading the file and printing it
print(f.read())
# function named rewind with file argument
def rewind(f):
# f.seek(0) moves to the start of the file
f.seek(0)
# function with 2 arguments: line_count and file
def print_a_line(line_count, f):
# f.readline() is reading a line from the file
print(line_count, f.readline())
# variable equals opening the input_file
current_file = open(input_file)
print("First let's print the whole file:\n")
# adding current_file argument to the function print_all
print_all(current_file)
print("Now let's rewinf, kind of like a tape.")
# adding current_file to the function rewind
rewind(current_file)
print("Let's print three lines:")
# current_line is 1
current_line = 1
# adding current_line count, and current_file as two arguents to 3rd function
print_a_line(current_line, current_file)
# + 1 line
current_line += 1
print_a_line(current_line, current_file)
# + 1 line
current_line += 1
print_a_line(current_line, current_file)
| true |
65a60828dd2ca8c261fcf8bfd64947e1eda334c3 | crhntr/IAA-Code | /Algorithms/1.9_Powers-of-2/power2.py | 957 | 4.375 | 4 | # Introduction to the Analysis of Algorithms (3rd ed)
# Michael Soltys
## Problem 1.9 - Powers of 2
## Ryan McIntyre
## 6/14/2017
## python 3.5.2
import sys
def power2(n):
#check precondition
try:
if n!=int(n) or n<1:
print(n,'is an invalid input')
return None
else:
n = int(n)
except:
print(n,'is an invalid input')
return None
#the algorithm
else:
x = n
while x > 1:
if x%2==0:
x = int(x/2)
else:
print(n,'IS NOT a power of 2.')
return False
print(n,'IS a power of 2.')
return True
if __name__ == '__main__':
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
try:
power2(int(arg))
except:
print(arg,'is an invalid input.')
else:
print('power2.py expected at least one additional input.') | true |
c3603ed6828beef2490dc353af9355416d5d1b42 | prateekgoel971/Python-Project | /Statments_28Jun.py | 2,031 | 4.34375 | 4 | # ----- Statments ----
# -- If else Statments in python
##Python supports the usual logical conditions from mathematics:
##Equals: a == b
##Not Equals: a != b
##Less than: a < b
##Less than or equal to: a <= b
##Greater than: a > b
##Greater than or equal to: a >= b
##a = 33
##b = 200
##if b > a:
## print("b is greater than a")
##Indentation
##Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
##a = 33
##b = 200
##if b < a:
##
## print("b is greater than a")
# --- If & elif Statmets -- If prvious condition is not true
##a = 33
##b = 33
##if b > a:
## print("b is greater than a")
##elif a == b:
## print("a and b are equal")
##
##
### --- If & elif & else --- If none of preceding condition is true
##a = 200
##b = 33
##if b > a:
## print("b is greater than a")
##elif a == b:
## print("a and b are equal")
##else:
## print("a is greater than b")
##
##
##
### Short Hand If -- if we have only 1 statment to execute
##
##a = 200
##b = 33
##
##if a > b: print("a is greater than b")
####
####
#### Short hand if & else
#### This technique is known as Ternary Operators, or Conditional Expressions.
##
##a = 2
##b = 330
##print("A") if a > b else print("B")
####
####
####
##### 1 statment with three conditions
####
##a = 330
##b = 330
##print("A") if a > b else print("=") if a == b else print("B")
##
##
##
### Operators with Condition Statments
##
### And
##
##a = 200
##b = 33
##c = 500
##if a > b and c > a:
## print("Both conditions are True")
##
##
### Or
##
##a = 200
##b = 33
##c = 500
##if a > b or a > c:
## print("At least one of the conditions is True")
##
##
### Nested If -- If statment inside if statment
##
##x = 41
##
##if x > 10:
## print("Above ten,")
## if x < 20:
## print("and also above 20!")
## else:
## print("but not above 20.")
##
##
# Pass statment
a = 33
b = 200
if b > a:
pass
| true |
f046c5588d41adc9c602e2a9c8dca928d722679c | prateekgoel971/Python-Project | /Dictonaries_DataType_26Jun.py | 1,044 | 4.21875 | 4 | # -- change the item value
d1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
d1["year"] = 2018
print(d1)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
# --- Add item to dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "red"
print(car)
student = {
"Name":"Prateek",
"Age":27,
"Subject":"Python"
}
student.update({"Class":"12th Standard"})
print(student)
# -- Remove item
##team = {
## "Name":"Dhoni",
## "Number":7,
## "Age":36
## }
##team.pop("Number")
##print(team)
##class= {
## "Name":"Rahul",
## "Age":25,
## "RollNo":33,
## "Phone":"2456788"
## }
##class.popitem()
##print(class)
thisdict = {
"brand": "Ford",
"model": "Mustang",s
"year": 1964
}
del thisdict["model"]
print(thisdict)
student = {
"Name":"Prateek",
"Age":27,
"Subject":"Python"
}
del student
print(student)
| false |
93658f1460db6229601b468e6f07dd5d5d73d709 | JeremyCoxBMI/PythonDataStructures | /p01_main.py | 2,255 | 4.34375 | 4 | __author__ = 'COX1KB'
import mytimer as mt
# Lesson: what is runtime? runtime ~ cost * O(n)
# Which would take longer? Adding 100 pairs of numbers or solving 100 differential equations?
# Which operations run in better time than others?
# Which class is best for run time performance?
# Why does Dr Talaga say "Always use a dictionary and not a list in python"?
# What disadvantage is there to using a dictionary over a list?
#main program
if __name__ == "__main__":
#let's try different data structures!
#they will be given the same tests
mylist = list()
mydict = dict()
myset = set()
testsize = 10000
maxrando = 50000
deletes = 1000
timer = mt.mytimer()
#construct full containers
randomsa = [mt.rando(maxrando) for x in range(0, testsize)]
randomsb = [mt.rando(maxrando) for x in range(0, testsize)]
print "\nAppend() operation"
timer.start()
for x in range(0,testsize):
mylist.append( randomsa[x] )
print "Appending to list took "+timer.elapsed()
timer.start()
for x in range(0,testsize):
mydict[ randomsa[x] ] = 1
print "Appending to dict took "+timer.elapsed()
timer.start()
for x in range(0,testsize):
myset.add( randomsa[x] )
print "Appending to set took "+timer.elapsed()
print "\nContains() operation"
timer.start()
for x in randomsb:
x in mylist #contains operator
print "Contains() in list took "+timer.elapsed()
timer.start()
for x in randomsb:
x in mydict #contains operator
print "Contains() in dict took "+timer.elapsed()
timer.start()
for x in randomsb:
x in myset #contains operator
print "Contains() in set took "+timer.elapsed()
print "\nDelete() operation"
timer.start()
for x in range(0,deletes):
mylist.remove(randomsa[x])
print "delete() in list took "+timer.elapsed()
timer.start()
for x in range(0,deletes):
if (randomsa[x] in mydict): mydict.pop(randomsa[x])
print "delete() in dict took "+timer.elapsed()
timer.start()
for x in range(0,deletes):
if (randomsa[x] in myset): myset.remove(randomsa[x])
print "delete() in set took "+timer.elapsed()
| true |
56777e8534922608fe5ef4965d49f74d532176db | MomokoXu/momokopy | /numlist.py | 605 | 4.125 | 4 | def numlist():
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
n = float(num)
except:
print 'Invalid input'
#print num
#for y in n:
if largest is None:
largest = n
elif n > largest:
largest = n
#print "Maximum is ", largest
#for x in n:
if smallest is None:
smallest = n
elif n < smallest:
smallest = n
print "Maximum is", largest
print "Minimum is", smallest
| true |
6636fb9c918ba1ef45706b7ff3d48083c5309275 | emmajs16/pythonfiles | /smallest_factor.py | 306 | 4.375 | 4 | # Emma Stoverink
# October 24, 2018
# Find the smallest factor of an integer other than 1
user_int = int(input("Enter an integer: "))
for i in range(2, user_int):
if user_int % i == 0:
smallest_factor = i
break
print("The smallest factor of {} is {}.".format(user_int, smallest_factor)) | true |
6f6d31b7f0697d4db6d36bcccfe47ddfaaf9f44a | emmajs16/pythonfiles | /even_odd.py | 264 | 4.28125 | 4 | # Emma Stoverink
# September 16, 2018
# Problem: find if a number is even or odd
a = int(input("Please enter a number:\n"))
even = a % 2 == 0
if even==True:
print("{} is an EVEN number.".format(a))
##if even==False:
else:
print("{} is an ODD number.".format(a)) | false |
af7d13bafe19fcf7ac5e78310a32aa6cd7d71806 | emmajs16/pythonfiles | /lab1.py | 2,017 | 4.28125 | 4 | #Emma Stoverink
#August 31, 2018
#Lab 1
#display three messages
def problem_one():
print("Welcome to Python")
print("Welcome to Computer Science")
print("Programming is fun")
#displays message five times
def problem_two():
for i in range(5):
print("Welcome to Python")
#Display a pattern that prints out the word FUN
def problem_three():
print("FFFFFFF U U NN NN")
print("FF U U NNN NN")
print("FFFFFF U U NN N NN")
print("FF U U NN N NN")
print("FF UUU NN NNN")
#Prints a table of values
def problem_four():
print("a\ta^2\ta^3")
print("1\t1\t1")
print("2\t4\t8")
print("3\t9\t27")
print("4\t16\t64")
#Computes an expression
def problem_five():
numerator = (9.5 * 4.5) - (2.5 *3)
denominator = 45.5 - 3.5
print(numerator /denominator)
def problem_six():
mile_in_km = 1.6
distance = 14
time= 45.5
hour = 60
scale = time / hour
distance_in_miles = distance / mile_in_km
print(scale * distance_in_miles)
print("MPH")
#display 3d box
def problem_seven():
#make first rectangle
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
#make line to connect
turtle.left(180)
turtle.right(45)
turtle.forward(100)
turtle.left(45)
turtle.right(90)
#make second rectangle
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
#connect the last two lines
turtle.right(180)
turtle.forward(100)
turtle.left(135)
turtle.forward(100)
turtle.left(45)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(45)
turtle.forward(100)
turtle.left(45)
turtle.forward(100)
turtle.left(135)
turtle.forward(100)
| false |
00477bb78877a958eac721b48810ddcb16d8ada2 | emmajs16/pythonfiles | /random_card.py | 756 | 4.375 | 4 | ## Emma Stoverink
## September 21, 2018
## Problem: Generate a random card for the user
import random
print("------------------------------------------")
print("|{:^40}|".format("Pick a Card!"))
print("------------------------------------------")
print("We will generate a random card for you\nfrom a standard deck of 52 cards.")
go = (input("Press \"ENTER\" to see your card!"))
rank = random.randint(1,13)
if rank == 1:
rank = "Ace"
if rank == 11:
rank = "Jack"
if rank == 12:
rank = "Queen"
if rank == 13:
rank = "King"
suit = random.randint(1,4)
if suit == 1:
suit = "Clubs"
elif suit == 2:
suit = "Diamonds"
elif suit == 3:
suit = "Hearts"
else:
suit = "Spades"
print("Your card is: The {} of {}.".format(rank,suit))
| true |
a306d7df3648b2db251f7eb90eac3481894f3ba2 | emmajs16/pythonfiles | /sort_nums.py | 787 | 4.21875 | 4 | # Emma Stoverink
# November 9, 2018
def display_sorted_numbers(num1, num2, num3):
if num1 < num2 and num1 < num3:
if num2 < num3:
return("{} {} {}".format(num1,num2,num3))
if num2 > num3:
return("{} {} {}".format(num1,num3,num2))
if num1 > num2 and num1 < num3:
if num2 < num3:
return("{} {} {}".format(num2,num1,num3))
if num2 > num3:
return("{} {} {}".format(num3,num2,num2))
else:
if num2 < num3:
return("{} {} {}".format(num2,num3,num1))
if num2 > num3:
return("{} {} {}".format(num3,num2,num1))
def main():
x, y, z = input("Enter three numbers: ").split()
print("The three sorted numbers are: {}".format(display_sorted_numbers(x,y,z)))
main() | false |
f6c853978f59d6f0bf6ae96345f5a9566ccede2c | Travel-Gird/travel-hack-backend | /utils.py | 339 | 4.1875 | 4 | from datetime import date, datetime
def birthday_to_age(birthday) -> int:
today = date.today()
birthday = datetime.strptime(birthday, '%m/%d/%Y')
return today.year - birthday.year - \
((today.month, today.day) < (birthday.month, birthday.day))
if __name__ == '__main__':
print(birthday_to_age('03/18/2000'))
| false |
abbeb0658fbd8be80f608c070ba70d552a5f15b8 | juanfariastk/FunnyAlgorithms | /Hash Functions/equal_hash.py | 407 | 4.1875 | 4 | # Python3 program to find given two arrays to see if they're equal or not.
def areEqual(arr1, arr2, n, m):
if (n != m):
return False
arr1.sort()
arr2.sort()
for i in range(0, n - 1):
if (arr1[i] != arr2[i]):
return False
return True
# Driver Code
arr1 = [3, 5, 2, 5, 2]
arr2 = [2, 3, 5, 5, 2]
n = len(arr1)
m = len(arr2)
if (areEqual(arr1, arr2, n, m)):
print("Yes")
else:
print("No")
| false |
0bba595f7f6ae5fe5858b8262fc4f7b3928ac8f9 | juanfariastk/FunnyAlgorithms | /Caesar Cipher/caesar_cipher.py | 2,573 | 4.5 | 4 | def letter_shift(letter: str, shift: int) -> str:
"""Function that shifts a given letter by a certain
shift that is also given, then returns the shifted
letter from the brazilian portuguese character set
Args:
letter (str): letter to be encrypted
shift (int): shift from the character set
Returns:
str: letter that was shifted
"""
# Caesar cipher implemented over brazilian portuguese character set
alphabet = 'abcdefghijklmnopqrstuvwyzàáãâéêóôõíúçABCDEFGHIJKLMNOPQRSTUVWYZÀÁÃÂÉÊÓÕÍÚÇ'
index_shifted = alphabet.find(letter) + shift
if index_shifted > len(alphabet) - 1:
index_shifted = index_shifted % len(alphabet)
letter_shifted = alphabet[index_shifted]
return letter_shifted
def caesar_cypher(str_user : str, shift: int = 3) -> str:
"""Function that shifts a string by a certain
shift that is also given, then returns the shifted
string from the brazilian portuguese character set
Args:
letter (str): letter to be encrypted
shift (int): shift from the character set
Returns:
str: letter that was shifted
"""
converted_str = ''
for letter in str_user:
if letter == ' ':
converted_str+= ' '
pass
else:
converted_str+=letter_shift(letter, shift)
return converted_str
def run() -> None:
"""Run function, provides a menu to the user to either encrypt a message with the default shift or
gives the option of encrypting the message with a custom shift, this application of the caesar cypher
utilizes the brazilian portuguese character set.
"""
print("Menu - Perfect Numbers Program \nTo Encrypt a message with the default shift - press 0\nTo Encrypt a message with a custom shift - press 1")
user_choice = int(input())
if user_choice == 0:
user_input = input("Please provide the message that will be cyphered: ")
cyphered_msg = caesar_cypher(user_input)
print(f'Your message cyphered by the caeser cypher is: {cyphered_msg}')
elif user_choice == 1:
user_input = input("Please provide the message that will be cyphered: ")
user_shift = int(input("Please provide the shift for cypher: "))
cyphered_msg = caesar_cypher(user_input, user_shift)
print(f'Your message cyphered by the caeser cypher is: {cyphered_msg}')
else:
print("Please select a valid option")
run()
if __name__ == "__main__":
run()
| true |
ceb6d3f80365dd142373eaa93f0863cb2e2e9f0e | nergizozgeerdagi/PythonProject | /finalProject.py | 1,142 | 4.28125 | 4 | #FIRST QUESTION SOLUTION
def flatten_list(some_list):
while True:
flattened_list = []
for element in some_list:
if type(element) != list:
flattened_list.append(element)
else:
for item in element:
flattened_list.append(item)
some_list = flattened_list
list_types = []
for element in some_list:
list_types.append(type(element))
if list not in list_types:
break
return some_list
example_list = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
print(f"Example list: {example_list}")
print(f"Flattened list: {flatten_list(example_list)}")
#SECOND QUESTION SOLUTION
def reverse_list(some_list):
new_list = []
for element in some_list[::-1]:
if type(element) == list:
new_list.append(element[::-1])
else:
new_list.append(element)
return new_list
example_list = [[1, 2], [3, 4], [5, 6, 7]]
print(f"Example list: {example_list}")
print(f"Reversed list: {reverse_list(example_list)}")
| true |
c890fb54e0413c177650fa2e586bc356a74fe2d9 | atchyutn/python_beginner_course_udemy_samples | /sets-dictonaries.py | 415 | 4.125 | 4 | """
sets are collection of unique objects
"""
fileSet = {2015,2016, 2017}
print(fileSet)
"""
Dictonaries are collection of key value pairs, similar to hashes in ruby
"""
fileDict = {"last year": 2016, "current year": 2017, "next year": 2018}
print(fileDict)
print(fileDict["last year"])
"""
A list can be converted to set by using set()
"""
fileList = [2015,2016,2016]
fileSet = set(fileList)
print(type(fileSet)) | true |
87e8dd2ec7848dfb782777b4276b1ac95cbd1471 | sshantel/coding-challenges | /pangrams.py | 998 | 4.40625 | 4 | """
A pangram is a string that contains every letter of the alphabet. Given a sentence determine whether it is a pangram in the English alphabet. Ignore case. Return either pangram or not pangram as appropriate.
Example
The string contains all letters in the English alphabet, so return pangram.
Function Description
Complete the function pangrams in the editor below. It should return the string pangram if the input string is a pangram. Otherwise, it should return not pangram.
pangrams has the following parameter(s):
string s: a string to test
Returns
string: either pangram or not pangram
Input Format
A single line with string s.
"""
def pangrams(s):
ascii_set = set()
for letter in s.lower():
if letter not in ascii_set and letter.isalpha():
ascii_set.add(letter)
print(ascii_set)
if len(ascii_set) == 26:
return "pangram"
else:
return "not pangram"
print(pangrams('We promptly judged antique ivory buckles for the next prize')) | true |
ab31159ab440e7f1902507de4370cf3484c243a8 | HoangHip/TaHoangAnh-fundamental-C4E-29 | /Session02/homework/Serious exercises1.py | 331 | 4.1875 | 4 | height = int(input("Your height(CM):"))
weight = int(input("Your weight:"))
height1 =height/100
BMI=weight/(height1**2)
print("Your BMI: ", BMI)
if BMI < 16 :
print("Severely underweight")
elif BMI< 18.5:
print("Underweight")
elif BMI< 25:
print("Normal")
elif BMI< 30:
print("Overweight")
else:
print("Obese")
| false |
38e0e77735b78d7393a46deceed44671b8c0f9e1 | jerquinigo/python-practice | /lambdaExpressionsMapAndFilter.py | 1,391 | 4.5625 | 5 | def square(num):
return num**2
myNums = [1,2,3,4,5]
# map took in the function square in the first argument and then the variable list in the second argument. We then looped through it and printed the results of it squared
for item in map(square, myNums):
print(item)
#1
#4
#9
#16
#25
# this way will put the results in a list format
print(list(map(square,myNums)))
# [1, 4, 9, 16, 25]
# example
#list1 = [2,4,6,8,10]
#def mult2(li):
# return li * 2
#print(list(map(mult2,list1)))
#for n in map(mult2, list1):
# print(n)
# this is iterating through the values of map
# both ways will return 4,8,12,16,20
# need to put in the values in a list for the map to return the results
# also got to put in a function in the first argument and then the list you want to apply that data to.
# transform it to a list or iterate through it
# a lambda expression is also known as an anonomous function. (means its a function that we only use one time.)
# it is the same as a regular function in python. Instead of naming it, you would call it lambda and no return value needs to be present because it will be return
#example
# traditional function
# def square(num):
# return num ** 2
# lambda function is not named
# square = lambda num: num ** 2
# square(3)
## you can use lambda in place of the function
#print(list(map(lambda num: num ** 2, [2,4,6])))
#[4, 16, 36] | true |
db453bf52db1ac0dc0a907f975a0c78c7c948ff5 | Bpratiksha/DS | /Fibonaci_series.py | 566 | 4.21875 | 4 | def fibo(n):
a,b=0,1
#if series contain 0 terms thn it will priint 0 only and for 1 it will print 0,1
if n==0:
print(a)
elif n==1:
print(a,b)
#if it contain more than 1 term thn it will print next terms according to fibonaci logic
else:
print(a,b, end=" ")
#logic for fibonaci series
for i in range(n-2):
c=a+b
a=b
b=c
print(c,end=" ")
#taking input from user
n=int(input("enter number of terms present in series: "))
fibo(n)
| true |
9112a29501a3309712e2bb32a2559bdfb9c82d4e | anik-ghosh-au7/attainu-course-repo | /coding-challenges/week05/Day1/cc2-w5d1.py | 1,283 | 4.375 | 4 | # Write a python program to do merge sort iteratively.
# input
# 8 6 9 4 2 3 7
# output
# 2 3 4 6 7 8 9
# explanation
# merging [8] and []
# at i = 0 result = [8]
# merging [6] and [8]
# at i = 1 result = [6, 8]
# merging [9] and [6, 8]
# at i = 2 result = [6, 8, 9]
# merging [4] and [6, 8, 9]
# at i = 3 result = [4, 6, 8, 9]
# merging [2] and [4, 6, 8, 9]
# at i = 4 result = [2, 4, 6, 8, 9]
# merging [3] and [2, 4, 6, 8, 9]
# at i = 5 result = [2, 3, 4, 6, 8, 9]
# merging [7] and [2, 3, 4, 6, 8, 9]
# at i = 6 result = [2, 3, 4, 6, 7, 8, 9]
# merge sort without using recursion
def merge_sort(arr):
result = []
for i in range(len(arr)):
# print("merging ", [arr[i]], " and ", result)
result = merge([arr[i]], result)
# print("at i = ", i, " result = ", result)
return result
def merge(list_1, list_2):
result = []
i = 0
j = 0
while i < len(list_1) and j < len(list_2):
if list_1[i] <= list_2[j]:
result.append(list_1[i])
i += 1
else:
result.append(list_2[j])
j += 1
result += list_1[i:]
result += list_2[j:]
return result
input_list = list(map(int, input().split()))
print(*merge_sort(input_list))
| false |
fba7aad6e852f7d0c5e2da0fdfbad0faf6d98e4e | anik-ghosh-au7/attainu-course-repo | /coding-challenges/week04/Day5/cc1-w4d3.py | 426 | 4.3125 | 4 | # Using the recursive fibonacci number function, print first n fibonacci numbers.
# input
# 5
# output
# 0 1 1 2 3
# input
# 9
# output
# 0 1 1 2 3 5 8 13 2
n = int(input())
if n == 0:
print(0, end=" ")
else:
print(0, end=" ")
print(1, end=" ")
def rec_fibonacci(n1, n2, n):
if n <= 1:
return
a = n1 + n2
print(a, end=" ")
return rec_fibonacci(n2, a, n-1)
rec_fibonacci(0, 1, n-1)
| false |
c62a87ee2af4e97caac45a0d008cabb17a9602ed | gabe0504/PythonProject--ComapreFiles | /DictionaryRearrange.py | 1,971 | 4.25 | 4 | #main function creates the dictionary 'd' and sets the parameters 'params.'
#main function then passes dictionary and parameters as arguments into the function p3_dictionary_manipualtions
def main():
d={'Canada': 'ca', 'United States':'us', 'Mexico':'mx'} #dictionary created with key-value elements
params=['Canada', 'France', 'sw', 'se'] #list of parameters
p3_dictionary_manipulations(d, params) #function which
def p3_dictionary_manipulations(d, params):
#for-loop checks for Canada and France in dictionary and prints the result
for items in params[:2]:
if items in d:
print('a.', items, 'in dict\n' + 'True\n')
else:
print('b.', items, 'in dict\n' + 'False\n')
#for-loop uses x variable to print keys and their associated values in a table
print('c. Keys and values in dict (key in field width 20)')
for x in d:
print(format(x, '20'), d.get(x))
#key Sweden added to dictionary with its incorrect country abbreviation added from parameters list as value
d['Sweden']=params[2]
print('\nd. Dict with Sweden set to \'sw\':')
print(d)
#lines 24-27 deletes they key-value pair for Sweden then adds it again with the correct country abbreviation
del d['Sweden']
d['Sweden']=params[3]
print('\ne. Dict with Sweden set to \'se\':')
print(d)
#lines 30-32 rearranges the order of the key-value elements and stores them in the variable d2.
#abbr:name sets new key-value arrangment. For loop iterates to variables over the items method
d2 = {abbr: name for name, abbr in d.items()} #'abbr:name' sets the new key-valu arrangement
print("\nf. Reverse mapping using dictionary comprehension:")
print(d2)
#lines 33-35 performs the above operation again but uses the upper() method to capitalize the country names
print('\ng. Reverse mapping uppercase using dictionary comprehension: ')
d2 = {abbr: name.upper() for name, abbr in d.items()}
print(d2)
main()
| true |
b1938b348e0ad00fd2724c0ab88c008891e126cb | samhita101/Python-Practice | /2Brothers_Riddle.py | 2,346 | 4.375 | 4 | answer = 2
wrong1 = 1
wrong3 = 3
print("THE RIDDLE:")
print("You are walking down a path when you come to two doors.")
print("Opening one of the doors will lead you to a life of prosperity and happiness, \nwhile opening the other door will lead to a life of misery and sorrow.")
print("You don't know which door leads to which life.")
print("In front of the doors are two twin guard brothers who know which door leads where.")
print("One of the brothers always lies, and the other always tells the truth.")
print("You don't know which brother is the liar and which is the truth-teller.")
print("You are allowed to ask one single question to one of the brothers (not both) to figure out which door to open.")
print("What question should you ask?")
print("")
print("YOUR CHOICES:")
print("1. You should ask either brother which door leads to a life of happiness and prosperity.")
print("2. You should ask either brother which door the other would pick if I asked them which leads to a life of happiness and prosperity.")
print("3. You should ask the truthful brother which door leads to a life of misery and sorrow.")
print("")
print("Pick one of the choices and enter the number that corresponds with the question you want to ask either brother:")
guess = int(input())
print("")
if guess == answer:
print("Correct.\nIf you were to ask the truthful brother which door his brother would pick,\nhe would point to the door that leads to misery and sorrow since that is what his brother would pick.\nIf you asked the lying brother which door his sibling would pick,\nhe will also point to the bad door,\nbecause this is not what his brother would point to.")
print("So whichever door is pointed to, you should go through the opposite.")
elif guess == wrong1:
print("Incorrect. If you were to ask the liar which door leads to a life of happiness and prosperity,\nhe would point to the oppsite of what his brother would point to.\nThis makes it impossible to know which is the right door, since they're each pointing at a different door.")
else:
guess == wrong3
print("Incorrect.If you were to ask the liar which door leads to a life of misery and sorrow,\nhe would point to the oppsite of what his brother would point to.\nThis makes it impossible to know which is the right door, since they're each pointing at a different door.")
| true |
aba97e6a886c66d256ae44d22f77ea1fc3def19d | samhita101/Python-Practice | /RectangleArea.py | 543 | 4.375 | 4 | print("Today we are figuring out the are of a rectangle.")
print("You get to define the length and width.")
print("")
print("Please keep in mind that this program can only take in REAL integer values, \nso refrain from using decimals, fractions, and anything with letters.")
print("")
print("Enter your desired width after the colon:")
width = int(input())
print("Enter your desired length after the colon:")
length = int(input())
print("Here is the area of a rectangle with the dimensions you chose:")
print(length * width, "units squared.") | true |
551e8c865ad849657ce40b8b6a04f017811ca201 | samhita101/Python-Practice | /Are the numbers equal?.py | 474 | 4.21875 | 4 | # prompting the user and getting input
print("Today we will find out if the 2 numbers you input are equal.")
print("User give your first number.")
Number_one = float(input())
print("User give your second number.")
Number_two = float(input())
# defining the function that checks if they are equal
def equal():
if Number_one == Number_two:
print("Your numbers are equal.")
else:
print("Your numbers are not equal.")
# calling the function
equal() | true |
aec636e87627eca3962e2b1709aeb1da390353f8 | samhita101/Python-Practice | /Median.py | 1,161 | 4.28125 | 4 | print("Today we will be finding the median of a list.")
print("User enter a length for your list:")
# users list length and list
list_length = int(input())
number_list = []
# asking the user to input the amount of numbers they wanted and adding them the list
for i in range(list_length):
print("User enter a number:")
users_num = float(input())
number_list.append(users_num)
# creating a function to find median
def median():
remainder = list_length % 2 # finds remainder
print(remainder)
sorted_list = sorted(number_list) # sorts list
print(sorted_list, "is your list sorted in ascending order")
if remainder == 1: # if remainder = 1, slices at halfway point, and prints
slice_position = (list_length + 1)//2 - 1
print(sorted_list[slice_position], "is the median of your list")
if remainder == 0: # if remainder = 0, slices at 2 positions - half and half + 1
sorted_list = sorted(number_list) # sorts list
slice_position2 = list_length/2
median1 = sorted_list(slice_position2)
median2 = sorted_list(slice_position2 - 1)
print((median1 + median2)/2)
median() | true |
666041def07fc8fea96c4d406ac05f8645add7af | samhita101/Python-Practice | /matchstick_houses.py | 364 | 4.125 | 4 | # collecting input
print("What is your step value?")
step = int(input())
# defining function to count number of matchsticks
def matchsticks_num(arg):
while step == int(step) and step >= 0: # allows only integer values and positive numbers
print(1 + 5*arg, "is the number of matchsticks in your step.")
# calling the function
matchsticks_num(step)
| true |
45d471cf05d3aa44bc65440c506f32a1fa701243 | samhita101/Python-Practice | /Unique factors.py | 1,010 | 4.21875 | 4 | print("User, today we will find the number of unique factors your number has.")
print("User give me a positive integer greater than 1:")
number = int(input())
factor_list = []
def prime(arg):
counter = 1
if arg <= 1:
print("Please enter a number greater than one.")
elif arg >= 2 and arg % 2 == 0:
for i in range(1, (arg // 2) + 1):
if arg % i == 0:
factor_list.append(i)
counter = counter + 1
print("There are", counter, "unique factors.")
factor_list.append(arg)
print("Here is a list with the factors:", factor_list)
else:
if arg >= 2 and arg % 2 != 0:
for i in range(1, (arg - 1 // 2)):
if arg % i == 0:
factor_list.append(i)
counter = counter + 1
print("There are", counter, "unique factors.")
factor_list.append(arg)
print("Here is a list with the factors:", factor_list)
prime(number)
| true |
e9f514aedbcc70dd033afbb56500dbeee5191a44 | RoboticsClubatUCF/Laki2 | /catkin_ws/src/laki2_navigation/slam/quad_tree/circle_square_collision.py | 1,657 | 4.125 | 4 | # Andrew Schroeder
# 8/30/2018
# Script to tell if any part of a circle intersects with any part of a rectangle
# This script is limited to rectangles that are aligned with the x and y axes
import math
import numpy as np
# circle is of form [(h, k), r], where (h, k) is the (x, y) of the center pt
# rect is of form [x_max, x_min, y_max, y_min]
def isRectInCircle(circle, rect):
# Check if circle center is inside square
if (xmin <= h) and (h <= xmax) and (ymin <= k) and (k <= ymax):
return True
# Check if dist from any rect corner to circle center is <= circle radius
if ((math.sqrt((xmax - h)**2 + (ymax - k)**2) <= r) or
(math.sqrt((xmin - h)**2 + (ymax - k)**2) <= r) or
(math.sqrt((xmin - h)**2 + (ymin - k)**2) <= r) or
(math.sqrt((xmax - h)**2 + (ymin - k)**2) <= r)):
return True
# Check the lines of the rectangle to see if they intersect with the circle
# This is done by checking the pts on the circle with the max and min x and y
# (This only works bc the rectangles are always aligned with the x and y axes)
# Top line (y = ymax)
if ((h <= xmax) and (h >= xmin) and ((k - r) <= ymax) and ((k - r) >= ymin)):
return True
# Bottom line (y = ymin)
elif ((h <= xmax) and (h >= xmin) and ((k + r) <= ymax) and ((k + r) >= ymin)):
return True
# Right line (x = xmax)
elif (((h - r) <= xmax) and ((h - r) >= xmin) and (k <= ymax) and (k >= ymin)):
return True
# Left line (x = xmin)
elif (((h + r) <= xmax) and ((h + r) >= xmin) and (k <= ymax) and (k >= ymin)):
return True
else
return False | true |
27fe8612b327339c89d9c0e6d0265758cbfcc1d2 | danielsunzhongyuan/my_leetcode_in_python | /sum_of_two_integers_371.py | 536 | 4.1875 | 4 | """
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
"""
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
while a != 0 and b != 0:
a, b = a^b, (a&b)<<1
if a > 1<<31 or b > 1<<31:
a %= 1<<31
b %= 1<<31
return a or b
if __name__ == "__main__":
a = Solution()
print a.getSum(-14, 16)
| true |
11e63cebcee6a0ed76bdb5829ba2e7d243b09bb6 | ilaoda/python | /11_面向对象编程-下/11_5_类属性、实例属性.py | 691 | 4.4375 | 4 | """
类属性
在类中声明的属性,即在方法外的属性
访问:
类名访问
实例对象访问
他是所有类的实例对象所共有的,在内存中只存在一个副本
实例属性
在方法中定义的属性
访问:
只能是实例对象访问
注意:
如果类属性 和 实例属性相同
通过对象访问的是实例属性
通过类名访问的是类小户型
"""
# 定义类
class Cat(object):
# 类属性
num = 0
# 实例属性-在方法中
def __init__(self):
# self.num = 100
self.age = 20
# 测试
cat = Cat()
# print(cat.num)
print(Cat.num)
print(cat.num) | false |
9614ecd1e18348844e99ab9c2088da4a7a806d6c | ilaoda/python | /11_面向对象编程-下/11_2_继承.py | 2,025 | 4.5625 | 5 | """
class 子类名(父类名):
如果定义类的时候,没有括号,表明默认继承自 object类
例如:
class Person(object): 等同于 class Person:
父类私有的属性和方法,不会被子类继承,并且子类也不能访问父类私有的。
单继承
多继承: python支持多继承, 即拥有多个父类
语法 class 子类(父类1, 父类2, ...)
多个父类同名方法
哪个父类在前面,就只执行前面父类中的同名方法
在复杂的继承关系中,python会根据__mro__() 算法找到合适的类
???那么能不能指定执行哪个类的同名方法呢???
"""
# 父类
class Cat(object):
def __init__(self, color="白色"):
self.color = color
def run(self):
print("父类的 猫 正在跑")
# 定义私有的方法让子类访问,肯定会出错
def __test(self):
print("我是父类私有的方法")
# 定义公开的方法
def test(self):
print("我是父类私有的方法")
# 子类,波斯猫
class PersianCat(Cat):
pass
# 测试
persianCat = PersianCat("黑色")
persianCat.run()
print("波斯猫的颜色:%s" %persianCat.color)
# 访问父类私有的方法
# persianCat.__test()
persianCat.test()
"""
多继承
飞鱼继承了 鸟 和 鱼类
"""
print("========== 多继承 ============")
# 父类 - 鸟类
class Bird:
# 飞
def fly(self):
print("--- 鸟儿在天空飞翔 ---")
# 测试,同名方法 breathe
def breathe(self):
print("鸟儿会呼吸")
# 父类 - 鱼类
class Fish:
# 游泳
def swim(self):
print("--- 鱼儿在水中遨游 ---")
# 测试,同名方法 breathe
def breathe(self):
print("鱼儿也会呼吸")
# 子类 - 飞鱼
class Volador(Bird, Fish):
pass
# 测试
vola = Volador()
vola.fly()
vola.swim()
# 测试多个父类同名方法
# 哪个父类在前面,就只执行前面父类中的同名方法
vola.breathe() # 鸟儿会呼吸
| false |
73da32647d81934a0b6809f842172eb76a125b31 | MattyHB/Python | /EarlyPython/Turtle.py | 509 | 4.21875 | 4 | import turtle # allows us to use the turtles library
wn = turtle.Screen() # creates a graphics window
alex = turtle.Turtle() # create a turtle named alex
for i in range(440):
alex.forward(1) # tell alex to move forward by 150 units
alex.left(1) # turn by 90 degrees
alex.forward(1) # complete the second side of a rectangle
alex.left(90)
alex.forward(230)
for i in range (360):
alex.left(1)
alex.forward(.25)
wn.exitonclick() | true |
491322433199894039bb98971f56294d927e3cfa | chaozui/workspace | /com/sunjian/BasePractice.py | 1,120 | 4.1875 | 4 | #coding:utf-8
"""
python 基础语法练习
"""
def f(x,*args,**args2):
print "x=" "%s" % x
print "args=",args
print "args2=",args2
t=(2,3,5,6)
tt={'a':3,'b':4,'c':5}
f(*t,**tt)
print "****************"
def ff(x,y):
return x*y
print ff(3,3)
v=lambda x,y:x*y
print v(4,5)
print "lambda************"
l = range(1,33)
print l
print reduce(lambda x,y:x*y, l)
print "***************"
print abs(-10)
print divmod(3,7)
print pow(3,4)
print round(3)
print callable(f)
tttt=[3,5,6,4]
print type(t)
print cmp(6,5)
print range(1,10)
print xrange(1,10)
print tuple(tttt)
# help(ord)
print ord('k')
#oct chr ord
s='hello world'
print s.capitalize()
print s.replace('hello','good')
print s.replace('o','x',1)
print s.split(" ")
print "****************************"
l=range(10)
print l
def f(x):
if x%2==0:
return x
ll= filter(f,l)
print ll
print zip(l,ll)
print map(None,l,ll)
j=[1,3,5]
jj=[2,4,6]
def mf(x,y):
return x*y
print map(mf,j,jj)
print "*********************"
l=range(1,101)
def rf(x,y):
return x+y
print reduce(rf,l)
print reduce(lambda x,y:x+y,l)
print filter(lambda x:x%2 ==0,l)
| false |
ad43d675da08a63fc7c006230ed7427c3b3882dc | Varun-Singhal/Algorithms-DataStructures | /insertion_sort.py | 604 | 4.375 | 4 | """
Insertion sort algorithm
Time Complexity - O(N^2)
Space Complexity- O(1)
"""
import sys
def insertion_sort(array):
"""
Function to perform bubble sort
Argument: Unsorted Array
Returns : Sorted Array
"""
for i in range(1,len(array)):
index = i-1
if array[i] < array[i-1]:
swap(array,i,i-1)
while(index>0):
if array[index] < array[index-1]:
swap(array,index,index-1)
index -= 1
return array
def swap(array, i, j):
array[i],array[j] = array[j],array[i]
if __name__ == '__main__':
array = list(map(int,sys.argv[1].strip("[]").split(",")))
print(insertion_sort(array)) | false |
85ca347cc6baf1a71e8e19a5f3b37de9a56d0f7f | fortyMiles/StanfordAlgorithmCourse | /InverseCount.py | 1,956 | 4.375 | 4 | """
Count the inverse pairs in an array. Such as: 4, 2, 1, 3
we get (4, 2), (4, 1), (4, 3), (2, 1) four inverse pairs.
"""
def inverse_count(array):
if len(array) == 1: return array, 0
else:
sorted_left, inverse_left = inverse_count(array[:len(array)//2])
sorted_right, inverse_right = inverse_count(array[len(array)//2:])
merged_sort, inverse_split = merge(sorted_left, sorted_right)
return merged_sort, inverse_left + inverse_right + inverse_split
def merge(array_1, array_2):
"""
Merges two sorted arrays into one sorted array and return the inverse number
of array1 and array1
:param array_1: sorted_array
:param array_2: sorted_array
:return: sorted_array, inverse_number concated array_1, array_2
"""
i, j = 0, 0,
sorted_result = []
inverse_num = 0
while i < len(array_1) or j < len(array_2):
if i >= len(array_1): sorted_result.append(array_2[j]); j += 1; continue
if j >= len(array_2): sorted_result.append(array_1[i]); i += 1; continue
if array_1[i] <= array_2[j]: sorted_result.append(array_1[i]); i += 1
else: sorted_result.append(array_2[j]); inverse_num += (len(array_1) - i); j += 1
return sorted_result, inverse_num
def do_assignment(file):
numbers = list(map(int, open(file)))
return inverse_count(numbers)[1]
if __name__ == '__main__':
assert merge([1, 2], [3, 4]) == ([1, 2, 3, 4], 0)
assert merge([3, 4], [1, 2]) == ([1, 2, 3, 4], 4)
assert merge([1], [2]) == ([1, 2], 0)
assert merge([3], [2]) == ([2, 3], 1)
assert merge([1, 2, 3], [2]) == ([1, 2, 2, 3], 1)
assert inverse_count([1, 2, 3, 4])[1] == 0
assert inverse_count([2, 3, 4, 1])[1] == 3
assert inverse_count([4, 3, 2, 1])[1] == 6
assert inverse_count([1, 4, 5, 3, 2])[1] == 5
print('test done!')
inverse_num = do_assignment('data/inverse_count_integer_array.txt')
print(inverse_num)
| true |
da5f1a0dd924681e3f5adf6e12998e74ce023813 | marciorpcoelho/practice_challenges | /challenge_09.py | 807 | 4.15625 | 4 | import numpy.random as nprnd
# Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
# (Hint: remember to use the user input lessons from the very first exercise)
def main():
a = int(nprnd.randint(9, size=1))
guess = int(input('I\'ve chosen a random number between 1 and 9. Care to guess it? '))
guess_count = 1
while guess != a:
if guess == a:
break
if guess > a:
print('Too high!')
elif guess < a:
print('Too low!')
guess = int(input('New guess? '))
guess_count += 1
print('After ' + str(guess_count) + ' tries, that\'s right, Congratulations!')
if __name__ == '__main__':
main()
| true |
954448b9639e482fb5579886e609e470be3302dd | DarkMarksDoe/useless-code-i-made | /python/1.4.List-Operations.py | 2,421 | 4.375 | 4 | # COURSE DATA STRUCTURES
#
# Native Python Data Structures, Operators for Sequence
# Types like: Strings, List, Tuples
# UDEMY LINK: https://www.udemy.com/course/python-data-structures-a-to-z/
# If this code works, it was written by DarkMarksDoe. If not, I don't know
# who wrote it, just pass away
# INFO ABOUT LISTS
# ~ General purpose
# ~ Most widely used data structure
# ~ Grow and shrink size as needed
# ~ Sequence type
# ~ Sortable
# CONSTRUCTORS / COMPREHENSION
x = list()
y = ['z', 21, 'Mark', 3.1416]
tuple1 = (99, 15)
z = list(tuple1)
# List Comprehension
a = [m for m in range(8)]
print('List 0 from 8:', a)
b = [i**2 for i in range(10) if i > 4]
print('Print square numbers when i > 4:', b)
# DELETE
print('\n')
# Delete a list or an item
x = [3, 7, 9, 1, 5]
# Delete 2nd character
del(x[1])
print('Delete', x)
# Delete entire list
del(x)
# APEND
print('\n')
# Apend an item to a list
x = [3, 7, 9, 1, 5]
# End of the list
x.append(10)
print('Append', x)
# EXTEND
print('\n')
# Append a sequence toa list
x = [3, 7, 9, 1, 5]
y = [13, 15, 17]
x.extend(y)
print('Extend', x)
# INSERT
print('\n')
# Insert an item at a given index
x = [3, 7, 9, 1, 5]
x.insert(0, 0)
print('Atend 1', x)
x.insert(1, ['m', 'a'])
print('Atend 2', x)
# POP
print('\n')
# Last item
x = [3, 7, 9, 1, 5]
x.pop()
print('Pop 1', x)
print('Pop Item:', x.pop())
# REMOVE
print('\n')
# Remove instance of the first item
x = [3, 1, 9, 1, 3]
x.remove(1)
print('Remove', x)
# REVERSE
print('\n')
# Reverse the order of the list. It is an in-place sort, meaning it changes the original list.
x = [3, 7, 9, 1, 5]
x.reverse()
print('Reverse', x)
# SORT
print('\n')
# Sorted(x) returns a new sorted list without changing the original
# x.sort() puts the items of x in sorted order.
x = [3, 7, 9, 1, 5]
x.sort()
print('Sort', x)
# REVERSE SORT
print('\n')
# The same that sort but, reverse JAJAJAJAJA xD
x = [3, 7, 9, 1, 5]
x.sort(reverse=True)
print('Reverse Sort', x)
| true |
042e92b82b0a52c6318c4db73bcc53db8255e8c0 | wangjinyu124419/beginning-python | /3_字符串/3.2_字符串格式化.py | 880 | 4.21875 | 4 | from string import Template
format="hello,%s,hello,%s"
values=('world','python')
# format % values
print(format % values)
#字符串模板
tem1=Template("hello,$A,hello,$B")
print(tem1.substitute(A='world', B='python'))
#format索引
format_str="{0} {1} {2} {3} {0} {1}".format('to','be','or','not')
print(format_str)
#format格式化
from math import pi
print('{name} is approximately {value}'.format(value=pi,name='pi'))
print('{name} is approximately {value:.2f}'.format(value=pi,name='pi'))
#在Python3.6以后,如果变量名与替换字段名相同,可以简写,字符串前面加个f
print(f"{pi} is approximately 3.14")
#转换标志
print("{pi!s} {pi!r} {pi!a}".format(pi='π'))
#用<>^指定左对齐中对齐右对齐
print('{:010.2f}'.format(pi))
# 0代表索引
print('{0:<10.2f}\n{0:>10.2f}\n{0:^10.2f}'.format(pi))
print('{a:^10.2f}'.format(a=pi))
| false |
03e11e6a5b6f1d1fd39c52a257f03115ca4daa2b | Lakhanbukkawar/Python_programs | /ArmstrongNumberUsingWhileLoop.py | 230 | 4.125 | 4 | num=int(input("enter the n digit number"))
add=0
temp=num
while temp>0:
digit=temp%10
add+=digit**3
temp//=10
if num==add:
print('the number is armstrong')
else:
print("the number is not armstrong")
| true |
23c17e229282e0d79d1d973e8baee0dadcb6e1bb | Lakhanbukkawar/Python_programs | /PalindromeUsingWhileLoop.py | 264 | 4.15625 | 4 | num=int(input("enter the n digit number"))
rev=0
orgnum=num
while num>0:
digit=num%10
rev=rev*10+digit
num=num//10
if rev==orgnum:
print('number is palindrome')
else:
print('number is not palindrome')
| false |
b5a9f75547f0fd98b52411ab55204d506374785f | Sergei-Morozov/Stanford-Algorithms | /Greedy Algorithms/week8/dsu.py | 2,029 | 4.53125 | 5 | """
Disjoint set implementation
Three operations:
- make_set(v) - creates a new set with element v
- union_sets(a, b) - merges the two specified sets (the set in which the element a is located, and the set in which the element b is located)
- find_set(v) - returns the representative (also called leader) of the set that contains the element v. This representative is an element of its corresponding set. It is selected in each set by the data structure itself (and can change over time, namely after union_sets calls). This representative can be used to check if two elements are part of the same set of not. a and b are exactly in the same set, if find_set(a) == find_set(b). Otherwise they are in different sets.
"""
class DSU:
"""
Naive implementation:
Each element has parent, multiple elements with same parent form a set
Adding:
ranks - determined on number of hops to get to the parent for the set
Adding:
find_set - update parents[v] each time visit elements
"""
def __init__(self, n):
self.parents = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
def make_set(self, v):
self.parents[v] = v
def find_set(self, v):
if v == self.parents[v]:
return v
self.parents[v] = self.find_set(self.parents[v])
return self.parents[v]
def union_sets(self, a, b):
a = self.find_set(a)
b = self.find_set(b)
if a != b:
if self.rank[a] > self.rank[b]:
self.parents[b] = a
elif self.rank[a] == self.rank[b]:
self.parents[b] = a
self.rank[a] += 1
else:
self.parents[a] = b
def test():
# items = [0,1,2,3,4,5]
dsu = DSU(6)
dsu.union_sets(0,1)
assert dsu.parents == [0,0,2,3,4,5]
dsu.union_sets(3,4)
assert dsu.parents == [0,0,2,3,3,5]
dsu.union_sets(1,3)
assert dsu.parents == [0,0,2,0,3,5]
if __name__ == '__main__':
test()
| true |
d67627a2ab76c6597e51faef6f98ff4bfc061f87 | by-AnnaBy/BasicPython_GB_Interactive | /HW_lesson1/AnnaBy_BP_1-2.py | 572 | 4.15625 | 4 | #!/usr/bin/env python3
TASK = """
Пользователь вводит время в секундах.
Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
"""
seconds = int(input('Введите время в секундах: '))
hours = seconds // 3600
minutes = (seconds - (hours * 3600)) // 60
seconds = seconds - minutes * 60 - hours * 3600
print('{:0>2}:{:0>2}:{:0>2}'.format(hours, minutes, seconds))
| false |
be575d9083ec685f825aac5afd0f3f89fe303b9d | roushzac/personal-redacted_word | /third_word_redacted.py | 2,222 | 4.5 | 4 | ''' this program takes a sentence or paragraph as input and turns all the third
words into all x's. this is a useless function but I couldn't figure out how to
do it at first, so I made a point of creating this program '''
###############################################################################
#ask user for input
#turn that input into a list
#create a new list which we will turn into a redated sentence at the end
#for each word in the sentence:
# if you find a third word, convert to a list and it's letters to x
# then add that word to a new list
#
# if you find a non-third word, just add it to the list:
#turn that new sentence list into a sentence
#print that sentence
###############################################################################
import string
# ask user for a passage to convert
s=input("input a sentence: ")
#turn that sentence into a list
s=s.split()
# create a new list where we will add the words and redacted words to
# we do this so we can join the list later and print that out
new_sentence_list=[]
# initialize a variable so we know when were a third word of the sentence
third=0
#if we are on the third word, convert it to a list and turn each letter into x
#then when all the letters are converted, turn it back into a string of x's
# add that new xxx word to the new sentence list
# if its just a normal word, add it to the new sentence list
for word in s:
third+=1
if third%3==0:
word=list(word)
index=0
for letter in word:
if letter in string.punctuation:
word[index]=letter
index+=1
else:
word[index]='x'
index+=1
word=''.join(word)
new_sentence_list.append(word)
else:
new_sentence_list.append(word)
#join the new sentence list into a string/sentence
new_sentence_list=' '.join(new_sentence_list)
#print empty line to separate input and output
print()
#print out the sentence with all the 3rd words converted to all x's
print(new_sentence_list)
| true |
49ccd5141002f9f27e4089a0a3fa83aae3359cbb | GirugaCode/Madlibs-Python | /madlibs.py | 1,412 | 4.40625 | 4 | # Story
'''
This is a story about (Enter name1:) and (Enter name2:). These two were madly in love.
Everyday they would (Enter verb:) eachother without thinking twice. However, one day
the two lovers went inside a (Enter noun:) and was never to be seen agian.
'''
# Create Variables
Name1 = input("Enter a name: ")
Name2 = input("Enter another name: ")
verb = input("Enter a verb: ")
noun = input("Enter a noun: ")
print("""This is a story about %s and %s. These two were madly in love.
Everyday they would start %s eachother without thinking twice.
However, one day the two lovers went
inside a %s and was never to be seen agian.
The End. """ % (Name1, Name2, verb, noun))
# Prompt the user to enter the madlibs (noun, adj, verb)
# Print the Story
# The world's simplest madlibs
# def zeus():
# verb = input("Enter a verb: ")
# noun = input("Enter a noun: ")
# anothernoun = input("Enter another noun: ")
# print("Zeus %sed %s but %s was unaffected by it." % (verb, noun, anothernoun))
#
#
# def about():
# adjective = input("Enter an adjective: ")
# adj = input("Enter another adjective: ")
# print("You're %s and %s" % (adjective, adj))
#
# story = input("Which story would you like to play Possible options thelightgod, aboutYourEnemy: ")
# if story == "thelightgod":
# zeus()
# elif story == "aboutYourEnemy":
# about()
# else:
# print("Doesn't Exist.")
| true |
f7e07c62277587f00b6ea7573f8b77a2802354b8 | chebozh/Algorithms | /01_unordered_sequential_search.py | 1,524 | 4.1875 | 4 | """Sequential search Starting at the first item in the list, we simply move from item to item, following the
underlying sequential ordering until we either find what we are looking for or run out of items. If we run out of
items, we have discovered that the item we were searching for was not present.
Worst case complexity O(n):
"""
import datetime
# Book example:
def sequentialSearch(alist, item):
pos = 0
found = False
while pos < len(alist) and not found:
if alist[pos] == item:
found = True
else:
pos = pos + 1
return found
# Alternative (slightly faster) version:
def sequential_search(a_list, element):
for n in a_list:
if n == element:
return True
return False
# Checks
if __name__ == '__main__':
testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print('Book version: ')
start = datetime.datetime.now()
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
finish = datetime.datetime.now()
print("--- %s ---" % (finish - start))
print('**' * 20)
print('Alternative version: ')
start = datetime.datetime.now()
print(sequential_search(testlist, 3))
print(sequential_search(testlist, 13))
finish = datetime.datetime.now()
print("--- %s ---" % (finish - start))
# Results after a few runs:
# Book version:
# False
# True
# --- 0:00:00.000038 ---
# ****************************************
# Alternative version:
# False
# True
# --- 0:00:00.000017 ---
| true |
0da51ce9df0f0cb73fb5718eb375a559f71779e2 | hellew/learn | /条件判断.py | 1,035 | 4.25 | 4 | age = 20
if age >= 18:
print('your age is', age)
print('adult')
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
'''
if <条件判断1>:
<执行1>
elif <条件判断2>:
<执行2>
elif <条件判断3>:
<执行3>
else:
<执行4>
'''
'''
# 只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
if 'x':
print('True')
birth = input('birth: ')
if birth < '2000':
print('00前')
else:
print('00后')
'''
h = float(input('身高 :'))
w = float(input('体重 :'))
bmi = w / (h * h)
if bmi < 18.5:
print('体重过轻:', 'bmi = ', bmi)
elif bmi < 25:
print('体重正常:', 'bmi = ', bmi)
elif bmi < 28:
print('体重过重:', 'bmi = ', bmi)
elif bmi < 32:
print('体重肥胖:', 'bmi = ', bmi)
else:
print('体重严重肥胖:', 'bmi = ', bmi)
| false |
a87a91e4df937fc39e131211ec979afa65118d04 | kcmuths/Python-work | /pay_credit_card_debt.py | 1,668 | 4.5 | 4 | ##Write a program to calculate the credit card balance after one year if a person
##only pays the minimum monthly payment required by the credit card company
##each month
##Use raw_input() to ask for the following three floating numbers:
##1. the outstanding balance on the credit card
##2. annual interest rate
##3. minimum monthly payment rate
##For each month print the minimum monthly payment, remaining balance,
##principle paid in the format shown in test cases. All numbers should be
##rounded to the nearest penny.
##Finally, print the result, which should include the total amount paid that year
##and the remaining balance.
outstanding_bal = float(raw_input('Enter your outstanding balance on credit card:'))
annual_interest_rate = float(raw_input('Enter annual interest rate as a decimal:'))
min_monthly_payment_rate = float(raw_input('Enter minimum monthly payment rateas a decimal:'))
total_amt_paid = 0
for i in range(1,13):
minimum_monthly_payment = min_monthly_payment_rate * outstanding_bal
interest_paid = annual_interest_rate / 12 * outstanding_bal
principal_paid = minimum_monthly_payment - interest_paid
remaining_balance = outstanding_bal - principal_paid
print 'Month:', i
print 'Minimum monthly payment:$',round(minimum_monthly_payment, 2)
print 'Principle paid:$',round(principal_paid, 2)
print 'Remaining balance:$',round(remaining_balance, 2)
outstanding_bal = remaining_balance
total_amt_paid += minimum_monthly_payment
print 'RESULT'
print 'Total amount paid: $',round(total_amt_paid, 2)
print 'remaining balance: $',round(outstanding_bal, 2)
| true |
346c741cca7341a861996d2d3fddd940d010d3e2 | KaiquanMah/Training | /Intermediate Python for Data Science/Dictionaries and Pandas/List Index | 282 | 4.125 | 4 | # Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# Get index of 'germany': ind_ger
ind_ger=countries.index('germany')
# Use ind_ger to print out capital of Germany
print(capitals[ind_ger])
| false |
d8d6b4ecf9ef8887e5b089ffd9e21b46be780417 | sergmilk/csv_parser | /csv_parser.py | 1,539 | 4.21875 | 4 | """ Need to create a python script that will open a csv file
and with a certain column compare values on each row, if
this value fits a regular expression - should add it to output,
also output must contain the number of values of each type and
values should be sorted by the number
some.csv content:
A,B
1,aaac
2,aaab
3,aaac
4,xxx
Run with command line parameters: B aaa
Output:
aaac 2
aaab 1
"""
import csv
import sys
import re
from collections import defaultdict
col_name = sys.argv[1]
reg = sys.argv[2]
#----------------------------------------------------------------------
def csv_dict_reader(file_obj):
"""
Read a CSV file using csv.DictReader,
compare a col_name row values and regular expression
if match we output values sorted by the number of matches
"""
d = defaultdict(int) #dictionary with matched values and number of matches
prog = re.compile(reg) #compiled regular expression from second command line parameter
reader = csv.DictReader(file_obj, delimiter=',')
#choose lines that match regular expression and add values to d dictionary
for line in reader:
result = prog.match(line[col_name])
if result is not None :
d[line[col_name]] += 1
#Sorted dictionary d output
for key in sorted(d.keys(),reverse = True):
print( str(key) + " " + str(d[key]))
#----------------------------------------------------------------------
with open("some.csv") as f_obj:
csv_dict_reader(f_obj)
| true |
fb89eca4661baa38b23e95b7ca117e78f3504658 | AiratValiullin/python_algorithm | /les2-2.py | 542 | 4.28125 | 4 | """2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5)."""
num = input('Введите число ')
enum = ''
onum = ''
for i in num:
if int(i) % 2 == 0:
enum += str(i)
else:
onum += str(i)
print(f' Четные числа - {enum}')
print(f' Нечетные числа - {onum}')
| false |
2ebbd075cbdb82d3c8a0c8de7593c8250120a081 | ravinduu/python | /python_basics/numpyArray.py | 549 | 4.125 | 4 | '''
There are many ways to declare array using NumPy
ex:
1)manually
2)using linspace()
3)using arange()
4)using logspace()
5)using zeros()
6)using ones()
'''
from numpy import *
#manually
arr = array([1,2,3,4,5],float)
print(arr)
print(arr.dtype)
#linspace()
arr1 = linspace(0,15,20)#from 1 to 15, 20 elements
print(arr1)
#arange
arr2 = arange(1,15,2) #from 1 to 15, by 2 steps
print(arr2)
#logspace
arr3 = logspace(1,40,5)#log something
print(arr3)
#zeros
arr4 = zeros(5) #size 5 array all 0s
#ones
arr5 = ones(1)#size 5 array all 1s
| true |
a943be55d7914de8a34404fa50933ac30892a9b5 | PythonStudyBuddies/BeginnerPythonProjects | /RockPaperScissorsTemplate.py | 1,373 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 12:09:54 2020
@author: Dylan
"""
#To make this more challenging, find a way to decrease human error.
#import a random integer from the library random
#Your code here
#create a list of play options
#t should equal one of the three choices Rock, Paper, or Scissors
#t =
#assign a random play to the computer
computer = t[randint(0,2)]
# set player to False
player = False
#This while loop will change to true when the player inputs their choice.
while player == False:
# #set player to true
# #Get the player to input Rock, Paper, or Scissors.
# player =
#
# #Start of the if statements
# #Computer Ties the Player
# if player == computer:
# print()
# #Player inputs Rock
# elif player == :
# if computer == :
# print()
# else:
# print()
# #Player inputs Paper
# elif player == :
# if computer == :
# print()
# else:
# print()
# #Player inputs Scissors
# elif player ==
# if computer ==
# print()
# else:
# print()
# #Else statement for if the person spells something wrong. Hint* this will be a print
# else:
# #Your Code Here#
# #Resets the player to False
# player = False
# computer =t[randint(0,2)] | true |
55887039ebd3e4eb7cd1868065deb4a1d9921578 | Feynman27/PythonSandbox | /bignum.py | 309 | 4.40625 | 4 | #!/usr/bin/python
input = int(raw_input('Please enter a number: '))
if (input == 1):
print 'You entered one.'
elif (input == 2):
print 'You entered two.'
elif (input == 3):
print 'You entered three.'
else:
print 'You entered a number > 3. Please enter a number <= 3.'
print 'End of program.'
| true |
57f0063f17d1da15bcd6bd4340bae832f6743aa7 | nana1243/python_tutorial | /effective_python/chap4_메타클래스와속성/betterway_31.py | 1,197 | 4.125 | 4 | """
31. 재사용 가능한 @property 메서드에는 디스크립터를 사용하자.
- @property로 데코레이터하는 메서드를 같은 클래스에 속한 여러 속성에 사용하지 못한다.
"""
class HomeWork(object):
def __init__(self):
self._grade = 0
@property
def grade(self):
return self._grade
@grade.setter
def grade(self, value):
if not (0 <= value <= 100):
raise ValueError("Grade must be between 0 and 100")
self._grade = value
class Exam(object):
def __init__(self):
self._writing_grade = 0
self._math_grade = 0
@staticmethod
def _check_grade(value):
if not (0 <= value <= 100):
raise ValueError("Grade must be between 0 and 100")
@property
def writing_grade(self):
return self._writing_grade
@writing_grade.setter
def writing_grade(self, value):
self._check_grade(value=value)
self._writing_grade = value
@property
def math_grade(self):
return self._math_grade
@math_grade.setter
def math_grade(self, value):
self._check_grade(value=value)
self._math_grade = value
| false |
bad1bd847ca4717168e0c373d32e90118fbff192 | tusharsadhwani/daily_byte | /p147_downward_spiral.py | 1,405 | 4.3125 | 4 | """
Given a 2D matrix, return a list containing all of its element in spiral
order.
Ex: Given the following matrix...
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
], return [1, 2, 3, 6, 9, 8, 7, 4, 5].
"""
def downward_spiral(grid: list[list[int]]) -> list[int]:
"""Returns the numbers iterated in spiral form"""
nums: list[int] = []
size = len(grid)
for index in range(size//2 + 1):
if index == size-1 - index:
nums.append(grid[index][index])
break
i = j = index
while j < size-index:
nums.append(grid[i][j])
j += 1
j -= 1
i += 1
while i < size-index:
nums.append(grid[i][j])
i += 1
i -= 1
j -= 1
while j >= index:
nums.append(grid[i][j])
j -= 1
j += 1
i -= 1
while i >= index+1:
nums.append(grid[i][j])
i -= 1
return nums
def main() -> None:
"""Main function"""
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# matrix = [
# [1, 2, 3, 4, 5, 6],
# [7, 8, 9, 10, 11, 12],
# [13, 14, 15, 16, 17, 18],
# [19, 20, 21, 22, 23, 24],
# [25, 26, 27, 28, 29, 30],
# [31, 32, 33, 34, 35, 36]
# ]
print(downward_spiral(matrix))
if __name__ == '__main__':
main()
| true |
1a1e63829b57500e824e354034adda3b697a1993 | tusharsadhwani/daily_byte | /p158_largest_pool.py | 1,949 | 4.46875 | 4 | """
You are building a pool in your backyard and want to create the largest
pool possible. The largest pool is defined as the pool that holds the
most water. The workers you hired to dig the hole for your pool didn’t
do a great job and because of this the depths of the pool at different
areas are not equal. Given an integer array of non-negative integers
that represents a histogram of the different heights at each position of
the hole for your pool, return the largest pool you can create.
Ex: Given the following heights...
heights = [1, 4, 4, 8, 2], return 8.
You can build your largest pool (most water) between indices 1 and 3
(inclusive) for a water volume of 4 * 2 = 8.
"""
# So basically, each value in the histogram is an individual "hole",
# you're free to dig more but you can't add material on top. So the
# solution is to find the two long holes and maximize
# ((shorter height of the two) * distance)
def largest_pool_area_bruteforce(heights: list[int]) -> int:
"""Finds largest pool area"""
max_area = 0
for index1, height1 in enumerate(heights):
for index2, height2 in enumerate(heights):
area = min(height1, height2) * abs(index1 - index2)
max_area = max(max_area, area)
return max_area
def largest_pool_area(heights: list[int]) -> int:
"""Finds largest pool area"""
start, end = 0, len(heights) - 1
max_area = 0
while start < end:
height1 = heights[start]
height2 = heights[end]
min_height = min(height1, height2)
area = (end - start) * min_height
max_area = max(max_area, area)
if height1 < height2:
start += 1
else:
end -= 1
return max_area
def main() -> None:
"""Main function"""
heights = [1, 4, 4, 8, 2]
print(largest_pool_area_bruteforce(heights))
# better solution
print(largest_pool_area(heights))
if __name__ == '__main__':
main()
| true |
0a7ac3021460f6243163d70555e65fdf5ecf7232 | tusharsadhwani/daily_byte | /p57_life_rafts.py | 2,227 | 4.1875 | 4 | """
A ship is about to set sail and you are responsible for its safety
precautions. More specifically, you are responsible for determining how
many life rafts to carry onboard. You are given a list of all the
passengers’ weights and are informed that a single life raft has a
maximum capacity of limit and can hold at most two people.
Return the minimum number of life rafts you must take onboard to ensure
the safety of all your passengers.
Note: You may assume that a the maximum weight of any individual is at
most limit.
Ex: Given the following passenger weights and limit...
weights = [1, 3, 5, 2] and limit = 5, return 3
weights = [1, 2] and limit = 3, return 1
weights = [4, 2, 3, 3] and limit = 5 return 3
"""
def find_largest_value_below(
limit: int,
array: list[int],
start: int,
end: int) -> int:
"""Uses binary search to find index of largest value below limit"""
if len(array) <= start or array[start] > limit:
return -1
mid = (start + end) // 2
if array[mid] == array[start] or array[mid] == array[end]:
return mid
if array[mid] > limit:
return find_largest_value_below(limit, array, start, mid-1)
return find_largest_value_below(limit, array, mid, end)
def minimum_containers(weights: list[int], limit: int) -> int:
"""Find minimum number of containers required to fit all weights"""
weights.sort()
containers = 0
while weights:
if len(weights) == 1:
containers += 1
return containers
last_weight = weights.pop()
last_index = len(weights) - 1
limit_left = limit - last_weight
while True:
index = find_largest_value_below(
limit_left, weights, 0, last_index
)
if index == -1:
containers += 1
break
value = weights.pop(index)
limit_left -= value
return containers
def main() -> None:
"""Main function"""
weights = [1, 3, 5, 2]
limit = 5
# weights = [1, 2]
# limit = 3
# weights = [4, 2, 3, 3]
# limit = 5
print(minimum_containers(weights, limit))
if __name__ == "__main__":
main()
| true |
964e0aa56dd20aba0278b87eacf3b5a31d4eb93f | tusharsadhwani/daily_byte | /p43_calculate_depth.py | 941 | 4.25 | 4 | r"""
Given a binary tree, return its maximum depth.
Note: the maximum depth is defined as the number of nodes along the
longest path from root node to leaf node.
Ex: Given the following tree...
9
/ \
1 2
return 2
Ex: Given the following tree...
5
/ \
1 29
/ \
4 13
return 3
"""
from data_types.node_tree import NodeTree, build_tree
def calculate_depth(node: NodeTree, level: int = 1) -> int:
"""Calculates depth of binary tree"""
left_level = right_level = level
if node.left is not None:
left_level = calculate_depth(node.left, level+1)
if node.right is not None:
right_level = calculate_depth(node.right, level+1)
return max(left_level, right_level)
def main() -> None:
"""Main function"""
tree = build_tree([9, 1, 2])
tree = build_tree([5, 1, [29, 4, 13]])
print(calculate_depth(tree))
if __name__ == "__main__":
main()
| true |
6fd0cb6f06a358406adc5d6a6a56602b9bf0a869 | tusharsadhwani/daily_byte | /p81_complementary_numbers.py | 778 | 4.15625 | 4 | """
Given a positive number, return its complementary number.
Note: The complement of a number is the number that results from
flipping every bit in the original number. (i.e. zero bits become one
bits and one bits become zero bits).
Ex: Given the following number...
number = 27, return 4.
27 in binary (not zero extended) is 11011.
Therefore, the complementary binary is 00100 which is 4.
"""
def main() -> None:
"""Main function"""
number = int(input('> '))
binary = f'{number:b}'
complement = ''.join('0' if bit == '1' else '1' for bit in binary)
complement_int = int(complement, 2)
print(complement_int)
# # Alternative approach:
# binary = f'{number:b}'
# print(~number + 2 ** len(binary))
if __name__ == "__main__":
main()
| true |
3c517202dda28055e5b14c042cc69b0fdcd774af | tusharsadhwani/daily_byte | /p105_reverse_number.py | 734 | 4.59375 | 5 | """
Given a 32 bit signed integer, reverse it and return the result.
Note: You may assume that the reversed integer will always fit within
the bounds of the integer data type.
Ex: Given the following integer num...
num = 550, return 55
Ex: Given the following integer num...
num = -37, return -73
"""
def reverse(num: int) -> int:
"""Returns the reverse of a number"""
negative = num < 0
num = abs(num)
reversed_num = 0
while num:
reversed_num *= 10
reversed_num += num % 10
num //= 10
return -reversed_num if negative else reversed_num
def main() -> None:
"""Main function"""
num = 550
# num = -37
print(reverse(num))
if __name__ == "__main__":
main()
| true |
eec159b9bbb16f4325145d7422fca0444ee92b38 | tusharsadhwani/daily_byte | /p102_diving_deep.py | 746 | 4.1875 | 4 | r"""
Given an N-ary tree, return its maximum depth.
Note: an N-ary tree is a tree in which any node may have at most N
children.
Ex: Given the following tree...
4
/ | \
3 9 2
/ \
7 2
return 3.
"""
from data_types.node_nary_tree import NodeNaryTree, build_nary_tree
def max_depth(tree: NodeNaryTree, depth: int = 1) -> int:
"""Returns max depth of N-ary tree"""
if not tree.children:
return depth
return max(max_depth(child, depth+1) for child in tree.children)
def main() -> None:
"""Main function"""
tree = build_nary_tree([
4, [
[3, [7]],
9,
[2, [2]],
]
])
print(max_depth(tree))
if __name__ == "__main__":
main()
| true |
02d66fd41b1da15b18ef604e37d40cee2a5a0514 | tusharsadhwani/daily_byte | /p119_new_value.py | 1,708 | 4.25 | 4 | r"""
Given the reference to a binary search tree and a value to insert,
return a reference to the root of the tree after the value has been
inserted in a position that adheres to the invariants of a binary search
tree.
Note: It is guaranteed that each value in the tree, including the value
to be inserted, is unique.
Ex: Given the following tree and value...
2
/ \
1 3
value = 4, return the following tree...
2
/ \
1 3
\
4
"""
from typing import Optional
from data_types.node_tree import NodeTree
class NodeBST(NodeTree):
"""Standard Binary Search Tree implementation"""
def __init__(self, value: int) -> None:
super().__init__(value)
self.left: Optional[NodeBST] = None
self.right: Optional[NodeBST] = None
def __repr__(self) -> str:
return f'<NodeBST value={self.value}>'
def bst_insert(tree: NodeBST, value: int) -> None:
"""Inserts value into BST"""
if tree.value > value:
if tree.left is None:
tree.left = NodeBST(value)
else:
bst_insert(tree.left, value)
else:
if tree.right is None:
tree.right = NodeBST(value)
else:
bst_insert(tree.right, value)
def build_bst(values: list[int]) -> NodeBST:
"""Builds a binary search tree from given values"""
if len(values) == 0:
raise ValueError("Cannot create empty BST")
tree = NodeBST(values[0])
for value in values[1:]:
bst_insert(tree, value)
return tree
def main() -> None:
"""Main function"""
bst = build_bst([2, 1, 3])
bst_insert(bst, 4)
bst.print_inorder()
if __name__ == "__main__":
main()
| true |
28d74701a8e292e162dff711f8f705120fe32a26 | tusharsadhwani/daily_byte | /p110_birthday_cake.py | 1,464 | 4.3125 | 4 | """
You are at a birthday party and are asked to distribute cake to your
guests. Each guess is only satisfied if the size of the piece of cake
they’re given, matches their appetite (i.e. is greater than or equal to
their appetite). Given two arrays, appetite and cake where the
ithelement of appetite represents the ith guest’s appetite, and the
elements of cake represents the sizes of cake you have to distribute,
return the maximum number of guests that you can satisfy.
Ex: Given the following arrays appetite and cake...
appetite = [1, 2, 3], cake = [1, 2, 3], return 3.
Ex: Given the following arrays appetite and cake...
appetite = [3, 4, 5], cake = [2], return 0.
"""
def max_guests(appetite: list[int], cake: list[int]) -> int:
"""Returns maximum number of guests you can satisfy"""
guest_count = 0
appetite_index = len(appetite) - 1
cake_index = len(cake) - 1
while appetite_index >= 0 and cake_index >= 0:
appetite_size = appetite[appetite_index]
cake_size = cake[cake_index]
if cake_size >= appetite_size:
# cake is fed
cake_index -= 1
guest_count += 1
# else, the person is skipped
appetite_index -= 1
return guest_count
def main() -> None:
"""Main function"""
appetite = [1, 2, 3]
cake = [1, 2, 3]
# appetite = [3, 4, 5]
# cake = [2]
print(max_guests(appetite, cake))
if __name__ == "__main__":
main()
| true |
22988db8cac48d2b965ffaa36bf50d404faab4a9 | tusharsadhwani/daily_byte | /p38_visible_values.py | 724 | 4.21875 | 4 | r"""
Given a binary tree return all the values you’d be able to see if you
were standing on the left side of it with values ordered from top to
bottom.
Ex: Given the following tree...
4
/ \
2 7
return [4, 2]
Ex: Given the following tree...
7
/ \
4 9
/ \ / \
1 4 8 9
\
9
return [7, 4, 1, 9]
"""
from data_types.node_tree import build_tree, level_order_traversal
def main() -> None:
"""Main function"""
tree = build_tree([4, 2, 7])
# tree = build_tree([7, [4, 1, 4], [9, 8, [9, None, 9]]])
levels = level_order_traversal(tree)
print([level[0] for level in levels])
if __name__ == "__main__":
main()
| true |
2c291c788ebfaae200e8b47df6b451184f08fb00 | tusharsadhwani/daily_byte | /p111_divisible_digits.py | 806 | 4.21875 | 4 | """
Given an integer N, return the total number self divisible numbers that
are strictly less than N (starting from one).
Note: A self divisible number if a number that is divisible by all of
its digits.
Ex: Given the following value of N...
N = 17, return 12 because 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15 are all
self divisible numbers.
"""
from typing import Generator
def self_divisible_numbers(limit: int) -> Generator[int, None, None]:
"""Returns self divisible number upto limit"""
for num in range(1, limit):
digits = (int(digit) for digit in str(num))
if all(digit != 0 and num % digit == 0 for digit in digits):
yield num
def main() -> None:
"""Main function"""
print(len(list(self_divisible_numbers(17))))
if __name__ == "__main__":
main()
| true |
3273e9a9a404262cfa4f28214f37dc67ed18ac5c | tusharsadhwani/daily_byte | /p86_reverse_vowels.py | 908 | 4.375 | 4 | """
Given a string, reverse the vowels of it.
Note: In this problem y is not considered a vowel.
Ex: Given the following strings s...
s = "computer", return "cemputor"
Ex: Given the following strings s...
s = "The Daily Byte", return "The Dialy Byte"
"""
def reverse_vowels(string: str) -> str:
"""Reverse the vowels in the string"""
vowels: list[int] = []
for idx, char in enumerate(string):
if char.lower() in 'aeiou':
vowels.append(idx)
chars = list(string)
half_length = len(vowels) // 2
for i in range(half_length):
idx = vowels[i]
reverse_idx = vowels[-1-i]
chars[idx], chars[reverse_idx] = chars[reverse_idx], chars[idx]
return ''.join(chars)
def main() -> None:
"""Main function"""
string = "computer"
# string = "The Daily Byte"
print(reverse_vowels(string))
if __name__ == "__main__":
main()
| true |
a1cb9a5fe1301f2f9c5a532954486fd0e9590edd | tusharsadhwani/daily_byte | /p60_popsicle_stand.py | 2,355 | 4.21875 | 4 | """
You’re running a popsicle stand where each popsicle costs $5. Each
customer you encountered pays with either a $5 bill, a $10 bill, or a
$20 bill and only buys a single popsicle. The customers that come to
your stand come in the order given by the customers array where
customers[i] represents the bill the ith customer pays with. Starting
with $0, return whether or not you can serve all the given customers
while also giving the correct amount of change.
Ex: Given the following customers...
customers = [5, 10], return true
collect $5 from the first customer, pay no change.
collet $10 from the second customer and give back $5 change.
Ex: Given the following customers...
customers = [10], return false
Explanation:
collect $10 from the first customer and we cannot give back change.
Ex: Given the following customers...
customers = [5, 5, 5, 10, 20], return true
Explanation:
collect $5 from the first 3 customers.
collet $10 from the fourth customer and give back $5 change.
collect $20 from the fifth customer and give back $10 change
($10 bill and $5 bill).
"""
def validate_change(customers: list[int]) -> bool:
"""Validates if the cashier can give change to each customer"""
fives, tens, twenties = 0, 0, 0
def try_pop(notes: int) -> bool:
if notes == 0:
return False
notes -= 1
return True
for cash in customers:
if cash == 5:
fives += 1
elif cash == 10:
tens += 1
elif cash == 20:
twenties += 1
change = cash - 5
while change > 0:
if change >= 20:
popped = try_pop(twenties)
if not popped:
return False
change -= 20
elif change >= 10:
popped = try_pop(tens)
if not popped:
return False
change -= 10
elif change >= 5:
popped = try_pop(fives)
if not popped:
return False
change -= 5
else:
return False
return True
def main() -> None:
"""Main function"""
customers = [5, 10]
# customers = [10]
# customers = [5, 5, 5, 10, 20]
print(validate_change(customers))
if __name__ == "__main__":
main()
| true |
97b17a701f3f9c41bb0fb542bb9ed08aaf0328b7 | tusharsadhwani/daily_byte | /p39_bottoms_up.py | 609 | 4.25 | 4 | r"""
Given a binary tree, returns of all its levels in a bottom-up fashion
(i.e. last level towards the root).
Ex: Given the following tree...
2
/ \
1 2
return [[1, 2], [2]]
Ex: Given the following tree...
7
/ \
6 2
/ \
3 3
return [[3, 3], [6, 2], [7]]
"""
from data_types.node_tree import build_tree, level_order_traversal
def main() -> None:
"""Main function"""
tree = build_tree([2, 1, 2])
# tree = build_tree([7, [6, 3, 3], 2])
levels = level_order_traversal(tree)
print(levels[::-1])
if __name__ == "__main__":
main()
| true |
0dea31e0b15d3bf16ecd86a570bf62182ba6828d | Guan-Ling/20210125 | /6-F.py | 610 | 4.28125 | 4 | # Fibonacci numbers are the numbers in the integer sequence starting with 1, 1 where every number after the first two is the sum of the two preceding ones:
# 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
# Given a positive integer n, print the nth Fibonacci number.
# 下一個數字=前兩個數字相加
# 印出第n個數字
n=int(input())
a=1
b=1
i=3
while i<=n:
c=a+b
a,b=b,c
i=i+1
if n==1 or n==2:
print(1)
else:
print(c,end=" ")
# 印出數列
# n=int(input())
# a=1
# b=1
# print(1,end=" ")
# print(1,end=" ")
# i=3
# while i<n:
# c=a+b
# print(c,end=" ")
# a,b=b,c
# i=i+1 | false |
c02745c0c0c0713679e239d7f6bd6358d75db1d8 | Guan-Ling/20210125 | /6-1.py | 252 | 4.15625 | 4 | # For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order.
# 50
# 1 4 9 16 25 36 49
# 印出小於n2的平方數
n=int(input())
i=1
while i**2<=n:
print(i**2,end=" ")
i=i+1
| true |
e3fec410d51986ac63efc29a2edf6c88c654f00f | Guan-Ling/20210125 | /3-A.py | 437 | 4.15625 | 4 | # Given three integers. Determine how many of them are equal to each other.
# The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
# 看三個數中 有幾個相等
a=int(input("first:"))
b=int(input("second:"))
c=int(input("third:"))
if a==b==c:
print(3)
elif a==b or b==c or a==c:
print(2)
else:
print(0) | true |
4ea47e76154d2b31659f86c51c20349ec95a8f29 | Guan-Ling/20210125 | /3-9.py | 255 | 4.375 | 4 | # Given a month - an integer from 1 to 12, print the number of days in it in the year 2017.
# 輸入月份 輸出天數
n=int(input("month:"))
if n==2:
print(28)
elif n==1 or n==3 or n==5 or n==7 or n==8 or n==10 or n==12:
print(31)
else:
print(30) | true |
d3c4120cf48f4e84c80f5d9f89e49bc80552c299 | Guan-Ling/20210125 | /4-2.py | 280 | 4.1875 | 4 | # Given two integers A and B. Print all numbers from A to B inclusively, in increasing order, if A < B, or in decreasing order, if A ≥ B.
a=int(input())
b=int(input())
if a>b:
for i in range(a,b-1,-1):
print(i,end=" ")
else:
for j in range(a,b+1):
print(j,end=" ") | true |
5be005793adb580ca9fe892d8a3bbe7d4da8fa6b | Guan-Ling/20210125 | /3-K.py | 496 | 4.1875 | 4 | # Given a month (an integer from 1 to 12) and a day in it (an integer from 1 to 31) in the year 2017, print the month and the day of the next day to it.
# 天數+1
m=int(input("month:"))
n=int(input("day:"))
if m==2 and n==28:
m=m+1
n=1
elif n==30:
if m==2 or m==4 or m==6 or m==9 or m==11:
m=m+1
n=1
else:
n=n+1
elif n==31:
if m==1 or m==3 or m==5 or m==7 or m==8 or m==10:
m=m+1
n=1
elif m==12:
m=1
n=1
else:
n=n+1
else:
n=n+1
print(m)
print(n) | false |
da6ad4bb64ec1d7b7fc64ca7146a5994402f215e | elenagradovich/python_ex | /module_2/__squares.py | 1,122 | 4.4375 | 4 | '''
Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами a и b
на квадраты с наибольшей возможной на каждом этапе стороной.
Выведите длины ребер получаемых квадратов и кол-во полученных квадратов.
'''
def get_squares(width_, height_):
global square_number
if width_ > 0.1 and height_ > 0.1:
if width_ < height_:
width_, height_ = height_, width_
print(f'Квадрат со стороной: {round(height_, 2)}')
square_number += 1
get_squares(width_ - height_, height_)
width = float(input("width: \n"))
height = float(input("height: \n"))
square_number = 0
if width == 0 or height == 0 or width < 0 or height < 0:
print('Такого квадрата не существует')
else:
get_squares(width, height)
print('----------------------')
print(f'Количество квадратов {square_number}')
| false |
96fdbe30d7d920dda1490b0cbb530a8a0269bd05 | Tiago-Baptista/CursoEmVideo_Python3 | /cursoemvideo/python3_mundo1/aula_08/aula08.py | 277 | 4.1875 | 4 | #import math
#num = int(input('Escreva um numero: '))
#raiz = math.sqrt(num)
#print('A raiz de {} é igual a: {}'.format(num, raiz))
from math import sqrt
num = int(input('Escreva um numero: '))
raiz = sqrt(num)
print('A raiz quadrada de {} é igual a: {}'.format(num, raiz))
| false |
dda2d0942295b772ba2d5195a5e4b20c10f776f7 | Hira63S/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,793 | 4.28125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index # we make the
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# go all the way to second_last index
for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]: # everything that is to the right of the index
smallest_index = j
# now replace
new = arr[smallest_index]
arr[smallest_index] = arr[cur_index]
arr[cur_index] = new
return arr
# Big O notation of n**2
# n(n) -> O(n**2)
# TO-DO: implement the Bubble Sort function below
# How it works:
# Compare the first two elements in array and compare if the left hand side is bigger
# than the right hand side
# Check if the swap actually happened
# if the left hand side is less than right hand side.
# holding n cards in the hand.
# the largest item is bubbled to the end of the array. We have to repeat the process
def bubble_sort( array ):
for i in range(len(array)-1,0,-1):
for j in range(i):
if array[j] > array[j+1]:
temp = array[j] # if the item at that index is greater than the next one, make it temp
array[j] = array[j+1] # make the next item in the list a temp[j] item so that when it loops thru, it will compare it with the next one
array[j+1] = temp # make the new item the temp.
# array[j], array[j+1] = array[j+1], array[j]
return array
# array = [30, 43, 9, 89, 40]
# bubble_sort(array)
# print(array)
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
return arr
| true |
fa707b2e124370cbaf4b1dfa8c6e7b4274e31dac | sachi-shah/DS | /practical7a.py | 967 | 4.1875 | 4 | # Implement the following for Hashing:
# a. Write a program to implement the collision technique.
size_list = 6
def search_from_hash(key, hash_list):
searched_index = hash_function(key)
if hash_list[searched_index] == key:
print("value found")
else:
print("value not in list")
def hash_function(value):
global size_list
return value%size_list
def map_hash2index(hash_return_value):
return hash_return_value
def create_hash_table(list_values, main_list):
for value in list_values:
hash_return_value = hash_function(value)
list_index = map_hash2index(hash_return_value)
if main_list[list_index]:
print("collision detected")
else:
main_list[list_index] = value
list_values = [1,3,4,5,8,60]
main_list = [None for x in range(size_list)]
print(main_list)
create_hash_table(list_values, main_list)
print(main_list)
search_from_hash(30, main_list)
| true |
d180ccbdc1c65f62cab4228985a5c846a355a783 | A-lone-Contributer/General-Algorithms | /Fast modulo Exponentiation.py | 1,336 | 4.46875 | 4 | # Fast Modular Exponentiation
# Modulus is the most common operation while handling overflows, we modulo the
# large number so limit it to primitive data types range.
# So the problem is to find the nth power of a number and find its modulo,
# it can be calculated faster than you think so lets discuss it.
# Approach:
# A common approach to find the power is to iteratively square the number and take modulo at the end
# but easy approach comes with time complexity of O(n). We want better than this!
# We cannot do it in O(1) as we have n in the equation itself. So what about O(log(n))?
# Algorithm:
# Divide the problem into subproblems of size n/2
# If the number is even then simply multiply the subproblems
# else we get an extra factor which we will multiply at each point
# Repeat till we power is exhausted.
def fast_exponentiation(digit, n, p):
# Initialise result
result = 1
# (ab) mod p = ( (a mod p) (b mod p) ) mod
# calculate initial modulo
digit = digit % p
# while there is power left
while n:
# check if odd
if int(n) & 1:
result = (result * digit) % p
# for even
n /= 2
digit = (digit ** 2) % p
return result
# Driver Code
print(fast_exponentiation(6, 23, 13))
# Time Complexity : O(log(n))
# Space Complexity : O(1)
| true |
d191d3717ad9d99abb396fc11b1387251e75ff9c | davidcoxch/PierianPython | /5_Python_Statements/first_letter.py | 249 | 4.59375 | 5 | '''
Use List Comprehension to create a list of the first letters of every word in the string below:
'''
st = 'Create a list of the first letters of every word in this string'
mylist = []
for x in st.split():
mylist.append(x[0])
print(mylist) | true |
3a625245a43638e3fba0179872f91907385d8958 | davidcoxch/PierianPython | /6_Methods_and_Functions/paper_doll.py | 373 | 4.1875 | 4 | """
PAPER DOLL: Given a string, return a string where for every character in the original there are three characters¶
paper_doll('Hello') --> 'HHHeeellllllooo'
paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
"""
def paper_doll(text):
st = ''
for x in text:
st = st + x*3
return st
print(paper_doll('Hello'))
print(paper_doll('Mississippi')) | true |
448c7abd589ca3bbe895883161c78cb6ab5aad57 | davidcoxch/PierianPython | /6_Methods_and_Functions/makes_twenty.py | 424 | 4.15625 | 4 | """
From 03-Function Practice Exercises.ipynb notebook
MAKES TWENTY: Given two integers, return True if the sum of the integers is
20 or if one of the integers is 20. If not, return False
makes_twenty(20,10) --> True
makes_twenty(12,8) --> True
makes_twenty(2,3) --> False
"""
def makes_twenty(a,b):
return a + b == 20 or 20 in (a,b)
print(makes_twenty(10,20))
print(makes_twenty(12,8))
print(makes_twenty(2,3))
| true |
87f59eac5827026a0cf6f0f1afa6c59bdec9bc11 | Mbyrne28/46_Python_Exercises | /q7.py | 442 | 4.53125 | 5 | # Define a function reverse() that computes the reversal of a string.
# reverse("I am testing") => "gnitset ma I"
# reverse("Hello world") => "dlrow olleH"
from test_fun import *
def reverse(s):
"""returns the reversal of a string"""
reversed_str = ""
for char in s:
reversed_str = char + reversed_str
return reversed_str
print(test_fun(reverse("I am testing"),"gnitset ma I"))
print(test_fun(reverse("Hello world"),"dlrow olleH")) | true |
b353e844347a0d6ec2c1f902a97f8303b9ac48d1 | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter3_programming4.py | 637 | 4.28125 | 4 | # Program calculates the distance to a lightning strike based on the time
# elapsed between the flash and the sound of thunder
def main():
# Constants
SPEED_OF_SOUND = 1100
MILE_IN_FEET = 5280
# Obtain the time elapsed from the user
time = int(input("Enter the time that elapsed between the flash" + \
"and the sound of thunder: "))
# Calculations
distance = SPEED_OF_SOUND * time
miles = distance // MILE_IN_FEET
feet = distance % MILE_IN_FEET
# Display the result for the user
print("\nThe distance to the lightning strike is about", miles, "miles and", \
feet, "feet from your current location.")
main()
| true |
7e62695555bc1007d911aa0ad201d2a0deb03e96 | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter6_programming5.py | 678 | 4.40625 | 4 | # Program calculating the cost per square inch of a circular pizza
# Input is diameter and price
import math
def areaPizza(diameter):
radius = diameter / 2 # need radius for our calculations, not diameter
area = math.pi * radius ** 2
return area
def cost(diameter, price):
return price / areaPizza(diameter)
def main():
# obtain the diameter and price from the user
diameter = int(input("Enter the diameter of the pizza in inches: "))
price = float(input("Enter the price of the pizza: "))
# Display the result for the user with the cost rounded to 2 decimal places
print("The cost is $", round(cost(diameter, price), 2), " per square inch.", sep='')
main()
| true |
1862b67dca8a6e6fc7598e54a53c5a611f8989a4 | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter11_programming12.py | 1,078 | 4.21875 | 4 | def censor(word):
# Iterate through characters and replace all letters with an asterisk
# This means that a censored word with a comma with still have the comma.
for i in range(len(word)):
if word[i].isalpha():
word = word[:i] + '*' + word[i+1:]
return word
def main():
filename = input("Enter the name of the file to censor: ")
text = open(filename, 'r')
words_filename = input("Enter the name of the file containing the censored words")
censored = open(words_filename, 'r')
censored_words = censored.read().split()
censored_text = ''
for line in text:
words = line.split()
# Check if the letters in one of the 'words' in the line spells out
# a censored word. If so, replace it with asterisk.
for i in range(len(words)):
word = ''
for letter in words[i]:
if letter.isalpha():
word += letter
if word in censored_words:
words[i] = censor(words[i])
censored_text += ''.join(words) + '\n'
text.close()
censored.close()
new_file = open('censored ' + filename, 'w')
new_file.write(censored_text)
new_file.close()
main()
| true |
af89718c4c3dbead0b235c657074f5749d9c9511 | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter2_convert.py | 589 | 4.3125 | 4 | # A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell
# introduction by Dora Belme
def main():
# Introduction
print("""
Convert.py is designed to convert temperature in Celsius to temperatures
in Fahrenheit. When prompted please enter the numerical value of the Celsius\
temperature and we will provide the corresponding value in Fahrenheit.""")
# The code
celsius = eval (input ("What is the Celsius temperature? ") )
fahrenheit = 9/5 * celsius + 32
print ("The temperature is", fahrenheit, "degrees Fahrenheit.")
main ()
input("Press the <Enter> key to quit.") | true |
15fda3f3c9152d33dea52191d9080c8718424e2f | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter4_ futval_graph2.py | 1,074 | 4.28125 | 4 | from graphics import *
def main():
# Introduction
print("This program plots the growth of a 10-year investment.")
# Get principla and interest rate
principal = float(input("Enter the initial principal: "))
apr = float(input("Enter the annualized interest rate: "))
# Create a graphics window with labels on left edge
win = GraphWin("Investment Growth Chart", 640, 480)
win.setBackground("white")
win.setCoords(-1.75, -200, 11.5, 10400)
Text(Point(-1, 0), ' 0.0K').draw(win)
Text(Point(-1, 2500), ' 2.5K').draw(win)
Text(Point(-1, 5000), ' 5.0K').draw(win)
Text(Point(-1, 7500), ' 7.5K').draw(win)
Text(Point(-1, 10000), ' 10.0K').draw(win)
# Draw bar for initial principal
bar = Rectangle(Point(0,0), Point(1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
# Draw a bar for each subsequent year
for year in range(1,11):
principal = principal * (1 + apr)
bar = Rectangle(Point(year, 0), Point(year + 1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
input("Press <Enter> to quit.")
win.close()
main()
| true |
31be57e124fa96138f2fd4096d1f0da0519fc27f | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter6_programming6.py | 1,241 | 4.28125 | 4 | # Program calculates the area of a triangle
# Input 3 sides
import math
from graphics import *
def square(x):
return x * x
def distance(p1,p2):
dist = math.sqrt(square(p2.getX() - p1.getX()) + \
square(p2.getY() - p1.getY()))
return dist
def area(side1, side2, side3):
s = (side1 + side2 + side3) / 2
A = math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
return A
def main():
win = GraphWin("Draw a Triangle")
win.setCoords(0.0, 0.0, 10.0, 10.0)
message = Text(Point(5, 1), "Click on three points")
message.setSize(10)
message.draw(win)
# Get and draw three vertices of traingle
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
# Use Polygon object to draw the triangle
triangle = Polygon(p1, p2, p3)
triangle.setFill("peachpuff")
triangle.setOutline("cyan")
triangle.draw(win)
# Calculate the side lenght
a = distance(p1, p2)
b = distance(p2, p3)
c = distance(p3, p1)
# Calculate the perimeter and area of the triangle
perimeter = a + b + c
ar = area(a,b,c)
message.setText(("The perimeter is: {0:0.2f}\nThe area is: " +\
"{1:0.2f}".format(perimeter, ar))
# Wait for another click to exit
win.getMouse()
win.close()
main()
| true |
2b8d923e9618e39f9f979bde5736bbb8e1cc7016 | Ryanyanglibin/algorithm004-01 | /Week 06/id_251/LeetCode_208_251.py | 2,334 | 4.1875 | 4 | # 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
#
# 示例:
#
# Trie trie = new Trie();
#
# trie.insert("apple");
# trie.search("apple"); // 返回 true
# trie.search("app"); // 返回 false
# trie.startsWith("app"); // 返回 true
# trie.insert("app");
# trie.search("app"); // 返回 true
#
# 说明:
#
#
# 你可以假设所有的输入都是由小写字母 a-z 构成的。
# 保证所有输入均为非空字符串。
#
# Related Topics 设计 字典树
# leetcode submit region begin(Prohibit modification and deletion)
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.end_of_word = '#'
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end_of_word] = self.end_of_word
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return self.end_of_word in node
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
if __name__ == '__main__':
t = Trie()
typ = {
'Trie': t,
'insert': t.insert,
'search': t.search,
'startsWith': t.startsWith
}
funcs = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
args = [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
correct_res = [None, None, True, False, True, None, True]
# res = []
# for func, arg in zip(funcs, args):
# res.append(typ[func](arg[0]) if arg else None)
res = [typ[func](arg[0]) if arg else None for func, arg in zip(funcs, args)]
print(res == correct_res)
| false |
f1f0a3f1f7709d032241b49fe8747acb45e356e9 | GyeongHyeonKim/py_lab | /aver_num.py | 203 | 4.1875 | 4 | #!/usr/bin/python
mysum = 0
num =int(input("Enter the number of num :"))
for i in range(num):
value= int(input("Give me number :"))
mysum+=value
myavg = mysum/num
print("avg = %d" % (myavg))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.