blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
50ec2d9c34bf0eff9417d031a4166ab4516ffb3f | musttafayildirim/PythonAlistirmalar | /Döngüler/fibonacci.py | 252 | 4.1875 | 4 | print("Fibonacci Hesaplama Programımız\n")
a = 1
b = 1
fibonacci = [a,b]
sayi = int(input("Kaçıncı sayıya kadar fibonacci serisini devam ettirmek istiyorsun? "))
for i in range(sayi-2):
a,b = b,a+b
fibonacci.append(b)
print(fibonacci)
| false |
aee1898ccce54fd53a8557d511fb245e45dbdbbc | ozadabuk/hackerrank-solutions | /MapAndLambdaExpression.py | 448 | 4.28125 | 4 | cube = lambda x: x ** 3 # complete the lambda function
def fibonacci(n):
if n <= 2:
return [x for x in range(0, n)]
f = [0, 1, 1]
for i in range(2, n - 1):
fib = f[-2] + f[-1]
# print("f[-2]:" + str(f[-2]) + " + f[-1]:" + str(f[-1]) + " = " + str(fib))
f.append(fib)
return f
# return a list of fibonacci numbers
if __name__ == '__main__':
n = 2
print(list(map(cube, fibonacci(n)))) | false |
e36e6fb60e9423809ff4dec53670cffe7ff71b26 | beats4myvan/python | /ListExercise/exam_prep/2.shoping_list.py | 933 | 4.1875 | 4 | initial_list = input().split("!")
command = input()
def urgent(item):
if item not in initial_list:
initial_list.insert(0, item)
def unnecessary(item):
if item in initial_list:
initial_list.remove(item)
def correct(olditem, newitem):
if olditem in initial_list:
current_index = initial_list.index(olditem)
initial_list[current_index] = newitem
def rearrange(item):
if item in initial_list:
initial_list.remove(item)
initial_list.append(item)
while command != "Go Shopping!":
command = command.split()
if command[0] == "Urgent":
urgent(command[1])
elif command[0] == "Unnecessary":
unnecessary(command[1])
elif command[0] == "Correct":
correct(command[1], command[2])
elif command[0] == "Rearrange":
rearrange(command[1])
command = input()
print(", ".join(initial_list))
| true |
2a7815a80f3f1373de5765c827b6a585fd1cb8f8 | Ericsb52/Python20-21repl.it | /Math Lab - Triangles.py | 367 | 4.1875 | 4 | # Create a variable named base and set it equal to 10
# Create a variable named height and set it equal to 5.0
# Create an "area" variable and set it equal to the expression "0.5 * base * height".
# This will calculate the area of a triangle. Then print the area to the screen.
# Use the type() and print() functions to print the type of the "area" variable
| true |
758c438d4f54a69f2e03432013253f674afb39af | tberhanu/RevisionS | /revision/10*.py | 800 | 4.125 | 4 | """ 10. Get common keys found in both the dict1 and dict2
Get keys found in dict1 but not in dict2
Get common k, v pairs found in both dict1 and dict2
Get the common characters/strings b/n str1 and str2
"""
dict1 = {10: 2, 30: 4, 50: 6, 31: 31, 21: 21}
dict2 = {11: 11, 21: 21, 31: 31, 51: 51, 10: 200}
intersection = dict1.items() & dict2.items()
print("intersection of dict.items() : {}".format(intersection))
print("intersection of dict.values() : {}".format(dict1.keys() & dict2.keys()))
difference = dict1.items() - dict2.items()
print("difference of items(): {}".format(difference))
print("difference of items(): {}".format(dict2.items() - dict1.items()))
str1 = "hello"
str2 = "warling"
print(set(str1) & set(str2))
str1 = "heee"
str2 = "warengerh"
print(set(str1) & set(str2))
| false |
0cca5d06a87e04a092c90d30d427dc650dbb5c4c | tberhanu/RevisionS | /revision_3/204****_count_primes.py | 662 | 4.21875 | 4 | """
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
"""
# ################## MUCH BETTER CODE BELOW ###########################
def count_primes(n):
"""
Runtime: 812 ms, faster than 40.16% of Python3 online submissions for Count Primes.
"""
primes = [1] * n
primes[0] = 0
primes[1] = 0
i = 2
while i * i <= n:
if primes[i]:
j = 2
while i * j < n:
primes[i * j] = 0
j = j + 1
i = i + 1
return sum(primes)
print(count_primes(10))
| true |
669fd932998ff037f1dcf33476658638360eed32 | tberhanu/RevisionS | /revision_2/32_longest_valid_parenthesis.py | 364 | 4.15625 | 4 | """
Given a string containing just the characters '(' and ')', find the length of the
longest valid (well-formed) parentheses substring.
"""
def longest_valid_parenthesis(string):
pass
print(longest_valid_parenthesis("()(()"))
print(longest_valid_parenthesis("(()))())"))
# print(longest_valid_parenthesis("(()"))
# print(longest_valid_parenthesis(")()())")) | true |
76137589ff9f54f1673baceb98ae686f4d3f282b | tberhanu/RevisionS | /revision/25.py | 564 | 4.28125 | 4 | """ 25. Make a dict using array1 as key and array2 as value
Zipping more than two elements of the tuple
Traverse thru arr1, and continue traversing to arr2 without concatenating them-->CHAIN
"""
from itertools import chain
arr1 = ["fname", "lname", "year"]
arr2 = ["John", "Bora", "Senior"]
dictionary = dict(zip(arr1, arr2))
print(dictionary)
for k, v in zip(arr1, arr2):
print(k,v)
print("****")
for x in chain(arr1, arr2):
print(x)
print("--------------------")
arr3 = [1, 2, 3]
for a, b, c in zip(arr1, arr2, arr3):
print(a, b, c)
| true |
4574f3960cdb0eac0ee4253a0fbdc023aa7e1d71 | tberhanu/RevisionS | /revision_3/217_contains_duplicate.py | 650 | 4.1875 | 4 | """
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
"""
def contains_duplicate(nums):
from collections import Counter
freq = Counter(nums)
return any(True if v > 1 else False for k, v in freq.items())
def contains_duplicate_better(nums):
return len(list(set(nums))) != len(nums)
print(contains_duplicate_better([1, 2, 3, 11])) | true |
9a84fe76b99b4087ea3d518ad47b5bf2872aaf1e | stuart727/edx | /edx600x/L10_Classes/L10_3_Class_of_integers.py | 984 | 4.15625 | 4 | class intSet(object):
'''is a set of integers
mpla mpla
'''
def __init__(self):
"""
Creates an empty list of integers
"""
self.vals = []
def insert(self, e):
"""
Assume e is an integer
"""
self.vals.append(e)
def remove(self, e):
try:
self.vals.remove(e)
except:
print "malakia ekanes, den yparxei to %s"%(e)
pass # Is a catch an error, just swallow it!!!!
def __str__(self):
"""
This method is used to alter the defaut representation of
object `s` (instance of class intSet), when I type
`print s` in IDLE.
Otherwise, `print s = <__main__.intSet object at 0x7f6f33a61350>
"""
self.vals.sort()
return '{'+','.join([str(i) for i in self.vals])+'}'
s = intSet()
s.insert(3)
s.insert(4)
print s
s.remove(5)
print s | true |
17356b94dccfbd1e092cd9812ba251ad49a9416e | DhvaniAjmera/Python-Programs | /Calculator.py | 1,358 | 4.125 | 4 | print(" ******************* WELCOME TO MY CALCULATOR ******************** \n\n")
num1 = int(input("Enter the first number : "))
num2 = int(input("Enter the second number: "))
task = int(
input("Select the operation you want to perform from- 1.Addition 2.Subtraction 3.Multiplication 4. Division "
"5. All of the above 6. Exit: "))
if task > 6:
print("Invalid Operation!")
# print("Task is : ",task)
if task == 1:
ans = num1 + num2
print("The addition of {} and {} is: ".format(num1, num2, ans))
elif task == 2:
ans = num1 - num2
print("The subtraction of {} and {} is: ".format(num1, num2), ans)
elif task == 3:
ans = num1 * num2
print("The multiplication of {} and {} is: ".format(num1, num2), ans)
elif task == 4:
ans = num1 / num2
print("The division of {} and {} is: ".format(num1, num2), round(ans, 2))
elif task == 5:
ans = num1 + num2
print("The addition of {} and {} is: ".format(num1, num2), ans)
ans = num1 - num2
print("The subtraction of {} and {} is: ".format(num1, num2), ans)
ans = num1 * num2
print("The multiplication of {} and {} is: ".format(num1, num2), ans)
ans = num1 / num2
print("The division of {} and {} is: ".format(num1, num2), round(ans,2))
elif task == 6:
print("Thank You!")
exit()
| true |
7c9bbef730d063c41711019ad61fb17ceabaa956 | sharazul/arthematic_exam_application | /arithmetic.py | 2,392 | 4.28125 | 4 | # write your code here
import random
import math
def simple_operations(number1, number2, sign):
if sign == '+':
return number1 + number2
elif sign == '-':
return number1 - number2
elif sign == '*':
return number1 * number2
def calculate_square(number):
return number * number
def result_compare(calculated_result):
s_marks = 0
while True:
try:
user_result = int(input())
if user_result == calculated_result:
s_marks += 1
print('Right!')
return s_marks
else:
print('Wrong!')
return 0
except ValueError:
print("Incorrect format.")
# program starts here
student_marks = []
while True:
print("Which level do you want? Enter a number:")
print("1 - simple operations with numbers 2-9")
print("2 - integral squares of 11-29")
try:
selected_operation = int(input())
break
except ValueError:
print("Incorrect format.")
if selected_operation == 1:
for i in range(1, 6):
number_1 = random.randint(2, 9)
number_2 = random.randint(2, 9)
operations = ['+', '-', '*']
selected_sign = random.choice(operations)
print(f'{number_1} {selected_sign} {number_2}')
result = simple_operations(number_1, number_2, selected_sign)
mark_obtained = result_compare(result)
student_marks.append(mark_obtained)
if selected_operation == 2:
for i in range(1, 6):
number_3 = random.randint(11, 29)
print(number_3)
sqrt_result = calculate_square(number_3)
mark_obtained = result_compare(sqrt_result)
student_marks.append(mark_obtained)
total_marks = sum(student_marks)
if selected_operation == 1:
description = "simple operations with numbers 2-9"
else:
description = "integral squares of 11-29"
print(f"Your mark is {total_marks}/5. Would you like to save the result? Enter yes or no.")
response = input()
response = response.upper()
if response == 'YES' or response == 'Y':
print("What is your name?")
name = input()
with open('results.txt', 'a') as file:
file.write(name + f': {total_marks}/5 in level {selected_operation}({description}).')
file.write('\n')
print(f'The results are saved in results.txt".')
else:
exit()
| true |
ac5c467e92462d003047cd305734a6e5967f3589 | kds3000/project_euler | /Even Fibonacci numbers.py | 679 | 4.15625 | 4 | """
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2,
the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
"""
def is_even(number):
return True if number % 2 == 0 else False
def fibonacci_even(max_value):
first = 1
second = 2
summ = 0
while second <= max_value:
if is_even(second):
summ += second
first, second = second, first + second
return summ
if __name__ == "__main__":
print(fibonacci_even(4000000))
| true |
5a76e14a7656daaf723c65bde3004d7315e19e2d | eda-ricercatore/Calabria-Digital-Bio | /reads-dna-seq/script3.py | 901 | 4.21875 | 4 | #!/usr/bin/python
"""
$UWHPSC/codes/python/script3.py
Modification of script2.py that allows a command line argument telling how
many points to plot in the table.
Usage example: To print table with 5 values:
python script3 5
"""
import numpy as np
def f(x):
"""
A quadratic function.
"""
y = x**2 + 1.
return y
def print_table(n=3):
print " x f(x)"
for x in np.linspace(0,4,n):
print "%8.3f %8.3f" % (x, f(x))
if __name__ == "__main__":
"""
What to do if the script is executed at command line.
Note that sys.argv is a list of the tokens typed at the command line.
"""
import sys
print "sys.argv is ",sys.argv
if len(sys.argv) > 1:
try:
n = int(sys.argv[1])
print_table(n)
except:
print "*** Error: expect an integer n as the argument"
else:
print_table()
| true |
fb32b038a154674dcae642a1b948bc7d1eff12ad | arun1167/my-project | /ex16.py | 701 | 4.21875 | 4 | from sys import argv
scripts,filename = argv
print "We'r going to erase %r ." %filename
print "If you don't want that , hit CTRL -C ."
print "If you do want that , hit RETURN. "
raw_input("?")
print "Opening the file ...."
target = open(filename,'r')
print "Truncating the file. Goodbye !"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
#target.write("\n")
target.write(line2)
#target.write("\n")
target.write(line3)
#target.write("\n")
print "And Finally , we close it"
target.close()
| true |
a6566f9d0678119ca2b9e876c2006dbc2826c282 | rakshya2001/pythonProject8 | /exercise4.py | 630 | 4.125 | 4 | command=""
started= False
while True:
command= input("> ").lower()
if command == "start":
if started:
print("CAr is already started")
else:
started= True
print(f'The car has started...')
elif command== "stop":
if not started:
print("Car is already stopped!")
else:
started= False
print(f'the car has stopped...')
elif command =="help":
print("""
start- to start the car
stop- to stop the car
quit- to exit
""")
elif command=="quit":
break
else:
print("I dont't understand this") | true |
a372faa98eaed4cbf541a98f5ea65ca82d785323 | rakshya2001/pythonProject8 | /smallestone.py | 361 | 4.375 | 4 | #give three integers, print the smallest one(three integers should be user input)
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
num3=int(input("Enter the third number:"))
if num1<num2:
print(f"{num1} is smallest one!")
elif num2<num3:
print(f"{num2} is smallest one")
else:
print(f"{num3} is the smallest")
| true |
13ae9b06edc08abbfd6095e7503b9ed1916b4055 | kielejocain/AM_2015_06_15 | /StudentWork/emcain-student/week03/string_to_ascii.py | 642 | 4.28125 | 4 | __author__ = 'Emily'
the_chr= raw_input("please enter a single character >> ")
print "this is your character rendered as a number: ", ord(the_chr)
print " \o/ <yay! "
the_number = raw_input("please enter a number between 0 and 225 (inclusive) >> ")
print "this is your number rendered as a character: ", chr(int(the_number))
print "cool, now let's do it for a string"
the_str = raw_input("please enter any amount of text >> ")
print "here are the numbers used to represent the characters in your string."
i = 0
for c in the_str:
print "Character", i, ",", c, "is represented by the number", ord(c)
i += 1
print "thanks for playing!"
| true |
c1712546f295e4e4c32dcda33cf0d380efa7d912 | kielejocain/AM_2015_06_15 | /StudentWork/ejames9/ohmslaw.py | 2,362 | 4.28125 | 4 | """Application solves for V, R or I in Ohm's Law equation."""
def solve_for_i():
volt = "s"
while not volt.isdigit():
volt = raw_input("What is the voltage, in volts, of the circuit? \n>")
if volt.isdigit():
volt = int(volt)
resist = raw_input("Great. What is the current, in amperes, of the circuit? \n>")
if resist.isdigit():
resist = int(resist)
current = volt / resist
print "In accorance with Ohm's Law, the current on this circuit must be: %d amperes." % current
break
else:
print "Really? Let's start over."
volt = "s"
else:
print "Really?"
def solve_for_r():
volt = "s"
while not volt.isdigit():
volt = raw_input("What is the voltage, in volts, of the circuit? \n>")
if volt.isdigit():
volt = int(volt)
current = raw_input("Great. What is the current, in amperes, of the circuit? \n>")
if current.isdigit():
current = int(current)
resist = volt / current
print "In accorance with Ohm's Law, the resistance on this circuit must be: %d ohms." % resist
break
else:
print "Really? Let's start over."
volt = "s"
else:
print "Really?"
def solve_for_v():
current = "s"
while not current.isdigit():
current = raw_input("What is the current, in amperes, of the circuit? \n>")
if current.isdigit():
current = float(current)
resist = raw_input("Great. What is the resistance, in ohms, of the circuit? \n>")
if resist.isfloat():
resist = float(resist)
volt = current * resist
print "In accorance with Ohm's Law, the voltage on this circuit must be: %d volts." % volt
break
else:
print "Really? Let's start over."
current = "s"
else:
print "Really?"
def begin():
print "Welcome to the Ohm's Law Calculator!"
choice = raw_input("Would you like to Solve for V (Voltage), I (Current) or R (Resistance)?")
if choice == "V" or choice == "v":
solve_for_v()
elif choice == "I" or choice == "i":
solve_for_i()
elif choice == "R" or choice == "r":
solve_for_r()
else:
choice2 = "0"
while choice2 != "Y" or choice2 != "y" or choice2 != "N" or choice2 != "n":
choice2 = raw_input("That was not a valid choice. Would you like to try again? Y/N?")
if choice2 == "Y" or choice2 == "y":
begin()
elif choice2 == "N" or choice2 == "n":
print "Goodbye."
else:
print "Really?"
begin() | true |
3fb249be684fb8871b7dce57e52820845df2ad53 | kielejocain/AM_2015_06_15 | /StudentWork/palmerev/python/timer_challenge.py | 2,433 | 4.25 | 4 | # TODO:
# 1. Add increment and decrement methods for minutes and hours.
# 2. If Seconds is at 59 and you increment:
# A. set seconds to zero
# B. increment minute
# 3. Likewise if minutes is 59 set to zero and increment minutes
# 4. Do similar work for hours.
class Timer(object):
MINUTES_IN_HOUR = 60
SECONDS_IN_MINUTE = 60
def __init__(self):
self.hours = 0
self.minutes = 0
self.seconds = 0
def change_time(self, num_seconds=None):
if num_seconds is None:
num_seconds = 0
total_seconds = num_seconds + self.time_to_int()
if total_seconds < 0:
raise ValueError("attempted to create negative time")
self.int_to_time(total_seconds)
def int_to_time(self, num_seconds):
self.hours = num_seconds / (Timer.SECONDS_IN_MINUTE * Timer.MINUTES_IN_HOUR)
num_seconds -= self.hours * (Timer.SECONDS_IN_MINUTE * Timer.MINUTES_IN_HOUR)
self.minutes = num_seconds / Timer.SECONDS_IN_MINUTE
num_seconds -= self.minutes * Timer.SECONDS_IN_MINUTE
self.seconds = num_seconds
def time_to_int(self):
total_seconds = 0
total_seconds += self.seconds
total_seconds += self.minutes * Timer.SECONDS_IN_MINUTE
total_seconds += self.hours * Timer.SECONDS_IN_MINUTE * Timer.MINUTES_IN_HOUR
return total_seconds
def test_timer():
t = Timer()
t.minutes = 59
t.seconds = 59
t.increment_seconds()
print(t, t.hours, t.minutes, t.seconds)
t.decrement_seconds()
print(t, t.hours, t.minutes, t.seconds)
t.hours = 0
t.minutes = 59
t.seconds = 0
print(t, t.hours, t.minutes, t.seconds)
t.increment_minutes()
print(t, t.hours, t.minutes, t.seconds)
t.seconds = 59
print(t, t.hours, t.minutes, t.seconds)
t.increment_seconds()
print(t, t.hours, t.minutes, t.seconds)
def test_change_time():
t = Timer()
print(t, t.hours, t.minutes, t.seconds)
t.change_time(5)
print(t, t.hours, t.minutes, t.seconds)
t.change_time(55)
print(t, t.hours, t.minutes, t.seconds)
t.change_time(3600)
print(t, t.hours, t.minutes, t.seconds)
t.change_time(-75)
print(t, t.hours, t.minutes, t.seconds)
t.seconds = 59
print(t, t.hours, t.minutes, t.seconds)
t.change_time(1)
print(t, t.hours, t.minutes, t.seconds)
#test_timer()
test_change_time() | true |
51e579679f113458b358e6c3d4bda166d43e6e3a | kielejocain/AM_2015_06_15 | /StudentWork/bestevez32/Kyle Class/PdxReverse.py | 819 | 4.34375 | 4 | # this script should take in a sentence or statement from the user,
# then repeat that statement back with the words in reverse order.
# Do not reverse the words themselves!
statement = raw_input("Please enter a statement to reverse.\n>> ")
#value =list[start:end]
#print value[end:start]
min = 0
max = 0
words = []
for i in range(len(statement)):
if statement[i] == ' ':
max = i
words.append(statement[min:max])
min = max + 1
words.append(statement[min:])
sdrow =words[::-1]
output =''
for word in sdrow[:-1]:
output += word
output += ' '
output += sdrow[-1]
print output
#print statement
# The statement below will reverse the statement one letter at a time
#print statement, "in reverse is", statement[::-1]
#for c in statement:
#do something
# Statement is A and B, to print B and A | true |
0aebb0a528604a3376a4a88ffc988ac7dff4fce1 | kielejocain/AM_2015_06_15 | /StudentWork/palmerev/python/reverse.py | 1,550 | 4.28125 | 4 | # Using not built in function,
# and just square bracket list notation,
# reverse the set of characters
characters = "ABCDEF"
character_goal = "FEDCBA"
def reverse_characters(c):
return c[::-1]
print(reverse_characters(characters))
# now do the same with words
# and use built in function
# like split join and reverse
words = "now is the time"
word_goal = "time the is now"
def reverse_words(words):
rev_list = []
word_list = words.split()
for word in reversed(word_list):
rev_list.append(word)
return " ".join(rev_list)
print(reverse_words(words))
# Finally EXTRA CREDIT do the same with words
# and DO NOT use built in function
# like split join and reverse
def split(s, delimiter=" "):
#TODO: fix skips last word
str_list = []
word = ""
for i, char in enumerate(s):
if char != delimiter:
word += char
else:
str_list.append(word)
word = ""
last_delimiter_index = i
str_list.append(s[last_delimiter_index+1:]) #get last word
return str_list
def join(seq, delimiter=" "):
outstring = ""
for item in seq:
outstring += str(item) + delimiter
outstring = outstring[:-len(delimiter)]
return outstring
def reverse_list(lst):
outlist = []
for i in range(len(lst)-1,-1,-1):
outlist.append(lst[i])
return outlist
def reverse_words_hard(words):
lst = split(words, " ")
rev_list = reverse_list(lst)
output = join(rev_list)
return output
print(reverse_words_hard(words))
| true |
d86c2a13563499e2606ccd980c1967d108964316 | kielejocain/AM_2015_06_15 | /Week_1/05_slicing.py | 649 | 4.375 | 4 | # Using the given string, here are a few string slicing exercises to attempt.
# string[start:end] or string[start:end:step]
s = "Hello world"
# Exercise 1: I want to live in a Jello world. Do it with slicing.
<<<<<<< HEAD
t = "J" + s[1:]
=======
t = s[:]
>>>>>>> 86ba04e2d2b54fee2d7888a1fbd0d9febd033a32
print t
# Exercise 2: Use stepping to get the string 'lowrd'.
<<<<<<< HEAD
u = s[2::2]
=======
u = s[::]
>>>>>>> 86ba04e2d2b54fee2d7888a1fbd0d9febd033a32
print u
# Exercise 3: Use a negative step to print 'row'. Hint: try s[::-1]
<<<<<<< HEAD
v = s[-3:-6:-1]
=======
v = s[::]
>>>>>>> 86ba04e2d2b54fee2d7888a1fbd0d9febd033a32
print v
| true |
428c17bee42587b721b4743f980523e127abff9e | kielejocain/AM_2015_06_15 | /StudentWork/bestevez32/Week_3/address_book_answer.py | 1,472 | 4.21875 | 4 | # 1. Create a Person class
# Include properties/attributes for
# a phone number, email address,
# and separate first and last name fields
# 2. Create an address book class
# Initialize it with an empty list of people
# Add methods to create, read, update, and delete.
# Each person added should be assigned a unique id.
# THe ID should be a simple number that gets incremented.
# e.g. 1, 2 , 3 etc
# Using the classes the following test code should work
# def test_book():
# book = AddressBook()
# person = Person()
# person.first_name = "Kevin"
# person.last_name = "Long"
# book.add(person)
# print(book.get_all())
# test_book()
class AddressBook():
def __init__(self):
self.people = {}
self.last_id = 1
def add(self, person):
# function is called by last name
person.id = self.last_id
# list [] gets created because it is mutable
# self.people[person.id] creates a hierarchy all person
# is people but not vice versa
self.people[person.id] = person
# This adds + 1 to the last record created
self.last_id +=1
def get_all(self):
return self.people
class Person(object):
def __init__(self):
self.first_name = ""
self.last_name = ""
def __repr__(self):
return "{id:" + str(self.id) + ", name: '" + self.first_name + " " + self.last_name + "'}"
test_book()
| true |
f5eb9c05f9cd757f3750a9775791a6ce77948c53 | kielejocain/AM_2015_06_15 | /StudentWork/emcain-student/week01/keywords_test.py | 1,476 | 4.1875 | 4 | # keywords test
import random;
print("Welcome to the Python Keywords quiz.")
print("This is based on the list of keywords at http://learnpythonthehardway.org/book/ex37.html.")
print("For the given definition, please enter the corresponding word.")
# access the file "keywords.txt"
the_file = open("keywords.txt")
# create a dictionary with keys as the first word per line of keywords.text and values as the rest of the string
words = {}
# loop over the lines of the file
for line in the_file:
entry = line.split("\t", 1) #tab, not space
words[entry[0]] = entry[1]
# split the first word from the rest of the line
# create an entry to the dictionary with the first word as the key and everything else as the value.
# play the game -- present a random value and prompt for the key. do different things depending on the answer--delete and congratulate if correct, say "wrong" and go to different question if wrong. Do this until all items in dictionary have been deleted.
right = 0
wrong = 0
looping = True
while words and looping:
current = random.choice(words.keys())
guess = raw_input(words[current] + ">> ")
if guess == current:
print "Good job, that is correct!"
del words[current]
right += 1
else:
print "Sorry, that is wrong. The correct answer is", current
wrong += 1
print "You have answered", right, "questions right and", wrong, "questions wrong."
print "Good job! You finished the quiz with only", wrong, "wrong answers." | true |
c41e425e8f3cb961bd0dd80bb03ecadd20eb10b9 | kielejocain/AM_2015_06_15 | /StudentWork/bestevez32/Notes/01_review.py | 1,210 | 4.28125 | 4 | ## Review of Week 1 concepts
# make a list of three movie titles.
movies = ['Terminator', 'The Avengers', 'The Princess Bride']
# using a loop and slicing (movies[start:end]), print the first five
# characters and last five characters of each movie title.
movies[0:6]
movies[-6:-1]
print movies
# you could also use a while loop if you like.
for movie in movies:
print movie[:5]
print movie[-5:]
#for thing in list:
#pass
# make a dictionary where the keys are fruits and the values are quantities.
# use at least three fruits.
fruits = {'oranges': 5, 'peaches': 10, 'mangos' : 1
}
# define a function that takes two arguments and uses them to update
# the quantity of a fruit. Please rename the variables to something
# relevant to their meaning.
def count_update(total, fruit):
if fruit in fruits:
fruits[fruit] += total
else:
fruits[fruit] = total
# Call the function to add 10 to the inventory of your favorite fruit,
# add 5 to the inventory of your second favorite fruit, and subtract
# 10 from the inventory of your least favorite fruit.
count_update(10, 'mangos')
count_update(5, 'oranges')
count_update(-10, 'peaches')
# check to see that it worked!
print fruits
| true |
83fed062a95feb1c2854b5753a412a1026f9e8d3 | kielejocain/AM_2015_06_15 | /StudentWork/bestevez32/Kyle Class/try_except.py | 1,346 | 4.375 | 4 | ## ValueError
print "Raise a ValueError by entering something other than an integer."
error = False
while not error:
try:
print 7 + int(raw_input("What number should I add to 7? > "))
except ValueError:
print "That's no integer..."
error = True
# IndexError, KeyError
fruits = ["apples", "bananas", "oranges"]
print "Raise an IndexError by entering an integer other than 0, 1, or 2."
error = False
while not error:
try:
print fruits[int(raw_input("Which of my fruits would you like? (0/1/2)> "))]
except IndexError:
print "I don't have a fruit by that number."
error = True
except ValueError:
print "We've already played with ValueErrors!"
# ZeroDivisionError
print "Raise a ZeroDivisionError by entering 0."
error = False
while not error:
try:
print "You have 20 cookies. How many friends do you have?"
print "Each friend gets %d cookies." % (20.0 / int(raw_input("> ")))
except ZeroDivisionError:
print "No one has 0 friends."
error = True
except ValueError:
print "Stop with the ValueErrors already!"
# TypeError
print "Finally, I'll raise a TypeError by adding a string and an integer."
print "I won't make a custom error handling, so the script will fail and end."
raw_input("Ready? ")
print "cheese" + 2
| true |
576d77c56f769ab2fd546290bb53a1dfc268811f | kielejocain/AM_2015_06_15 | /StudentWork/orionbuyukas/week_3/address_book.py | 2,166 | 4.21875 | 4 | # 1. Create a Person class
# Include properties/attributes for
# a phone number, email address,
# and separate first and last name fields
# 2. Create an address book class
# Initialize it with an empty list of people
# Add methods to create, read, update, and delete.
# Each person added should be assigned a unique id.
# THe ID should be a simple number that gets incremented.
# e.g. 1, 2 , 3 etc
class Person(object):
def __init__(self, first_name, last_name, phone_number, ID):
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
self.email_address = email_address
self.ID = ID
#or
def __init__(self):
self.first_name = "" #then assign using the .method. ie person.first_name = "orion"
self.last_name = ""
self.phone_number = ""
self.email_address = ""
self.id = ""
class AddressBook(object):
def __init__(self):
self.people = {}
self.last_id = 1
def read_contacts(self, id):
if person.id in self.people:
return self.people[id]
return person # create new person
def create_contact(self, person):
person.id = last_id
self.people[person.id] = person #person gives all fields for person get was probably used to find
self.last_id += 1
return person.id
def update_contact(self):
def delete_contact(self, person):
if person.id in self.people:
del self.people[person.id]
""" def __init__(self, people, person):
people = []
def read_contact(self):
contact_search = raw_input("Who are you looking for? ")
if contact_search in people:
print Person(contact_search)
elif:
make_new_contact = raw_input("That contact doesn't exist. Would you like to make a new contact? y/n").lower
if make_new_contact == 'y':
return create_contact()
elif make_new_contact == 'n':
return read_contact()"""
| true |
72f848faff2a538b593e2b703f352cf9c23ed1bd | Anbranin/projects | /hard_python/ex3.py | 1,856 | 4.375 | 4 | # The order of operations is PEDMAS
# Parentheses Exponents Multiplication Division Addition Subtraction
# This line prints an explanation of what the calculations about
# hens and roosters are for
print "I will now count my chickens"
# this line calculates the number of hens. The order of operations prefers the
# / (division) first, so it's 30/6 (5) plus 25, which is 30.
print "Hens:", 25.0 + 30.0 / 6.0
# this line calculates to 97. How?
# Multiplication is first. 25 * 3 = 75
# Then comes modulo. Modulo gives the remainder of dividing the first number
# by the second, but if the second is larger than the first it just returns
# the first number. The remainder of dividing 75 by 4 is 3.
# 100 minus 3 is 97. So the expression with the order of operations laid bare is
# 100 - ((25 * 3) % 4)
print 'Roosters', 100.0 - 25.0 * 3.0 % 4.0
# This line explains what the following calculation is.
print 'Now I will count my eggs:'
# the calculation returns 7.
# 3 + 2 + 1 - 5 + ( 4 % 2 ) - ( 1 / 4 ) + 6
# 1 + 0 + .25 + 6 = 7
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
# this is a question that prints out
print 'is it true that 3.0 + 2.0 < 5.0 - 7?'
# this is its answer, but we cannot see why in the console
print 3.0 + 2.0 < 5.0 - 7.0
# until we print out the questions and answers
print 'what is 3.0 + 2.0?', 3.0 + 2.0
# asking what the result of each calculation is
print 'what is 5.0 - 7.0?', 5.0 - 7.0
# and saying to ourselves oh, that's why
print "Oh, that's why it's false."
# how about some more, just so we can get in some more operations
print "How about some more."
# is five greater than negative two?
print "is it greater?", 5.0 > -2.0
# is five greater than or equal to negative two?
print "is it greater or equal?", 5.0 >= -2.0
# is five less than or equal to negative two?
print "is it less or equal?", 5.0 <= -2.0
| true |
0157cec435a3f6515bf0852196c627684203d8b9 | Fredmty/estudos-pythonicos | /modo_abertura_arquivo.py | 935 | 4.3125 | 4 | """
modos de abertura de arquivo
r -> abre para leitura - padrao
w -> abre para escrita - sobrescreve caso o arquivo ja exista
x-> abre para escrita - somente se o arquivo n existir
a -> abre para escrita - adicionando no final do arquivo
+ -> abre para o modo de atualização (leitura e escrita)
#abrindo com o modo 'a', sginifica append, se não houver o arquivo
será criado. Senão vai ser escrito no final.
"""
#exemplo x
with open('university.txt', 'x'): as arquivo:
arquivo.write('texte de conteudo')
#exemplo a
with open ('frutas.txt', 'a') as arquivo:
while True:
fruta = input('escreve fruta aqui campeão')
if fruta != 'sair':
arquivo.write(fruta)
else:
break
#exemplo escrita no topo c r+. onde temos o controle do cursor
with open('outro.txt', 'r+') as arquivo:
arquivo.write('add')
arquivo.seek(11)
arquivo.write('nova linha')
arquivo.seek(12) | false |
bad6ce311240e73354678e79e3a18d979f2253fe | Fredmty/estudos-pythonicos | /leitura_de_arquivos.py | 1,047 | 4.25 | 4 | """
leitura de arquivos
para arquivos em pthon, utilizamos a funcao open()
open()-> passamos um parametro de entrada (não é seu unico parametro, apenas o OBRIGATÓRIO), que é o caminho do arquivo
a ser lido. essa funcao tem como retorno isso:
__io.TextIOWrapper e é com ele que trabalhamos o arquivo.
por padrão, a funcção open() abre o arquivo para leitura.
este arquivo DEVE existir senão gera "FileNotFoundError"
mode='r' é modo de leitura. r-> read() siginfica que só está lendo o arquivo
modo default do open é LEITURA.
o python utuliza um recurso para trabalhar com arquivos cahamado 'cursor', aquela coisa
que pisca enquanto digita
"""
arquivo = open('texto.txt')
ret = arquivo.read()
reta = ret.split('\n') #arruma o texto para quando há quebra de linha n aparecer o \n
#transforma em uma lista de string.
print(arquivo)
print(type(arquivo))
#para ler o conteudo de um arquivo, depois do open, devemos utilizar read()
print(arquivo.read()) #é possível limitar o numero de caracteres por padrão que serao lindo | false |
a3423c4893ecf41e7f154d35c98d3f674f96fb10 | ankitsingh03/code-python | /tutorial/exercise_1.py | 281 | 4.125 | 4 | # one, two, three = input("enter two no.").split(",")
# total = float(one)+float(two)+float(three)
# avg = total/3
# print(f"average of number is {avg}")
one, two, three = input("enter three no.").split(",")
print(f"average of number are : {(int(one)+ int(two)+ int(three))/3 }")
| false |
373522208ab69d6ebae467c25fde6c6fb798c62d | DillonSteyl/SCIE1000 | /Week 11/linearpractice_solution.py | 1,700 | 4.1875 | 4 | from pylab import *
# Since we are randomly generating the questions, we need to use the random library
import random
# this function will randomly generate an m value between -10 and 10
def generate_m():
return(round(random.random()*20-10))
# this function will randomly generate a c value that is between m/2 and 3m/2
def generate_c(m):
return(round(random.random()*m+m/2))
# this function will generate a data set using the m and c values provided
def generate_data(m, c):
# the x values will be randomly chosen from 0 to 25
x = array([random.randrange(25) for i in range(25)])
# the y values will be calculated using y = mx+c + a random number scaled using m
y = array([((m*i+c+(random.random()-0.5)*5*m)) for i in x])
return x, y
# the m and c values are randomly generated
m = generate_m()
c = generate_c(m)
# the x and y arrays are randomly generated using m and c
x, y = generate_data(m , c)
# the data is plotted using black circles
plot(x, y, 'ko')
grid(True)
xlabel("x")
ylabel("y")
title("Linear Model")
show()
# the user guesses the m and c values
m_guess = float(input("Enter your m value: "))
c_guess = float(input("Enter your c value: "))
# let the user know if their guesses are close enough
if m-3<=m_guess<= m+3:
if c-3<=c_guess<= c+3:
print("Both values are close enough!")
else:
print("The m value is close enough, but the c value is not.")
else:
if c-3<=c_guess<= c+3:
print("The c value is close enough, but the m value is not.")
else:
print("Both values are not close enough.")
# tell the user the actual values
print("The actual m value is", m, "and the actual c value is", c)
| true |
65714f93b458dec5635dd97ed0935f71b1b20abe | DillonSteyl/SCIE1000 | /Week 2/brackets_2_solution.py | 316 | 4.34375 | 4 | from pylab import *
#This is a program to calculate the hypotenuse of a triangle
a = float(input("Enter the first side length of the triangle: "))
b = float(input("Enter the second side length of the triangle: "))
h_squared = a**2 + b**2
h = h_squared**(1/2)
print("The third side length of the triangle is", h)
| true |
01ac200b3d9dfce0901ce7fa7a4f7c97a66d795f | xingzhui89/PythonLearningWay | /Old/KW12/7-多态.py | 2,265 | 4.1875 | 4 | '''
多态的定义
由不同的类实例化得到的对象,调用同一个方法,执行的逻辑不同。
多态的概念指出了对象如何通过他们共同的属性和动作来操作及访问,而不需要考虑他们具体的类。
在python中一切皆对象,不同的对象可以调用相同的方法。
比如说del删除命令,可以作用于不同的变量,比如数字,字符,列表等。
再比如,len()方法,可以用来计算字符串,列表,元组的长度,所以这些对象都可以调用len方法。
在下面的实例中,我们定义了一个H2O类,这个类包含name和temperature属性,包含了turn_ice()方法。
然后我们通过继承的方法,定义了Water、Ice和Steam类。
这些子类中都没有具体的属性和方法实现。
在分别初始化这几个子类之后,我们使这几个实例都调用turn_ice方法,是可以运行的。
我们再来考虑一下,turn_ice函数中的self,表示的是H2O类,子类的实例之所以能够调用该函数,说明子类实例本质上还是H2O类的。
'''
class H2O:
def __init__(self,name,temperature):
self.name=name
self.temperature=temperature
def turn_ice(self):
if self.temperature < 0:
print('[%s]温度太低结冰了' %self.name)
elif self.temperature > 0 and self.temperature < 100:
print('[%s]液化成水' %self.name)
elif self.temperature > 100:
print('[%s]温度太高变成了水蒸气' %self.name)
def aaaaaa(self):
pass
class Water(H2O):
pass
class Ice(H2O):
pass
class Steam(H2O):
pass
w1=Water('水',25)
i1=Ice('冰',-20)
s1=Steam('蒸汽',3000)
w1.turn_ice()
i1.turn_ice()
s1.turn_ice()
'''
我们再来考虑一下,如果不想通过每个实例来调用turn_ice()方法,可否定义一个函数,这个函数能够接收所有的子类实例,并且运行实例的方法。
请看下面的例子。
与上面的执行结果是完全相同的。
这是动态语言和静态语言(例如Java)最大的差别之一。动态语言调用实例方法,不检查类型,只要方法存在,参数正确,就可以调用。
'''
def func(obj):
obj.turn_ice()
func(w1)
func(i1)
func(s1)
| false |
b36b8f262dfeb48419ba4b3ce5fa00b961fc32fa | xingzhui89/PythonLearningWay | /Old/KW11/18-高阶函数.py | 1,612 | 4.34375 | 4 | '''
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
'''
# import time
# def foo():
# time.sleep(3)
# print('你好啊林师傅')
#
# def test(func):
# # print(func)
# start_time=time.time()#获取当前时间,记录下来
# func()#执行传入的函数,请注意,如果不加括号,那么就是函数名,加括号才是执行
# stop_time = time.time()
# print('函数运行时间是 %s' % (stop_time-start_time))
# # foo()
# test(foo)#传入参数名,而不是传入一个执行函数
# def foo():
# print('from the foo')
# def test(func):
# return func#返回的是一个函数名
# res=test(foo)#res是一个函数名
# # print(res)
# res()#此时才是执行函数
# foo=test(foo)
# # # print(res)
# foo()
# import time
def foo():
time.sleep(3)
print('来自foo')
#不修改foo源代码
#不修改foo调用方式
#多运行了一次,不合格
# def timer(func):
# start_time=time.time()
# func()
# stop_time = time.time()
# print('函数运行时间是 %s' % (stop_time-start_time))
# return func
# foo=timer(foo)
# foo()
#没有修改被修饰函数的源代码,也没有修改被修饰函数的调用方式,但是也没有为被修饰函数添加新功能
import time
def timer(func):
start_time=time.time()
return func# 这里设置return,下面的语句就不会被执行了
stop_time = time.time()
print('函数运行时间是 %s' % (stop_time-start_time))
foo=timer(foo)
foo() | false |
92de7a7e4e44f3a773d8d8b91314523e20481082 | ryantroywilson/python | /compare_arrays.py | 735 | 4.375 | 4 | """
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical
print "The lists are the same". If they are not identical print "The lists are not the same." Try the following
test cases for lists one and two:
"""
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
list_one2 = [1,2,5,6,5]
list_two2 = [1,2,5,6,5,3]
list_one3 = [1,2,5,6,5,16]
list_two3 = [1,2,5,6,5]
list_one4 = ['celery','carrots','bread','milk']
list_two4 = ['celery','carrots','bread','cream']
if list_one2 == list_two2:
print "The lists are the same!"
else:
print "The lists are not the same!"
| true |
378cd2212c68e5930b322c287b6eab54d98eac4b | ryantroywilson/python | /Multiples_sums_average.py | 970 | 4.65625 | 5 | """
Multiples
Part I - Write code that prints all the odd numbers from 1 to 1000. Use
the for loop and don't use a list to do this exercise.
Part II - Create another program that prints all the multiples
of 5 from 5 to 1,000,000.
Sum List
Create a program that prints the sum of all the values in
the list: a = [1, 2, 5, 10, 255, 3]
Average List
Create a program that prints the average of the values in
the list: a = [1, 2, 5, 10, 255, 3]
"""
#PART ONE: PRINT ALL ODD NUMBERS FROM 1 - 1000 (for loop) no lists
count = range(0,1000)
for i in count:
if i%2!=0:
print i
# PART TWO: prints all the multiples of 5 from 5 to 1,000,000.
count = range(0,1000000)
for i in count:
if i%5==0:
print i
# SUM LIST: print sum of all the values in list: a = [1, 2, 5, 10, 255, 3]
x = [1, 2, 5, 10, 255, 3]
y = sum(x)
print y
#Average List Create a program that prints the average of the values in
a = [1, 2, 5, 10, 255, 3]
b = sum(a)/len(a)
print b
| true |
a997452f81e8b1d4ca43da2f8794436c6237231e | down-to-earth1994/python_study | /helloWorld.py | 1,447 | 4.25 | 4 | #! /usr/bin/python
# -*- coding: UTF-8 -*-
# print "Hello, World!"
# 数字类型
# myNumberOne = 1
# del myNumberOne
# myNumberOne = 2
# print(myNumberOne)
# 字符串类型
# s = 'abcdef'
# print(s[1:5])
#列表类型
# list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
# tinylist = [123, 'john']
# print list # 输出完整列表
# print list[0] # 输出列表的第一个元素
# print list[1:3] # 输出第二个至第三个元素
# print list[2:] # 输出从第三个开始至列表末尾的所有元素
# print tinylist * 2 # 输出列表两次
# print list + tinylist # 打印组合的列表
# 元组
# tuple = ('runoob', 786, 2.23, 'john', 70.2)
# tinytuple = (123, 'john')
#
# print tuple # 输出完整元组
# print tuple[0] # 输出元组的第一个元素
# print tuple[1:3] # 输出第二个至第三个的元素
# print tuple[2:] # 输出从第三个开始至列表末尾的所有元素
# print tinytuple * 2 # 输出元组两次
# print tuple + tinytuple # 打印组合的元组
# 字典
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
# python 3
print(dict['one'])
# python 2
# print dict['one'] # 输出键为'one' 的值
# print dict[2] # 输出键为 2 的值
# print tinydict # 输出完整的字典
# print tinydict.keys() # 输出所有键
# print tinydict.values() # 输出所有值 | false |
7a2e1660fee1ae9273ca4f0d98376bbf0ff5539f | CarmenRocks88/AWS_re-Start | /numeric_data_types.py | 969 | 4.59375 | 5 | # Numeric Data Types
print("Python has 3 numeric types: int, float, complex")
# Creating Variables
# The Int (Integer) Data Type - Use for whole numbers
myInteger = 1
print(myInteger)
print(type(myInteger))
print(str(myInteger) + " is of data type " + str(type(myInteger)))
# The Float Data Type - Use for decimals
myFloat = 3.14
print(myFloat)
print(type(myFloat))
print(str(myFloat) + " is of data type " + str(type(myFloat)))
# The Complex Data Type - use for mixed math/complex numbers
myComplex = 5j
print(myComplex)
print(type(myComplex))
print(str(myComplex) + " is of data type " + str(type(myComplex)))
# The Bool (Boolean) Data Type - Use for True/False data True = 1 ,False = 0
myBoolean_1 = True
print(myBoolean_1)
print(type(myBoolean_1))
print(str(myBoolean_1) + " is of data type " + str(type(myBoolean_1)))
myBoolean_0 = False
print(myBoolean_0)
print(type(myBoolean_0))
print(str(myBoolean_0) + " is of data type " + str(type(myBoolean_0)))
| false |
ba17b6d72bffab9c183410c63b873e75e6d4a5f7 | stpnkv/lp-homework | /homework01/if_age.py | 1,288 | 4.25 | 4 | # Возраст
# Попросить пользователя ввести возраст.
# По возрасту определить, чем он должен заниматься: учиться в детском саду, школе, ВУЗе или работать.
# Вывести занятие на экран.
def where_to_go(age):
if age < 0:
print("You haven't been born yet!")
elif 0 <= age < 3:
print("Go to sleep!")
elif 3 <= age < 7:
print("Go to the kindergarten!")
elif 7 <= age < 17:
print("Go to School!")
elif age == 17:
answer =input("Have you finished school? ")
if answer.upper() == 'YES':
print("Go to the University!")
else:
print("Try to finish school first!")
elif 18 <= age < 21:
print("Go to the University!")
else:
answer =input("Have you finished the University? ")
if answer.upper() == 'YES':
print("Go to work!")
else:
print("Try to finish the University first!")
while True:
try:
age = int(input("Your age: "))
except KeyboardInterrupt:
print("Bye, bye")
break
except ValueError:
print("Please, enter a number")
where_to_go(age)
| false |
b4e306a1e12670545218c6907aaf2ab9cf48a036 | litovkas/21.10 | /1.py | 590 | 4.1875 | 4 | # Написать функцию, которая будет принимать два параметра A и N.
# Функция должна возвести число A в целую степень N, и вернуть ответ
def turn_to_1(n):
while n == int:
if n % 2 == 0:
n /= 2
if n == 1:
break
if n % 2 == 1:
n = (n * 3 + 1) / 2
if n == 1:
break
return n
if __name__ == "__main__":
n = int(input("insert the number: \n"))
result = turn_to_1(n)
print("Yes") | false |
785b62ea037de2a5b0f4131130f923d9dbf58701 | nathansuraj58/python-internship | /task 4(3).py | 677 | 4.28125 | 4 | #creating a list
n = int(input("enter the size of list:"))
my_list = []
for i in range(n):
item = int(input())
my_list.append(item)
print(my_list)
#adding an item into list
item = int(input("enter the item to be added in the list:"))
my_list.append(item)
print("list after appending: ",my_list)
#delete
item = int(input("Enter the item to be deleted: "))
my_list.remove(item)
print("list after removing the selected item ",my_list)
#largest number in the list
largest_value = max(my_list)
print("Largest value in the list ",largest_value)
#Smallest value in the list
smallest_value = min(my_list)
print("Smallest value in the list",smallest_value)
| true |
5ecd137c2b42ff82ce7e70efdb751c243374d533 | JanithDeSilva/hacktoberfest_2021 | /Average _of_List.py | 305 | 4.15625 | 4 | mylist = []
lenoflist =int(input("Enter the length of the list: "))
for i in range(lenoflist):
element=int(input("Enter element " + str(i+1) + ": "))
mylist.append(element)
print(mylist)
sumoflist = sum(mylist)
average = float(sumoflist/lenoflist)
print(f"The average of the list is {average}")
| true |
0ef89fff0ef0960a9c7c10f0c25bbb7ed2c377bc | bricruz/pythonpractice | /09_is_palindrome/is_palindrome.py | 673 | 4.1875 | 4 | def is_palindrome(phrase):
"""Is phrase a palindrome?
Return True/False if phrase is a palindrome (same read backwards and
forwards).
>>> is_palindrome('tacocat')
True
>>> is_palindrome('noon')
True
>>> is_palindrome('robert')
False
Should ignore capitalization/spaces when deciding:
>>> is_palindrome('taco cat')
True
>>> is_palindrome('Noon')
True
"""
reversed_list_phrase = list(reversed(phrase))
list_phrase = list(phrase)
if list_phrase == reversed_list_phrase:
return True
else:
return False
print(is_palindrome('howdy')) | false |
ecbfe1a5f6315e9cc17f6f800b0a4a29afd9a1f7 | praneethsrivatsa/Datascience- | /Day2_Que2.py | 2,980 | 4.4375 | 4 | #
# Assignment no : 2(Que 2)
# Questions 2:
# Create a notebook on LIST COMPREHENSION. This exercise is to put you in a Self learning mode
my_list = [] # empty list creates
print("print empty list :", my_list)
my_list1 = [10, 20, 15, 68, 9, 56, 85, 95, 64, 58, 56, 32, 32] # int List create
print("List of int :", my_list1)
mixed_list = [10, 'yogi', 20.0, "Pune"]
print("mixed list is :", mixed_list)
print('X' * 50) # indication purpose
from collections import Counter
list = [1, 2, 3, 4, 5, 3, 2, 3, 4, 5, 6, 5, 4, 6, 7, 8, 9, 0, 7, 6, 5, 4, 6, 7, 7, 9]
print(Counter(list))
str = 'I am yogi Halagunaki and i am from pune itself and i am doing cdac in Data science '
word_list = str.split()
print(Counter(word_list))
print('X'*50)
# print(my_list.append(10))
print(my_list1.append(mixed_list))
print(my_list1[1])
print(my_list1[:3])
print(my_list1[3:])
# print(my_list1.count())
print('X'*50)
print(mixed_list)
mixed_list.remove(mixed_list[2])
print(mixed_list)
mixed_list.append("Teju")
my_list1.append("Ashu")
print(mixed_list)
print(my_list1)
my_list1.remove(my_list1[3])
print(my_list1)
print('X'*50)
my_list.append(13)
my_list.append(11)
my_list.append(1)
my_list.append(2)
my_list.append(20)
my_list.append(17)
print(my_list)
my_list.remove(my_list[3])
print(my_list)
print("Unsorted list :",list)
list.sort()
print("Sorted list :",list)
print('X'* 50)
print("Sum of list is :",sum(list))
print("ASCII : :",ascii(list))
#
# Output :
# /home/yogi/Desktop/Python_Code/venv/bin/python /home/yogi/Desktop/Python_Code/Lets_Upgrade_Assignments/day2/Day2_Que2.py
# print empty list : []
# List of int : [10, 20, 15, 68, 9, 56, 85, 95, 64, 58, 56, 32, 32]
# mixed list is : [10, 'yogi', 20.0, 'Pune']
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# Counter({4: 4, 5: 4, 6: 4, 7: 4, 3: 3, 2: 2, 9: 2, 1: 1, 8: 1, 0: 1})
# Counter({'am': 3, 'and': 2, 'i': 2, 'I': 1, 'yogi': 1, 'Halagunaki': 1, 'from': 1, 'pune': 1, 'itself': 1, 'doing': 1, 'cdac': 1, 'in': 1, 'Data': 1, 'science': 1})
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# None
# 20
# [10, 20, 15]
# [68, 9, 56, 85, 95, 64, 58, 56, 32, 32, [10, 'yogi', 20.0, 'Pune']]
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# [10, 'yogi', 20.0, 'Pune']
# [10, 'yogi', 'Pune']
# [10, 'yogi', 'Pune', 'Teju']
# [10, 20, 15, 68, 9, 56, 85, 95, 64, 58, 56, 32, 32, [10, 'yogi', 'Pune', 'Teju'], 'Ashu']
# [10, 20, 15, 9, 56, 85, 95, 64, 58, 56, 32, 32, [10, 'yogi', 'Pune', 'Teju'], 'Ashu']
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# [13, 11, 1, 2, 20, 17]
# [13, 11, 1, 20, 17]
# Unsorted list : [1, 2, 3, 4, 5, 3, 2, 3, 4, 5, 6, 5, 4, 6, 7, 8, 9, 0, 7, 6, 5, 4, 6, 7, 7, 9]
# Sorted list : [0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 9, 9]
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# Sum of list is : 128
# ASCII : : [0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 9, 9]
#
# Process finished with exit code 0
| true |
2ff637997a70d0c230289ab43efc7bfa89beb5ce | nxnarbais/python4excel | /class_exercises/4-python_basics/main-if.py | 1,063 | 4.25 | 4 | #####################
# Write an if statement print the content of a variable called myVar if it is positive or the opposite if not
#####################
myVar = 22
if myVar > 0:
print(myVar)
else:
print(-myVar)
#####################
# Write an if statement that prints "yes" if the letter "a" is included in a variable called myString otherwise prints "no"
#####################
myString = "hello world"
if "a" in myString:
print("yes")
else:
print("no")
#####################
# Writate an if statement, if the value of a variable is above 10, print something and concatenate the number value. If it is above 100, print something else. If it is between 0 and 10, print another thing and if this is below or equal to 0 print one last message
#####################
myFavoriteNumber = 42
if myFavoriteNumber > 10:
print("What a big number: " + myFavoriteNumber)
if myFavoriteNumber > 100:
print("It is actually above 100, that's a lot")
elif myFavoriteNumber > 0:
print("Just a single digit?")
else:
print("Really, a negative number!") | true |
3db2a82a88cd0d74d49b5ac2864baa835cee0cc3 | 1a2a222/leetcode | /用两个栈来实现队列.py | 1,358 | 4.125 | 4 | class Stack:
"""栈的实现"""
def __init__(self):
self.__list = []
def push(self,node):
self.__list.append(node)
def pop(self):
self.__list.pop()
def peek(self):
"""返回栈顶元素"""
if self.__list:
return self.__list[-1]
else:
return None
def is_empty(self):
return self.__list == []
def size(self):
return len(self.__list)
class Queue:
"""队列的实现"""
def __init__(self):
self.__list = []
def enqueue(self,node):
"""入队操作"""
self.__list.append(node)
def dequeue(self):
self.__list.pop(0)
def is_empty(self):
return self.__list ==[]
def size(self):
return len(self.__list)
class Solution:
"""用两个栈来实现队列"""
def __init__(self):
self.__stack1 = []
self.__stack2 = []
def push(self,node):
self.__stack1.append(node)
def pop(self):
if len(self.__stack1)==0 and len(self.__stack2)==0:
return
elif len(self.__stack2)==0:
while len(self.__stack1)>0:
self.__stack2.append(self.__stack1.pop())
return self.__stack2.pop()
queue = Solution()
for i in range(10):
queue.push(i)
for i in range(10):
a = queue.pop()
print(a,end=' ') | false |
05342de6d62aa5891248de69e1402328942ff994 | momentum-cohort-2019-02/w2d2-palindrome-rob-taylor543 | /palindrome.py | 1,151 | 4.21875 | 4 |
def clean_text(input_string):
"""Takes a string as an argument and returns it all lower case and with no special characters or punctuation"""
return (''.join(e for e in input_string if e.isalnum())).casefold()
def palindrome(input_string):
"""Takes a string as an argument, cleans it of punctuation, spaces, and special characters, and returns True if it is a palindrome and False otherwise."""
cleaned_input_string = clean_text(input_string)
return cleaned_input_string == cleaned_input_string[::-1]
def palindrome_recursively(input_string):
"""Takes a string as an argument, cleans it of punctuation, spaces, and special characters, and returns True if it is a palindrome and False otherwise."""
cleaned_input_string = clean_text(input_string)
return (len(cleaned_input_string) <= 1) or ((cleaned_input_string.endswith(cleaned_input_string[0])) and palindrome_recursively(cleaned_input_string[1:-1]))
user_input = input("Write something to find out if it is a palindrome: ")
if palindrome_recursively(user_input):
print(user_input + " is a palindrome")
else:
print(user_input + " is not a palindrome") | true |
15b9a929c241beb0557a63745741b095a884f6fc | Akhlaquea01/Python_Practice | /Practice/dictionary.py | 411 | 4.34375 | 4 | new_dict = {
"brand": "Honda",
"model": "Civic",
"year": 1995
}
print(new_dict)
x = new_dict["brand"]
print(x)
new_dict["year"] = 2020
print(new_dict)
# print all key names in the dictionary
for x in new_dict:
print(x)
print("*****")
# print all values in the dictionary
for x in new_dict:
print(new_dict[x])
# loop through both keys and values
for x, y in new_dict.items():
print(x, y)
| true |
66220cbaad18168d73795ddb9adc342e0c1504c4 | Theo-cath/python_exo | /exercice25.py | 584 | 4.125 | 4 | #Exercice 25 : Faire un programme python qui demande à un utilisateur d’entrer un entier positif. Le programme indique ensuite si l’entier positif est pair ou impair ? Le programme vérifie et redemande l’entier si ce n’est pas un entier positif.
txt = int(input("veuillez entrer un entier positif :"))
while txt < 0 :
txt2 = int(input("Cette entier est négatif,veuillez entrer un entier positif :"))
if txt2 % 2 == 0 :
print("pair")
else :
print("impair")
else :
if txt % 2 == 0 :
print("pair")
else :
print("impair")
| false |
f7b07d73a246e414a2da3eb5057eded6febe46a3 | sadiqkanner/Python | /Task_1.py | 956 | 4.1875 | 4 | print("Enter the date or day of your birth")
day = int(input())
while day > 31 or day < 1:
print("try again the day of your birth")
day = int(input())
if day > 13:
nmonth = 10-month
td = 31+13-day
elif day <= 13:
td = 13-day
nmonth = 11-month
print("Enter the month of your birth")
month = int(input())
while month >12 or month < 1:
print("try again for the month of your birth")
month = int(input())
if month > 11:
nmonth = 12+11-month
elif month <= 11:
nmonth = 11-month
print("Enter the year of your birth")
year = int(input())
while year >2018 or year < 0:
print("try again the year of your birth")
year = int(input())
else:
if day==13 and month==11 and year==2018:
print("Congrats You Born Today 13/11/2018")
else:
nyear = 2018-year
print("Your "+str(nyear)+" years old & "+str(nmonth)+" month & "+str(td)+" day")
| false |
5563d1e05439715a9149aa96ab86255d765f02ca | sanjayms1999/1BM18CS418-PYTHON | /pgm8.py | 1,861 | 4.125 | 4 | import sqlite3
from sqlite3 import Error
conn = sqlite3.connect('student.db')
print("Connection Established")
cur = conn.cursor()
def create_table():
cur.execute("CREATE TABLE STUDENT0 (SID int primary key, name text, age int, marks int)")
conn.commit()
print("STUDENT table created.")
def insertor():
cur.execute("INSERT INTO STUDENT0(SID,NAME,AGE,MARKS) VALUES(1000, 'John', 20, 81)")
cur.execute("INSERT INTO STUDENT0(SID,NAME,AGE,MARKS) VALUES(1001, 'Smith', 21, 80)")
cur.execute("INSERT INTO STUDENT0(SID,NAME,AGE,MARKS) VALUES(1002, 'Virat', 21, 78)")
cur.execute("INSERT INTO STUDENT0(SID,NAME,AGE,MARKS) VALUES(1003, 'Raju', 20, 70)")
conn.commit()
print("Values inserted into STUDENT0 Table.")
def DisplayAll():
print('All Student\'s Data:')
val = cur.execute('SELECT * FROM STUDENT0')
for row in val:
print('Student ID:', row[0])
print('Student Name:', row[1])
print('Student Age:', row[2])
print('Student Marks:', row[3])
print('')
def DisplayQuery():
print('Students With Marks Less Than 75:')
val = cur.execute('SELECT * FROM STUDENT0 WHERE marks<75')
for row in val:
print('Student ID:', row[0])
print('Student Name:', row[1])
print('Student Age:', row[2])
print('Student Marks:', row[3])
print('')
def updator():
cur.execute('UPDATE STUDENT0 SET name = "Suraj" where SID = 1003')
conn.commit()
def delete():
cur.execute('DELETE FROM STUDENT0 WHERE SID = 1002')
conn.commit()
n=0
while n==0:
try:
create_table()
insertor()
DisplayAll()
DisplayQuery()
updator()
DisplayAll()
delete()
DisplayAll()
except Error as e:
print(e)
n=1
| false |
3c05c6d0adf94f0149bad4f718c7a4f461554b8c | kasia-jablonski/Intermediate-Python | /remember.py | 1,493 | 4.1875 | 4 | import sys
'''
def rememberer(thing):
# Open file
file = open("database.txt", "a")
# Write thing to file
file.write(thing + "\n")
# Close file
file.close()
'''
def rememberer(thing):
with open("database.txt", "a") as file:
file.write(thing + "\n")
def show():
#open file
with open("database.txt") as file:
for line in file:
print(line)
if __name__ == '__main__':
if sys.argv[1].lower() == '--list':
show()
else:
rememberer(' '.join(sys.argv[1:]))
'''
open(filename, mode="r")opens a file. More info in the docs.
file.read(bytes=-1) would read the entire contents of the file. You can control the number of bytes read by passing in an integer. Relatedly, file.seek() will move the read/write pointer to another part of the file.
file.readlines() reads the entire file into a list, with each line as a list item.
The context manager pattern for dealing with files is:
with open("my_file.txt", "r") as file:
file.read(10)
'''
'''
open(filename, mode="r")opens a file. More info in the docs.
file.write("hello world") would write "hello world" to whatever file the file variable points at.
file.close() closes the pointer to the file file.
The two most common modes or flags for writing are "w", for truncating and then writing, and "a" for appending to the file.
The context manager pattern for dealing with files is:
with open("my_file.txt", "a") as file:
file.write("Hello world")
'''
| true |
8ed21f6d94134bcfff40258ce351c833bb39a320 | erikperillo/mc346 | /python/trabalho/interval.py | 2,658 | 4.28125 | 4 | class Interval:
"""
Class representing an integer and closed interval.
"""
def __init__(self, x_min, x_max):
self.x_min = x_min
self.x_max = x_max
def left_crosses(self, ival):
"""Interval crosses ival from left. It may be inside it or not."""
return self.x_max >= ival.x_min and self.x_max <= ival.x_max
def left_cross_size(self, ival):
"""Crossing size in the case there is a left crossing."""
return self.x_max - ival.x_min - max(0, self.x_min - ival.x_min)
def inside(self, ival):
"""Returns true if interval is inside if ival."""
return self.left_crosses(ival) and self.x_min >= ival.x_min
def no_cross_dist(self, ival):
"""Minimum distance between intervals in case there is no crossing."""
return min(abs(self.x_min - ival.x_max), abs(ival.x_min - self.x_max))
def size(self):
"""Size of interval."""
return self.x_max - self.x_min
def __repr__(self):
"""To be used in print etc."""
return "Interval [%d, %d]" % (self.x_min, self.x_max)
def link(self, ival):
"""Gets the link size between two intervals."""
if self.left_crosses(ival):
return self.left_cross_size(ival)
if ival.left_crosses(self):
return ival.left_cross_size(self)
else:
return -self.no_cross_dist(ival)
def sort(ivals):
"""Sorts a list of intervals by x_min."""
return sorted(ivals, key=lambda x: x.x_min)
def separate(ivals):
"""
Separates a list of intervals in a list of intervals that are inside
other intervals and a list of intervals that are not.
Assumes intervals list is sorted by x_min.
"""
inside = []
outside = []
for k, ival in enumerate(ivals):
same_x_min = []
max_k = k
#intervals with same x_min may also contain ival
for i in xrange(k+1, len(ivals)):
if ivals[i].x_min == ival.x_min:
max_k += 1
else:
break
#finding out whether ival is inside some interval
outside.append(ival)
for i in xrange(max_k, -1, -1):
if ival.inside(ivals[i]) and i != k:
inside.append(outside.pop())
break
return inside, outside
def min_link(ivals):
"""Gets minimum link of a list of intervals."""
sorted_ivals = sort(ivals)
inside, outside = separate(sorted_ivals)
min_out = min(outside[i].link(outside[i+1]) for i in range(len(outside)-1))
if inside:
return min(min(i.size() for i in inside), min_out)
return min_out
| true |
4827649d7e60800dc508e5ea1e131578e94aeb34 | jstechnologyes/Python | /Programme4.py | 435 | 4.1875 | 4 | number1=int(input("Enter first number:"))
number2=int(input("Enter Second number:"))
result=number1+number2
print("The Result is:",result)
result=number1-number2
print("The Result is:",result)
result=number1*number2
print("The Result is:",result)
result=number1/number2
print("The Result is:",result)
result=number1**number2
print("The Result is:",result)
result=number1//number2
print("The Result is:",result) | true |
27f8ba1e8c9a03f65d83ccb838973208be577c85 | jjaviergalvez/CarND-Term3-Quizzes | /search/optimum_policy.py | 2,295 | 4.25 | 4 | # ----------
# User Instructions:
#
# Write a function optimum_policy that returns
# a grid which shows the optimum policy for robot
# motion. This means there should be an optimum
# direction associated with each navigable cell from
# which the goal can be reached.
#
# Unnavigable cells as well as cells from which
# the goal cannot be reached should have a string
# containing a single space (' '), as shown in the
# previous video. The goal cell should have '*'.
# ----------
grid = [[0, 1, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0]]
grid = [[0, 1, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 0, 1, 1, 0]]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1 # the cost associated with moving from a cell to an adjacent one
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']
def optimum_policy(grid,goal,cost):
# ----------------------------------------
# insert code below
# ----------------------------------------
# make sure your function returns a grid of values as
# demonstrated in the previous video.
value = [[99 for col in range(len(grid[0]))] for row in range(len(grid))]
closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]
policy = [[' ' for col in range(len(grid[0]))] for row in range(len(grid))]
# initialization
value[goal[0]][goal[1]] = 0
closed[goal[0]][goal[1]] = 1
policy[goal[0]][goal[1]] = '*'
lst = [goal]
for e in lst:
x = e[0]
y = e[1]
step = value[x][y] + cost
for i in range(len(delta)):
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
value[x2][y2] = step
lst.append([x2,y2])
closed[x2][y2] = 1
policy[x2][y2] = delta_name[(i+2)%4]
return policy
result = optimum_policy(grid, goal, cost)
for row in result:
print(row) | true |
040b4757e71f7bdd13a09cd9ea9799df38c5ebd5 | lhd0320/AID2003 | /official courses/month01/day08/work03.py | 605 | 4.25 | 4 | """
定义根据边长打印矩形的函数
length_of_side = int(input("请输入一个整数:"))
for number in range(length_of_side): # 0 1 2 3 4
# 头尾
if number == 0 or number == length_of_side - 1:
print("*" * length_of_side)
else: # 中部
print("*%s*" % (" " * (length_of_side - 2)))
"""
def print_rectangle(length_of_side,char):
for number in range(length_of_side):
if number == 0 or number == length_of_side - 1:
print(char * length_of_side)
else:
print(char+" " * (length_of_side - 2)+char)
print_rectangle(4,"#") | false |
b0befaffd3d7c9630a878b09a170bfb735314052 | Joseph-I-Jess/new_cs162_learning_git | /hello/hello_world.py | 677 | 4.1875 | 4 | """Get input from user, print it back to the string."""
#a change!
class Cat:
"""Class representing a cat..."""
def __init__(self):
"""Initialize a default cat."""
self.limbs = 4
self.tail = "long"
def __str__(self):
"""Return self represented as a string."""
return f"THis cat has {self.limbs} limbs and has a {self.tail} tail."
def main():
"""Run my tests."""
print("Hello?")
"""
number = input("Please enter a number: ")
print(f"You entered {number}")
"""
my_cat = Cat()
print(f"""my_cat: {my_cat}""") # will call my_cat.__str__() for us...
if __name__ == "__main__":
main()
| true |
c14b533776f7f66561f54640dcb46b356bbe25c9 | bhavyajaink/Python | /sort_list().py | 207 | 4.1875 | 4 | #to sort the element of the list
fr=['bhvaya','komal','khushi','akshuni','divya']
print('before the sort operation of fr value are:=',fr)
fr.sort()
print('after the sort opertion of fr value are:=',fr)
| false |
c687260a7833c0fc5cfececbb48a60e1e13b2c5b | 1ntourist/makes_part_2 | /task_10.py | 518 | 4.34375 | 4 | string = input("give a string: ").upper()
print("third character of this string: ", string[3])
print("second to last character of this string: ", string[-2])
print("first five characters of this string: ", string[:6])
print("all but the last two characters of this string: ", string[:-2])
print("all the characters of this string with even indices: ", string[1::2])
print("the characters of this string with odd indices: ", string[::2])
print("string in reverse: ", string[::-1])
print("len of string: ", len(string))
| true |
fac5a38c49f691cec7ea16f9b0d05409cd04ffd3 | toonarmycaptain/Automate-the-Boring-Stuff | /phone_and_email.py | 2,909 | 4.21875 | 4 | #! python3
# phone_and_email.py - Finds phone numbers & email addresses on the clipboard.
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 12 23:23:25 2017
Project: Phone Number and Email Address Extractor
Say you have the boring task of finding every phone number and email address in
a long web page or document. If you manually scroll through the page, you might
end up searching for a long time. But if you had a program that could search
the text in your clipboard for phone numbers and email addresses, you could
simply press CTRL-A to select all the text, press CTRL-C to copy it to the
clipboard, and then run your program. It could replace the text on the
clipboard with just the phone numbers and email addresses it finds.
Whenever you’re tackling a new project, it can be tempting to dive right into
writing code. But more often than not, it’s best to take a step back and
consider the bigger picture. I recommend first drawing up a high-level plan for
what your program needs to do. Don’t think about the actual code yet—you can
worry about that later. Right now, stick to broad strokes.
For example, your phone and email address extractor will need to do the
following:
Get the text off the clipboard.
Find all phone numbers and email addresses in the text.
Paste them onto the clipboard.
from Automate:
https://automatetheboringstuff.com/chapter7/
@author: david.antonini
"""
import re
import pyperclip
# Phone number regex:
phone_number_regex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
(\d{3}) # first 3 digits
(\s|-|\.) # separator
(\d{4}) # last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? # extension
)''', re.VERBOSE)
# Email regex:
email_address_regex = re.compile(r'''(
[a-zA-Z0-9._%+-]+ # username
@ # @ symbol
[a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4}) # dot-something
)''', re.VERBOSE)
# Find matches in clipboard text:
text = str(pyperclip.paste())
phone_numbers = []
email_addresses = []
for groups in phone_number_regex.findall(text):
found_phone_number = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
found_phone_number += ' x' + groups[8]
if found_phone_number not in phone_numbers:
phone_numbers.append(found_phone_number)
for groups in email_address_regex.findall(text):
if groups[0] not in email_addresses:
email_addresses.append(groups[0])
numbers_and_emails = phone_numbers + email_addresses
# Copy results to the clipboard:
if len(numbers_and_emails) > 0:
pyperclip.copy('\n'.join(numbers_and_emails))
print('Copied to clipboard:')
print('\n'.join(numbers_and_emails))
else:
print('No phone numbers or email addreses found.')
| true |
cde1b9c8f779b37ad87b9ec5beecc2169445bf9a | chrisjonmeyer/PythonFun | /FunctionsTesting.py | 485 | 4.125 | 4 | # Using this test functions for practice.
# def first_function():
# '''
# DOCSTRING: This is your commet area for the function
# '''
# print("Hello")
# first_function()
# Create a function that takes an arbitrary number of arguments and returns a list containing
# only the arguments that are even
def myfunc(*args):
evens = []
for x in args:
if x % 2 == 0:
evens.append(x)
return evens
value = myfunc(1,2,3,4,5,6,7,8)
print (value) | true |
a0a194bccd069242e6c242a7c76153cf4f4467d5 | chrisjonmeyer/PythonFun | /ObjectOrientedTesting.py | 1,856 | 4.46875 | 4 | # Object Oriented Homework From Bootcamp
# Use https://github.com/Pierian-Data/Complete-Python-3-Bootcamp
# Create a class with methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
# class Line:
# def __init__(self,coor1,coor2):
# self.coor1 = coor1
# self.coor2 = coor2
# def distance(self):
# x1,y1 = self.coor1
# x2,y2 = self.coor2
# return ((x2-x1)**2 + (y2-y1)**2)**0.5
# def slope(self):
# x1,y1 = self.coor1
# x2,y2 = self.coor2
# return (y2-y1)/(x2-x1)
# coordinate1 = (3,2)
# coordinate2 = (8,10)
# li = Line(coordinate1, coordinate2)
# print(li.distance())
# print(li.slope())
# For this challenge, create a bank account class that has two attributes:
# owner
# balance
# and two methods:
# deposit
# withdraw
# As an added requirement, withdrawals may not exceed the available balance.
# Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn.
class Account:
def __init__(self,owner,balance):
self.owner = owner
self.balance = balance
def deposit(self,deposit_amount):
self.balance += deposit_amount
print("Deposit accepted")
def withdraw(self,withdraw_amount):
if (withdraw_amount < self.balance):
self.balance -= withdraw_amount
print("Withdrawl accepted")
else:
print("Insufficent Funds. Withdrawl declined")
# Use this to override the string interpretation of the class to change what happens when you print the object
def __str__(self):
return f"Account Owner: {self.owner}\nAccount Balance: ${self.balance}"
acct1 = Account('Chris',100)
print(acct1)
acct1.deposit(50)
acct1.withdraw(100)
acct1.withdraw(100)
print(acct1) | true |
2135707d3e61e14422aa69fc76af0f3febfedae3 | UmamaheshMaxwell/my-python-app | /20.json.py | 1,216 | 4.125 | 4 | """
JSON
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
"""
# Python has a built-in package called json, which can be use to work with JSON data.
import json
# Parse JSON - Convert from JSON to Python
# If you have a JSON string, you can parse it by using the json.loads() method.
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York" }'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y)
# Convert from Python to JSON
# If you have a Python object, you can convert it into a JSON string by using
# the json.dumps() method.
# a Python object (dict):
x = {
"name": "Uma",
"age": 36,
"city": "Bangalore"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
# You can convert Python objects of the following types, into JSON strings:
#
# dict
# list
# tuple
# string
# int
# float
# True
# False
# None
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
| true |
9d8358378144ddeda03a09f9648eafc7f90ef273 | UmamaheshMaxwell/my-python-app | /3.numbers.py | 1,786 | 4.46875 | 4 | # Please run python 3.numbers.py in terminal to see the output
"""
There are three numeric types in Python
1. int - Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length
2. float - Float, or "floating point number" is a number, positive or negative,
containing one or more decimals
3. complex - Complex numbers have their uses in many applications
related to mathematics and python provides useful tools
to handle and manipulate them
"""
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(x)
print(y)
print(z)
# type of the variable
print(type(x))
print(type(y))
print(type(z))
# positive or negative Integer
intValue1 = 1
intValue2 = 2345678987
intValue3 = -45678
print(intValue1, " is of type ", type(intValue1))
print(intValue2, " is of type ", type(intValue2))
print(intValue3, " is of type ", type(intValue3))
# positive or negative float
floatValue1 = 1.154
floatValue2 = 1.0
floatValue3 = -35.59
print(floatValue1, " is of type ", type(floatValue1))
print(floatValue2, " is of type ", type(floatValue2))
print(floatValue3, " is of type ", type(floatValue3))
# Float can also be scientific numbers with an "e" to indicate the power of 10
floatValue4 = 35e3
floatValue5 = 12E4
floatValue6 = -22.4e100
print(floatValue4, " is of type ", type(floatValue4))
print(floatValue5, " is of type ", type(floatValue5))
print(floatValue6, " is of type ", type(floatValue6))
# Complex numbers are written with a "j" as the imaginary part
complexValue1 = 3+5j
complexValue2 = 5j
complexValue3 = -5j
print(complexValue1, " is of type ", type(complexValue1))
print(complexValue2, " is of type ", type(complexValue2))
print(complexValue3, " is of type ", type(complexValue3))
| true |
318a5918b3e23c3897a3b36450658ff576a36adb | UmamaheshMaxwell/my-python-app | /2.variables.py | 537 | 4.34375 | 4 | # Please run python 2.variables.py in terminal to see the output
# Declare variables
x = 5;
y = "john";
print(x)
print(y)
# display output of variables
x = "awesome";
print("Python is " + x);
# + character to add a variable to another variable
x = "Python is ";
y = "awesome";
z = x + y;
print(z);
# + character works as a mathematical operator
x = 5;
y = 6;
print(x +y);
# try to combine a string and a number, Python will give you an error
x = 5;
y = "John";
# print(x +y); # unsupported operand type(s) for +: 'int' and 'str' | true |
d7b756808b04dee4e5044d711e60a43ae01b82b0 | jhosep7/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,256 | 4.53125 | 5 | #!/usr/bin/python3
class Square:
"""Square Class with a private instance
"""
def __init__(self, size=0, position=(0, 0)):
"""
Arguments:
size: the size of the square
"""
if type(size) != int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
else:
self.__size = size
if type(position) != tuple or len(position) != 2:
raise TypeError("position must be a tuple of 2 positive integers")
elif position[0] < 0 or position[1] < 0:
raise ValueError("position must be a tuple of 2 positive integers")
elif type(position[0]) != int and type(position[1]) != int:
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = position
"""GET - SIZE
"""
@property
def size(self):
return (self.__size)
"""SET - SIZE
"""
@size.setter
def size(self, value):
if type(value) != int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
"""GET - POSITION
"""
@property
def position(self):
return (self.__position)
"""SET - POSITION
"""
@position.setter
def position(self, value):
if type(position) != tuple or len(position) != 2:
raise TypeError("position must be a tuple of 2 positive integers")
elif position[0] < 0 or position[1] < 0:
raise ValueError("position must be a tuple of 2 positive integers")
elif type(position[0]) != int and type(position[1]) != int:
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = position
"""METHOD
"""
def area(self):
return (self.__size ** 2)
def my_print(self):
if self.size == 0:
print()
else:
for i in range(self.position[1]):
print()
for i in range(self.size):
print(" " * self.position[0], end="")
print("#" * self.size)
| true |
0beeff44a0b887c00def5c174ba2a22045d88468 | areeta/beginner-projects-solutions | /coin-estimator-by-weight.py | 1,710 | 4.21875 | 4 | # Coin Estimator By Weight
# Allow the user to input the total weight of each type of
# coin they have (pennies, nickels, dimes, and quarters).
# Print out how many of each type of coin wrapper they would need,
# how many coins they have, and the estimated total value of
# all of their money.
# Subgoals:
# Round all numbers printed out to the nearest whole number.
# Allow the user to select whether they want to submit the
# weight in either grams or pounds.
# This is based on American standards.
# User input should accurate to the coin amounts.
user = input("Would you like to use grams or pounds? ")
p_weight = float(input("Input weight of pennies: "))
n_weight = float(input("Input weight of nickels: "))
d_weight = float(input("Input weight of dimes: "))
q_weight = float(input("Input weight of quarters: "))
if user == "grams":
p_amount = p_weight/2.5
n_amount = n_weight/5.0
d_amount = d_weight/2.268
q_amount = q_weight/5.67
elif user == "pounds":
p_amount = p_weight/0.00551156
n_amount = n_weight/0.0110231
d_amount = d_weight/0.0050000841
q_amount = q_weight/0.01250021
def find_total(p, n, d, q) -> int:
total = (p*0.01) + (n*0.05) + (d*0.10) + (q*0.25)
return round(total, 2)
print("Penny wrapper(s) needed: " + str(int(p_amount/50)))
print("Nickel wrapper(s) needed: " + str(int(n_amount/40)))
print("Dimes wrapper(s) needed: " + str(int(d_amount/50)))
print("Quarters wrapper(s) needed: " + str(int(q_amount/40)))
print("Total amount of coins: " + str(int(p_amount + n_amount + d_amount + q_amount)))
print("Total value of your money: " +
str(find_total(p_amount, n_amount, d_amount, q_amount)))
| true |
5fcc5ded24d93bbae1f7c6192419a0fbc540f27b | joraso/ToolBox | /Python/Generators.py | 2,099 | 4.75 | 5 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 14:59:46 2021
Basic creation/usage of a generator, with Fibonacci number example.
@author: Joe Raso
"""
from sys import getsizeof
def Fibonacci(n):
"""Generator for the first n Fibonacci numbers."""
f1 = 0; f2 = 1
for i in range(n): # note that range() iteslf is NOT a generator.
# Here is where the magic happens: 'yield' pauses the function and
# returns value. When the next value is requested (with 'next()' or
# in anything that iterates, like a for loop), it continues until it
# finds the next yield statement. Yielding instead of returning is the
# halmark that the function is a generator.
yield f1
# apply the Fibonacci rule to get the next number
f1, f2 = f2, f1 + f2
if __name__ == '__main__':
# Generator are useful for looping:
print ("Looping over the first 10 fibonacci numbers:")
for f in Fibonacci(10):
print(f)
print(50*'-')
# Or values gan be retrieved with next
print("Calling Fibonacci numbers with 'next()':")
fib = Fibonacci(10)
print(next(fib), end=', ')
print(next(fib), end=', ')
print(next(fib))
print(50*'-')
# But they don't store their values, making them very memory efficient:
print("Comparing a generator and list size for 1000 Fibonacci numbers:")
fgen = Fibonacci(1000)
print(f"The generator takes up {getsizeof(fgen)} bytes,", end=' ')
flist = list(fgen)
print(f"while the list takes up {getsizeof(flist)} bytes.")
print(50*'-')
# They can also be constructed in a manner similar to list comprehension
# by simply replacing the "[]" with "()".
print("Creating generators on the fly:")
Squares10a = [x**2 for x in range(10)]
print(f"Squares10a is {Squares10a.__str__()}") # this is a list
Squares10b = (x**2 for x in range(10))
print(f"Squares10b is {Squares10b.__str__()}") # this is a generator
print(50*'-')
# To investigate later: .send(), .throw(), .close() | true |
c349c49b20677f99e70e74d463503375ae6af78a | KyrillosWalid/TheAlgorithms | /SortingAlgorithms/ShellSort.py | 1,661 | 4.25 | 4 | # ---------------------
# Shell sort algorithm.
# ---------------------
def shellsort(a, n):
k, r = n // 2, 0 # Searching middle position in list.
while k > 0: # Passing through in list.
for i in range(0, n - k): # Passing through in half list.
j = i # Copying i index to j variable.
while (j >= 0) and (a[j] > a[j + k]): # Searching position for swap.
a[j], a[j + k] = a[j + k], a[j] # Swap a[j] and a[j + k].
j, r = j - 1, r + 1 # Decrement j for passing through in list and increment r.
print(" ", [r], "-->", a) # Printing sorting status.
k = k // 2 # Split list for next passing.
return a, r # Return sorted list and number passages.
def visualization():
from random import randint # Importing randint item in random module.
n = 10 # Amount items in list.
a = [randint(0, n) for i in range(n)] # Filling list of randoms numbers.
print("Initial list:", a) # Printing initial list.
print("Visualization of algorithm work.") # Printing decription.
a, i = shellsort(a, n) # Sorting list.
print("Final list:", a) # Printing final list.
print("Total numbers of passages:", i) # Printing numbers of passages.
import timeit
elapsed_time = timeit.timeit(visualization, number = 1) # Start program and counting elapsed time.
print("Elapsed time: ", round(elapsed_time, 3), "sec.") # Printing elapsed time. | true |
8f0a4da19d4f96d539e630e26478949a86d9a627 | mmaithani/python-data | /exception handling/output.py | 479 | 4.28125 | 4 | # Q.3- What will be the output of the following code:
# Program to depict Raising Exception
try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or not
#above will give error on name error
#here is the solution
try:
raise NameError("Hi there") # Raise Error
except Exception:
print ("An exception")
# To determine whether the exception was raised or not
| true |
566070a28296ab5e13be09d48eb1768452fb1407 | mmaithani/python-data | /exception handling/create_own_exception.py | 568 | 4.3125 | 4 | # Q.6- Create a user-defined exception AgeTooSmallError()
# that warns the user when they have entered age less than 18. The code must keep
# taking input till the user enters the appropriate age number(less than 18).
class AgeTooSmallError(Exception): #inherit exception into class 'agetoosmallerror'
pass #we have nothing to write here so we use pass for empty class
age=0
while age<18:
age=int(input("enter your age=>"))
try:
if age<18:
raise AgeTooSmallError("age is too small try again")
except Exception as e:
print(e) | true |
d16af297bc0887f62f2ee993354f371578845cfd | ggsant/pyladies | /iniciante/Mundo 01/Anotações das Aulas e Desafios/Aula 07/Código 02 - Ordem de Precedência.py | 642 | 4.3125 | 4 | """
Ordem de Precedência (O que é levado em conta primeiro no código do Python):
#1 () - Parênteses
#2 ** - Potência/Exponenciação
#3 *, /, // e % - Multiplicação, Divisão, Divisão Inteira e Resto da Divisão (O que aparecer primeiro no código, executa primeiro)
#4 + e - - Adição e Subtração (O que aparecer primeiro no código, executa primeiro)
"""
print(5 + 3 * 2) # Primeiro se resolve a Multiplicação, depois a Adição
print(3 * 5 + 4 ** 2) # Primeiro se resolve a Exponenciação, depois a Multiplicação, e por fim a Adição
print(3 * (5 + 4) ** 2) # 1º: Parênteses; 2º: Exponenciação; 3: Multiplicação
| false |
e4d2e16dbcd3a509deb07b77d1bcca3502881860 | ggsant/pyladies | /iniciante/Mundo 02/Anotações das Aulas e Desafios/Aula 03 - 14/Desafio 063.py | 1,057 | 4.125 | 4 | """
DESAFIO 063: Sequência de Fibonacci v1.0
Escreva um programa que leia um número n inteiro qualquer e mostre
na tela os n primeiros elementos de uma Sequência de Fibonacci.
Ex: 0 → 1 → 1 → 2 → 3 → 5 → 8
"""
"""
# Feito com for
x = 1
y = 0
n = int(input('Digite quantos primeiros elementos da Sequência de Fibonacci você quer exibir: '))
if n > 0:
if n == 1:
print('0')
else:
print('0', end=' → ')
for i in range(1, n):
z = x + y
if i == n - 1:
print(z, end='')
else:
print(z, end=' → ')
x = y
y = z
"""
# Feito com while
contador = 1
x = 1
y = 0
n = int(input('Digite quantos primeiros elementos da Sequência de Fibonacci você quer exibir: '))
if n > 0:
if n == 1:
print('0')
else:
print('0', end=' → ')
while contador < n:
z = x + y
if contador == n - 1:
print(z, end='')
else:
print(z, end=' → ')
x = y
y = z
contador += 1
| false |
cc3947c04185f671d818c0a8c60937b698492016 | ggsant/pyladies | /iniciante/Mundo 03/Anotações das Aulas e Desafios/Aula 04 - 19/Desafio 094.py | 1,338 | 4.125 | 4 | """
DESAFIO 094: Unindo Dicionários e Listas
Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de
cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre:
A) Quantas pessoas cadastradas.
B) A média de idade.
C) Uma lista com mulheres.
D) Uma lista com idade acima da média.
"""
pessoa = dict()
pessoas = list()
media = 0
while True:
pessoa['nome'] = str(input('Nome: '))
pessoa['sexo'] = str(input('Sexo [M/F]: ')).upper().strip()[0]
pessoa['idade'] = int(input('Idade: '))
media += pessoa['idade']
pessoas.append(pessoa.copy())
continuar = str(input('Quer continuar [S/N]? ')).upper().strip()[0]
if 'N' in continuar:
break
print('-=' * 30)
if len(pessoas) == 1:
leg1 = 'pessoa'
else:
leg1 = 'pessoas'
print(f'- O grupo tem {len(pessoas)} {leg1}.')
print(f'- A média de idade é de {media / len(pessoas):.2f} anos.')
print('- As mulheres cadastradas foram: ', end='')
for p in pessoas:
if p['sexo'] == 'F':
print(f'{p["nome"]}', end=' ')
print()
print('- Lista das pessoas que estão acima da média: ')
for pes in pessoas:
if pes['idade'] > media / len(pessoas):
print()
for k, v in pes.items():
print(f'{k.capitalize()} = {v};', end=' ')
print()
print()
print('<< ENCERRADO >>')
| false |
ca92169b07236c58e07f0b4f8a95f26b3b102531 | ggsant/pyladies | /iniciante/Mundo 02/Anotações das Aulas e Desafios/Aula 01 - 12/Desafio 044.py | 2,272 | 4.125 | 4 | """
DESAFIO 044: Gerenciador de Pagamentos
Elabore um programa que calcule o valor a ser pago de um produto,
considerando o seu preço normal, e condição de pagamento:
- À vista no dinheiro/cheque: 10% de desconto
- À vista no cartão: 5% de desconto
- Em até 2x no cartão: preço normal
- 3x ou mais no cartão: 20% de juros
"""
produto = float(input('Qual é o preço normal do produto? R$ '))
print('Qual será o método de pagamento?')
print('Para pagamento à vista em dinheiro/cheque (10% de desconto), digite 1.')
print('Para pagamento à vista no cartão de crédito (5% de desconto), digite 2.')
print('Para pagamento parcelado em até 12x no cartão de crédito (20% de juros a partir de 3x), digite 3.')
pagamento = int(input('Digite a opção desejada: '))
if pagamento == 1:
valor = produto - (produto * 10 / 100)
print('O produto à vista em dinheiro/cheque, com 10% de desconto,', end=' ')
print('fica de R$ {:.2f} por R$ {:.2f}!'.format(produto, valor))
elif pagamento == 2:
valor = produto - (produto * 5 / 100)
print('O produto à vista no cartão de crédito, com 5% de desconto,', end=' ')
print('fica de R$ {:.2f} por R$ {:.2f}!'.format(produto, valor))
elif pagamento == 3:
parcelas = int(input('Em quantas vezes deseja parcelar? Digite um número de 2 a 12: '))
if parcelas == 1:
valor = produto - (produto * 5 / 100)
print('O produto à vista no cartão de crédito, com 5% de desconto,', end=' ')
print('fica de R$ {:.2f} por R$ {:.2f}!'.format(produto, valor))
elif parcelas == 2:
valor = produto
par = valor / parcelas
print('O produto parcelado em 2x de R$ {:.2f} no cartão de crédito,'.format(par), end=' ')
print('sem nenhum desconto, continua por R$ {:.2f}!'.format(produto))
elif 2 < parcelas <= 12:
valor = produto + (produto * 20 / 100)
par = valor / parcelas
print('O produto parcelado em {}x de R$ {:.2f} no cartão de crédito,'.format(parcelas, par), end=' ')
print('com 20% de juros, fica de R$ {:.2f} por R$ {:.2f}!'.format(produto, valor))
else:
print('Número inválido de parcelas! Digite um número de 2 a 12.')
else:
print('Opção inválida! Digite um número de 1 a 3.')
| false |
d51cb0b43ca7460166e034102d4505e7d1f25f4e | ggsant/pyladies | /iniciante/Mundo 01/Anotações das Aulas e Desafios/Aula 07/Desafio 009.py | 578 | 4.25 | 4 | """
DESAFIO 009: Tabuada
Faça um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada.
"""
n = int(input('Digite um número: '))
print('A tabuada de {} é:\n'.format(n))
print('{} x 1 = {}'.format(n, n * 1))
print('{} x 2 = {}'.format(n, n * 2))
print('{} x 3 = {}'.format(n, n * 3))
print('{} x 4 = {}'.format(n, n * 4))
print('{} x 5 = {}'.format(n, n * 5))
print('{} x 6 = {}'.format(n, n * 6))
print('{} x 7 = {}'.format(n, n * 7))
print('{} x 8 = {}'.format(n, n * 8))
print('{} x 9 = {}'.format(n, n * 9))
print('{} x 10 = {}'.format(n, n * 10))
| false |
9114f3e8fd67e45799c7c8fee959106fbddc64a1 | ggsant/pyladies | /iniciante/Mundo 01/Anotações das Aulas e Desafios/Aula 09/Desafio 022.py | 670 | 4.28125 | 4 | """
DESAFIO 022: Analisador de Textos
Crie um programa que leia o nome completo de uma pessoa e mostre:
> O nome com todas as letras maiúsculas e minúsculas.
> Quantas letras ao todo (sem considerar espaços).
> Quantas letras tem o primeiro nome.
"""
nome = input('Digite seu nome completo: ')
nome_sem_espacos = len(nome) - nome.count(' ')
primeiro_nome = len(nome.split()[0])
print('\nNome em letras maiúsculas: {}'.format(nome.upper()))
print('Nome em letras minúsculas: {}'.format(nome.lower()))
print('Quantidade total de letras (sem contar os espaços): {}'.format(nome_sem_espacos))
print('Quantidade de letras do primeiro nome: {}'.format(primeiro_nome))
| false |
6f492e52e5466a54bf3e8c9b1c96665fbea595ea | ggsant/pyladies | /iniciante/Mundo 02/Anotações das Aulas e Desafios/Aula 01 - 12/Desafio 042.py | 860 | 4.125 | 4 | """
DESAFIO 042: Analisando Triângulos v2.0
Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
- Equilátero: todos os lados iguais
- Isósceles: dois lados iguais
- Escaleno: todos os lados diferentes
"""
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
if r1 == r2 and r1 == r3:
print('Os segmentos acima podem formar um triângulo EQUILÁTERO!')
elif r1 == r2 and r1 != r3 or r1 == r3 and r1 != r2 or r2 == r3 and r2 != r1:
print('Os segmentos acima podem formar um triângulo ISÓSCELES!')
else:
print('Os segmentos acima podem formar um triângulo ESCALENO!')
else:
print('Os segmentos acima NÃO PODEM FORMAR um triângulo!')
| false |
3eff06fb5f324102a352c5479e7654c650a37889 | ggsant/pyladies | /iniciante/Mundo 03/Anotações das Aulas e Desafios/Aula 01 - 16/Código 01 - Variáveis Compostas (Tuplas).py | 2,044 | 4.625 | 5 | """
Em Python, existem 3 tipos de Variáveis Compostas:
- Tuplas
- Listas
- Dicionários
Exemplo de Variável Simples:
lanche = 'Hambúrguer'
Exemplo de Tupla (Variável Composta):
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
Índices: [0] [1] [2] [3]
NOTA 1: As Tuplas são IMUTÁVEIS!
NOTA 2: Tuplas são identificadas por "()" (parênteses). Nas versões mais atuais do Python
nem é necessário colocar entre "()", mas facilita para melhor entendimento do código.
"""
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim') # Tupla "lanche"
print(lanche) # Exibe ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
# lanche[1] = 'Refrigerante' -> Comando impossível, pois tuplas são imutáveis
print(lanche[0]) # Exibe Hambúrguer
print(lanche[1]) # Exibe Suco
print(lanche[2]) # Exibe Pizza
print(lanche[3]) # Exibe Pudim
print(lanche[0:2]) # Exibe ('Hambúrguer', 'Suco')
print(lanche[1:3]) # Exibe ('Suco', 'Pizza')
print(lanche[1:]) # Exibe ('Suco', 'Pizza', 'Pudim')
print(lanche[:2]) # Exibe ('Hambúrguer', 'Suco')
print(lanche[-1]) # Exibe Pudim
print(lanche[-2]) # Exibe Pizza
print(lanche[-3:]) # Exibe ('Suco', 'Pizza', 'Pudim')
print(len(lanche)) # Exibe 4 (número de elementos de "lanche")
print(sorted(lanche)) # Exibe os elementos da tupla "lanche" em ordem alfabética, na forma de lista
# For 1 - Somente o elemento
for comida in lanche: # Para cada "comida" em "lanche"...
print(f'{comida}') # Exibe a "comida" atual
# For 2.1 - Elemento e posição com o comando "range"
for cont in range(0, len(lanche)): # Para cada número "cont" de 0 ao número de elementos em "lanche"...
print(f'{lanche[cont]} na posição {cont}') # Exibe o elemento na posição "cont" de "lanche" e o valor de "cont"
# For 2.2 - Elemento e posição com o comando "enumerate"
for pos, quecomida in enumerate(lanche): # Para cada posição "pos" e elemento "quecomida" em "lanche"...
print(f'{quecomida} na posição {pos}') # Exibe o elemento "quecomida" e a posição "pos" atuais
| false |
9b6d2756f155d00e494bca378f815e3d402fa183 | ggsant/pyladies | /iniciante/Mundo 01/Exercícios Corrigidos/Exercício 004.py | 625 | 4.21875 | 4 | """
EXERCÍCIO 004: Dissecando uma Variável
Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo
e todas as informações possíveis sobre ele.
"""
a = input('Digite algo: ')
print('O tipo primitivo deste valor é: {}'.format(type(a)))
print('Só tem espaços? {}'.format(a.isspace()))
print('É um número? {}'.format(a.isnumeric()))
print('É alfabético? {}'.format(a.isalpha()))
print('É alfanumérico? {}'.format(a.isalnum()))
print('Está em maiúsculas? {}'.format(a.isupper()))
print('Está em minúsculas? {}'.format(a.islower()))
print('Está capitalizada? {}'.format(a.istitle()))
| false |
6d9903259beb7949d75a5185baf5b55f9b03d620 | ggsant/pyladies | /iniciante/Mundo 03/Exercícios Corrigidos/Exercício 085.py | 617 | 4.15625 | 4 | """
EXERCÍCIO 085: Listas com Pares e Ímpares
Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha
separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.
"""
num = [[], []]
valor = 0
for c in range(1, 8):
valor = int(input(f'Digite o {c}º valor: '))
if valor % 2 == 0:
num[0].append(valor)
else:
num[1].append(valor)
print('-=' * 30)
num[0].sort()
num[1].sort()
print(f'Os valores pares digitados foram: {num[0]}')
print(f'Os valores ímpares digitados foram: {num[1]}')
| false |
37a815c2c1d1527a8076282283ee2e062ec7e7fc | ggsant/pyladies | /iniciante/Mundo 01/Anotações das Aulas e Desafios/Aula 08/Desafio 018.py | 412 | 4.125 | 4 | """
DESAFIO 018: Seno, Cosseno e Tangente
Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
"""
from math import radians, sin, cos, tan
a = float(input('Digite o ângulo para calcular: '))
ac = radians(a)
s = sin(ac)
c = cos(ac)
t = tan(ac)
print('\nO seno de {:.2f}º é {:.2f}, o cosseno é {:.2f}, e a tangente é {:.2f}!'.format(a, s, c, t))
| false |
b384b68fb81f39fc8df0971d86f4f286396812eb | RaviPrakashMP/Python-programming-practise | /S02AQ01.py | 364 | 4.3125 | 4 | #Using the starting and ending values of your car’s odometer,calculate its mileage
def MPG():
print("The car's miles-per-gallon is",MilesPerGallon,"miles/gallon")
MilesDriven = float(input("Enter the number of miles driven"))
GallonsofGasUsed = float(input("Enter the gallons of gas used"))
MilesPerGallon = MilesDriven/GallonsofGasUsed
MPG()
| true |
09dbb6868277a90c344002c48640bdd711d47c08 | indranilp/pythonprograms | /untitled/DataStructure/LinkedList1.py | 2,587 | 4.125 | 4 | class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def insert(self,item):
newnode = Node(item)
newnode.setNext(self.head)
self.head = newnode
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
list = ""
while (temp):
list = list + str(temp.data)
if temp.next != None:
list = list + "-->"
temp = temp.next
print(list)
def size(self):
temp = self.head
count = 0
while(temp):
count = count + 1
temp = temp.next
return count
def search(self,item):
temp = self.head
while(temp):
if(temp.data == item):
return True
temp = temp.next
return False
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current =current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def reverse(self):
current = self.head
previous = None
next = current.getNext()
while(current):
current.setNext(previous)
previous = current
current = next
if next:
next = next.getNext()
self.head = previous
# Function to reverse the linked list
def reverse1(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
class Node:
def __init__(self,initdata):
self.data =initdata
self.next = None
def getData(self):
return self.data
def setData(self,newdata):
self.data = newdata
def getNext(self):
return self.next
def setNext(self,newnext):
self.next = newnext
mylist = LinkedList()
print(vars(mylist))
print(mylist.isEmpty())
mylist.insert(85)
mylist.insert(5)
mylist.insert(20)
mylist.insert(15)
print(mylist.isEmpty())
mylist.printList()
print(mylist.size())
print(mylist.search(5))
mylist.remove(5)
print(mylist.search(5))
mylist.printList()
mylist.reverse1()
mylist.printList() | true |
2bfc0a72f50ab58c16a6084120afce6d119dce57 | dotonebit/Project-Euler | /Problem1.py | 458 | 4.3125 | 4 | """
Project Euler - Problem 1
Find the sum of all the multiples of 3 or 5 below 1000.
See: projecteuler.net/problem=1
"""
# Variable to hold the sum.
# Start at 0.
sum = 0
# Create a for loop to iterate through numbers up to 1000.
# Write a condition to test if the number is a multiple of 3 or 5.
# If the condition is true, add the number to the sum.
for n in range(1000):
if n % 3 == 0 or n % 5 == 0:
sum += n
# Print the sum.
print(sum)
| true |
1ad6a96104d6ef45d2553469898fbdaa43064692 | AarjuGoyal/Python_Beginner_Projects | /Inheritance.py | 990 | 4.3125 | 4 | """A program about basics of Inheritance and Classes"""
class Parent():
def __init__(self, last_name_parent, eye_colour_parent):
print "Parent constructor called"
self.last_name = last_name_parent
self.eye_colour = eye_colour_parent
def print_info(self):
print( "Last Name " + self.last_name)
print("Eye Colour " + self.eye_colour)
class Child(Parent):
def __init__(self, last_name_parent, eye_colour_parent, number_of_toys_child):
print "child constructor called"
Parent.__init__(self, last_name_parent, eye_colour_parent)
self.number_of_toys = number_of_toys_child
def print_info(self):
print( "Last Name " + self.last_name)
print( "Eye colour " + self.eye_colour)
print( "Number Of toys " + str(self.number_of_toys) )
billy_cyrus = Parent("cyrus", "blue")
billy_cyrus.print_info()
miley_cyrus = Child("cyrus", "blue", 5)
miley_cyrus.print_info()
| false |
e674fb10b6d248101826c548402dddc7afa03475 | nithinreddykommidi/pythonProject | /PYTHON_WORLD/1_PYTHON/11_IMP_small_topics/2_map.py | 414 | 4.34375 | 4 | '''
1. map is used to do operation on each iterable value and it will return all operations result in map object foramt.
2. Map taks two parameters one is function another one is iterable object
'''
## Map with def fucntion
def add(a):
return a + 10
#mo = map(add, (1,2,3,4,5,6))
#print(list(mo))
## Map with lambda function
mo = map(lambda a, b: a + b ,[1,2,3,4,5,6], [10,20,30,40])
print(tuple(mo))
| true |
bfa46658fbe62bd80cc9e3ac3588d19f6be1926d | nithinreddykommidi/pythonProject | /PYTHON_WORLD/1_PYTHON/1_DATA_TYPES/3_Variable_operations/2_list_operations.py | 802 | 4.25 | 4 | l = [1,2,3]
l2 = ['A','B','C']
# To add new value into list it will add in end of the list
l.append(4)
# To add new value based on index
l.insert(2, 99)
# To appends the values of sequence to list
l.extend(l2)
print(l)
# clear is used to remove all the values in a list
l.clear()
print(l)
# copy is used to copy all the values into another varibale
l3 = l2.copy()
print(l3)
# pop is used to remove value bases on index if you don't give any index it will remove last value
l3.pop(0)
print(l3)
# remove is used to delete values bases on value
l3.remove('B')
# to reverse a total list values
l3.reverse()
print(l3)
# to sort a list in ascending order
sl = [3,5,9,2,1,7]
sl.sort()
print(sl)
# to sort a list in descending order
sl = [3,5,9,2,1,7]
sl.sort(reverse=True)
print(sl)
| true |
3f304bcd57ff727e2c7311bb1fd8611914ff70b8 | nithinreddykommidi/pythonProject | /PYTHON_WORLD/1_PYTHON/11_IMP_small_topics/6_list_comprehesion.py | 435 | 4.34375 | 4 | '''
Using list comprehensions we can do loop operations inside a square brackets.
List comprehensions are used for creating new list from another iterables.
'''
l = [1, 2, 3, 4]
## Basic list comprehension
#r = [ n + 10 for n in l]
#print(r)
## list comprehension with if condition
#r = [n + 2 for n in l if n > 2]
#print(r)
## list comprehension with if and else condition
r = [n + 100 if n > 2 else n + 10 for n in l]
print(r)
| true |
b3443b5ba91d5e4856004640241506d836dceef5 | nithinreddykommidi/pythonProject | /PYTHON_WORLD/1_PYTHON/3_Loops/4_loop_statments.py | 521 | 4.25 | 4 | '''
3. Loop statements
1. break ==> break is used to terminates the loop
2. continue ==> continue is used to skipe the current iteration
3. pass ==>
1. pass will do nothing
2. we use pass when statement is require to aviod syntax issues.
'''
for i in range(4, 8):
print(i)
if i > 4 : break
for i in range(4):
if i : continue
print(i)
for i in range(6):
if i >= 4 : continue
print(i)
if i == 2 : break
for i in range(5):
pass
#if 2 == 2: break
| true |
34e783a76b2157641d13fa8bd880dd2b48583240 | edwinkim16/Password-locker | /password_test.py | 2,829 | 4.28125 | 4 | import unittest # importing unittest module
from Password_Locker import Password
class TestPassword(unittest.TestCase):
"""
Here is where we will perfome all our test
"""
def setUp(self):
"""
This function will create a new instance password before each test
"""
self.new_password = Password("twitter", "edwin", "2021")
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_password.account,"twitter")
self.assertEqual(self.new_password.username,"edwin")
self.assertEqual(self.new_password.password,"2021")
def tearDown(self):
"""
Here will be clearing password after every test to avoid confusion
"""
Password.password = []
def test_new_pass(self):
"""
Here will test if a new password is initiated correctly
"""
self.assertEqual(self.new_password.account, "twitter")
self.assertEqual(self.new_password.username, "edwin")
self.assertEqual(self.new_password.password, "2021")
def test_save_new_password(self):
"""
Here it will check weather the new password is added in the list
"""
self.new_password.save_password()
self.assertEqual(len(Password.password_list), 1)
def test_add_generate_password(self):
"""
This will check if the new password added to the list
"""
new_password = Password("facebook", "2021", Password.generate_(6))
new_password.save_password()
self.assertEqual(len(Password.password))
def test_display_password(self):
"""
Here it checks weather the display_Password function will return the password in the password list
"""
def save_password(self):
self.new_password.save_password()
new_pass = Password("facebook", "2021")
new_pass.save_password()
self.assertEqual(len(Password.password),
len(Password.display_passwords()))
def test_delete(self):
"""
This test will check whether the password gets deleted from the passwords list
"""
self.new_password.save_password()
new_password = Password("facebook", "2021")
new_password.save_password()
Password.delete_password("instagram")
self.assertEqual(len(Password.password_list), 1)
def test_password_exist(self):
"""
This will check whether the password_exists function works
"""
self.new_password.save_password()
self.assertTrue(Password.password_exist("instagram"))
if __name__ == "__main__":
unittest.main() | true |
99cff3945a0d9a7213e625d15854b640fb8cca06 | Ursinus-IDS301-S2020/Week10Class | /NearestNeighbors2D.py | 1,266 | 4.46875 | 4 | """
The purpose of this code is to show how to use the
nearest neighbor class as part of the scikit-learn
library, which is a faster way of finding k-nearest neighbors
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import NearestNeighbors
# We first setup the points exactly as we did in
# the naive example
N = 100
X = np.random.randn(N*2, 2)
X[100::, :] += np.array([10, 10])
# Query point, which now has to be put along
# the row of a 2D array
q = np.array([[3, 3]])
# The code to perform nearest neighbors
n_neighbors = 10
# First we create the nearest neighbors object
nbrs = NearestNeighbors(n_neighbors=n_neighbors)
# Then we "train" it on the points in X
nbrs.fit(X)
# Now we're ready to query the nearest neighbors
# object with a particular point, which returns
# both the distances and indices of the k-nearest
# neighbors in parallel arrays, so we don't
# need to use argsort anymore
distances, neighbors = nbrs.kneighbors(q)
distances = distances.flatten()
neighbors = neighbors.flatten()
plt.figure(figsize=(8,8))
plt.scatter(X[:, 0], X[:, 1])
plt.scatter(q[0, 0], q[0, 1], 40, marker='x')
# Plot ten nearest neighbors
print(neighbors)
plt.scatter(X[neighbors, 0], X[neighbors, 1], 100, marker='*')
plt.show() | true |
2ddd848aa532a1c245c99e8f9b8276c206670a1d | Kor-KTW/PythonWorkSpace | /Basic/8_1_Class.py | 1,170 | 4.125 | 4 | # marine : asult unit, soldier, use gun
marine_name = "marine"
marine_hp = 40
marine_damage = 5
print("{0} unit is created".format(marine_name))
print("hp {0}, damage {1}\n".format(marine_hp, marine_damage))
tank_name = "tank"
tank_hp = 150
tank_damage = 35
tank2_name = "tank"
tank2_hp = 150
tank2_damage = 35
print("{0} unit is created".format(tank_name))
print("hp {0}, damage {1}\n".format(tank_hp, tank_damage))
print("{0} unit is created".format(tank2_name))
print("hp {0}, damage {1}\n".format(tank2_hp, tank2_damage))
def attack(name, location, damage):
print("{0} : {1} 방향으로 적군을 공격합니다. [공격력 {2}]".format(name, location, damage))
attack(marine_name, "1시", marine_damage)
attack(tank_name, "1시", tank_damage)
#using class
print("-------------using class-------------")
class Unit:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
print("{0} unit is created".format(self.name))
print("hp {0}, damage {1}\n".format(self.hp, self.damage))
marine1 = Unit("Marine", 40, 5)
marine2 = Unit("Marine", 40, 5)
tank1 = Unit("Tank", 150, 35)
| false |
8a640aea1fbb1f13a80bc7192f1de1995cc59a85 | Kor-KTW/PythonWorkSpace | /Basic/5_1_if.py | 443 | 4.28125 | 4 | weather = input("how is the weather? ")
if weather== "rain" or weather=="snow" or weather=="cloudy":
print("take your umbrella")
elif weather == "fine dust warning" :
print("take your mask")
else :
print("have a nice day. nothing to prepare")
temp = int(input("what is temperature?"))
if 30<=temp:
print("too hot, don't go outside")
elif 10<=temp:
print("take your jaket")
else:
print("too cold, don't go outside")
| true |
d57fed4b14393e9fe76e69495670dc9b953d8f83 | tashvit/beginner_python_problems | /11_unit_conv.py | 2,891 | 4.5 | 4 | # Converts various units between one another.
# The user enters the type of unit being entered,
# the type of unit they want to convert to and then the value.
# The program will then make the conversion.
# temp, currency, volume
# List of units
units = ["temperature", "currency", "volume"]
def get_user_input():
"""Function to get user input"""
print("Convert units between one another.")
input_unit = None
while input_unit not in units:
input_unit = input("Pick type of unit to convert.\n"
"(Temperature, Currency, Volume, Mass, Length)\n : ").lower()
return input_unit
def temperature():
"""
Function to convert temperature units
Celsius/Fahrenheit
"""
temp_unit = None
while (temp_unit != "1") and (temp_unit != "2"):
temp_unit = input("Celsius -> Fahrenheit. Enter 1.\n"
"Fahrenheit -> Celsius. Enter 2.\n : ")
while True:
try:
temp_value = int(input("Enter value to be converted: "))
except ValueError:
print("Input must be a number")
else:
break
if temp_unit == "1":
return f"{temp_value} Celsius = {(temp_value * 9/5) + 32} Fahrenheit"
else:
return f"{temp_value} Fahrenheit = {(temp_value - 32) * 5/9} Celsius"
def currency():
"""
Function to convert currency units
USD/GBP
"""
currency_unit = None
while (currency_unit != "1") and (currency_unit != "2"):
currency_unit = input("Dollar -> Pound. Enter 1.\n"
"Pound -> Dollar. Enter 2.\n : ")
while True:
try:
currency_value = int(input("Enter value to be converted: "))
except ValueError:
print("Input must be a number")
else:
break
if currency_unit == "1":
return f"{currency_value} dollars = {currency_value * 0.78} pounds"
else:
return f"{currency_value} pounds = {currency_value * 1.28} dollars"
def volume():
"""
Function to convert volume units
Litres/Millilitres
"""
volume_unit = None
while (volume_unit != "1") and (volume_unit != "2"):
volume_unit = input("Litres -> Millilitres. Enter 1.\n"
"Millilitres -> Litres. Enter 2.\n : ")
while True:
try:
volume_value = int(input("Enter value to be converted: "))
except ValueError:
print("Input must be a number")
else:
break
if volume_unit == "1":
return f"{volume_value} Litres = {volume_value * 1000} Millilitres"
else:
return f"{volume_value} Millilitres = {volume_value / 1000} Litres"
user_unit = get_user_input()
if user_unit == units[0]:
print(temperature())
if user_unit == units[1]:
print(currency())
if user_unit == units[2]:
print(volume())
| true |
85de214b772324e76aabfa22c0c6c8ac9126e31b | shivam2509/hacktoberfest2020-basics-of-pyhton | /program4.py | 464 | 4.15625 | 4 | print('To find all the Prime numbers between any Two number')
lower = int(input('Enter the Prime number between '))
upper = int(input('and '))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
print("HELLO WORLD")
| true |
03bbfec20c9923e411cf6816436f501a07d05b98 | marleydebrah/python | /idle python - pay.py | 619 | 4.34375 | 4 | #Create variables
hourly_rate = float(input("how much do you earn per hour?"))
hours_worked = int(input("please enter number of hours you have worked this week?"))
#Calculate wages based on hourly_rate and hours_worked
weekly_pay = hourly_rate * hours_worked
weekly_pay *= 0.8
annual_pay = weekly_pay * 52
#Print the result
print("your weekly income is {}" .format(weekly_pay))
print("your annual income is {}" .format(annual_pay))
#Add if/else statements based around results
if annual_pay <=34000:
print("you have a low income")
elif annual_pay <=50000:
print("you have a medium income")
| true |
d703d478207044e77b8eea2e0fa93cb3d2c9e01b | qcgm1978/py-test | /test/AlgorithmDesign/sorting.py | 2,208 | 4.125 | 4 | def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Find the middle point and devide it
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return merge(left_list, right_list)
# Merge the sorted halves
def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
def insertion_sort(InputList):
ret=InputList.copy()
for i in range(1, len(ret)):
j = i-1
nxt_element = ret[i]
# Compare the current element with next one
while (ret[j] > nxt_element) and (j >= 0):
ret[j+1] = ret[j]
j=j-1
ret[j + 1] = nxt_element
return ret
def shellSort(input_list):
ret=input_list.copy()
gap = len(ret) // 2
while gap > 0:
for i in range(gap, len(ret)):
temp = ret[i]
j = i
# Sort the sub list for this gap
while j >= gap and ret[j - gap] > temp:
ret[j] = ret[j - gap]
j = j-gap
ret[j] = temp
# Reduce the gap for the next element
gap = gap // 2
return ret
def selection_sort(input_list):
ret=input_list.copy()
for idx in range(len(ret)):
min_idx = idx
for j in range( idx +1, len(ret)):
if ret[min_idx] > ret[j]:
min_idx = j
# Swap the minimum value with the compared value
ret[idx], ret[min_idx] = ret[min_idx], ret[idx]
return ret | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.