blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3259d55b1aa7a9a2112a9eafe5ef2234966e0adc | udhayprakash/PythonMaterial | /python3/13_OOP/b_MRO_inheritance/01_single_inheritance.py | 1,521 | 4.28125 | 4 | """
Purpose: Single Inheritance
Parent - child classes relation
Super - sub classes relation
NOTE: All child classes should make calls to the parent class
constructors
MRO - method resolution order
"""
class Account:
"""
Parent or super class
"""
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
# a1 = Account()
# print(vars(a1))
# print(dir(a1))
class MinimumBalanceAccount(Account):
"""
Child or sub class
"""
def __init__(self):
# calling the constructor of the parent class
Account.__init__(self)
def withdraw(self, amount):
if self.balance - amount < 100:
print("Please maintain minimum balance. transaction failed!!!")
else:
Account.withdraw(self, amount)
a2 = MinimumBalanceAccount()
print(vars(a2)) # {'balance': 0}
print(dir(a2)) # 'balance', 'deposit', 'withdraw'
# MRO - Method Resolution Order
print(Account.__mro__)
# (<class '__main__.Account'>, <class 'object'>)
print(MinimumBalanceAccount.__mro__)
# (<class '__main__.MinimumBalanceAccount'>, <class '__main__.Account'>, <class 'object'>)
print(f"Initial balance :{a2.balance}")
print(dir(a2))
print()
a2.deposit(1300)
print(f"After deposit(1300) :{a2.balance}")
a2.withdraw(900)
print(f"After withdraw(900) :{a2.balance}")
a2.withdraw(400)
| true |
b92994e333cf4ef258773b508a5107d81a1d321c | udhayprakash/PythonMaterial | /python3/13_OOP/a_OOP/11_static_n_class_methods.py | 1,243 | 4.28125 | 4 | #!/usr/bin/python
"""
Methods
1. Instance Methods
2. class Methods
3. static Methods
Default Decorators: @staticmethod, @classmethod, @property
"""
class MyClass:
my_var = "something" # class variable
def display(self, x):
print("executing instance method display(%s,%s)" % (self, x))
@classmethod
def cmDisplay(cls, x):
print("executing class method display(%s,%s)" % (cls, x))
@staticmethod
def smDisplay(x):
print("executing static method display(%s)" % x)
# neither use instance methods, instance variable, class methods nor class variables
if __name__ == "__main__":
a = MyClass()
a.display("Django") # accessing instance method
MyClass.display(a, "Django") # accessing instance method
a.cmDisplay("Django") # accessing class method
MyClass.cmDisplay("Django") # accessing class method
a.smDisplay("Django") # accessing static method
MyClass.smDisplay("Django") # accessing static method
class Myclass:
val = 0
def __init__(self):
self.val = 0
@staticmethod
def incr(self):
Myclass.val = Myclass.val + 1
I = Myclass()
print(f"{I.val = }")
I.incr()
print(f"{I.val = }")
Myclass.incr()
| true |
23978697bff6a4c96fa402731c3a700a5ab6a6ab | udhayprakash/PythonMaterial | /python3/06_Collections/02_Tuples/04_immutability.py | 471 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Tuples are immutable
- They doesnt support in-object changes
"""
mytuple = (1, 2, 3)
print("mytuple", mytuple, id(mytuple))
# Indexing
print(f"{mytuple[2] =}")
# updating an element in tuple
try:
mytuple[2] = "2.2222"
except TypeError as ex:
print(ex)
print("tuple objects are not editable")
# Overwriting
print("\noverwriting (re-assigning)")
mytuple = (1, "2.2222", 3)
print("mytuple", mytuple, id(mytuple))
| true |
c81f107aece79ddbbddbe4b9185f3dd2ab40f8a7 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/00_static_code_analyses/e_ast_module.py | 1,820 | 4.15625 | 4 | #!/usr/bin/python
"""
Purpose: AST(Abstract Syntax Tree) Module
Usage
- Making IDEs intelligent and making a feature everyone knows as intellisense.
- Tools like Pylint uses ASTs to perform static code analysis
- Custom Python interpreters
- Modes of Code Compilation
- exec: We can execute normal Python code using this mode.
- eval: To evaluate Python’s expressions, this mode will
return the result fo the expression after evaluation.
- single: This mode works just like Python shell which
execute one statement at a time.
"""
import ast
# Executing code
code = ast.parse("print('Hello world!')")
print(f"{code =}")
print(f"{type(code) =}")
exec(compile(code, filename="", mode="exec"))
# To see AST created for above object
print(f"{ast.dump(code) =}")
print("\n\n")
# Evaluating Python Expression
expression = "6 + 8"
code = ast.parse(expression, mode="eval")
print(f"{code =}")
print(f"{type(code) =}")
print(eval(compile(code, "", mode="eval")))
# To see AST created for above object
print(f"{ast.dump(code) =}")
print("\n\n")
# Constructing multi-line ASTs
tree = ast.parse(
"""
fruits = ['grapes', 'mango']
name = 'peter'
for fruit in fruits:
print('{} likes {}'.format(name, fruit))
"""
)
print(ast.dump(tree))
print("\n\n")
class NodeTransformer(ast.NodeTransformer):
def visit_Str(self, tree_node):
return ast.Str("String: " + tree_node.s)
class NodeVisitor(ast.NodeVisitor):
def visit_Str(self, tree_node):
print("{}".format(tree_node.s))
tree_node = ast.parse(
"""
fruits = ['grapes', 'mango']
name = 'peter'
for fruit in fruits:
print('{} likes {}'.format(name, fruit))
"""
)
NodeTransformer().visit(tree_node)
NodeVisitor().visit(tree_node)
| true |
089032f1e919883ee09451761df8261fe17c238a | udhayprakash/PythonMaterial | /python3/02_Basics/02_String_Operations/t_string_module.py | 1,412 | 4.25 | 4 | #!/usr/bin/python3
"""
Purpose: String Module
"""
import string
# print(dir(string))
print(string.__doc__, end="\n\n")
print(f"{string.ascii_letters =}")
print(f"{string.ascii_lowercase =}")
print(f"{string.ascii_uppercase =}")
print(f"{string.digits =}")
print(f"{string.hexdigits =}")
print(f"{string.octdigits =}")
print(f"{string.printable =}")
print(f"{string.punctuation =}")
print(f"{string.whitespace =}")
print()
print(f'{string.capwords("aaaaaaaaaaaaaaaaa")=}')
print(f'{string.capwords("11111111111111111")=}')
print(f'{string.capwords("one two three 345")=}') # str.title
print()
s = "let us capitalize every word of this sentence."
print(string.capwords(s))
print(s.title())
t = string.Template("Hello $name!")
t.substitute(name="World") # 'Hello World!'
t = string.Template("""name: $name - $$name - $$$name age : ${age}years""")
# t.substitute(name='World') # KeyError: 'age'
t.substitute(name="World", age=30) # 'name: World - $name - $World age : 30years'
# NOTE: $$ is an escape; it is replaced with a single $.
# ${identifier} is equivalent to $identifier
string.Template("$who likes $what").substitute({"who": "udhay", "what": "python"})
# 'udhay likes python'
string.Template("$who likes $what").substitute({"who": "udhay"})
# KeyError: 'what'
string.Template("$who likes $what").safe_substitute({"who": "udhay"})
# 'udhay likes $what'
| false |
52d5d2268407c434c4ca567c1cf52bc3d8c72783 | udhayprakash/PythonMaterial | /python3/03_Language_Components/09_Loops/i_loops.py | 916 | 4.28125 | 4 | #!/usr/bin/python3
"""
Purpose: Loops
break - breaks the complete loop
continue - skip the current loop
pass - will do nothing. it is like a todo
sys.exit - will exit the script execution
"""
import sys
i = 0
while i <= 7:
i += 1
print(i, end=" ")
print("\n importance of break")
i = 0
while i <= 7:
i += 1
if i % 2 == 0:
break
print(i, end=" ")
print("\n importance of continue")
i = 0
while i <= 7:
i += 1
if i % 2 == 0:
continue
print(i, end=" ")
print("\n importance of pass")
i = 0
while i <= 7:
i += 1
if i % 2 == 0:
pass # It acts as a placeholder
print(i, end=" ")
print("\nimportance of sys.exit")
i = 0
while i < 7:
i += 1
if i % 2 == 0:
sys.exit(0)
print(i, end=" ")
# exit code 0 - successful/normal termination
# exit code non-zero - abnormal termination
print("next statement")
| true |
151a7dcf87ee5c6458eac386a5831f90dcc746a3 | udhayprakash/PythonMaterial | /python3/15_Regular_Expressions/a_re_match.py | 734 | 4.5 | 4 | """
Purpose: Regular Expressions
Using re.match
- It helps to identify patterns at the starting of string
- By default, it is case-sensitive
"""
import re
# print(dir(re))
target_string = "Python Programming is good for health"
search_string = "python"
print(f"{target_string.find(search_string) =}")
print(f"{search_string in target_string =}")
print()
reg_obj = re.compile(search_string)
print(reg_obj, type(reg_obj))
result = reg_obj.match(target_string)
print(f"{result =}")
if result:
print(f"result.group():{result.group()}")
print(f"result.span() :{result.span()}")
print(f"result.start():{result.start()}")
print(f"result.end() :{result.end()}")
else:
print("NO match found")
| true |
31fcb6bff7762bc0fb0ea7aa7911c04d21ca77ad | udhayprakash/PythonMaterial | /python3/10_Modules/03_argparse/a_arg_parse.py | 1,775 | 4.34375 | 4 | #!/usr/bin/python3
"""
Purpose: importance and usage of argparse
"""
# # Method 1: hard- coding
# user_name = 'udhay'
# password = 'udhay@123'
# server_name = 'issadsad.mydomain.in'
# # Method 2: input() - run time
# user_name = input('Enter username:')
# password = input('Enter password:')
# server_name = input('Enter server name:')
# # Method 3: input() - run time with getpass for password
# import getpass
# user_name = input('Enter username:')
# password = getpass.getpass('Enter password:')
# server_name = input('Enter server name:')
# # Method 4: sys.argv
# import sys
# if len(sys.argv) != 4:
# print('Help:')
# print(f'python {__file__} username password server_fqdn')
# sys.exit(1)
# user_name = sys.argv[1]
# password = sys.argv[2]
# server_name = sys.argv[3]
# unpacking
# user_name, password, server_name = sys.argv[1:]
# Method 5: argparse
import argparse
parser = argparse.ArgumentParser(
description="Details to login to server", epilog="-----Please follow help doc ----"
)
# description: for the text that is shown before the help text
# epilog: for the text shown after the help text
parser.add_argument("-u", "--username", help="login user name", type=str, required=True)
parser.add_argument(
"-p", "--password", help="login user password", type=str, required=True
)
parser.add_argument(
"-s",
"--servername",
help="server name",
type=str,
required=False,
default="www.google.com",
)
args = parser.parse_args()
user_name = args.username
password = args.password
server_name = args.servername
print(
f"""
The server login details are:
USER NAME : {user_name}
PASSWORD : {password}
SERVER NAME : {server_name}
"""
)
# python a_example.py -h
# python a_example.py --help
| false |
6473f82475a39c63e9c3cdd46726b15656253137 | udhayprakash/PythonMaterial | /python3/07_Functions/030_closures_ex.py | 492 | 4.59375 | 5 | #!/usr/bin/python3
"""
Purpose: closure example demo
"""
def outer(num1):
num3 = 30
def hello_world():
print("Hello world")
def wrapper(num2): # closure function
result = num1 + num2 + num3
return result
print(f"{hello_world.__closure__ =}")
print(f"{wrapper.__closure__ =}")
return wrapper
outer_result = outer(10)
print(f"{type(outer_result)} {outer_result}")
print(f"{outer.__closure__ =}")
# <function outer.<locals>.hello_world
| false |
696622f014f6ab152e691c301c2ae66a054aa1c9 | udhayprakash/PythonMaterial | /python3/07_Functions/032_currying_functions.py | 1,944 | 5.03125 | 5 | #!/usr/bin/python3
"""
Purpose: Currying Functions
- Inner functions are functions defined inside another function that can be used for various purposes, while
currying is a technique that transforms a function that takes multiple arguments into a sequence of functions that each take a single argument.
- Inner functions can be used to create closures, encapsulate helper functions, or implement decorators, while
currying is useful for creating more flexible and composable functions in functional programming.
- While inner functions can be used to implement currying, they are not the same thing, and
currying can also be implemented using other techniques such as lambda functions or partial function application.
"""
# Example of inner functions
def outer(x):
def inner(y):
return x + y
return inner
add5 = outer(5)
print(add5(3)) # Output: 8
# Example of currying using lambda functions
def add(x):
return lambda y: x + y
add5 = add(5)
print(add5(3)) # Output: 8
# ------------------------------------------------------------
# Example of inner functions
def multiply_by(x):
def inner(y):
return x * y
return inner
double = multiply_by(2)
print(double(5)) # Output: 10
# Example of currying using lambda functions
def multiply(x):
return lambda y: x * y
triple = multiply(3)
print(triple(5)) # Output: 15
# --------------------------------------------------------------
# Example of inner functions
def compose(f, g):
def inner(x):
return f(g(x))
return inner
def square(x):
return x * x
def add(x):
return x + 1
square_and_add = compose(add, square)
print(square_and_add(3)) # Output: 10
# Example of currying using partial function application
from functools import partial
def compose(f, g, x):
return f(g(x))
square_and_add = partial(compose, add, square)
print(square_and_add(3)) # Output: 10
| true |
713d449e4646683292f37d3e16792f2eaa58052d | udhayprakash/PythonMaterial | /python3/11_File_Operations/01_unstructured_file/i_reading_large_file.py | 757 | 4.1875 | 4 | #!/usr/bin/python3
"""
Purpose: To read large file
"""
from functools import partial
def read_from_file(file_name):
"""Method 1 - reading one line per iteration"""
with open(file_name, "r") as fp:
yield fp.readline()
def read_from_file2(file_name, block_size=1024 * 8):
"""Method 2 - reading block size per iteration"""
with open(file_name, "r") as fp:
while True:
chunk = fp.read(block_size)
if not chunk:
break
yield chunk
def read_from_file3(file_name, block_size=1024 * 8):
"""Method 3 - reading block size per iteration (clean code)"""
with open(file_name, "r") as fp:
for chunk in iter(partial(fp.read, block_size), ""):
yield chunk
| true |
208da5282d2ac39f6a51343025bd78f422d2441b | alecbw/Learning-Projects | /Bank Account.py | 1,147 | 4.34375 | 4 | """ This code does the following things
Top level: creates and manipulates a personal bank account
* accepts deposits
* allows withdrawals
* displays the balance
* displays the details of the account """
class BankAccount(object):
balance = 0
def __init__(self, name):
self.name = name
def __repr__(self):
return "This account belongs to %s and it has a balance of $%.2f" % (self.name, self.balance)
def show_balance(self):
print "The balance is $%.2f" % self.balance
def deposit(self, amount):
if amount <= 0:
print "You can't deposit a negative amount"
return
else:
print "So you're depositing $%.2f" % amount
self.balance += amount
self.show_balance()
def withdraw(self, amount):
if amount >= self.balance:
print "You can't withdraw more than you have"
return
else:
print "So you're withdrawing $%.2f" % amount
self.balance -= amount
self.show_balance()
my_account = BankAccount("alec")
my_account.__repr__()
print my_account
my_account.show_balance()
my_account.deposit(2000)
my_account.withdraw(1000)
print my_account
| true |
13408db5de2e32cd359d691ac80ad724b2495253 | TaiPham25/PhamPhuTai---Fundamentals---C4E16 | /Session04/clera.py | 742 | 4.15625 | 4 |
print ('Guess your number game')
print ('Now think of a number from 0 to 100, then press " Enter"')
input()
print("""
All you have to do is to asnwer to my guess
'c' if my guess is 'C'orrect
'l' if my guess is 'L'arge than your number
's' if my guess is 'S'mall than your number
""")
#string formatting
from random import randint
# n = randint(0,100)
high = 100
low = 0
while True:
mid = (low + high) // 2
answer = input("Is {0} your number? ".format(mid)).lower()
if answer == 'c':
print("'C'orrect")
break
elif answer == 's':
low = mid
print("'S'maller than your number")
elif answer == 'l':
high = mid
print("'L'arge than you number")
else:
print('zzzz')
| true |
ef28f1eb265cb90c47a2c1fec8c714d3542f7d8c | Toruitas/Python | /Practice/Daily Programmer/DP13 - Find number of day in year.py | 2,659 | 4.40625 | 4 | __author__ = 'Stuart'
"""
http://www.reddit.com/r/dailyprogrammer/comments/pzo4w/2212012_challenge_13_easy/
Find the number of the year for the given date. For example, january 1st would be 1, and december 31st is 365.
for extra credit, allow it to calculate leap years, as well.
https://docs.python.org/3.4/library/datetime.html
http://www.tutorialspoint.com/python/python_date_time.htm
"""
def test_leap(date):
"""
Year evenly divisible by 4, by 400, but not 100.
:param date:
:return:Boolean for leap year confirmation
"""
if date % 400 != 0 and date % 100 == 0:
return False
elif date %4 == 0:
return True
else:
return False
def lazyway(year,month,day):
"""
Returns number of day in teh year. Includes leap year calculation already. Super Lazy.
d.timetuple() == time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.
:param year: Year you wanna check
:param month: Month
:param day: Day
:return: ordinal date in the year
"""
that_day = datetime.date(year,month,day)
return that_day.timetuple()[7]
if __name__ == "__main__":
import calendar # if I were a lazy man, I could use this to test for leapness
import datetime # or could use date.timetuple()'s yday to find it easily from a date object
months = {"january":1,
"february":2,
"march":3,
"april":4,
"may":5,
"june":6,
"july":7,
"august":8,
"september":9,
"october":10,
"november":11,
"december":12}
days = [31,28,31,30,31,30,31,31,30,31,30,31] #days in each month
thedate = input("What is the date you want to test? Format January 21st, 1987 please.")
thedate = thedate.split()
thedate[0],thedate[1],thedate[2] = thedate[0].lower(),int(thedate[1].replace("st","").replace("th","").replace(",","")),int(thedate[2])
month_index = months[thedate[0]]-1 #since month indexes start at 1 in the dictionary, but 0 in the days list
year = thedate[2]
month = months[thedate[0]] #months start at 1 for this library too, so no need to -1
day = thedate[1]
print(lazyway(year,month,day))
if test_leap(thedate[2]): #test for leapness
days[1] += 1
numday = 0
for i in range(month_index): #adds all the months before the entered month
numday += days[i]
numday += thedate[1] #then adds the date of current month
print(numday) | true |
185f03b68bac3ca937ecee2d5b4b033314fb3d06 | Toruitas/Python | /Practice/Daily Programmer/Random Password Generator.py | 811 | 4.15625 | 4 | __author__ = 'Stuart'
"""
Random password generator
default 8 characters, but user can define what length of password they want
"""
def password_assembler(length=8):
"""
Takes user-defined length (default 8) and generates a random password
:param length: default 8, otherwise user-defined
:return: password of length length
"""
password = ""
for i in range(length+1):
password += random_character()
return password
def random_character():
"""
random character generator
:return: random character
"""
characters = string.printable
return random.choice(characters)
if __name__ == "__main__":
import random
import string
length = input("What length password would you like? Default is 8")
print(password_assembler(int(length))) | true |
47567240773ccbedbccd4a4f098e3911419cd163 | Toruitas/Python | /Practice/Daily Exercises/day 11 practice.py | 1,409 | 4.25 | 4 | _author_ = 'stu'
#exercise 11
#time to complete: 15 minutes
"""Ask the user for a number and determine whether the number is prime or not.
(For those who have forgotten, a prime number is a number that has no divisors.)
You can (and should!) use your answer to Exercise 4 to help you.
Take this opportunity to practice using functions, described below."""
"""
def get_integer(help_text="Give me a number: "): #using help_text = gives it a default argument, for when there is no argument submitted
return int(input(help_text))
age = get_integer("Tell me your age: ")
school_year = get_integer("What grade are you in? ")
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
"""
def get_number(help_text="Give me a number: "): #gets number to test from user
return int(input(help_text))
def prime_test(number):
divisors = []
for i in range(2,number/2 +1): #iterates through the list of values. Excludes 1, by definition of prime only divisible by self and 1.
if number % i == 0: #tests if it is a divisor
divisors.append(i) #adds to list of divisors
if len(divisors) == 0: #if any numbers tested have been added to the list, returns prime/not prime
return number," is a prime number."
else:
return number," is not a prime number."
print prime_test(get_number("Give me a number to test: ")) | true |
e825be3736c83d1579e2e155ac0a1c2d3bc8255c | fabiancaraballo/CS122-IntroToProg-ProbSolv | /project1/P1_hello.py | 213 | 4.25 | 4 | print("Hello World!")
print("")
name = "Fabian"
print("name")
print(name)
#print allows us to print in the console whenever we run the code.
print("")
ambition = "I want to be successful in life."
print(ambition)
| true |
634ad3c17d105f95cd627425354fd78826177710 | meridian-school-computer-science/pizza | /src/classes_pizza.py | 930 | 4.53125 | 5 | # classes for pizza with decorator design
class Pizza:
"""
Base class for the building of a pizza.
Use decorators to complete the design of each pizza object.
"""
def __init__(self, name, cost):
self.name = name
self.cost = float(cost)
def __repr__(self):
return f"Pizza({self.name})"
def __str__(self):
return f"{self.name}"
def get_cost(self):
return self.cost
class PizzaType(Pizza):
def __init__(self, name, cost):
super().__init__(name, cost)
class PizzaElement(Pizza):
def __init__(self, name, cost, pizza):
super().__init__(name, cost)
self.decorate = pizza
def get_cost(self):
return self.cost + self.decorate.get_cost()
def __str__(self):
return self.decorate.__str__() + f" + {self.name}"
@property
def show_cost(self):
return f" ${self.get_cost():.2f}"
| true |
684ada57ad12df9053cad5f14c71452e1625c0f2 | bear148/Bear-Shell | /utils/calculatorBase.py | 637 | 4.28125 | 4 | def sub(num1, num2):
return int(num1)-int(num2)
def add(num3, num4):
return int(num3)+int(num4)
def multiply(num5, num6):
return int(num5)*int(num6)
def divide(num7, num8):
return int(num7)/int(num8)
# Adding Strings vs Adding Ints
# When adding two strings together, they don't combine into a different number, they are only put next to eachother.
# For example, if I were to add str(num7)+str(num8), and num7 == "4" then num8 == "6", instead of getting 10, you'd
# get 46. However, with an integer, it add the numbers and you'd get 10. So make sure when doing this you make the numbers integers
# before the get added together. | true |
bf3a5caa3e68bdf5562bf7270ba11befeb5ab21c | jijo125-github/Solving-Competitive-Programs | /LeetCode/0001-0100/43-Multiply_strings.py | 832 | 4.28125 | 4 | """ Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
"""
class Solution:
def multiply(self, num1: str, num2: str) -> str:
li, lj = len(num1), len(num2)
i, j = 0, 0
n1, n2 = 0, 0
while i < li:
n1 += (ord(num1[i]) - 48) * (10 ** (li-i-1))
i += 1
while j < lj:
n2 += (ord(num2[j]) - 48) * (10 ** (lj-j-1))
j += 1
return str(n1*n2)
obj = Solution()
num1, num2 = "123", "456"
print(obj.multiply(num1,num2)) | true |
f3901e5c758a2fc0d785d9c20769d5f0169a797f | daniloaugusto0212/EstudoPython | /Python-Udemy/Básico/aula15Listas.py | 788 | 4.125 | 4 |
idade = [] #inicializando lista vazia
idade.append(18) #adiciona o valor 18 à lista
idade.append(50)
idade.append(35)
idade.append(48)
idade.append(40) #adiciona o valor 18 ao final da lista
idade.insert(1, 30) #adiciona o valor 30 na posição 1 da lista
idade.pop() #remove o valor da última posição da lista
idade.pop(1) #remove o valor da posição 1 da lista
idade.remove(50) #remove o valor especificado
len(idade) #mostra a quantidade de elementos que está dentro da lista
idade.sort() #ordena a lista
idade.sort(reverse = True) #ordena a lista em ordem decrescente
idade.reverse() #inverte a ordem da lista
max(idade) #mostra o maior valor dentro da lista
min(idade) #mostra o menor valor dentro da lista
sum(idade) #soma todos os valores dentro da lista
print(idade) | false |
95e04761f619193d2190a9d62d5ec9c0ffe0beea | SharmaManish/crimsononline-assignments | /assignment1/question2.py | 863 | 4.15625 | 4 | def parse_links_regex(filename):
"""question 2a
Using the re module, write a function that takes a path to an HTML file
(assuming the HTML is well-formed) as input and returns a dictionary
whose keys are the text of the links in the file and whose values are
the URLs to which those links correspond. Be careful about how you handle
the case in which the same text is used to link to different urls.
For example:
You can get file 1 <a href="1.file">here</a>.
You can get file 2 <a href="2.file">here</a>.
What does it make the most sense to do here?
"""
pass
def parse_links_xpath(filename):
"""question 2b
Do the same using xpath and the lxml library from http://lxml.de rather
than regular expressions.
Which approach is better? (Hint: http://goo.gl/mzl9t)
"""
pass | true |
130b0896fc57c51d0601eea2483449f51de4142d | xfLee/Python-DeepLearning_CS5590 | /Lab_2/Source/Task_1.py | 640 | 4.1875 | 4 | """
Python program that accepts a sentence as input and remove duplicate words.
Sort them alphanumerically and print it.
"""
# Taking the sentence as input
Input_Sentence = input('Enter any sentence: ')
# Splitting the words
words = Input_Sentence.split()
# converting all the strings to lowercase
words = [element.lower() for element in words]
# Taking the words as a set to remove the duplicate words
words = set(words)
# Now taking the set of words as list
word_list = list(words)
# Sorting the words alphanumerically
word_list = sorted(word_list)
# Printing the sorted words
print(' '.join(word for word in word_list))
| true |
eec458d8c6806cacabeef7b0188edd7db65306bc | xfLee/Python-DeepLearning_CS5590 | /Lab_2/Source/Task_2.py | 433 | 4.28125 | 4 | """
Python program to generate a dictionary that contains (k, k*k).
And printing the dictionary that is generated including both 1 and k.
"""
# Taking the input
num = int(input("Input a number "))
# Initialising the dictionary
dictionary = dict()
# Computing the k*k using a for loop
for k in range(1,num+1):
dictionary[k] = k*k
# Printing the whole dictionary
print('Dictionary with (k, k*k) is ')
print(dictionary)
| true |
591d265f4773fab8be1362b349278cd8ed41574a | mercy17ch/dictionaries | /dictionaries.py | 2,262 | 4.375 | 4 | '''program to show dictionaries'''
#A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values
#
#creating dictionary#
thisdict={"name":"mercy",
"sex":"female",
"age":23}
print(thisdict)
#dictionary methods#
#clear() Removes all the elements from the dictionary#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.clear()
print(person)
#copy() Returns a copy of the dictionary#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.copy()
print(x)
#fromkeys() Returns a dictionary with the specified keys and value#
x = ('key1', 'key2', 'key3')
y = 4
thisdict = dict.fromkeys(x, y)
print(thisdict)
#get() Returns the value of the specified key#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.get("age")
print(x)
#items() Returns a list containing a tuple for each key value pair#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.items()
print(x)
#keys() Returns a list containing the dictionary's keys#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.keys()
print(x)
#pop() Removes the element with the specified key#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.pop("age")
print(person)
#popitem() Removes the last inserted key-value pair#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.popitem()
print(person)
#setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.setdefault("age","18")
print(x)
#update() Updates the dictionary with the specified key-value pairs#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.update({"skin color":"brown"})
print(person)
#values() Returns a list of all the values in the dictionary#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.values()
print(x)
| true |
d4e2cb6d1dac6e74e0097146360ac77b5e7132ea | sajjad065/assignment2 | /Function/function5.py | 270 | 4.1875 | 4 | def fac(num):
fact=1;
if(num<0):
print(int("Please enter non-negative number"))
else:
for i in range(1,(num+1)):
fact=fact*i
print("The factorial is: ")
print(fact)
number=int(input("Enter number "))
fac(number)
| true |
b1282fc3cf4bfe3895451cbbbd18fa6517f92dce | sajjad065/assignment2 | /Function/function17.py | 295 | 4.28125 | 4 | str1=input("Enter any string:")
char=input("enter character to check:")
check_char=lambda x: True if x.startswith(char) else False
if(check_char(str1)):
print(str1 +" :starts with character :" +char)
else:
print(str1 +": does not starts with character: " +char)
| true |
d6c476378fac0c7a2ce31678cb34da2f1977ee57 | sajjad065/assignment2 | /Datatype/qsn28.py | 637 | 4.21875 | 4 | total=int(input("How many elements do you want to input in dictionary "))
dic={}
for i in range(total):
key1=input("Enter key:")
val1=input("Enter value:")
dic.update({key1:val1})
print("The dictionary list is :")
print(dic)
num=int(input("please input 1 if you want to add key to the given dictionary "))
if(num==1):
total=int(input("How many elements do you want to input in the given dictionary "))
for i in range(total):
key2=input("Enter key:")
val2=input("Enter value:")
dic.update({key2:val2})
print("The final dictionary list is :")
print(dic)
| true |
ddf383029c7040717604fa0ee2d79cef71cd0140 | 15271856796/python_study | /day05 拷贝/02 copy库.py | 739 | 4.1875 | 4 | import copy
a=[1,2,3,4]
b=copy.copy(a)
b.append(7)
print(a,b) #[1, 2, 3, 4] [1, 2, 3, 4, 7]
a={'1':2,'2':3}
b=copy.copy(a)
b['3']=4
print(a,b) #{'1': 2, '2': 3} {'1': 2, '2': 3, '3': 4}
#copy.copy()只能实现最外层的copy值
a=[1,2,3,[7,8]]
b=copy.copy(a)
print("a=%s,b=%s"%(a,b)) #a=[1, 2, 3, [7, 8]],b=[1, 2, 3, [7, 8]]
a[1]=22
a[3][1]=88
print("a=%s,b=%s"%(a,b)) #a=[1, 22, 3, [7, 88]],b=[1, 2, 3, [7, 88]]
#为了实现完全的copy copy.deepcopy()
a=[1,2,3,[7,8]]
b=copy.deepcopy(a)
print("a=%s,b=%s"%(a,b)) #a=[1, 2, 3, [7, 8]],b=[1, 2, 3, [7, 8]]
a[3][1]=88
print("a=%s,b=%s"%(a,b)) #a=[1, 2, 3, [7, 88]],b=[1, 2, 3, [7, 8]]
| false |
218bc4a2009026a338abad42c9ac11c4818bf0d7 | pasqualespica/my-realpyhton-tutorial | /InheritanceCompositionOOPGuide/Decorators/simple_decorator.py | 1,512 | 4.34375 | 4 | import functools
# def my_decorator(func):
# def wrapper():
# print("Something is happening before the function is called.")
# func()
# print("Something is happening after the function is called.")
# return wrapper
# def say_whee():
# print("Whee!")
# say_whee = my_decorator(say_whee)
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
# So, @my_decorator is just an easier way of saying
# say_whee = my_decorator(say_whee).
# It’s how you apply a decorator to a function.
@my_decorator
def say_whee():
print("Whee!")
say_whee()
def do_twice(func):
@functools.wraps(func)
def wrapper_do_twice(*args, **kwargs):
func(*args, **kwargs)
func(*args, **kwargs)
return wrapper_do_twice
# @do_twice
# def stampa_due_volte():
# print("Sono Anonimo !!!")
@do_twice
def stampa_due_volte():
print("Sono Anonimo !!!")
stampa_due_volte()
# Decorating Functions With Arguments
@do_twice
def greet(variabile):
print(f"Hello {variabile}")
greet("Pasquale Ciaooo ")
@do_twice
def greet_ext(variabile:str, lista:list, mappa:dict):
print(f"Hello {variabile}")
for e in lista :
print(e)
for k,v in mappa.items():
print(k,v)
print(">>>>>>>>>>>>>.")
greet_ext("Passssss", (1,2,3), {"saldi":100 , "neg": "coop"})
print(greet_ext.__name__)
| false |
8e22e05cf4401dd89fa578671472c856cd9e824c | danielvillanoh/datatypes_operations | /primary.py | 2,323 | 4.5625 | 5 | #author: Daniel Villano-Herrera
# date: 7/1/2021
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numbers
# 2 - create a print statement that prints the sum of three numbers
# 3 - create a print statement the prints the sum of two negative numbers
print(3 + 5)
print(4 + 12 + 42)
print(-53 + -42)
# subtraction
# instructions
# 1 - create a print statement that prints the difference of two numbers
# 2 - create a print statement that prints the difference of three numbers
# 3 - create a print statement the prints the difference of two negative numbers
print(95-2)
print(2 - 53 - 632)
print(-32 - -34)
# multiplication and true division
# instructions
# 1 - create a print statement the prints the product of two numbers
# 2 - create a print statement that prints the dividend of two numbers
# 3 - create a print statement that evaluates an operation using both multiplication and division
print(21 * 9)
print(23/4)
print(21*3/5)
# floor division
# instructions
# 1 - using floor division, print the dividend of two numbers.
print(6//3)
# exponentiation
# instructions
# 1 - using exponentiation, print the power of two numbers
print(32**7)
# modulus
# instructions
# 1 - using modulus, print the remainder of two numbers
print(23 % 3)
# --------------- Section 2 --------------- #
# ---------- String Concatenation --------- #
# concatenation
# instructions
# 1 - print the concatenation of your first and last name
# 2 - print the concatenation of five animals you like
# 3 - print the concatenation of each word in a phrase
print('Daniel' + ' Villano-Herrera')
print('Cat' + ' Rabbit' + ' Bird' + ' Bear' + ' Seal')
print('I\'m' + ' very' + ' short.')
# duplication
# instructions
# 1 - print the duplpication of your first 5 times
# 2 - print the duplication of a song you like 10 times
print('Daniel' * 5)
print('In da Club' * 10)
# concatenation and duplpication
# instructions
# 1 - print the concatenation of two strings duplicated 3 times each
print('Wow' * 3 + 'lol' * 3)
| true |
12d70ddace6d64ace1873bd5e1521efe579daf6f | pedronobrega/ine5609-estrutura-de-dados | /doubly-linked-list/__main__.py | 967 | 4.21875 | 4 | from List import List
from Item import Item
if __name__ == "__main__":
lista: List = List(3)
# This will throw an exception
# lista.go_ahead_positions(3)
# This will print None
print(lista.access_actual())
# This will print True
print(lista.is_empty())
# This will print False
print(lista.is_full())
item1 = Item(123)
lista.insert_at_the_start(item1)
# This will print 123
print(lista.access_actual().value)
item2 = Item(456)
lista.insert_at_the_end(item2)
lista.go_to_last()
# This will print 456
print(lista.access_actual().value)
item3 = Item(789)
lista.insert_at_the_start(item3)
lista.go_to_first()
# This will print 789
print(lista.access_actual().value)
lista.remove_element(456)
lista.go_to_last()
# This will print 123
print(lista.access_actual().value)
item4 = Item(111)
lista.insert_in_position(2, item4)
lista.go_to_last()
# This will print 111
print(lista.access_actual().value) | true |
54a38474bcfc39ee234c64a8b7808d3df7e31c7d | payal-98/Student_Chatbot-using-RASA | /db.py | 1,205 | 4.15625 | 4 | # importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("students.db")
# cursor
crsr = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE students (
Roll_No INTEGER PRIMARY KEY,
Sname VARCHAR(20),
Class VARCHAR(30),
Marks INTEGER);"""
# execute the statement
crsr.execute(sql_command)
# SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (1, "Payal", "10th", 100);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (2, "Devanshu", "9th", 98);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (3, "Jagriti", "8th", 95);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (4, "Ansh", "5th", 90);"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
| true |
f3543b7840f1d43d53abfe9c303836825ddacc63 | javaInSchool/python1_examples | /les2/example1.py | 363 | 4.34375 | 4 | print("Почему сегодня идет снег?")
fred = "Привет, меня зовут фред!"
text = "Как дела?"
string = 'Что-то пошло не так'
print(string)
name = "д'Артаньян"
#name = 'д'Артаньян'
print(name)
name2 = 'д\'Артаньян'
name3 = '''д'Арта"нья"н
и три
мушкетера''' | false |
bf0e360370d704920509e4a61e7c0b79f983c2de | Maxim1912/python | /list.py | 352 | 4.15625 | 4 | a = 33
b = [12, "ok", "567"]
# print(b[:2])
shop = ["cheese", "chips", "juice", "water", "onion", "apple", "banana", "lemon", "lime", "carrot", "bacon", "paprika"]
new_element = input("Что ещё купить?\n")
if new_element not in shop:
shop.append(new_element)
print('We need to buy:')
for element in shop:
print(" - ", element)
| true |
86de52a241ae3645d41c693383b7b232c95126c5 | gcnTo/Stats-YouTube | /outliers.py | 1,256 | 4.21875 | 4 | import numpy as np
import pandas as pd
# Find the outlier number
times = int(input("How many numbers do you have in your list: "))
num_list = []
# Asks for the number, adds to the list
for i in range(times):
append = float(input("Please enter the " + str(i+1) + ". number in your list: "))
num_list.append(append)
print("Your list of numbers now include: " + str(num_list))
# Finding 25th and 75th quantiles and the IQR
def ascend(name_of_the_list):
name_of_the_list = name_of_the_list.sort()
return name_of_the_list
ascend(num_list)
q1 = np.quantile(num_list, .25)
q3 = np.quantile(num_list, .75)
iqr = q3 - q1
# Finding the outliers
outlier_range_lower = q1 - 1.5 * iqr
outlier_range_upper = q3 + 1.5 * iqr
outliers = []
for i in range(times):
if num_list[i] < outlier_range_lower or num_list[i] > outlier_range_upper:
outliers.append(num_list[i])
#else:
# print(str(i) + " is not an outlier.")
# Printing out the outliers.
for i in range(len(outliers)):
if len(outliers) > 1:
print(str(outliers[i]) + " are the outliers).")
elif len(outliers) > 0:
print(str(outliers[i]) + " is the outlier.")
else:
print("There were no outliers to be found.")
| true |
03362a677a4b090f092584c63197e01151937781 | ihanda25/SCpythonsecond | /helloworld.py | 1,614 | 4.15625 | 4 | import time
X = raw_input("Enter what kind of time mesurement you are using")
if X == "seconds" :
sec = int(raw_input("Enter num of seconds"))
status = "calculating..."
print(status)
hour = sec // 3600
sec_remaining = sec%3600
minutes = sec_remaining // 60
final_sec_remaining = sec_remaining%60
time.sleep(5)
status = "Done!"
print status
time.sleep(0.5)
print(hour, "hours", minutes, "minutes", final_sec_remaining, "seconds")
else:
if X == "minutes":
if (type(X)) == int:
minutes = int(raw_input("Enter num of minutes"))
status = "calculating..."
print status
sec = minutes *60
hour = sec//3600
sec_remaining = sec %3600
final_minutes = sec_remaining // 60
final_sec_remaining = sec_remaining%60
time.sleep(5)
status = "Done!"
print(status)
time.sleep(0.5)
print(hour, "hours", final_minutes, "minutes", final_sec_remaining, "seconds")
else:
minutes = float(raw_input("Enter num of minutes"))
status = "calculating..."
print status
sec = minutes *60
hour = sec//3600
sec_remaining = sec %3600
final_minutes = sec_remaining // 60
final_sec_remaining = sec_remaining%60
time.sleep(5)
status = "Done!"
print(status)
time.sleep(0.5)
print(hour, "hours", final_minutes, "minutes", final_sec_remaining, "seconds")
| true |
4785fd11ab80f0e29f7f8ef7ec60a8dab5c893de | japneet121/Python-Design-Patterns | /facade.py | 1,006 | 4.21875 | 4 | '''
Facade pattern helps in hiding the complexity of creating multiple objects from user and encapsulating many objects under one object.
This helps in providing unified interface for end user
'''
class OkButton:
def __init__(self):
pass
def click(self):
print("ok clicked")
class CancelButton:
def __init__(self):
pass
def click(self):
print("cancel clicked")
class SaveButton:
def __init__(self):
pass
def click(self):
print("save clicked")
'''
Page class encapsulates the behaviour of all the three buttons and the end user only needs to manage one object
'''
class Page:
def __init__(self):
self.ok=OkButton()
self.save=SaveButton()
self.cancel=CancelButton()
def press_ok(self):
self.ok.click()
def press_save(self):
self.save.click()
def press_cancel(self):
self.cancel.click()
p=Page()
p.press_cancel()
p.press_ok()
p.press_save() | true |
2f9f0e381ba3e08a5a2487967a942d82292ab48c | Kenny-W-C/Tkinter-Examples | /drawing/draw_image.py | 866 | 4.1875 | 4 | #!/usr/bin/env python3
"""
ZetCode Tkinter tutorial
In this script, we draw an image
on the canvas.
Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""
from tkinter import Tk, Canvas, Frame, BOTH, NW
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("High Tatras")
self.pack(fill=BOTH, expand=1)
self.img = Image.open("tatras.jpg")
self.tatras = ImageTk.PhotoImage(self.img)
canvas = Canvas(self, width=self.img.size[0]+20,
height=self.img.size[1]+20)
canvas.create_image(10, 10, anchor=NW, image=self.tatras)
canvas.pack(fill=BOTH, expand=1)
def main():
root = Tk()
ex = Example()
root.mainloop()
if __name__ == '__main__':
main()
| true |
5a9c60245722eb710122e1af18778d212db4a84a | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m07_stacks/min_parenthesis_to_make_valid.py | 1,008 | 4.25 | 4 | #
# Given a string S of '(' and ')' parentheses, we add the minimum number of
# parentheses ( '(' or ')', and in any positions ) so that the resulting
# parentheses string is valid.
#
# Formally, a parentheses string is valid if and only if:
# It is the empty string, or
# It can be written as AB (A concatenated with B), where A and B are valid
# strings, or It can be written as (A), where A is a valid string.
#
# Given a parentheses string, return the minimum number of
# parentheses we must add to make the resulting string valid.
#
# Input
# S.length <= 1000
# S only consists of '(' and ')' characters.
#
def minAddToMakeValid(S):
stack = []
for ch in S :
if ch == ")" and "(" in stack:
stack.pop()
else:
stack.append(ch)
return len(stack)
sampleInput = '()'
print(minAddToMakeValid(sampleInput))
# Sample Output
# input#1
# ())
# output#1
# 1
#
# input#2
# (((
# output#2
# 3
#
# input#3
# ()
# output#3
# 0
#
#
# input#4
# ()))((
# output#4
# 4
| true |
e978f07ced6f205af8593c88b55503e436f75a88 | catwang42/Algorithm-for-data-scientist | /basic_algo_sort_search.py | 2,886 | 4.4375 | 4 |
#Algorithms
"""
Search: Binary Search , DFS, BFS
Sort:
"""
#bubble sort -> compare a pair and iterate though 𝑂(𝑛2)
#insertion sort
"""
Time Complexity: 𝑂(𝑛2),
Space Complexity: 𝑂(1)
"""
from typing import List, Dict, Tuple, Set
def insertionSort(alist:List[int])->List[int]:
#check from index 1
for i in range(1,len(alist)):
currentValue = alist[i]
while (i-1)>0 and alist[i-1]>currentValue: #if current value less than lagest, move forward
alist[i]=alist[i-1]
i -= 1
alis[i] = currentValue #if larger than current value, don't move
#Merge Sort
"""
Time Complexity: 𝑂(𝑛log𝑛)
Space Complexity: 𝑂(𝑛)
"""
def merge(left:List[int],right:List[int])->List[int]:
result = []
left_index, right_index = 0, 0
while left_index < len(left) and right_index < len(right):
if left[left_index]<=right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index +=1
#one of the list will end first and leaving the other list unmerged
#so append the remaining list to the result
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(alist=List[int])->List[int]:
#need to build a base case first
#recursion can only happend in the else
if len(alist)<=1:
return alist
mid = len(alist)//2
left_list = merge_sort(alist[:mid])
right_list = merge_sort(alist[mid:])
return merge(left_list, right_list)
def create_array(size=10, max=50):
from random import randint
return [randint(0,max) for _ in range(size)]
merge_sort(array)
#quick sort
"""
Time Complexity: average 𝑂(𝑛log𝑛), worest 𝑂(𝑛2)
Space Coplexity: 𝑂(𝑛log𝑛)
check the validility , this print out the value
"""
def quickSort(l:int,h:int,alist:List[int])->List[int]:
while(h>l):
pivot = partition(l,h,alist)
quickSort(l,pivot-1,alist)
quickSort(pivot,h,alist)
def partition(l,h,alist):
pivot = alist[l]
i, j = l, h
while(i<j):
if alist[i]<=pivot:
i +=1
if alist[j]>=pivot:
j -=1
i, j = j, i
pivot, j = j , pivot
return j
#Heapsort
#binary search
def binarySearch(alist:List[int], num:int)->bool:
first = 0
last = len(alist)-1
result = False
while last >= first and not result: #be careful when checking the logic
mid = (last+first)//2
if num == alist[mid]:
result = True
else:
if num < alist[mid]:
last = mid-1
else:
first = mid+1
return result
alist = [2,7,19,34,53,72]
print(binarySearch(alist,34))
#depth first search
#breadth first search | true |
fd84dcb1ea5513f1a8447155147761d345f2e0dd | Taranoberoi/PYTHON | /practicepython_ORG_1.py | 580 | 4.28125 | 4 | # 1 Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
import datetime as dt
Name = input("Please Enter the Name :")
# Taking input and converting into Int at the same time
Age = int(input("Please Enter your age in Years please:"))
yr = dt.datetime.today().year
calc = (yr+(100 - Age))
# using "f" to reduce the code
print(f"Name of the Person is {Name} and Age is {Age}")
# print("Age",Age)
print("You would be 100 years old in Year:::", calc) | true |
de4dd804df9777ac13b9e1f4ba3b0b96c701da3a | Taranoberoi/PYTHON | /Practise1.py | 874 | 4.15625 | 4 | #1 Practise 1 in favourites
#1Write a Python program to print the following string in a specific format (see the output). Go to the editor
#Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output :
####Str = "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
####print("Twinkle, twinkle, little star,\n\tHow I wonder what you are!\n\t\t\tUp above the world so high\n\t\t\tLike a diamond in the sky.\nTwinkle, twinkle, little star,\n\tHow I wonder what you are")
#2 Write a Python program to get the Python version you are using
#### import sys
#### print(sys.version)
#### print(sys.version_info)
| true |
39a34d0c8e530b0a5a55cb177677886e57a0e6f4 | pghanem/Data-Structures-Algorithms | /3_1_threeInOne.py | 1,372 | 4.3125 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def threeInOne():
#this could be done with an array of fixed size 3, with a linked list
# at each index representing a stack. each individual stack could be
# accessed from that index in the array and assuming your implementation
# of the linked list adds and removes nodes at the same side, it is a
# way of creating 3 stacks from a single array.
# another way to do this is to have a circular array that starts by
# splitting the array into thirds, one for each stack. when a stack
# outgrows its third, the start index of the other arrays shifts up
# and data is inserted in that spot.
| false |
b5c65b127bd73e309ab64b3a81a059adcd995da6 | saurabh-deochake/DS | /sorting/bubblesort.py | 541 | 4.25 | 4 | #!/bin/python
"""
Copyright 2016 Saurabh Deochake
1. Bubble Sort
O(n^2)
"""
def sort_bubblesort(my_list):
for pos_upper in xrange(len(my_list)-1,0,-1):
for i in xrange(pos_upper):
if my_list[i] > my_list[i+1]:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
print "pos_upper: " + str(pos_upper) + " i: " + str(i) + " my_list: " + str(my_list)
return my_list
if __name__ == "__main__":
my_list = [54,26,93,17,77,31,44,55,20]
print my_list
print sort_bubblesort(my_list) | false |
81e5bd642345c074b4ac9c55ee4e630a7d6ebd73 | BSchweikart/CTI110 | /M3HW1_Age_Classifier_Schweikb0866.py | 726 | 4.25 | 4 | # CTI - 110
# M3HW1 : Age Classifier
# Schweikart, Brian
# 09/14/2017
def main():
print('Please enter whole number, round up or down')
# This is to have user input age and then classify infant, child,...
# Age listing
Age_a = 1
Age_b = 13
Age_c = 20
# 1 year or less = infant
# 1 year less then 13 = child
# 13 years - 19 = teenager
# 20 + = Adult
# user input for age
age =int(input('Enter age'))
if age <= Age_a:
print('Infant')
elif age > Age_a and age < Age_b:
print('Child')
elif age >= Age_b and age < Age_c:
print('Teenager')
else:
print('Adult')
# program start
main()
| true |
4bd2765c5c80cdb85fa9a2f6c1d9603ac6f26bd6 | Varunaditya/practice_pad | /Python/stringReversal.py | 1,454 | 4.125 | 4 | """
Given a string and a set of delimiters, reverse the words in the string while
maintaining the relative order of the delimiters.
For example, given "hello/world:here", return "here/world:hello"
"""
from sys import argv, exit
alphabets = ['a', 'b', 'c', 'd', 'e',
'f' , 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z']
def delims_handler(ch: str, delims: dict, wc: int) -> dict:
if wc not in delims:
delims[wc] = ch
else:
delims[wc] += ch
return delims
def get_words_delims(inp: str) -> (list, dict):
global alphabets
prev_delim = False
words, word, word_count = list(), str(), 0
delims = dict()
for char in inp:
if char.lower() in alphabets:
prev_delim = False
word += char
else:
words.append(word)
word = str()
if not prev_delim:
word_count += 1
prev_delim = True
delims = delims_handler(char, delims, word_count)
if word:
words.append(word)
return (words, delims)
def rearr(inp: str) -> str:
words, delims = get_words_delims(inp)
output = str()
word_count = 0
for word in words[::-1]:
if word_count in delims:
output += delims[word_count]
output += word
word_count += 1
if word_count in delims:
output += delims[word_count]
return output
def main():
if len(argv) <= 1 :
print('No Input!')
exit(-1)
inp = argv[1]
new_sent = rearr(inp)
print(new_sent)
if __name__ == '__main__':
main()
| true |
91c5976e429e09729f3857b8e5a633073837b368 | Varunaditya/practice_pad | /Python/merge_accounts.py | 1,915 | 4.28125 | 4 | """
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name,
and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email
that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people
as people could have the same name. A person can have any number of accounts initially, but all of their accounts
definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name,
and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
"""
def merge_accounts(accounts: list) -> list:
merged_accounts, temp = list(), set()
visited = list()
while accounts:
temp = set()
current_account = accounts.pop(0)
if len(accounts) < 1:
merged_accounts.append(sorted(current_account))
break
for i in range(1, len(accounts)):
[temp.add(i) for i in current_account]
if current_account[0] == accounts[i][0]:
if len(set(current_account[1:]).intersection(set(accounts[i][1:]))):
[temp.add(i) for i in accounts[i][1:]]
visited.append(accounts[i])
visited.append(current_account)
if list(temp) not in merged_accounts and len(temp) > 0:
merged_accounts.append(sorted(list(temp)))
return merged_accounts
def main():
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"],
["John", "johnnybravo@mail.com"],
["John", "johnsmith@mail.com", "john_newyork@mail.com"],
["Mary", "mary@mail.com"]]
ans = merge_accounts(accounts)
print(ans)
if __name__ == "__main__":
main()
| true |
dc363f27cc6e52277b539fbaabd2aedae1691933 | gpastor3/Google-ITAutomation-Python | /Course_2/Week_2/iterating_through_files.py | 971 | 4.5 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 11/28/2020
"""
with open("Course_2/Week_2/spider.txt") as file:
for line in file:
print(line.upper())
# when Python reads the file line by line, the line variable will always have
# a new line character at the end. In other words, the newline character is
# not removed when calling read line. When we ask Python to print the line,
# the print function adds another new line character, creating an empty line.
# We can use a string method, strip to remove all surrounding white space,
# including tabs and new lines.
with open("Course_2/Week_2/spider.txt") as file:
for line in file:
print(line.strip().upper())
# Another way we can work with the contents of the file is to read the file
# lines into a list. Then, we can do something with the lists like sort
# contents.
file = open("Course_2/Week_2/spider.txt")
lines = file.readlines()
file.close()
lines.sort()
print(lines)
| true |
77efe1b0c6dce387b29f9719ec8be6c217373b86 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/iterating_over_the_contents_of_a_dictionary.py | 1,835 | 4.6875 | 5 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/20/2020
"""
# You can use for loops to iterate through the contents of a dictionary.
file_counts = {"jpg": 10, "txt": 14, "csc": 2, "py": 23}
for extension in file_counts:
print(extension)
# If you want to access the associated values, you can either use the keys as
# indexes of the dictionary or you can use the items method which returns a
# tuple for each element in the dictionary. The tuple's first element is the
# key. Its second element is the value.
# We can use the .items method to get key, value pairs
for ext, amount in file_counts.items():
print("There are {} files with the .{} extension". format(amount, ext))
# Sometimes you might just be interested in the keys of a dictionary. Other
# times you might just want the values. You can access both with their
# corresponding dictionary methods
# Use the keys() method to just get the keys
print(file_counts.keys())
# Use the values() method to just get the values
print(file_counts.values())
for value in file_counts.values():
print(value)
# Complete the code to iterate through the keys and values of the cool_beasts
# dictionary. Remember that the items method returns a tuple of key, value
# for each element in the dictionary.
cool_beasts = {"octopuses": "tentacles", "dolphins": "fins", "rhinos": "horns"}
for beast, apendage in cool_beasts.items():
print("{} have {}".format(beast, apendage))
# Dictionaries are a great tool for counting elements and analyzing frequency.
def count_letters(text):
result = {}
for letter in text:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
print(count_letters("aaaaa"))
print(count_letters("tenant"))
print(count_letters("a long string with a lot of letters"))
| true |
2d593998eaf8c47e2b476f7d5c50143ef75f409a | gpastor3/Google-ITAutomation-Python | /Course_2/Week_5/charfreq.py | 873 | 4.1875 | 4 | #!/usr/bing/env python3
"""
This script is used for course notes.
Author: Erick Marin
Date: 12/26/2020
"""
# To use a try-except block, we need to be aware of the errors that functions
# that we're calling might raise. This information is usually part of the
# documentation of the functions. Once we know this we can put the operations
# that might raise errors as part of the try block, and the actions to take
# when errors are raised as part of a corresponding except block.
def character_frequency(filename):
"""Count the frequency of a character in a given file."""
# First try to open the file
try:
f = open(filename)
except OSError:
return None
# now process the file
characters = {}
for line in f:
for char in line:
characters[char] = characters.get(char, 0) + 1
f.close()
return characters
| true |
7c1386e726f4867617ac9682657532da2425df07 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/returning_values.py | 1,324 | 4.25 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def area_triangle(base, height):
""" Calculate the area of triange by multipling `base` by `height` """
return base * height / 2
def get_seconds(hours, minutes, seconds):
""" Calculate the `hours` and `minutes` into seconds, then add with
the `seconds` paramater. """
return 3600*hours + 60*minutes + seconds
def convert_seconds(seconds):
""" Convert the duration of time in 'seconds' to the equivalent
number of hours, minutes, and seconds. """
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
remaining_seconds = seconds - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
def greeting(name):
""" Print out a greeting with provided `name` parameter. """
print("Welcome, " + name)
AREA_A = area_triangle(5, 4)
AREA_B = area_triangle(7, 3)
SUM = AREA_A + AREA_B
print("The sum of both areas is: " + str(SUM))
AMOUNT_A = get_seconds(2, 30, 0)
AMOUNT_B = get_seconds(0, 45, 15)
result = AMOUNT_A + AMOUNT_B
print(result)
HOURS, MINUTES, SECONDS = convert_seconds(5000)
print(HOURS, MINUTES, SECONDS)
# Assigning result of a function call, where the function has no return
# will result in 'None'
RESULT = greeting("Christine")
print(RESULT)
| true |
aa96e9acb44032b35e1b53784b117d989af43758 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/iterating_over_lists_and_tuples.py | 2,405 | 4.59375 | 5 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/20/2020
"""
animals = ["Lion", "Zebra", "Dolphin", "Monkey"]
chars = 0
for animal in animals:
chars += len(animal)
print("Total characters: {}, Average length: {}".format(chars, chars/len(animals)))
# The 'enumerate' function returns a tuple for each element in the list. The
# first value in the tuple is the index of the element in the sequence. The
# second value in the tuple is the element in the sequence.
winners = ["Ashley", "Dylan", "Reese"]
for index, person in enumerate(winners):
print("{} - {}".format(index + 1, person))
# Try out the enumerate function for yourself in this quick exercise. Complete
# the skip_elements function to return every other element from the list, this
# time using the enumerate function to check if an element is on an even
# position or an odd position.
def skip_elements(elements):
new_elements = []
for element_index, element in enumerate(elements):
# Becuase you are enumerating the list, no need for index += 1
# to cycle the loop to the next index for evaulation.
if element_index % 2 == 0:
new_elements.append(element)
return new_elements
# Should be ['a', 'c', 'e', 'g']
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
# Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
def full_emails(people):
result = []
for email, name in people:
result.append("{} <{}>".format(name, email))
return result
print(full_emails([("alex@example.com", "Alex Diego"),
("shay@example.com", "Shay Brandt")]))
# Because we use the range function so much with for loops, you might be
# tempted to use it for iterating over indexes of a list and then to access
# the elements through indexing. You could be particularly inclined to do this
# if you're used to other programming languages before. Because in some
# languages, the only way to access an element of a list is by using indexes.
# Real talk, this works but looks ugly. It's more idiomatic in Python to
# terate through the elements of the list directly or using enumerate when you
# need the indexes like we've done so far. There are some specific cases that
# do require us to iterate over the indexes, for example, when we're trying to
# modify the elements of the list we're iterating.
| true |
b0570c87b7a5d7389973b315aca7d79de585a452 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/defining_functions.py | 919 | 4.125 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def greeting(name, department):
""" Print out a greeting with provided `name` and department
parameters. """
print("Welcome, " + name)
print("Your are part of " + department)
# Flesh out the body of the print_seconds function so that it prints the total
# amount of seconds given the hours, minutes, and seconds function parameters.
# Remember that there are 3600 seconds in an hour and 60 seconds in a minute.
def print_seconds(hours, minutes, seconds):
""" Prints the total amount of seconds given the hours, minutes,
and seconds function parameters. Note: There are 3600
seconds in an hour and 60 seconds in a minute. """
print((hours * 3600) + (minutes * 60) + seconds)
greeting("Blake", "IT Department")
print("\n")
greeting("Ellis", "Software Engineering")
print("\n")
print_seconds(1, 2, 3)
| true |
123187441133b573b5058569e0a972964d11221b | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/the_parts_of_a_string.py | 1,668 | 4.34375 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/11/2020
"""
# String indexing
name = "Jaylen"
print(name[1])
# Python starts counting indices from 0 and not 1
print(name[0])
# The last index of a string will always be the one less than the length of
# the string.
print(name[5])
# If we try to access index past the characters availble, we get an index
# error telling us that it's out of range.
# print(name[6])
# IndexError: string index out of range
# Using negative indexes lets us access the positions in the string starting
# from the last.
""" text = "Random string with a lot of characters"
print(text[-1])
print(text[-2]) """
# Want to give it a go yourself? Be my guest! Modify the first_and_last
# function so that it returns True if the first letter of the string is the
# same as the last letter of the string, False if they’re different. Remember
# that you can access characters using message[0] or message[-1]. Be careful
# how you handle the empty string, which should return True since nothing is
# equal to nothing.
def first_and_last(message):
emptystr = ""
if message == emptystr:
return True
elif message[0] == message[-1]:
return True
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# Slice - The portion of a string that can contain more than one character;
# also sometimes called a substring.
color = "Orange"
# In this case, we start with indexed one, the second letter of the string,
# and go up to index three, the fourth letter of the string.
print(color[1:4])
fruit = "Pineapple"
print(fruit[:4])
print(fruit[4:])
| true |
2eb52a42c37125937cbffd68468398956aa7d575 | foofaev/python-project-lvl1 | /brain_games/games/brain_progression.py | 1,454 | 4.25 | 4 | """
Mini-game "arithmetic progression".
Player should find missing element of provided progression.
"""
from random import randint
OBJECTIVE = 'What number is missing in the progression?'
PROGESSION_SIZE = 10
MIN_STEP = 1
MAX_STEP = 10
def generate_question(first_element: int, step: int, index_of_missing: int):
"""Generate string representing arithmetic progression with missing element.
Args:
first_element (int): initial element of the progression
step (int): Step of the progression
index_of_missing (int): Index of missing element
Returns:
str: Description of return value
"""
progression = ''
index = 0
while index < PROGESSION_SIZE:
separator = '' if index == 0 else ' '
next_element = (
'..'
if index_of_missing == index
else first_element + index * step
)
progression += '{0}{1}'.format(separator, next_element)
index += 1
return progression
def generate_round():
"""Generate question and correct answer for game round.
Returns:
tuple of question and answer
"""
first_element = randint(0, 100)
index_of_missing = randint(0, PROGESSION_SIZE - 1)
step = randint(MIN_STEP, MAX_STEP)
missing_element = first_element + step * index_of_missing
question = generate_question(first_element, step, index_of_missing)
return (question, str(missing_element))
| true |
5f1d89b45c61f68d2b23aa01bfb4c83d6e88fd1b | Sungmin-Joo/Python | /Matrix_multiplication_algorithm/Matrix_multiplication_algorithm.py | 1,284 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
if __name__ == '__main__':
print("Func_called - main")
A = np.array([[5,7,-3,4],[2,-5,3,6]])
B = np.array([[3,0,8],[-5,1,-1],[7,4,4],[2,4,3]])
len_row_A = A.shape[0]
len_col_A = A.shape[1]
len_col_B = B.shape[1]
result = np.zeros((len_row_A,len_col_B))
print("---------- use numpy function ----------")
print(np.dot(A,B))
print("----------------------------------------")
'''
Python can easily implement difficult algorithms.
But I wanted to practice implementing algorithms with python.
'''
for row in range(0,len_row_A):
for col in range(0,len_col_B):
for index in range(0,len_col_A):
result[row,col] = result[row,col] + A[row,index]*B[index,col]
print("----------- use my algorithm -----------")
print(result)
print("----------------------------------------")
else:
print('Func_called - imported')
'''
----------result----------
Func_called - main
---------- use numpy function ----------
[[-33 11 33]
[ 64 31 51]]
----------------------------------------
----------- use my algorithm -----------
[[-33. 11. 33.]
[ 64. 31. 51.]]
----------------------------------------
--------------------------
''' | true |
73d9af8a966990d3c06060b56516c7e22e637fda | andyly25/Python-Practice | /data visualization/e01_simplePlot.py | 761 | 4.34375 | 4 | '''
1. import pyplot module and using alias plt to make life easier.
2. create a lit to hold some numerical data.
3. pass into plot() function to try plot nums in meaningful way.
4. after launching, shows you simple graph that you can navigate through.
'''
# 1
import matplotlib.pyplot as plt
# input values will help set what the x-axis values would be
input_values = [1, 2, 3, 4, 5]
# 2
squares = [1, 4, 9, 16, 25]
# 3
# line width controls thickness of line plot() generates.
plt.plot(input_values, squares, linewidth=5)
# set chart title and label axes
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# set size of tick labels
plt.tick_params(axis='both', labelsize=14)
plt.show()
| true |
69681798f10be785c5e6d247222832f32e7fcf91 | andyly25/Python-Practice | /AlgorithmsAndChallenges/a001_isEven.py | 1,008 | 4.34375 | 4 | '''
I've noticed the question of determining if a number is an even number
often, and it seems easy as you can just use modulo 2 and see if 0 or some
other methods with multiplication or division.
But here's the catch, I've seen a problem that states:
You cannot use multiplication, modulo, or division operators in doing so.
So what does that leave? Bitwise operators:
here's a small tutorial on them:
AND: 1 & 1 = 1
OR: 0 | 1 = 1, 1 | 0 = 1, 1 | 1 = 1
XOR: 0^1 = 1 , 1^0 = 1
NOT: !0 = 1
Here's an example with AND
010 : 2
011 : 3
----
010 : 2
now using that 2 & with 010 : 1
010 : 2
001 : 1
----
000 : 0
thus we can say that even numbers &1 gives 0
'''
def is_even(k):
if((k&1)==0):
return True;
return False;
# x = input("Input an int")
num1 = 3
num2 = 50
num3 = 111111111111
print("is num1 even? ", is_even(num1))
print("is num2 even? ", is_even(num2))
print("is num3 even?", is_even(num3)) | true |
1a3689681b252e87b0c323aa73b32166bb3e8469 | oktaran/LPTHW | /exercises.py | 1,367 | 4.21875 | 4 |
"""
Some func problems
~~~~~~~~~~~~~~~~~~
Provide your solutions and run this module.
"""
import math
def add(a, b):
"""Returns sum of two numbers."""
return a + b
def cube(n):
"""Returns cube (n^3) of the given number."""
# return n * n * n
# return n**3
return math.pow(n, 3)
def is_odd(n):
"""Return True if given number is odd, False otherwise."""
return n % 2 == 1
def print_nums(num):
"""Prints all natural numbers less than given `num`."""
for i in range(num):
print(i)
def print_even(num):
"""Prints all even nums less than a given `num`."""
for i in range(num):
if not is_odd(i):
print(i)
def cube_lst(lst):
"""Returns a list of cubes based on input list."""
# lst_1 = []
#
# for i in lst:
# lst_1.append(cube(i))
#
# return lst_1
return [cube(i) for i in lst]
# === Don't modify below ===
def test():
assert add(3, 2) == 5
assert add(8, -1) == 7
assert cube(3) == 27
assert cube(-1) == -1
assert is_odd(3)
assert is_odd(5)
assert is_odd(11)
assert not is_odd(2)
assert cube_lst([1, 2, 5]) == [1, 8, 125]
def main():
try:
test()
except AssertionError:
print("=== Tests FAILED ===")
else:
print("=== Success! ===")
if __name__ == '__main__':
main()
| true |
89cd8a2e36b129a705836170fb6a0a48e4b6bbbb | ParthikB/Data-Structures | /Data Structures/quickSort.py | 1,428 | 4.125 | 4 | class Sort:
def __init__(self, list_):
self.list = list_
def quickSort(self):
pivot = -1
arr = self.list
def quickSortRecurse(arr):
l, r = 0, len(arr) - 2
# print("recursing :::::::::::::::::::::", arr)
# print("original :::::::::::::::::::::", self.list)
if len(arr) < 3:
if arr[0] > arr[-1]:
arr[0], arr[-1] = arr[-1], arr[0]
return arr
while l < r:
# print(arr, l, r)
if arr[l] < arr[pivot]:
l += 1
if arr[r] > arr[pivot]:
r -= 1
if arr[l] > arr[pivot] and arr[r] < arr[pivot]:
arr[l], arr[r] = arr[r], arr[l]
l += 1
r -= 1
if l == r:
# print(arr, arr[pivot], l, r, pivot)
while arr[l] <= arr[pivot]:
l += 1
arr[pivot], arr[l] = arr[l], arr[pivot]
# print(f"swap : {arr[pivot]}, pivot : {arr[l]}")
# print("---------------------------------------------",arr)
left, right = arr[:l], arr[l+1:]
quickSortRecurse(left)
quickSortRecurse(right)
return arr
return quickSortRecurse(self.list) | false |
a7c29d07ecaff79c7890dc20d201dabd2c2c0213 | MksYi/Python3-NPCTU-TQC-Example | /Problem2/PYD02.py | 525 | 4.1875 | 4 | #-*- codeing: utf-8 -*-
import sys
"""
input
55
36
92
15
output
55 is a multiple of 5.
36 is a multiple of 3.
92 is not a multiple of 3 or 5.
15 is a multiple of 3 and 5.
"""
number = int(input())
anwser = 0
if not number % 3:
anwser += 3
if not number % 5:
anwser += 5
if anwser == 3:
print('%d is a multiple of 3.' %(number))
elif anwser == 5:
print('%d is a multiple of 5.' %(number))
elif anwser == 8:
print('%d is a multiple of 3 and 5.' %(number))
else:
print('%d is not a multiple of 3 or 5.' %(number))
| false |
bcb369678e7debc40c1ce49ab3e9d409f5e13d19 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Tuple/03_Unpacking.py | 351 | 4.4375 | 4 | """program to unpack a tuple in several variables"""
a, b, c = (4, 'hello', [1, 2, 3]) # unpacking of in several variables
print(a, b, c)
'''
x = (4, 'hello', [1, 2, 3]) # packing
(a, b, c) = x # unpacking
print(a, b, c)
a, _, c = x # ignoring 2nd item '_' holds 2nd item '_' used as variable name
print(a, c)
''' | false |
3a097f2425a884b0869818f8bf2646854f2ef6af | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Programs/Factorial.py | 556 | 4.25 | 4 | """Find factorial of given number"""
def fact(num):
if num < 0:
return 'factorial of negative number not possible'
elif num == 0:
return 1
else:
factorial= 1
for i in range(1, num+1):
factorial *= i
return factorial
def recurse_fact(num):
if num < 0:
return 'Factorial of negative number not possible'
elif num == 0 or num == 1:
return 1
else:
return num*recurse_fact(num-1)
num= int(input('Enter number:'))
print(fact(num))
print(recurse_fact(num))
| true |
7aa66e034df46248f0a8cc6d12617137533fc4ab | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Strings/03_ReplaceChar.py | 377 | 4.1875 | 4 | """program to get a string from a given string where all occurrences of its first char have been
changed to '$', except the first char itself"""
string = 'restart'
ch = 'r'
i = string.index(ch) # using str.replace() method returns new string with all replacements
print(string[:i+1]+string[i+1:].replace(ch, '$'))
# count given replace that many characters only
| true |
546f755653d647de1c8afec21f7b630aab5ef626 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/13_CountValuesAsList.py | 343 | 4.125 | 4 | """Program to count number of items in a dictionary value that is a list"""
dict1 = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': 1, 'd': 'z', 'e': (1,)}
# if value is list added True i.e. 1 else False i.e. 0
count = sum(isinstance(value, list) for value in dict1.values()) # sum fn & generator expression
print(f'{count} values are list')
| true |
25778e07eadbe6059b64b6d79cc384bc7150525c | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/01_SortByValue.py | 418 | 4.4375 | 4 | """Sort (ascending and descending) a dictionary by value"""
d = {'a': 26, 'b': 25, 'y': 2, 'z': 1}
# to access and map key value pairs dict.item gives list of tuples of key, value pairs
print(f'Ascending order by value {dict(sorted(d.items(),key=lambda x: x[1]))}') # using second element of tuple
print(f'Descending order by value {dict(sorted(d.items(),key=lambda x: x[1], reverse= True))}') # reverse parameter
| true |
dcca3f992e91118ce37e7bb14a2942cef6ea431c | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Sorting Algorithms/InsertionSort.py | 488 | 4.15625 | 4 | """Sort numbers in list using Insertion sort algorithm"""
numbers = [int(i) for i in input('Enter list of numbers:').split()]
print(numbers)
for i in range(1, len(numbers)): # first element already sorted
j = i # insert element at j index in left part of array at it's appropriate position
while j >= 1:
if numbers[j] < numbers[j-1]:
numbers[j], numbers[j-1] = numbers[j-1], numbers[j]
j -= 1
print(numbers)
| true |
33bb259270a1bc8fd006b9f441a6b3267cff63b5 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/List/06_RemoveDuplication.py | 205 | 4.15625 | 4 | """Program to remove duplicates from a list"""
numbers = [10, 15, 15, 20, 50, 55, 65, 20, 30, 50]
print(f'Unique elements: {set(numbers)}') # set accepts only unique elements so typecasting to set
| true |
79cd83079e88f7d62fc64f5398d00bb70cabf4f7 | Bakalavr163/Alexander_Donskoy | /Easy_homework 6.py | 2,992 | 4.46875 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (int или float).
Результат:
- float.
"""
return (a * b) ** 0.5
a = float(input("a = "))
b = float(input("b = "))
c = avg(a, b)
print("Среднее геометрическое = {:.2f}".format(c))
# Исправленная версия программы
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (int или float).
Результат:
- float.
Исключения:
- ValueError: вычисление не возможно.
"""
if a * b >= 0:
return (a * b) ** 0.5
else:
raise ValueError("Невозможно определить среднее геометрическое указанных чисел.")
try:
a = float(input("a = "))
b = float(input("b = "))
c = avg(a, b)
print("Среднее геометрическое = {:.2f}".format(c))
except ValueError as err:
print("Ошибка:", err, ". Проверьте введенные числа.")
except Exception as err:
print("Ошибка:", err)
# ПРИМЕЧАНИЕ: Для решения задач 2-4 необходимо познакомиться с модулями os, sys!
# СМ.: https://pythonworld.ru/moduli/modul-os.html, https://pythonworld.ru/moduli/modul-sys.html
# Задача-2:
# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,
# из которой запущен данный скрипт.
# И второй скрипт, удаляющий эти папки.
import os
print('Ваща текущая директория {}'.format(os.getcwd()))
def makedir(i):
os.mkdir('{}'.format(i))
def removedir(i):
os.rmdir('{}'.format(i))
def chdir(i):
os.chdir(i)
for r in range(9):
makedir('dir_{}'.format(r+1))
print(os.listdir())
for r in range(9):
removedir('dir_{}'.format(r+1))
# Задача-3:
# Напишите скрипт, отображающий папки текущей директории.
import os
# отобразить папки текущей директории
print("Текущая деректория:", os.getcwd())
# Задача-4:
# Напишите скрипт, создающий копию файла, из которого запущен данный скрипт. | false |
74207f09ecbe9354d93ace2c3d0edd34613997fb | thesayraj/DSA-Udacity-Part-II | /Project-Show Me Data Structures/problem_2.py | 863 | 4.21875 | 4 | import os
def find_files(suffix = "", path = "."):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
files = []
if os.path.isfile(path):
if path.endswith(suffix):
return [path]
else:
new_paths = os.listdir(path)
for item in new_paths:
files += find_files(suffix, "{}/{}".format(path, item))
return files
ff = find_files(suffix=".c",path="C:/Users/Sumit/Downloads/testdir")
for f in ff:
print(f)
| true |
258decfc38f5f05740389356d78bcdfaf780bfc8 | lujamaharjan/pythonAssignment2 | /question5.py | 791 | 4.75 | 5 | """
5. Create a tuple with your first name, last name, and age. Create a list,
people, and append your tuple to it. Make more tuples with the
corresponding information from your friends and append them to the
list. Sort the list. When you learn about sort method, you can use the
key parameter to sort by any field in the tuple, first name, last name,
or age.
"""
my_tuple = ('sachin', 'maharjan', '23')
people = list()
people.append(my_tuple)
people.append(('Kathy', 'Williams', '24'))
people.append(('Raman', 'Dangol', '22'))
print(people)
#sorts according to first member of tuple
people.sort()
print(people)
#sorts according to last name
people.sort(key = lambda people: people[1])
print(people)
#sorts according to age
people.sort(key = lambda people: people[2])
print(people)
| true |
6065ac1867f7dafea2872a50162e1b8f4f2a2527 | lujamaharjan/pythonAssignment2 | /question15.py | 700 | 4.3125 | 4 | """
Imagine you are designing a bank application.
what would a customer look like? What attributes
would she have? What methods would she have?
"""
class Customer():
def __init__(self, account_no, name, address, email, balance):
self.account_no = account_no
self.name = name
self.address = address
self.email = email
self.balance = balance
def get_balance(self):
return self.balance
def add_balance(self, amount):
self.balance = self.balance + amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough balance")
else:
self.balance = self.balance - amount
| true |
14569d9e12b63f29b2002c014fe8fdb79d990bcf | babbgoud/maven-project | /guess-numapp/guessnum.py | 765 | 4.15625 | 4 | #! /usr/bin/python3
import random
print('Hello, whats your name ?')
myname = input()
print('Hello, ' + myname + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1,20)
for guesses in range(1,7):
print('Take a guess.?')
guessNumber = int(input())
if int(guessNumber) > secretNumber:
print('sorry, your guess is too high.')
elif int(guessNumber) < secretNumber:
print(' sorry, your guess is too low.')
else:
break # this is condition for the correct guess(number)!
if guessNumber == secretNumber:
print('Good Job, ' + myname + '! you guessed the number correct in ' + str(guesses) + ' guesses!')
else:
print('Nope. The nuber I was thinking of was ' + str(secretNumber))
| true |
0dcc567b62cb6e81893fd99471a32737388d04b2 | ramyanaga/MIT6.00.1x | /Pset2.py | 2,332 | 4.3125 | 4 | """
required math:
monthly interest rate = annual interest rate/12
minimum monthly payment = min monthly payment rate X previous balance
monthly unpaid balance = previous balance - min monthly payment
updated balance each month = monthly unpaid balance + (monthly interest rate X monthly unpaid balance)
NEED TO PRINT:
Month:
Minimum monthly payment:
Remaining balance:
"""
#don't specify variables balance, annualInterestRate, monthlyPaymentRate
#balance = 4213
#annualInterestRate = .2
#monthlyPaymentRate = .04
#total_paid = 0
def question1():
for month in range(1,13):
monthly_interest_rate = annualInterestRate/12
min_monthly_payment = monthlyPaymentRate*balance
monthly_unpaid_balance = balance - min_monthly_payment
balance = monthly_unpaid_balance + (monthly_interest_rate*monthly_unpaid_balance)
total_paid += min_monthly_payment
print "Month:" + str(month)
print "Minimum monthly payment:" + str(round(min_monthly_payment,2))
print "Remaining balance:" + str(round(balance,2))
if month == 12:
print "Total paid:" + str(round(total_paid,2))
print "Remaining balance:" + str(round(balance,2))
#balance = 4773
#annualInterestRate = .2
#updatedBalance = balance
def question2():
lowestPayment = 10
monthlyInterestRate = annualInterestRate/12
while updatedBalance > 0:
for month in range(1,13):
monthlyUnpaidBalance = updatedBalance - lowestPayment
updatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)
if updatedBalance < 0:
print "Lowest Payment:" + str(lowestPayment)
else:
updatedBalance = balance
lowestPayment+=10
def question3():
updatedBalance = balance
monthlyInterestRate = annualInterestRate/12
paymentLb = balance/12
paymentUb = (balance*(1+monthlyInterestRate)**12)/12
mid = (paymentLb + paymentUb)/2
while (updatedBalance > .01) or (updatedBalance < -.01):
for month in range(1,13):
monthlyUnpaidBalance = updatedBalance - mid
updatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)
if updatedBalance > .01:
paymentLb = mid
mid = (paymentUb+paymentLb)/2
updatedBalance = balance
elif updatedBalance < -.01:
paymentUb = mid
mid = (paymentUb+paymentLb)/2
updatedBalance = balance
else:
mid = round(mid,2)
print "lowestPayment:" + str(mid)
| true |
3eb482c7861a7a2ea0e293cacce0d75d2f41de77 | AlexDT/Playgarden | /Project_Euler/Python/001_sum.py | 542 | 4.1875 | 4 | # coding: utf-8
#
# ONLY READ THIS IF YOU HAVE ALREADY SOLVED THIS PROBLEM!
# File created for http://projecteuler.net/
#
# Created by: Alex Dias Teixeira
# Name: 001_sum.py
# Date: 06 Sept 2013
#
# Problem: [1] - Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of
# 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#
total = 0
for i in range(1000):
if (i % 3 == 0) or (i % 5 == 0):
total = total + i
print total
| true |
059b1b036fd32d0df3d23ef4fed084586b92202a | softwarefaith/PythonFullStack | /PythonFullStack/000Basic/Day02-集合遍历/day02/11-拆包.py | 481 | 4.21875 | 4 | #拆包通俗理解:把容器类型(字符串,列表,元组,字典,结合)
#每一个数据使用不同的变量保存一下
#字符串
my_str = "abc"
a,b,c = my_str
print(a,b,c)
#列表
my_list = [1,5]
num1,num2 = my_list
print(num1,num2)
#元组
my_tuple = (1,5)
num1,num2 = my_tuple
print(num1,num2)
#拆字典(默认拆取的是key)
my_dict = {"name":"胡亮","age":"20"}.values()
key1,key2 = my_dict
print(key1,key2)
#集合
my_set = {3,5}
num1,num2 = my_set
print(num1,num2)
| false |
ec97c964601cfb0e8f6b37dbaa0b14b96d0728f0 | softwarefaith/PythonFullStack | /PythonFullStack/000Basic/Day02-集合遍历/day02/03-元组.py | 1,236 | 4.28125 | 4 | #元组:以小括号形式的数据集合,比如(1,2,"abc")
#可以存储任意数据类型
#注意,元组可以根据下标获取数据,但是不能对元组进行数据修改
my_tuple = (1,4,"abc",True,1.2)
print(my_tuple)
#根据下标取值
value = my_tuple[-1]
print(value)
# #元组不能根据下标删除数据
# del my_tuple[2]
# print(my_tuple)
#修改也是不可以
# my_tuple[0] = 3
# # print(my_tuple)
# #直接根据下标修改数据是不可以的,不论元组里面装的是什么数据类型
# my_tuple = (1,[3,5])
# my_tuple[1] = [2,4]
# print(my_tuple)
#my_list list类型
my_list = my_tuple[1]
my_list = [2,4]
print(my_list)
#创建空的元组
my_tuple = ()
print(my_tuple)
#元组只装一个元素
#注意是个坑:元组如果只有一个元素,那么元组的类型是元素的类型
#如果想元组里面只装一个元素,元组要求是元组类型,那么在元素后面加上逗号
my_tuple = (1,)
print(type(my_tuple))
#判断数据是否存在在元组里面
my_tuple = (5,10,10,10)
result = 5 in my_tuple
print(result)
result = 5 not in my_tuple
print(result)
#元组中元素的下标
index = my_tuple.index(5)
print(index)
#元组中元素的个数
result = my_tuple.count(10)
print(result)
| false |
8b342f9279fd4a380434b2f01d874f0fd3171894 | softwarefaith/PythonFullStack | /PythonFullStack/004Exception/000exception.py | 1,357 | 4.1875 | 4 | # 异常处理
""""""
"""
内置了一套try...except...finally...的错误处理机制
"""
try:
print('try...')
r = 10 / int('a')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
"""
1.Python的错误其实也是class,所有的错误类型都继承自BaseException,
所以在使用except时需要注意的是,
它不但捕获该类型的错误,还把其子类也“一网打尽”
2.使用try...except捕获错误还有一个巨大的好处,就是可以跨越多层调用
"""
# 抛出错误
"""
如果要抛出错误,首先根据需要,
可以定义一个错误的class,
选择好继承关系,
然后,用raise语句抛出一个错误的实例:
只有在必要的时候才定义我们自己的错误类型。
如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError),
]尽量使用Python内置的错误类型。
"""
def foo(s):
n = int(s)
if n == 0:
raise ValueError('invalid value: %s' % s)
return 10 / n
def bar():
try:
foo('0')
except ValueError as e1:
print('ValueError!')
raise # 最恰当的方式是继续往上抛,让顶层调用者去处理
bar() | false |
e69c10620674ce54416070ef1b8c2fdc08cdd452 | softwarefaith/PythonFullStack | /PythonFullStack/000Basic/day04/10-切片.py | 701 | 4.40625 | 4 | #切片:根据下标的范围获取一部分数据:字符串,列表可以使用切片
#正数下标的切片
my_str = "hello"
result = my_str[0]
print(result)
#[起始下标,结束下标,步长](下标从0开始)
#切片结束下标不取
result = my_str[0:4:1]
print(result)
#前三个数据(默认步长为0)
result = my_str[0:3]
print(result)
#前两个可以省略
result = my_str[::3]
print(result)
#快速获取整个字符串
result = my_str[:]
print(result)
#使用负数下标切片的方式获取数据
my_str = "hello"
#获取最后三个元素,默认取到最后的数据
result = my_str[-3:]
print(result)
#步长是负数(步长不能为0)
result = my_str[-2:-5]
print(result,"--------") | false |
fbe7386c2a4425dc87bf76982cf9dc23c54f938b | softwarefaith/PythonFullStack | /PythonFullStack/000Basic/day07-类/06-类的定义.py | 654 | 4.21875 | 4 | #类的定义需要使用class关键字 人有特征和行为(动作)
#类有属性(特征)和方法(行为)
#定义一个老师类(继承父类)
#创建类的方式,是旧式类方式创建
#python3默认继承object
#python2中里面就没有父类
class Teacher():
#国籍(属性)
country = "中国"
#方法
def show(self):
print("大家好,我是大家的授课老师")
#通过类来创建对象,类好比是一个图纸,根据图纸创建对象
teacher = Teacher()
#通过对象调用方法
teacher.show()
#通过对象查看方法
print(teacher.country)
#查看Teacher类继承的父类(object)
print(Teacher.__bases__)
| false |
0adc3d68701d28d0094280378b9cb2e068a4ae3b | softwarefaith/PythonFullStack | /PythonFullStack/000Basic/day07-类/10-__str_魔法方法.py | 397 | 4.125 | 4 | #__str_:当使用print打印对象的时候回自动调用
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
#返回一个字符串信息
return "我叫:%s 年龄:%d" %(self.name,self.age)
#创建对象
person = Person("张三",18)
#打印对象的属性值
print(person.name,person.age)
print(person) | false |
caa473a30bcfab1f491e58b5f017ab4eb4eb99e2 | SamNel2000/FreshmenProjects | /Fibonacci and Lucas Sequences.py | 773 | 4.15625 | 4 | name = input("Enter 'A' for Fibonacci Sequence and 'B' for Lucas Sequence: ")
def fib(a, b):
n = int(input("Enter the ordinal value of the term you want: ")) - 1
for x in range(n):
a = a + b
b = a - b
print("The " + str(n + 2) + "th term of the fibonacci sequence is:", a, "\nThe approximation of the golden ratio is:", a/b)
def lucas(a, b, c):
n = int(input("Enter the ordinal value of the term you want: ")) - 1
if n == -1:
c = 2
for x in range(n):
a = b + c
b = c
c = a
print("The " + str(n + 2) + "th term of the lucas sequence is:", c, "\nThe approximation of the golden ratio is:", c/b)
if name == 'A':
fib(1, 1)
if name == 'B':
lucas(0, 2, 1)
| false |
34534abc70987c7c05910c3436868db6b0a97148 | sasathornt/Python-3-Programming-Specialization | /Python Basics/Week 4/assess_week5_01.py | 331 | 4.34375 | 4 | ##Currently there is a string called str1. Write code to create a list called chars which should contain the characters from str1. Each character in str1 should be its own element in the list chars
str1 = "I love python"
# HINT: what's the accumulator? That should go here.
chars = []
for letter in str1:
chars.append(letter) | true |
aff493107f2fe0b300cb3c222480c48161ae51f0 | Neves-Roberto/python-course | /soma_hipotenusas.py | 1,771 | 4.125 | 4 | '''
Exercício 2 - (Difícil) Soma das hipotenusas
Escreva uma função soma_hipotenusas que receba como parâmetro um número
inteiro positivo n e devolva a soma de todos os inteiros entre 1 e n que
são comprimento da hipotenusa de algum triângulo retângulo com catetos
inteiros.
DIca1: um mesmo número pode ser hipotenusa de vários triângulos, mas deve
ser somado apenas uma vez. Uma boa solução para este exercício é fazer um
laço de 1 até n testando se o número é hipotenusa de algum triângulo e
somando em caso afirmativo. Uma solução que dificilmente vai dar certo é
fazer um laço construindo triângulos e somando as hipotenusas inteiras
encontradas.
Dica2: primeiro faça uma função é_hipotenusa que diz se um número inteiro
é o comprimento da hipotenusa de um triângulo com lados de comprimento
inteiro ou não.
Exemplo:
# Para n = 25, as hipotenusas são:
# 5, 10, 13, 15, 17, 20, 25
# note que cada número deve ser somado apenas uma vez. Assim:
soma_hipotenusas(25)
# deve devolver 105
'''
def soma_hipotenusas(n):
soma = 1
hipo = 0
while soma <= n:
if é_hipotenusa(soma):
hipo += soma
soma += 1
return hipo
def é_hipotenusa(n):
from math import sqrt
ca = 1
co = 1
hipo = False
while ca <= n and not hipo:#loop cateto adjacente
while co <= n and not hipo: #loop cateto oposto
hipotenusa = sqrt(ca ** 2 + co ** 2)
if n == hipotenusa:
#print('hipotenusa: {} cateto adjacente {} cateto oposto {}'.format(hipotenusa, ca ,co))
hipo = True
co += 1
co = 1
ca += 1
return hipo
def main():
n = int(input('eh hipotenusa: '))
print(soma_hipotenusas(n))
main() | false |
8c3568887faf1683f43f2b8fce66ab007f98be63 | Neves-Roberto/python-course | /pontos.py | 858 | 4.125 | 4 | '''Exercício 1 - Distância entre dois pontos
Receba 4 números inteiros na entrada. Os dois primeiros devem corresponder,
respectivamente, às coordenadas x e y de um ponto em um plano cartesiano.
Os dois últimos devem corresponder, respectivamente, às coordenadas x e y
de um outro ponto no mesmo plano.
Calcule a distância entre os dois pontos. Se a distância for maior ou
igual a 10, imprima
longe
na saída. Caso o contrário, quando a distância for menor que 10, imprima
perto'''
from math import sqrt
p1x = int(input('Digite o valor de X do ponto P1: '))
p1y = int(input('Digite o valor de Y do ponto P1: '))
p2x = int(input('Digite o valor de X do ponto P2: '))
p2y = int(input('Digite o valor de Y do ponto P2: '))
distancia = sqrt(((p2x-p1x) ** 2) + ((p2y-p1y) ** 2))
if (distancia >= 10):
print('longe ')
else:
print('perto ')
| false |
1d71ab1f3585ef7d344998afffe54b01ab443c59 | KazuoKitahara/challenge | /cha45.py | 275 | 4.125 | 4 |
def f(x):
"""
Returns float of input string.
:param x: int,float or String number
try float but if ValueError, print "Invalid input"
"""
try:
return float(x)
except ValueError:
print("Invalid input")
print(f(10))
print(f("ten"))
| true |
d14fecadef87c5fe1cbb2c7dc1a321e21fa51f60 | ReddivariShalini/fibanocci-mycaption | /extension.py | 243 | 4.15625 | 4 | def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input('Enter a number, N, N>=2 : '))
fibo_series = []
for i in range(0,n):
fibo_series.append(fibonacci(i))
print(fibo_series)
| false |
1aba84f4c9ccb999895378980f14101ba10d3adb | Fang-Molly/CS-note | /python3 for everybody/exercises_solutions/ex_09_05.py | 897 | 4.375 | 4 | '''
Python For Everybody: Exploring Data in Python 3 (by Charles R. Severance)
Exercise 9.5: This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program, print out the contents of your dictionary.
python schoolcount.py Enter a file name: mbox-short.txt {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8}
'''
domain_counts = dict()
fname = input('Enter a file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fhand:
words = line.split()
if len(words) < 3 or words[0] != 'From':
continue
word = words[1]
email = word.split('@')
domain = email[1]
domain_counts[domain] = domain_counts.get(domain,0) + 1
print(domain_counts)
| true |
537ab14e1654a023e4de4c0cd4c3dc37ab2394e1 | paulcockram7/paulcockram7.github.io | /10python/l05/Exercise 2.py | 261 | 4.125 | 4 | # Exercise 2
# creating a simple loop
# firtly enter the upper limit of the loop
stepping_variable = int(input("Enter the amount of times the loop should run "))
#set the start value
i = 0
for i in range(stepping_variable):
print("line to print",str(i))
| true |
92a8edcc1b4419cda07813c301607d0e036de96f | Biytes/learning-basic-python | /loops.py | 749 | 4.15625 | 4 | '''
Description:
Author: Biytes
Date: 2021-04-12 17:55:57
LastEditors: Biytes
LastEditTime: 2021-04-12 18:50:23
FilePath: \python\basic\loops.py
'''
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
people = ['John', 'Paul', 'Sara', 'Susan']
# Simple for loop
# for person in people:
# print(f'Current Person: {person}')
# Break
# for person in people:
# if person == 'Sara':
# break
# print(f'Current Person: {person}')
# range
# for i in range(1, 11):
# print(f'Number: {i}')
# while loops execute a set of statements as long as a condition is true
count = 0
while count < 10:
print(f'Count: {count}')
count += 1
print(f'Count: {count}')
| true |
ca4aabd62635f10edb934d941c09e1865b02f5b2 | applepie787/Cloud_AI_Study | /python_workspace/tuple_test.py | 608 | 4.15625 | 4 | # 튜플 - 리스트와 유사한 자료형
# 한번 결정된 요소는 바뀔 수 없습니다.
tuple_data = (10, 20, 30)
tuple_data2 = 10, 20, 30 # 괄호가 없어도 튜플로 선언됩니다.
print(tuple_data)
print(tuple_data2)
print(type(tuple_data))
print(type(tuple_data2))
# tuple_data[0] = 100 튜플에 새로운 값을 할당 할 수는 없다.
name, age, major = "이루다", 28, "전자전기공학"
print(name,"|", age,"|", major)
# swapping
a, b = 10, 20
print(a, b)
temp = a
a = b
b = temp
print(a, b)
# 튜플을 사용하면 한줄로 스왑 할 수 있다.
a, b = b, a
print(a, b) | false |
1d1795475f2656f95beaaeadcc30daca4d5c5c67 | applepie787/Cloud_AI_Study | /python_workspace/loops.py | 963 | 4.3125 | 4 | array_ = [1, 2, 3, 4, 5]
for data in array_:
print(data, end="") # print로 인한 라인 변경을 막아준다.
print("")
for data in array_:
print(data)
print("_______________________________________________")
for i in range(len(array_)):
print(array_[i])
print("_______________________________________________")
for i in reversed(range(len(array_))):
print(array_[i])
print("_______________________________________________")
list_ = range(1, 11)
i = -1
while(True):
if(i >= len(list_)):
break
i += 1
if( i % 2 == 0):
continue
print(list_[i])
print("_______________________________________________")
for x in range(2,10):
for y in range(1, 10):
print( x, " * ", y, " = ", x*y)
print("_______________")
for y in range(1,10):
for x in range(2, 10):
print("{0} * {1} = {2}".format(x, y, x*y), end="\t")
print("")
print("_______________________________________________")
| false |
e690dad132239e95a67f7d735ea872ba9f2da917 | anik511/My_Python | /Basic/25_list_comprehensions.py | 671 | 4.28125 | 4 | # normal method
# making double of list
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
NewLi = []
for x in li:
NewLi.append(2*x)
print("New List:", NewLi)
# List Comprehension Method
Comprehension = [2 * x for x in li]
print("List Comprehension: ", Comprehension)
# Finding Even Numbers
# normal method
even = []
for x in li:
if x % 2 == 0:
even.append(x)
print('Normal Method Even Numbers:', even)
# List Comprehension Method
evenNmbr = [x for x in li if x % 2 == 0]
print("List Comprehension for Even Numbers: ", evenNmbr)
#Exr : sqr
# List Comprehension Method
sqr = [x * x for x in li]
print("List Comprehension ExR: ", sqr)
| false |
14e5b26ac617c4e2f871fd162b8c07d64132ce9f | koltpython/python-slides | /Lecture7/lecture-examples/lecture7-1.py | 828 | 4.34375 | 4 |
# Free Association Game
clues = ('rain', 'cake', 'glass', 'flower', 'napkin')
# Let's play a game. Give the user these words one by one and ask them to give you the first word that comes to their mind.
# Store these words together in a dictionary, where the keys are the clues and the values are the words that the user tells.
# We want another user to be able to learn the previous user's associations. For this reason, ask the user which word's association
# they want to learn and print the related word.
pairs = dict()
for word in clues:
answer = input(f"What word comes to your mind when you see {word} ")
pairs[word] = answer
print(pairs)
key = input("What do you want to learn? ")
while key != 'exit':
print(pairs[key])
key = input("What do you want to learn? ")
open("texts/my_text.txt", mode='w') | true |
ec9a757fbf7807641a17c4f4eb73feab391f8033 | koltpython/python-slides | /Lecture3/code-examples/branching_example.py | 238 | 4.15625 | 4 | operation = int(input())
num1 = int(input())
num2 = int(input())
if operation == 1:
sum_two_numbers(num1, num2)
elif operation == 2:
multiply_two_numbers(num1, num2)
else:
divide_two_numbers(num1, num2)
print('I am here')
| false |
8013c5a1d5760cd65eca1c8c3c009003dc53b8a3 | JulianTrummer/le-ar-n | /code/01_python_basics/examples/02_lists_tuples_dictionaries/ex4_tuples.py | 333 | 4.34375 | 4 | """Tuple datatypes"""
# A tuple is similar to a list, however the sequence is immutable.
# This means, they can not be changed or added to.
my_tuple_1 = (1, 2, 3)
print(my_tuple_1, type(my_tuple_1))
print(len(my_tuple_1))
my_tuple_2 = tuple(("hello", "goodbye"))
print(my_tuple_2[0])
print(my_tuple_2[-1])
print(my_tuple_2[1:3]) | true |
483d8c2a95519c1e81242ec1420e7b80640595bc | JulianTrummer/le-ar-n | /code/01_python_basics/examples/05_classes/ex1_class_intro.py | 606 | 4.25 | 4 | # Classes introduction
# Class definition
class Vehicle():
# Initiation function (always executed when the class object is being initiated)
def __init__(self, colour, nb_wheels, name):
self.colour = colour
self.nb_wheels = nb_wheels
self.name = name
# Creating objects from class
vehicle_1 = Vehicle("blue", 2, "bike")
vehicle_2 = Vehicle("red", 4, "car")
# Print the results
print("This is a", vehicle_1.colour, vehicle_1.name, "with", vehicle_1.nb_wheels, "wheels.")
print("This is a {} {} with {} wheels.".format(vehicle_2.colour, vehicle_2.name, vehicle_2.nb_wheels)) | true |
44712e0fbd75dd14e249a32416a4d47a55df1280 | JulianTrummer/le-ar-n | /code/01_python_basics/examples/01_datatypes_operators_conditionals/ex4_arithmetic_operators.py | 315 | 4.15625 | 4 | """Arithmetic Operators"""
# using values:
a = 10
b = 5.5
c = 3
# Addition and Subtraction
d = a + c
e = d - b
print(d)
print(e)
# Multiplication and Division
f = c / 10 + b * 5
print(f)
# Exponentation
f_square = f**2
print(f_square)
# Modulus
f_modulus_2 = f_square % 2
print(f_modulus_2)
print(f_square % 3)
| false |
1d7659b09b39394fbc031fe4799a21530d5cf8f1 | jarrettdunne/coding-problems | /daily/problem1.py | 1,077 | 4.21875 | 4 | import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
'''
input:
[1, 2, 3]
output:
3
'''
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
def two_sum(lst, k):
seen = set()
for num in lst:
if k - num in seen:
return True
seen.add(num)
return False
if __name__ == '__main__':
# unittest.main()
test = unittest.TestCase()
lst = [10, 15, 3, 7]
k = 17
test.assertEqual(two_sum(lst, k), True) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.