blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a856fb36597912de35ac0cbce90aadb781d63599 | bria051/Game | /Tic_tac_toe/choose.py | 345 | 4.21875 | 4 | def choosing():
print("Choose O or X to play the Game:")
while (True):
user = input()
if (user == 'O'):
computer = 'X'
break
elif (user == 'X'):
computer = 'O'
break
else:
print("You chose the wrong one. Choose again")
return user,computer
| true |
881c561f1e8ca930a70a4c7a35be7df48b8bbc04 | jiuash/python-lessons-cny | /code-exercises-etc/section_04_(lists)/ajm.lists01_attendees.20170218.py | 983 | 4.125 | 4 | ##things = []
##print things
attendees = ['Alison', 'Belen', 'Rebecca', 'Nura']
#print attendees
print attendees[0]
##name = 'Alison'
##print name[0]
print attendees[1:3]
print attendees[:3]
#print attendees[4]
#print len(attendees)
number_of_attendees = len(attendees)
print number_of_attendees
attendees.append("Andrea")
print attendees
##print "\n\n\n"
## oh by the way, our list can contain a mix of strings and numbers!
##attendees.append(4)
##print attendees
## change the first peron's name to be spelled wrong
##print attendees[0]
##attendees[0] = "Allison"
##print attendees
attendees.insert(2, "Samantha")
print attendees
#### a list of numbers! just to see it a different way ####
attendees_ages = []
print attendees_ages
print len(attendees_ages)
attendees_ages.append(28)
print attendees_ages
print len(attendees_ages)
attendees_ages.append(27)
print attendees_ages
print len(attendees_ages)
attendees_ages[0] = attendees_ages[0] + 1
print attendees_ages
| true |
495f7f47477d142d149095c3c84906575ab22bdd | Austin306/Python-Assessment | /prob2.py | 704 | 4.3125 | 4 | def comparator( tupleElem ) :
'''This function returns last element of tuple'''
return tupleElem[1]
def main():
'''This function takes the tuple as input and sorts it'''
final_list = []
lines = input('Enter the list of tuples separated by , : ')
for tup in lines.split('),('):#This For Loop is used to obtian the tuble from entered list
tup = tup.replace(')','').replace('(','')
final_list.append(tuple(tup.split(',')))
print('The Entered List of tuples is: ')
print(final_list)#Display unsorted list
final_list.sort(key=lambda elem: elem[1])#Sort the tuples based on last element
print('The Sorted List of Tuples is')
print(final_list)
main()
| true |
bcf6cc01615591b36df9c3822ae51821c684d6ff | nicholaskarlson/Object-Oriented-Programming-in-Python | /off day.py | 2,170 | 4.125 | 4 | # creating a class of my class.
class Science:
form ="c"
num_student=0
def __init__(self,name,college_num,fav_sub):
self.name=name
self.college_num=college_num
self.fav_sub=fav_sub
Science.num_student+=1
def introduce(self):
print(f"Hey! I am {self.name}.My form is {self.form} and college number is {self.college_num}. I like {self.fav_sub} most.")
def change_sub(self,sub):
self.fav_sub=sub
print("My favourite subject is {} now!".format(self.fav_sub))
@classmethod
def change_form(emp,form):
emp.form=form
print("Science C is now become Science {} ".format(emp.form))
@staticmethod
def school_day(day):
if day.weekday==5 or day.weekday==6:
return False
else:
return True
def __add__(self,other):
return self.college_num+other.college_num
def __len__(self):
return len(self.name)
@property
def print_name(self):
print(self.name)
@print_name.setter
def print_name(self,name):
self.name=name
print(self.name)
@print_name.deleter
def print_name(self):
self.name=None
class Hater_mkj(Science):
def __init__(self,name,college_num,fav_sub,hate):
super().__init__(name,college_num,fav_sub)
self.hate=hate
def prove(self):
if self.hate:
print("MKJ is the worst teacher in the world. Piss on you!")
else:
print("I think MKJ and ME both are foolish :(")
student1=Science("Shawki",5130,"Math")
student2=Science("Hasnine",5150,"Chemistry")
student3=Science("Arko",5162,"Math")
student4=Science("Mahidul",5139,"Physics")
student5=Science("Abir",5169,"eating")
student6=Hater_mkj("Anonymus",0000,"not chemistry",False)
student1.introduce()
student2.introduce()
student5.introduce()
print()
student3.change_sub("Physics")
print(student1.form)
print(student2.form)
print(Science.form)
student6.introduce()
student6.prove()
print(student1+student2)
print(len(student1))
student1.print_name
student1.print_name="New_name"
del student1.print_name
student1.print_name | true |
537a10b2964afb6cbecdce161536769f24eb410f | sokuro/PythonBFH | /03_Exercises/Stings/06_SplitStringDelimiter.py | 278 | 4.28125 | 4 | """
split a string on the last occurrence of the delimiter
"""
str_input = input('Enter a String: ')
# create a list from the string
temp_list = list(str_input)
int_input = int(input('Enter a Number of split Characters: '))
print(str(temp_list).rsplit(',', int_input))
| true |
3fc66aa0b3bde5ee6a7d3bafdeb6bab46f0c926e | sokuro/PythonBFH | /01_Fundamentals/Strings/Exercises/04_IsString.py | 344 | 4.40625 | 4 | """
get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
"""
def IsString(str):
if len(str) >= 2 and str[:2] == 'Is':
return str
else:
return 'Is' + str
print(IsString("Testing"))
print(IsString("IsTesting"))
| true |
c8c32cfec48b1307d4b5156bbe8881d0303063d0 | sokuro/PythonBFH | /01_Fundamentals/Lists/Lists.py | 477 | 4.125 | 4 | """
* Lists are MUTABLE ordered sequence of items
* Lists may be of different type
* [] brackets
* Expressions separated by a comma
"""
list1 = [1, 2.14, 'test']
list2 = [42]
list3 = [] # empty list
list4 = list() # empty list
# ERROR
# list5 = list(1, 2, 3)
# Solving
list6 = list((1, 2, 3)) # List out of the Tuple
print(list1) # >> [1, 2.14, 'test']
print(list2) # >> [42]
print(list3) # >> []
print(list4) # >> []
print(list6) # >> [1, 2, 3]
| true |
286f659c944c2744440dcdf9b3ffba55d4e4b1c1 | sokuro/PythonBFH | /01_Fundamentals/Sort/01_Sort.py | 414 | 4.21875 | 4 | """
sort(...)
L.sort(key=None, reverse=False)
"""
# List of Names
names = ["Karol", "Rebeca", "Daniel", "Michael", "Patrik", "Richard"]
# sort alphabetically
names.sort()
print(names)
# sort reversed
names.sort(reverse=True)
print(names)
# Tuple of Names
names_tuple = ("Karol", "Rebeca", "Daniel", "Michael", "Patrik", "Richard")
# names_tuple.sort() # ERROR: Tuples are not mutable!
| true |
da46590dcb44a879d75f9ebe34eeb043545760c8 | nithin-kumar/urban-waffle | /LucidProgramming/paranthesis_balance_stack.py | 551 | 4.15625 | 4 | from stack import Stack
def is_balanced(expression):
stack = Stack()
for item in expression:
if item in ['(', '[', '{']:
stack.push(item)
else:
if is_matching_paranthesis(stack.peek(), item):
stack.pop()
else:
return False
if not stack.is_empty():
return False
return True
def is_matching_paranthesis(p1, p2):
if p1 == '(' and p2 == ')':
return True
elif p1 == '[' and p2 == ']':
return True
elif p1 == '{' and p2 == '}':
return True
return False
if __name__ == '__main__':
print is_balanced("()[]{{(())}")
| true |
abcbb6f7a02de5de2d19df7a96a2fa018d2d1985 | nithin-kumar/urban-waffle | /InterviewCake/max_product_3.py | 699 | 4.125 | 4 | import math
def highest_product_of_3(list_of_ints):
# Calculate the highest product of three numbers
if len(list_of_ints) < 3:
raise Exception
return
window = [list_of_ints[0], list_of_ints[1], list_of_ints[2]]
min_number = min(window)
min_index = window.index(min_number)
prod = reduce(lambda x, y: x*y, window)
for i in range(3, len(list_of_ints)):
if list_of_ints[i] > min_number:
window[min_index] = list_of_ints[i]
min_number = min(window)
min_index = window.index(min_number)
prod = max(prod, reduce(lambda x, y: x*y, window))
return prod
print highest_product_of_3([-10, 1, 3, 2, -10]) | true |
a8798d0623136431334ef7e791b6b5cd2a81e187 | nachobh/python_calculator | /main.py | 1,064 | 4.1875 | 4 | def compute(number1, operation, number2):
if is_number(number1) and "+-*/^".__contains__(operation) and is_number(number2):
result = 0
if operation == "+":
result = float(number1) + float(number2)
elif operation == "-":
result = float(number1) - float(number2)
elif operation == "*":
result = float(number1) * float(number2)
elif operation == "/":
result = float(number1) / float(number2)
elif operation == "^":
result = pow(float(number1), float(number2))
print(number1 + " " + operation + " " + number2 + " = " + format(result, ".2f"))
else:
print("Error, some character is not ok")
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
if __name__ == '__main__':
input_a = input("First number? ")
input_b = input("Operation (+, -, /, *, ^)? ")
input_c = input("Second number? ")
compute(input_a, input_b, input_c)
| true |
a1b1b2983bf4721f26de6b1cf85468509703bc46 | SjorsVanGelderen/Graduation | /python_3/features/classes.py | 1,010 | 4.125 | 4 | """Classes example
Copyright 2016, Sjors van Gelderen
"""
from enum import Enum
# Enumeration for different book editions
class Edition(Enum):
hardcover = 0
paperback = 1
# Simple class for a book
class Book:
def __init__(self, _title, _author, _edition):
self.title = _title
self.author = _author
self.edition = _edition
print("Created book {} by {} as {}".format(self.title, self.author, self.edition))
# Simple class for an E-reader
class E_Reader:
def __init__(self, _model, _brand, _books):
self.model = _model
self.brand = _brand
self.books = _books
print("Created E-reader {} by {} containing {}".format(self.model, self.brand, self.books))
# Main program logic
def program():
kindle = E_Reader("Kindle", "Amazon", [Book("1984", "George Orwell", Edition.hardcover)])
kobo = E_Reader("Aura", "Kobo", [
Book("Dune", "Frank Herbert", Edition.hardcover),
Book("Rama", "Arthur Clarke", Edition.paperback)
])
program()
| true |
6a33fc24a8ebcbae955ef6e91e6cd5f6d918596c | ankit1765/Hangman-and-other-fundamental-programs | /HIghScores.py | 700 | 4.15625 | 4 | #This program asks is a high score displayer.
#It asks the user how many entries they would like to input
#and how many top scores it should display
scores = []
numentries = int(raw_input("How many entries would you like to Enter? "))
numtop = int(raw_input("How many top scores would you like to display? "))
count = 1
while count <= numentries:
name = raw_input("\nEnter the name: ")
score = int(raw_input("Enter their scrore: "))
entry = score, name
scores.append(entry)
count += 1
scores.sort(reverse=True)
scores = scores[0:numtop]
print"\t\t\tTOP", numtop, "\tSCORES\n"
print "\t\t\tPLAYER\tSCORE"
for entries in scores:
s, p = entries
print "\t\t\t",p,"\t",s
| true |
0ee0d2873e2aec1ab8e74319127281ac81eb79c6 | Arween/PythonMIT-lessons | /Lecture-test/lect2_t2.py | 753 | 4.25 | 4 | outstandingBalance = float(raw_input("Enter the outstanding balance on your credit card: "));
interestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "));
monthlyPayment = 0;
monthlyInterestRate = interestRate/12;
balance = outstandingBalance;
while balance > 0:
monthlyPayment += 10;
balance = outstandingBalance;
numMonths = 0;
while numMonths < 12 and balance > 0:
numMonths += 1;
interest = monthlyInterestRate * balance;
balance -= monthlyPayment;
balance += interest;
balance = round(balance, 2);
print "RESULT";
print "Monthly payment to pay off debt in 1 year: ", monthlyPayment;
print "Number of months need: ", numMonths;
print "Balance: ", balance; | true |
646d6816429c5dac188fd8693ffb4406aa57e752 | aamartinez25/effective-system | /cpu.py | 1,482 | 4.1875 | 4 | #
#Author: Adrian Martinez
#Description: takes a few inputs on CPU specs and organizes them accordingly
#
#
cpu_ghz = float(input('Enter CPU gigahertz:\n')) #input for CPU specs
cpu_core = int(input('Enter CPU core count:\n'))
cpu_hyper = input('Enter CPU hyperthreading (True or False):\n')
print()
if cpu_core >= 20:
print('That is a high-performance CPU.')
exit(0)
if (cpu_hyper == "True") or (cpu_hyper == 'true'): #setting bool for hyperthreading spec
cpu_hyper = True
elif (cpu_hyper == 'False') or (cpu_hyper == 'false'):
cpu_hyper = False
else:
print('Please enter True or False for hyperthreading')
exit(0)
if cpu_hyper: #CPUs with hyperthreading
if (cpu_ghz >= 2.7) and (cpu_core >= 6):
print ('That is a high-performance CPU.')
exit(0)
elif (cpu_ghz >= 2.4) and (cpu_core >= 4):
print('That is a medium-performance CPU.')
exit(0)
elif (cpu_ghz >= 1.9) and (cpu_core >= 2):
print('That is a low-performance CPU.')
exit(0)
else: #CPUs without hyperthreading
if (cpu_ghz >= 3.2) and (cpu_core >= 8):
print('That is a high-performance CPU.')
exit(0)
elif (cpu_ghz >= 2.8) and (cpu_core >= 6):
print('That is a medium-performance CPU.')
exit(0)
elif (cpu_ghz >= 2.4) and (cpu_core >= 2):
print('That is a low-performance CPU.')
exit(0)
# everything else
print('That CPU could use an upgrade.') | true |
9a576e7335c48f855798d6c1e42d8be4da138fd5 | niksanand1717/TCS-434 | /03 feb/solution_2.py | 499 | 4.15625 | 4 | num1 = eval(input("Enter the first number: "))
num2 = eval(input("Enter the second number: "))
count1, count2 = 0, 0
print("\n\nNumbers divisible by both 3 and 5")
for num in range(num1, num2+1):
if num%3 == 0 and num%5 == 0:
print(num)
count1+= 1
print("Total numbers of numbers:",count1)
print("\n\nNumbers divisible by 3 or 5")
for num in range(num1, num2+1):
if num%3 == 0 or num%5 == 0:
print(num)
count2+=1
print("Total numbers of numbers:",count2) | true |
360b2dba16714f2e2fee62d85537d49faefab8c1 | niksanand1717/TCS-434 | /28 april/fourth.py | 292 | 4.34375 | 4 | """Input a string and return all the words starting with vowels"""
import re
pattern = '^[aeiou]'
str1 = input("enter string: ")
print("Following are the words in entered string starting with vowel: ", end=' ')
[print(word, end=' ') for word in str1.split(" ") if re.match(pattern, word)] | true |
e3c9452a5563afe71101af97ced7f3834d042b83 | niksanand1717/TCS-434 | /28 april/first.py | 276 | 4.5 | 4 | """Print all the words from a string having length of 3"""
import re
pattern = '(...)$'
input_data = input("input string: ")
print("Following are the words which have length 3: ")
for words in input_data.split(" "):
if re.match(pattern, words): print(words, end=" ")
| true |
d448f3cebeff50b9eb66a2d1749d703c7a4f635e | farmani60/coding_practice | /topic10_bigO/log_n.py | 1,147 | 4.15625 | 4 | """
Logarithmic time complexities usually apply to algorithms
that divide problems in half every time.
If we implement (Algorithm A) going through all the elements
in an array, it will take a running time of O(n). We can try
using the fact that the collection is already sorted.
Later, we can divide in half as we look for the element in
question. O(log(n))
"""
def binarySearch(arr, element, offest=0):
middle = len(arr) // 2
current = arr[middle]
if current == element:
return middle + offest
elif element > current:
right = arr[middle:]
return binarySearch(right, element, offest+middle)
else:
left = arr[:middle]
return binarySearch(left, element, offest)
arr = [1, 3, 5, 6, 8, 9, 10, 13, 15]
print(binarySearch(arr, 1))
def binarySearch(arr, element, offset=0):
middle = len(arr) // 2
current = arr[middle]
if element == current:
return middle + offset
elif element > current:
right = arr[middle:]
return binarySearch(right, element, offset+middle)
else:
left = arr[:middle]
return binarySearch(left, element, offset) | true |
0f8fe20a3d49ce95591f9d9c46dd57d17e007866 | nomatterhowyoutry/GeekPython | /HT_1/Task6.py | 263 | 4.28125 | 4 | # 6. Write a script to check whether a specified value is contained in a group of values.
# Test Data :
# 3 -> [1, 5, 8, 3] : True
# -1 -> (1, 5, 8, 3) : False
list = [1, 5, 8, 3]
tuple = tuple(list)
print(3 in list)
print(-1 in tuple) | true |
96819f1bdd9469451af6089d77a9c6a979709856 | vanTrant/py4e | /ex3_try_exec/script.py | 361 | 4.1875 | 4 | # hours = input('Enter Hours: ')
# rate = input('Enter Rate: ')
try:
hours = float(input('Enter Hours: '))
rate = float(input('Enter Rate: '))
except:
print('Please enter a valid number')
quit()
if hours > 40:
overtime_pay = (hours - 40) * (rate * 1.5)
pay = 40 * rate + overtime_pay
else:
pay = hours * rate
print('Pay: ', pay)
| true |
d5b0514e7c3e53f7f1bf6ec53717c79f81325591 | yevgenybulochnik/lp3thw | /ex03/drill1.py | 859 | 4.375 | 4 | # Simple print statement that prints a string
print("I will count my chickens:")
# Prints a string then divides 30 by 6 then adds 25
print("Hens", 25 + 30 / 6)
# Prints a string then gives you the remainder of 75/3 or 3 and subtracts from 100
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
# 4/2 remainder = 0, total adds up to 6.75
print(3 + 2 + 1 - 5 + 4 % 2 -1 / 4 + 6)
# Prints a string
print("Is it true that 3 + 2 < 5 - 7?")
# false statement
print(3 + 2 < 5 - 7)
# string plus result of 3 add 2
print("What is 3 + 2?", 3 + 2)
# string plus result of 5 subtract 7
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
# Returns true
print("Is it greater?", 5 > -2)
# Returns true
print("Is it greater or equal?", 5 >= -2)
# Returns false
print("Is it less or equal?", 5 <= -2)
| true |
8905a8a1c3bd892fef8604ff4e1c8741c730654a | PaulSweeney89/squareroot | /sqrt_test.py | 830 | 4.3125 | 4 | # defining a fuction to calculate the square root of a positive real number
# using Newton's method (ALTERNATIVE)
while True:
A = float(input("Please input positive value "))
if A > 0:
break
else:
print(A, " is a negative value")
continue
def sqrt(A):
x = 1
for n in range(0, 10): # using a for loop with 10 iterations
f1 = (x * x - A)
f2 = 2 * x
x = (x - (f1 / f2))
n = n + 1
if f1 == 0:
break
return (x)
ans = sqrt(A)
print("The square root of ", A , "is ", ans)
| true |
0ad794722abfb826b414f7d7eeb51f6b59293c5f | ljsauer/DS-From-Scratch | /Notes/Chapter 4.py | 1,188 | 4.375 | 4 | """Linear Algebra:
the branch of math that deals with vector spaces
"""
#
# Vectors - objects that can be added together to form new vectors,
# and that can be multiplied by scalars; points in some
# finite-dimensional space
from typing import List
Vector = List[float]
height_weight_age = [70, # inches
170, # pounds
40] # years
grades = [95, # exam 1
80, # exam 2
75, # exam 3
62] # exam 4
# Python lists *aren't* vectors, so we need to build our own tools
# Zip the vectors together and use list comprehension to perform
# arithmetic operations on them:
def add(v: Vector, w: Vector) -> Vector:
"""Adds corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i + w_i for v_i, w_i in zip(v, w)]
assert add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
def subtract(v: Vector, w: Vector) -> Vector:
"""Subtracts corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i - w_i for v_i, w_i in zip(v, w)]
assert subtract([5, 7, 9], [4, 5, 6]) == [1, 2, 3]
| true |
6b997548a37e7a761a789a4b44df67cfa69651d8 | blainekuhn/Python | /Reverse_text.py | 255 | 4.15625 | 4 | def reverse(text):
word = [text]
new_word = ""
count = len(text) - 1
for letter in text:
word.insert(0, letter)
for a in range(len(word) - 1):
new_word = new_word + word[a]
return new_word
print reverse("This is my text to reverse")
| true |
494d979b41757904cbcc0e9f10a6adfb0d5132f2 | Gopi3998/UPPERCASE-AND-LOWERCASE | /Uppercase and Lowercase...py | 527 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print('Starting the program for count the upper and lower case'.center(80,'*'))
sample = input('enter string: ')
uppercase = 0
lowercase = 0
for ch in sample:
if str .isupper(ch):
uppercase+=1
elif str.islower(ch):
lowercase+=1
print('No of uppercase character..',uppercase)
print('No of lowercase character..',lowercase)
print("THE END".center(80,'*'))
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
6e9034990271d7ed4549663f9d537dd7ac8f6a86 | Veletronic/Farmville | /Sheep_class.py | 1,217 | 4.125 | 4 | from Animal import *
class Sheep(Animal): #Cow inherits from Animal
"""A sheep"""
#Constructor
def __init__(self):
#Call the parent class constructor with default value
#Growth rate =1; food requirement = 3; water requirement = 3
super().__init__(1,3,3)
self._type = "Sheep" #basic sub-class
#Overrides growth method for subclasses
def grow(self,food,water):
if food>= self._food_req and water >= self.water_req:
if self._status == "infant" and water > self._water_req:
self._growth += self._growth_r8
elif self._status == "Young" and water >self._water_req:
self._growth += self._growth_r8 * 1.25
else:
self._growth += self._growth_r8
#Increments days
self._days_growing += 1
#Status update
self._update_status()
def main():
#Creates sheep
sheep_animal = Sheep()
print(sheep_animal.report())
#manually grows
manual_grow(sheep_animal)
print(sheep_animal.report())
if __name__ == "__main__":
main()
| true |
14025dd27c8f83cf0fed8b4cfea0c76badea0319 | sarahovey/AnalysisOfAlgos | /hw1/mergesort.py | 1,995 | 4.15625 | 4 | #Sort
#Merge Sort
def merge_sort(numbers):
#Divide the list into halves recursively
if len(numbers) > 1:
#get midpoint of list
mid = len(numbers)/2
left = numbers[:mid]
right = numbers[mid:]
merge_sort(left)
merge_sort(right)
#index variables
i = 0 #left half
j = 0 #right half
k = 0 #final numbersay
#Sorting
#Make sure that the index falls in the bounds of the respective halves
while i < len(left) and j < len(right):
if left[i] < right[j]:
numbers[k] = left[i]
#increment
i=i+1
else:
numbers[k] = right[j]
j += 1
k +=1
#Merging
while i < len(left):
numbers[k] = left[i]
i += 1
k += 1
while j < len(right):
numbers[k] = right[j]
j += 1
k += 1
#Reading from file
with open('data.txt', 'r') as fIn:
count =1
line = fIn.readline()
while line:
#Get the first number
#numbersIn = fIn.readline()
numbersIn = line
toSort = numbersIn[0]
int(toSort)
print("Numbers to sort:")
print toSort
#get the remaining numbers into a list as integers
numStrIn = numbersIn[1:]
#print (numStr)
numbers = [int(s) for s in numStrIn.split()]
print("Unsorted values:")
print(numStrIn)
#Call function
merge_sort(numbers)
#Write to file
with open('merge.out', 'a') as fOut:
#format sorted values for writing
numStrOut = ' '.join(str(e) for e in numbers)
fOut.write("%s\n" % (numStrOut))
print("Sorted values:")
print(numStrOut)
line = fIn.readline()
count +=1
| true |
2ad2891489db9ee7ddfd36acf02fbf71eac598bf | codeaudit/tutorial | /exercises/exercise01.py | 1,863 | 4.125 | 4 | # The goal of this exercise is to show how to run simple tasks in parallel.
#
# EXERCISE: This script is too slow, and the computation is embarrassingly
# parallel. Use Ray to execute the functions in parallel to speed it up.
#
# NOTE: This exercise should work even if you have only one core on your
# machine because the function that we're parallelizing is just sleeping.
# However, in general you would not expect a larger speedup than the number of
# cores on the machine.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
import time
if __name__ == "__main__":
# Start Ray. By default, Ray does not schedule more tasks concurrently than
# there are CPUs. This example requires four tasks to run concurrently, so we
# tell Ray that there are four CPUs. Usually this is not done and Ray
# computes the number of CPUs using psutil.cpu_count(). The argument
# redirect_output=True just hides some logging.
ray.init(num_cpus=4, redirect_output=True)
# This function is a proxy for a more interesting and computationally
# intensive function.
def slow_function(i):
time.sleep(1)
return i
# Sleep a little to improve the accuracy of the timing measurements below.
time.sleep(2.0)
start_time = time.time()
# This loop is too slow. The calls to slow_function should happen in
# parallel.
results = []
for i in range(4):
results.append(slow_function(i))
end_time = time.time()
duration = end_time - start_time
assert results == [0, 1, 2, 3]
assert duration < 1.1, ("The loop took {} seconds. This is too slow."
.format(duration))
assert duration > 1, ("The loop took {} seconds. This is too fast."
.format(duration))
print("Success! The example took {} seconds.".format(duration))
| true |
cf3480dca530bcedcb764f2cb0655914d004a409 | Abhishek-kr7/Basic-Python-Programming | /09_Functions_in_python.py | 1,759 | 4.375 | 4 | def hello():
"""This function will print the Hello Message when called"""
print('Hey there! Hello')
# hello()
def hello_user(user):
'''This function will take a parameter or name and will print hello with
the parameter/name'''
print("Hello",user, "How are you")
hello_user('abhi')
print(help(hello_user))
def mycountry(country='India'):
"""This function will print the country name which has been passed as parameter
If Nothing passed, then default value as 'India' will be Printed"""
print('My country is :' ,country)
mycountry('America')
mycountry()
def myfood(food):
"""This function will take list as input will print all the items"""
for item in food:
print('You can have ' + item)
fruits = ['Apple','Banana','Cherry']
myfruits = tuple(fruits)
print(myfruits)
myfood(myfruits)
def multipliers(x):
return x**5
print(multipliers(5))
import math
def sphereVol(r):
"""This function will take a parameter as r and calculate Volume of Sphere with that r value"""
return 4/3 * math.pi * r**3
# print(sphereVol(3))
# print(help(sphereVol))
def tri_area(b,h):
"""This Function will take 2 parameter as base and height and will return the area of triangle"""
return 0.5 * b * h
# print(tri_area(3,5))
def centi(feet=0, inch=0):
"""This function will take feet/inch or both
1 feet = 12 inches
1 inch = 2.54 cm
and will convert into centimeter
This function parameter have 0 as default value assigned"""
feet_to_cm = feet * 12 * 2.54
inch_to_cm = inch * 2.54
return feet_to_cm + inch_to_cm
print(centi(5))
print(centi(feet = 5))
print(centi(inch = 10))
print(centi(inch = 10, feet = 5))
def g(y, x = 0,):
print(x + y)
print(g(4,5))
print(g(x = 5))
| true |
5fc1530a3fb637127abf517484c0e96f3940fdd4 | Axl11475581/Projects-Folder | /Python Exercises/Python Basics/Practical Exercise.py | 2,256 | 4.53125 | 5 | # 7 Exercise to practice the previous topics viewed 1
price_product_1 = input("What is the price of the product 1?: \n ")
quantity_product_1 = input("How many of the product 1 will you buy?: \n ")
price_product_2 = input("What is the price of the product 2?: \n ")
quantity_product_2 = input("How many of the product 2 will you buy?: \n ")
price_product_3 = input("What is the price of the product 3?: \n ")
quantity_product_3 = input("How many of the product 3 will you buy?: \n ")
result_product_1 = float(price_product_1)*float(quantity_product_1)
result_product_2 = float(price_product_2)*float(quantity_product_2)
result_product_3 = float(price_product_2)*float(quantity_product_3)
result = result_product_1+result_product_2+result_product_3
print("Your final price is: \n" + str(result))
# Exercise to practice the previous topics viewed 2
name_1 = input("Write your name: \n")
name_2 = input("Write your name: \n")
name_3 = input("Write your name: \n")
slices_in_pizza = input("How many slices had the pizza?: \n")
pizza_price = input("How much did the pizza cost? \n")
percentage_ate_by_person_1 = input(name_1 + "How many slices did you ate?: \n")
percentage_ate_by_person_2 = input(name_2 + "How many slices did you ate?: \n")
percentage_ate_by_person_3 = input(name_3 + "How many slices did you ate?: \n")
number_of_slices_ate_by_person_1 = float(percentage_ate_by_person_1)*float(slices_in_pizza)
number_of_slices_ate_by_person_2 = float(percentage_ate_by_person_2)*float(slices_in_pizza)
number_of_slices_ate_by_person_3 = float(percentage_ate_by_person_3)*float(slices_in_pizza)
price_paid_by_name_1 = float(percentage_ate_by_person_1)*float(pizza_price)
price_paid_by_name_2 = float(percentage_ate_by_person_2)*float(pizza_price)
price_paid_by_name_3 = float(percentage_ate_by_person_3)*float(pizza_price)
print(name_1 + " have ate " + str(number_of_slices_ate_by_person_1) + " of slices, and paid " + str(price_paid_by_name_1) + "$ for the meal")
print(name_2 + " have ate " + str(number_of_slices_ate_by_person_2) + " of slices, and paid " + str(price_paid_by_name_2) + "$ for the meal")
print(name_3 + " have ate " + str(number_of_slices_ate_by_person_3) + " of slices, and paid " + str(price_paid_by_name_3) + "$ for the meal") | true |
770dfec0ac2a38cd1d55cd33087dde8caf87db28 | ikamesh/Algorithms | /inputs.py | 1,314 | 4.375 | 4 | import random
"""This is file for generating input list for algorithms"""
#input method1 -- filling list with try-except
def infinite_num_list():
print("""
Press enter after each input.
Press 'x' to when done...!
""")
num_list = []
while True:
num = input("Enter num to fill the list : ")
if type(num) == 'int':
num_list.append(num)
elif num.lower() == "x":
break
else:
pass
return num_list
# input method2 -- filling element with for loop
def finite_num_list():
num_of_element = int(input("\nHow many elements do you have..? : "))
print(f"Enter {num_of_element} elements :")
num_list = []
for _ in range(num_of_element):
num_list.append(int(input()))
return num_list
# Input Method3 -- Generating num with random
def random_num_list_generator():
num_of_element = int(input("\nHow many num in list you want to generate : "))
num_list = []
for _ in range(num_of_element):
num_list.append(random.randint(0, num_of_element))
if input("\nDo you want to print the list (Y/N): ").lower() == "y":
print("\n", num_list)
return num_list
if __name__ == "__main__":
infinite_num_list()
finite_num_list()
random_num_list_generator()
| true |
7504bbb277af091a8b5b4bd1230ea416f169a5b3 | uit-inf-1400-2021/uit-inf-1400-2021.github.io | /lectures/oop-02-03-oo-concepts/code/extending.py | 1,281 | 4.375 | 4 | #!/usr/bin/env python3
"""
Based on code from the OOP book.
"""
class ContactList(list):
def search(self, name):
'''Return all contacts that contain the search value
in their name.'''
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList() # class level / shared
def __init__(self, name, email):
self.name = name
self.email = email
self.all_contacts.append(self)
def __str__(self):
return "({}, {}, {})".format(super().__str__(), self.name, self.email)
def __repr__(self):
return "({}, {}, {})".format(super().__repr__(), self.name, self.email)
t = ContactList([
Contact("foo", "foo@bar.com"),
Contact("foo2", "foo2@bar.com"),
])
t2 = ContactList()
print("t : ", t.search("foo2"))
print("t2 : ", t.search("foo2"))
print(Contact.all_contacts)
class Friend(Contact):
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
class Friend(Contact):
def __init__(self, name, email, phone):
super().__init__(name, email)
self.phone = phone
| true |
d0fec4e684b774cbc4b07cce6c7d7bacfa6681ca | shortma1/Coyote | /day6.py | 615 | 4.25 | 4 | # # functions
# print("Hello") # print() is a function
# num_char = len("Hello") # len() is also a function
# print(num_char)
# def my_function(): # def defines function, my_function() is the name of the function, and : finished the function definition
# print("Hello")
# print("Bye")
# my_function() # to call the function, otherwise it will not run
# Defining Functions
# def my_function():
# #Do this
# #Then do this
# Then Call the function
# my_function()
# While Loops
# while something is True
# do something
number = 6
while number > 0:
print(f"Number is: {number}")
number -= 1
| true |
a08f76a2e3ccc91b0e0ebae2c191fd09f7c43063 | piluvr/Python | /max.py | 233 | 4.125 | 4 | # your code goes here
nums =[]
input1 = int(input("Enter a number: "))
input2 = int(input("Enter a number: "))
input3 = int(input("Enter a number: "))
nums.append(input1)
nums.append(input2)
nums.append(input3)
print(str(max(nums)))
| true |
d8c92e58919689ff644004479aad9cbae61218e2 | shanjiang1994/LeetCode_for_DataScience | /Solutions/Array/88.Merge Sorted Array.py | 2,809 | 4.34375 | 4 |
'''
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Constraints:
-10^9 <= nums1[i], nums2[i] <= 10^9
nums1.length == m + n
nums2.length == n
'''
# Runtime: 32 ms, faster than 94.10% of Python3 online submissions for Merge Sorted Array.
# Memory Usage: 13.8 MB, less than 53.32% of Python3 online submissions for Merge Sorted Array.
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1,m,nums2,n):
while m>0 and n>0: #incase the position are stepped to 0
if nums2[n-1]>=nums1[m-1]:
nums1[m+n-1]=nums2[n-1]
n-=1
else: #nums1[m-1]>=nums2[n-1]
nums1[m+n-1],nums1[m-1]= nums1[m-1],nums1[m+n-1] #it's okay we just let nums1[m+n-1] = nums1[m-1]
m-=1
# corner case
if m==0 and n>0:
nums1[:n] = nums2[:n]
print(nums1)
# call the function
merge(nums1,m,nums2,n)
########################################################
# Methodology: #
# - two pointer #
# - start from the end to the front #
########################################################
# [1,2,3,0,0,0]
# [2,5,6]
# Normal case:
# --------------------------------------------
# while m>0 and n>0:
# if nums1[m-1]<=nums2[n-1]?
# nums1[1,2,3,0,0,0]
# ↑(m-1)
# nums2[2,5,6]
# ↑(n-1)
# answer is True
# Then we let nums1[m+n-1]=nums2[n-1], and n = n-1
# nums1[1,2,3,0,0,6]
# ↑(m-1)
# nums2[2,5,6]
# ↑(n-1)
# so on and so forth until:
# else nums1[m-1]>nums2[n-1]
# nums1[1,2,3,0,5,6]
# (m-1)↑ ↑(m+n-1)
# nums2[2,5,6]
# ↑(n-1) = 0 # n still > 0
# move nums1[m-1] to the place nums1[m+n-1] and move m forward = m-1
# nums1[1,2,0,3,5,6]
# ↑(m-1)
# nums2[2,5,6]
# ↑(n-1) = 0
# # here is the previous loop we get:
# nums1[1,2,2,3,5,6]
# now n is zero, break the loop
# Other cases that we need to concern
# --------------------------------------------
# [1,2,3,0,0,0]
# 3
# [2,5,6]
# 3
# --------------------------------------------
# [0,0,0,0,0]
# 0
# [1,2,3,4,5]
# 5
# --------------------------------------------
# so we need add this :
# if m==0 and n>0:
# nums1[:n] = nums2[:n] | true |
92b23cdfa9a34ba5230c0353dbc1958a63a38658 | Skryvvara/DS1-Soullevel-Calculator | /soullevelcalc.py | 1,287 | 4.1875 | 4 | # returns cost of the given level
# when level = 12 the returned cost is from level 11 -> 12
def get_level_cost(level: int) -> int:
return int(round((0.02 * pow(level, 3)) + (3.06 * pow(level, 2)) + (105.6 * level) - 895, 0))
# returns the amount of possible levelups
# takes the current level and the amount of held souls
# a boolean can be given as last parameter to supress print statement
def get_possible_ups(currentLevel: int, souls: int, silent: bool = False) -> int:
level: int = currentLevel + 1
cost: int = get_level_cost(level)
ups: int = 0
while (souls >= cost):
if (silent == False):
print(f"Cost from level {level-1} to {level}: {cost} Souls.")
souls -= cost
level += 1
ups += 1
cost = get_level_cost(level)
return ups
# takes the current level and amount of souls from user input
# then prints the amount of possible level ups
def start():
try:
print("Enter your starting level.")
currentLevel: int = int(input("> "))
print("Enter the amount of souls you have.")
souls: int = int(input("> "))
ups: int = get_possible_ups(currentLevel, souls)
print(ups)
except:
print("Something happened :c, try entering real numbers.")
start()
| true |
cf79d548cfb65bb4ea3073cd0d1723981cea1400 | sydoruk89/math_series | /math_series/series.py | 1,177 | 4.1875 | 4 | def fibonacci(n):
"""
The function return the nth value in the fibonacci series.
Args:
n (int): integer
"""
if n >= 0:
if n < 2:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
else:
return 'Please provide a positive number'
def lucas(n):
"""
The function return the nth value in the lucas series.
Args:
n (int): integer
"""
if n >= 0:
if n == 0:
return 2
elif n == 1:
return n
else:
return lucas(n - 1) + lucas(n - 2)
else:
return 'Please provide a positive number'
def sum_series(n, prev = 0, next = 1):
"""
Calling this function with no optional parameters will produce numbers from the fibonacci series.
Args:
n (int): integer
prev (int, optional): [description]. Defaults to 0.
next (int, optional): [description]. Defaults to 1.
"""
if n >= 0 and prev >= 0 and next >= 0:
for i in range(n):
prev, next = next, prev + next
return prev
else:
return 'Please provide a positive number'
| true |
45521599af6d990c059840b0f1b70c9d3c482c6f | anshdholakia/Python_Projects | /map_filter.py | 1,387 | 4.21875 | 4 | # numbers=["1","2","3"]
#
# # for i in range(len(numbers)): # not suitable every-time to use a for loop
# # numbers[i]=int(numbers[i])
#
# # using a map function
# numbers=list(map(int,numbers))
#
#
# numbers[2]=numbers[2]+5
#
# print(numbers[2])
# def sq(a):
# return a*a
# num=[1,2,124,4,5,5,123,23,3,53]
# square=list(map(sq, num))
# print(square)
#
#
#
# num=[1,2,124,4,5,5,123,23,3,53]
# square=list(map(lambda x:x*x, num))
# print(square)
# def square(a):
# return a*a
#
# def cube(a):
# return a*a*a
#
# function=[square,cube]
#
# for i in range(6): #[0,6)
# func=list(map(lambda x:x(i),function ))
# print(func)
######################################## FILTER ########################################################
#FILTER FUNCTION
# It makes a list of elements on which the given function is true
# list_1=[1,2,3,4,5,6,7,8,9]
# def is_greater_5(num):
# return num>5
#
# # gr_than_5=filter(is_greater_5,list_1) this will give you a filter variable
# # print(gr_than_5)
# gr_than_5=list(filter(is_greater_5,list_1))
# print(gr_than_5)
######################################## REDUCE #############################################################3
from functools import reduce
list1=[1,2,3,4] # how to add all the numbers in the list
num=reduce(lambda x,i:x+i, list1)
print(num)
| true |
6c465540793c7d032822d027ff5e58837b8fcf31 | lovaraju987/Python | /learning concepts and practising/basics/sep,end,flash.py | 443 | 4.15625 | 4 | ''' sep, end, flash'''
print('slfhs',2,'shalds',end = ' ') # by default print statement ends with \n(newline).so, this 'end' is used to change to ending of the print statement when we required it
print('sfjsaa',3,'hissa')
print('sfjsaa',2,'hissa',sep = ' ') # by default multiple statemnets in one print without any space. so the 'sep' seperates the multiple statements in print with given string by ou
print('sfjsaa',3,'hissa',sep = ' ')
| true |
5733608db00de58d07cd64754e9592302e8e7dd6 | badri-venkat/Computational-Geometry-Algorithms | /PolygonHelper.py | 849 | 4.21875 | 4 | def inputPolygon(numberOfPoints):
polygonArray = []
print(
"Enter the points in cyclic order. Each point is represented by space-separated coordinates."
)
i=0
while i<numberOfPoints + 1:
x, y = map(int, input().split())
polygonArray.append(tuple([x, y]))
i+=1
if isValidPolygon(numberOfPoints, polygonArray):
polygonArray.pop()
return polygonArray
else:
return None
def printPolygon(polygonArray):
for count, point in enumerate(polygonArray):
print(count + 1, " ", point)
def isValidPolygon(numberOfPoints, polygonArray):
if numberOfPoints < 3 or polygonArray[0] != polygonArray[numberOfPoints]:
print("The 2D object is not a Polygon.")
return False
else:
print("The 2D object is a Polygon.")
return True
| true |
e01e7b007f7041fccc232fc3e9ab9ecacb44dec4 | kradical/ProjectEuler | /p9.py | 467 | 4.15625 | 4 | # A Pythagorean triplet is a set of three
# natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet
# for which a + b + c = 1000.
# Find the product abc.
def test():
for a in range(1, 333):
for b in range(1000-a):
c = 1000-b-a
if a**2 + b**2 == c**2:
print(a*b*c)
return
if __name__ == "__main__":
test() | true |
732c172fbce4e4cac32875feb880b5e1c6ac59f4 | CucchiettiNicola/PythonProgramsCucchietti | /Compiti-Sistemi/Es32/Es32.py | 1,475 | 4.75 | 5 | the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quartiers']
# this first kind of for-loop goes trough a list
for number in the_count:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# also we can go trough mixed lists too
# notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counte
for i in range(0,6):
print(f"Adding {i} to the list")
# append is a function that lists understand
elements.append(i)
# this print out element values
print("Elements -> {}".format(elements))
# now we can print them out too
for i in elements:
print(f"Element was: {i}")
# Study Drills
# 1. Take a look at how you used range. Look up the range function to understand it.
# > range() function create a list of numbers from the first to the second.
# For example: range(2, 5) -> [2,3,4] (5 it's not included)
# 2. Could you have avoided that for-loop entirely on line 22 and just assigned range(0,6) directly
# to elements ?
# > elements = range(0,6)
# 3. Find the Python documentation on lists and read about them. What other operations can you do
# to lists besides append ?
# > clear, copy, extend, index, insert, pop, remove, reverse, sort
| true |
272d6b26253dfb3573be18709097920d1dbb07ab | cb-kali/Python | /Day13.py | 1,021 | 4.1875 | 4 | '''
Introduction to python class:
Class --> it's like a blueprint of codedesing.
class
method --> A function writen inside a class is called a method.
attributes --> a variable writen inside a class is called an attributes.
Introduction of a class/object
'''
# req:-
'''
You have to create a class, it should your name as an input, it should your name as an input, it should great you as well at the end
'''
class Greet: # create name
'''Creating a greet class for greeting an user '''
def create_name(self,name):
self.name = name
def display_name(self):
print(self.name)
def greet_user(self):
print(f'Hello, good to you are again in training class {self.name}')
'''
Object is the key... any thing you wanted to touch inside a class number other option
'''
# Object creation
superman = Greet()
superman.create_name('chetan')
superman.display_name()
superman.greet_user()
# OOPs concept --> object
# New object
a = Greet()
a.create_name('Anu')
a.display_name()
a.greet_user()
| true |
29e91abac0e3e1202cd2fef2f4666bfe681dc9be | robert0525/Python- | /hello.py | 393 | 4.1875 | 4 | first_name = input("What's is your first name? ")
print("Hello", first_name)
if first_name == "Robert":
print(first_name, "is learning Python")
elif first_name == "Maxi":
print(first_name, " is learning with fellow students in the Comunity! Me too!")
else:
print("You should totally learn Python, {}!".format(first_name))
print("Have a greate day {}!".format(first_name))
| true |
a8cb384dc0440a3f8ae962d3c543af8e179fa9cd | riteshelias/UMC | /ProgramFlow/guessgame.py | 1,734 | 4.125 | 4 | import random
answer = random.randint(1, 10)
print(answer)
tries = 1
print()
print("Lets play a guessing game, you can exit by pressing 0")
guess = int(input("try count - {}. Please enter a number between 1 and 10: ".format(tries)))
while guess != answer:
if guess == 0:
print("Bye, have a nice day!")
break
if tries == 5:
print("You have reached your guess limit. Bye!")
break
tries += 1
guess = int(input("try count - {}. Please enter a number between 1 and 10: ".format(tries)))
else:
if tries == 1:
print("Wow, correct guess at the first time!")
else:
tries += 1
print("You took {} tries to guess right!".format(tries))
# if guess == answer:
# print("Woah! You got that right at the first go!")
# else:
# if guess < answer:
# print("Please guess a higher number")
# else:
# print("Please guess a lower number")
# guess = int(input("Try again: "))
# if guess == answer:
# print("You get it finally")
# else:
# print("Oops! Still wrong!")
# if guess != answer:
# if guess < answer:
# print("Please guess a higher number")
# else:
# print("Please guess a lower number")
# guess = int(input("Guess again: "))
# if guess == answer:
# print("You finally got it")
# else:
# print("Sorry, you still didn't get it")
# else:
# print("Woah! You got it right the first time")
# if guess < 1 or guess > 10:
# print("The entered number is not in the requested range")
# elif guess < answer:
# print("Please guess a higher number")
# elif guess > answer:
# print("Please guess a lower number")
# else:
# print("You guessed right!")
| true |
16f595b7e1ff1b8b22ab8ba1221d96448a03d15e | daniel10012/python-onsite | /week_01/03_basics_variables/07_conversion.py | 526 | 4.375 | 4 | '''
Celsius to Fahrenheit:
Write the necessary code to read a degree in Celsius from the console
then convert it to fahrenheit and print it to the console.
F = C * 1.8 + 32
Output should read like - "27.4 degrees celsius = 81.32 degrees fahrenheit"
NOTE: if you get an error, look up what input() returns!
'''
def fahrenheit(c):
f = int(c*1.8 + 32)
return f
c = int(input("Degrees Celcius:"))
print(f"{c} degrees celcius = {fahrenheit(c)} degrees fahrenheit") | true |
9e6b89661cd68140884634d1a7978e4afc899e98 | daniel10012/python-onsite | /week_02/11_inheritance/01_class_attributes.py | 910 | 4.40625 | 4 |
'''
Flush out the classes below with the following:
- Add inheritance so that Class1 is inherited by Class2 and Class2 is inherited by Class3.
- Follow the directions in each class to complete the functionality.
'''
class Class1:
def __init__(self, x):
self.x = x
# define an __init__() method that sets an attribute x
class Class2(Class1):
def __init__(self, x, y):
super().__init__(x)
self.y = y
# define an __init__() method that sets an attribute y and calls the __init__() method of its parent
class Class3(Class2):
def __init__(self, x, y,z):
super().__init__(x,y)
self.z = z
# define an __init__() method that sets an attribute z and calls the __init__() method of its parent
# create an object of each class and print each of its attributes
obj1 = Class1(3)
obj2 = Class2(4, 5)
obj3 = Class3(7, 9, 8)
print(obj3.y) | true |
fe26c3fa3494717d2cb65c234594323fae19a5f0 | daniel10012/python-onsite | /week_04/intro_apis/01_countries.py | 1,117 | 4.375 | 4 | '''
Use the countries API https://restcountries.eu/ to fetch information
on your home country and the country you're currently in.
In your python program, parse and compare the data of the two responses:
* Which country has the larger population?
* How much does the are of the two countries differ?
* Print the native name of both countries, as well as their capitals
'''
import requests
url1 = "https://restcountries.eu/rest/v2/name/france?fullText=true"
url2 ="https://restcountries.eu/rest/v2/name/germany?fullText=true"
r1 = requests.get(url1).json()
r2 = requests.get(url2).json()
country1 = r1[0]["name"]
country2 = r2[0]["name"]
population1 = r1[0]["population"]
population2 = r2[0]["population"]
area1 = r1[0]["area"]
area2 = r2[0]["area"]
if population1 > population2:
print(f"{country1} is more populous than {country2}")
else:
print(f"{country2} is more populous than {country1}")
print(f"the difference in area is {abs(population2-population1)} sq km")
print(f"{r1[0]['nativeName']} has for capital {r1[0]['capital']}")
print(f"{r2[0]['nativeName']} has for capital {r2[0]['capital']}") | true |
06774114cb67d9626933f4f3d752b8beb4f9f2b2 | daniel10012/python-onsite | /week_03/01_files/04_rename_doc.py | 1,156 | 4.125 | 4 | '''
Write a function called sed that takes as arguments a pattern string,
a replacement string, and two filenames; it should read the first file
and write the contents into the second file (creating it if necessary).
If the pattern string appears anywhere in the file, it should be
replaced with the replacement string.
If an error occurs while opening, reading, writing or closing files,
your program should catch the exception, print an error message,
and exit.
Solution: http://thinkpython2.com/code/sed.py.
Source: Read through the "Files" chapter in Think Python 2e:
http://greenteapress.com/thinkpython2/html/thinkpython2015.html
'''
def sed(pattern_string, replacement_string, file1,file2):
try:
with open(file1,"r") as fin:
content = fin.readlines()
except FileNotFoundError:
print(f"{file1} doesn't exist")
try:
with open(file2, "w") as fout:
for line in content:
new_line = line.replace(pattern_string,replacement_string)
fout.write(new_line)
except UnboundLocalError:
pass
sed("strings", "Notstrings", "words3.txt", "wordss3.txt")
| true |
cd99f695faa50653c2ca9488547a528059c94d62 | daniel10012/python-onsite | /week_02/06_tuples/01_make_tuples.py | 502 | 4.34375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
my_list = [5,3,32,1,3,9,5,3,2,2,5]
my_list.sort()
if len(my_list) % 2 != 0:
my_list.append(0)
#
print(my_list)
pairs = [(my_list[i], my_list[i+1]) for i in range(0,len(my_list),2)]
print(pairs)
for i in pairs:
print(i)
| true |
fd1561a9a0a9c1cf29c24efbf299c0e3e135fa19 | balaramhub1/Python_Test | /Tuple/Tuple_03.py | 668 | 4.125 | 4 | '''
Created on Jul 17, 2014
@author: HOME
The script is to see the function of T.index[x] and T.count(x) methods of Tuple
'''
list1=['hello','balaram']
color = ("red","green","blue",list1)
fruit =(5,"lemon",8,"berry",color,"grapes","cherry")
numtup=(4,6,3,2,5,23,3,2,4,2,3,5)
print("Elements of List1 are : ",list1)
print("Elements of tuple 'color' are : ",color)
print("Elements of tuple 'fruit' are : ",fruit)
print("Index value of 'hello' is : ",fruit[4][3][0].index('hello'))
print("Index value of 'blue' is : ",fruit[4].index('blue'))
print("count of '3' in numtup is : ",numtup.count(3))
print("Index of '3' in numtup is : ",numtup.index(3))
| true |
bd2ca872c954096e50e818e402969a3bc9a1ff8b | balaramhub1/Python_Test | /Math/math_03.py | 394 | 4.125 | 4 | '''
Created on Jun 14, 2020
Usage of Random module
@author: beherb2
'''
import random
print(random.random())
# Choose a random number from a list
l=[1,2,3,4,5,6]
print(random.choice(l))
# generate a random number between a range
print(random.randint(10,100))
# end number is not included
print(random.randrange(10,100))
# generate a floating random number
print(random.uniform(10,20))
| true |
9b1e5b1a994bc633e8eabe5131f79db0bbfd2c21 | jage6277/Portfolio | /Discrete Structures/Unsorted to Sorted List.py | 1,559 | 4.21875 | 4 | # This function takes two sorted lists and merges them into one sorted list
# Input: L1,L2 - Two sorted lists
# Output: L - One sorted list
def merge(L1,L2):
L = [] # Array where the sorted list will be stored
while len(L1) != 0 and len(L2) != 0:
# While L1 and L2 are both nonempty
if L1[0] < L2[0]:
# If L1 contains the 1st smaller element, remove element and add to end of L
print(L1[0],end="")
print('<', end = "")
print(L2[0], end = "")
print()
L.append(L1[0])
L1.remove(L1[0])
else:
# If L2 contains the 1st smaller element, remove element and add to end of L
print(L2[0], end = "")
print('<', end = "")
print(L1[0], end = "")
print()
L.append(L2[0])
L2.remove(L2[0])
while len(L1) != 0:
L.append(L1[0])
L1.remove(L1[0])
while len(L2) != 0:
L.append(L2[0])
L2.remove(L2[0])
return L
# This function takes an unordered list and transforms it to an ordered list
# Input: An unordered list
# Returns: A ordered list (ascending)
def mergeSort(L):
if len(L) > 1:
# Check if the size of the list is greater than 1
m = len(L) // 2 # m = floor(n/2)
L1 = L[:m] # L1 = a1, a2, ..., am
L2 = L[m:]# L2 = am+1, am+2, ..., an
L = merge(mergeSort(L1), mergeSort(L2))
return L
print(mergeSort([1, 3, 2, 7, 12, 14, 5, 9])) | true |
9ca92b5f121723702b7901dfa4d2d3f86885b077 | rnagle/pycar | /project1/step_2_complete.py | 810 | 4.25 | 4 | # Import built-in python modules we'll want to access csv files and download files
import csv
import urllib
# We're going to download a csv file...
# What should we name it?
file_name = "banklist.csv"
# Use urllib.urlretrieve() to download the csv file from a url and save it to a directory
# The csv link can be found at https://www.fdic.gov/bank/individual/failed/banklist.html
target_file = urllib.urlretrieve("http://www.fdic.gov/bank/individual/failed/banklist.csv", file_name)
# Open the csv file
with open(file_name, "rb") as file:
# Use python's csv reader to access the contents
# and create an object that represents the data
csv_data = csv.reader(file)
# Loop through each row of the csv...
for row in csv_data:
# and print the row to the terminal
print row
| true |
2f00505d175bd72b047b898d367fc9a201b9c0e8 | vivekbhadra/python_samples | /count_prime.py | 684 | 4.125 | 4 | '''
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
count_primes(100) --> 25
By convention, 0 and 1 are not prime.
'''
"""
Spyder Editor
This is a temporary script file.
"""
def isprime(num):
flag = True
for n in range(2, (num // 2) + 1):
if num % n == 0:
flag = False
if flag:
print('{} is prime'.format(num))
return flag
def count_primes(num):
count = 0
for n in range(1, num):
if isprime(n):
count += 1
return count
def main():
print(count_primes(100))
if __name__ == '__main__':
main()
| true |
3c043341d16e6c27c947230779d248f00b72a6c6 | glennpantaleon/python2.7 | /doughnutJoe.py | 2,197 | 4.4375 | 4 | '''
A program designed for the purpose of selling coffee and donuts.
The coffee and donut shop only sells one flavor of coffee and donuts at a fixed price.
Each cup of coffee cost seventy seven cents and each donut cost sixty four cents.
This program will imediately be activated upon a business.
\/\/\/\\/\/\/\
DOUGHNUT JOE
\/\/\/\\/\/\/\
__ cups of coffee: $__.__
__ doughnuts: $__.__
tax: $__.__
Amount Owed: $_____
Thank you for purchasing local.
'''
import os
tax_rate = 0.0846
coffee_cost = 0.77
donut_cost = 0.64
def getOrder ():
'''Retrives the customer's order.'''
number_of_donuts = raw_input("How many donuts would you like to order? ")
donut = int(number_of_donuts)
number_of_coffee = raw_input("How many cups of coffee do you want? ")
coffee = int(number_of_coffee)
return donut,coffee
def calcAmount (donut,coffee):
'''Calculates the total amount of money paid for the coffee and donuts.'''
total_cost_of_donuts = donut * donut_cost
total_cost_of_coffee = coffee * coffee_cost
bill_before_tax = total_cost_of_donuts + total_cost_of_coffee
total_tax = bill_before_tax * tax_rate
total_cost = bill_before_tax + total_tax
return total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost
def presentBill (total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost,donut,coffee):
'''Presents the bill after the calculations are done.'''
print "/\/\/\/\/\/\/\/\/\/\\"
print " DOUGHNUT JOE "
print "/\/\/\/\/\/\/\/\/\/\\"
print str(coffee) + " cups of coffee: $" + str (total_cost_of_coffee)
print str(donut) + " doughnuts: $" + str (total_cost_of_donuts)
print "Tax: $" + str (total_tax)
print "Amount Owed: $" + str (total_cost)
print '''
Thank you for buying
'''
def main():
donut,coffee = getOrder ()
total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost = calcAmount (donut,coffee)
presentBill (total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost,donut,coffee)
os.system ("pause")
main()
| true |
7f7d73dd0b2be68187d745c8a3893d52a587a2e3 | erickclasen/PMLC | /xor/xor_nn_single_layer.py | 1,571 | 4.21875 | 4 | import numpy as np
# sigmoid function
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
print("XOR: With a hidden layer and the non-linear activation function on the output layer.")
print("Fails!")
'''
2 inputs 1 output
l0 is the input layer values, aka X
l1 is the hidden layer values
syn0 synapse 0 is the weight matrix for the output layer
b0 is the bias for the output layer.
X is the input matrix of features.
Y is the target to be learned.
'''
# input dataset
X = np.array([ [0,0],
[0,1],
[1,0],
[1,1] ])
# output dataset
y = np.array([[0,1,1,0]]).T
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)
# How wide are the layers, how many neurons per layer?
input_layer = 2
output_layer = 1
# initialize weights randomly with mean 0
# syn0 weights for input layer with input_layers to output_layers dimension
syn0 = 2*np.random.random((input_layer,output_layer)) - 1
# One output_layer bias
b0 = 2.0*np.random.random((1,output_layer)) - 1
for iter in range(10000):
# forward propagation
l0 = X
l1 = nonlin(np.dot(l0,syn0) + b0)
# how much did we miss?
l1_error = y - l1
# multiply how much we missed by the
# slope of the sigmoid at the values in l2
l1_delta = l1_error * nonlin(l1,True)
# update weights and biases
syn0 += np.dot(l0.T,l1_delta)
b0 += np.sum(l1_delta,axis=0,keepdims=True)
print("Output After Training:")
print(l1)
| true |
71716899604df84cc40aa5650cad8dc91df5c05c | shouvikbj/IBM-Data-Science-and-Machine-Learning-Course-Practice-Files | /Python Basics for Data Science/loops.py | 532 | 4.34375 | 4 | num = 2
# for loop in a range
for i in range(0, num):
print(i + 1)
for i in range(num):
print(i + 1)
# for loop in case of tuples
names = ("amrita", "pori", "shouvik", "moni")
for name in names:
print(name)
# for loop in case of lists
names = ["amrita", "pori", "shouvik", "moni"]
for name in names:
print(name)
# for loop in case of dictionaries
names = {
"name_1": "amrita",
"name_2": "pori",
"name_3": "shouvik",
"name_4": "moni"
}
for key, name in names.items():
print(f"{key} : {name}") | true |
c1649abbfeea25a8b318f96a8dfe086a1d8a1a40 | cyphar/ncss | /2014/w2/q4complex.py | 1,806 | 4.1875 | 4 | #!/usr/bin/env python3
# Enter your code for "Mysterious Dates" here.
# THIS WAS MY INITAL SOLUTION.
# IT DOES NOT PASS THE TEST CASES.
# However, the reason I added this is because this code will take any date
# format (not just the given ones) and brute-force the first non-ambiguous
# representation. It is (in my opinion) a more "complete" solution.
import re
import itertools
PATTERN = r"(\d+).(\d+).(\d+)"
MONTHS = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
DAY = 0
MONTH = 1
YEAR = 2
def is_month(part):
return 0 < part <= 12
def is_day(part, month):
return 12 < part <= MONTHS[month]
def is_year(part, month):
return MONTHS[month] < part <= 9999
def brute_force_order(date):
for fmt in itertools.permutations([DAY, MONTH, YEAR], 3):
fmt = list(fmt)
day = date[fmt.index(DAY)]
month = date[fmt.index(MONTH)]
year = date[fmt.index(YEAR)]
if not is_month(month) or not is_day(day, month) or not is_year(year, month):
continue
return [fmt.index(DAY), fmt.index(MONTH), fmt.index(YEAR)]
return None
def ambiguity_order(dates):
for date in dates:
order = brute_force_order(date)
if order:
break
else:
return None
fmt = {
"day": order[DAY],
"month": order[MONTH],
"year": order[YEAR],
}
return fmt
def main():
with open("ambiguous-dates.txt") as f:
data = f.read()
dates = re.findall(PATTERN, data)
if not dates:
return
dates = [tuple(int(p) for p in d) for d in dates]
order = ambiguity_order(dates)
# No order found.
if not order:
print("No unambiguous dates found")
return
for date in dates:
day = date[order["day"]]
month = date[order["month"]]
year = date[order["year"]]
print("%.4d-%.2d-%.2d" % (year, month, day))
if __name__ == "__main__":
main()
| true |
76c2a205292169daea9e1c5c085dea4525992e94 | javedbaloch4/python-programs | /01-Basics/015-print-formatting.py | 490 | 4.125 | 4 | #!C:/python/python
print("Content-type: text/html\n\n")
s = "string"
x = 123
# print ("Place my variable here: %s" %s) # Prints the string and also convert this into string
# print("Floating point number: %0.3f" %1335) # Prints the following floating number .3 is decimal point
# print("Convert into string %r" %x) # %r / %s convert into string
# print("First: %s Second: %s Third: %s" %('Hi','Hello',3))
print("First: {x} Second: {y} Third: {x}" .format(x='Interested', y= 'Hi'))
| true |
54a10d41ef8a3bc55c624d1115bff0d731dff64f | androidSec/SecurityInterviews | /docs/custom_linked_list.py | 837 | 4.15625 | 4 | '''
Create a linked list that supported add and remove.
Numbers are added in ascending order, so if the list
was 1,3,5 and 4 was added it would look like 1,3,4,5.
'''
class custom_linked_list:
def __init__(self):
self.custom_list = []
def add(self, number):
if len(self.custom_list) == 0:
self.custom_list.append(number)
return
for i, n in enumerate(self.custom_list):
if n >= number:
self.custom_list.insert(i, number)
return
self.custom_list.append(number)
def remove(self, number):
if len(self.custom_list) == 0:
raise
for i, n in enumerate(self.custom_list):
if n == number:
del self.custom_list[i]
return
cll = custom_linked_list()
cll.add(4)
cll.add(9)
cll.add(1)
cll.add(7)
cll.add(0)
assert cll.custom_list == [0, 1, 4, 7, 9]
cll.remove(4)
assert cll.custom_list == [0, 1, 7, 9]
| true |
51fce45bb405ab2fc62e3f0cdfd92759b9e4f515 | vijayb5hyd/class_notes | /turtle_race.py | 2,138 | 4.28125 | 4 | import turtle # Import every object(*) from module 'turtle'
from turtle import *
speed(100)
penup()
# The following code is for writing 0 to 13 numbers on the sheet
# By default, the turtle arrow starts at the middle of the page. goto(x,y) will take it to (x,y).
goto(-120,120)
for step in range(14):
write(step, align='center')
forward(20) # the turtle arrow is moving 20 pixels with every step. But, it's not drawing since the pen is up.
# The following code is to draw 0 to 13 lines
goto(-120,120)
for step in range(14):
right(90)
forward(10)
pendown() # Starts drawing
forward(200) # 200 pixels line
penup() # stops
left(180)
forward(210)
right(90)
forward(20)
# Import 'randint' object/member from the module 'random'
from random import randint
# Define turtle1 and start the race
tigress=Turtle() # uppercase T in the function 'Turtle()', lowercase t will lead to NameError.
tigress.color('orange')
tigress.shape('turtle')
tigress.penup()
tigress.goto(-140,70)
tigress.pendown()
for turn in range(100):
tigress.forward(randint(1,5))
# randint(x,y) generates random integers between x and y. Forward the turtle with the random number generated.
# Define turtle2 and start the race
viper=Turtle()
viper.color('green')
viper.shape('turtle')
viper.penup()
viper.goto(-140,35)
viper.pendown()
for turn in range(100):
viper.forward(randint(1,5))
# Define turtle3 and start the race
monkey=Turtle()
monkey.color('yellow')
monkey.shape('turtle')
monkey.penup()
monkey.goto(-140,0)
monkey.pendown()
for turn in range(100):
monkey.forward(randint(1,5))
# Define turtle4 and start the race
mantis=Turtle()
mantis.color('blue')
mantis.shape('turtle')
mantis.penup()
mantis.goto(-140,-35)
mantis.pendown()
for turn in range(100):
mantis.forward(randint(1,5))
# Define turtle5 and start the race
crane=Turtle()
crane.color('gray')
crane.shape('turtle')
crane.penup()
crane.goto(-140,-70)
crane.pendown()
for turn in range(100):
crane.forward(randint(1,5))
turtle.exitonclick()
| true |
fdc37d4b6119ef863393cc36eec3fe8cbeafa09f | ramchinthamsetty/learning | /Python3/Advanced/decorators2.py | 2,605 | 4.65625 | 5 |
"""
1. Demystifying Decorators for Simple Use.
2. Helps in Building Libraries and Frameworks.
3. Encapuslating details and providing simple interface.
"""
def simple_func1(x):
'''
@return - Square of given values
'''
return x*x
# Passing the reference to a varibaale
# dec_func is stored as a variable in Stack and it refers to address of simple_func
dec_func = simple_func1
print(dec_func(10)) # Complete a simple test
'''
Call function in function by passing function reference as variable
'''
def simple_func2(func, x, y):
'''
func - A Function reference called.
x - an Integer
y - an Integer.
@return - Sum of outputs returned by func() referene called here
'''
return func(x) + func(y)
print(simple_func2(simple_func1, 10, 10)) # Test the output of function.
def simple_func3(x):
print("x - {}".format(x))
def inside_func(y):
print("y - {}".format(y))
return x + y
return inside_func # returns the reference of inside_func
'''
Found the trick here :)
1. simple_func calls passing 4 and returns the refence of inside_func
2. func_var will call the internal reference and it finally exceutes and outputs the results
'''
func_var = simple_func3(4) # simple_func() returns the interval reference of inside_func
print(func_var(5)) # Calling inside_func with value
'''
Decorator function executes before main starts execution
'''
def trace(f):
print("I was called here to return internal reference of g")
def g(x):
print(f.__name__, x)
print("I am executing this time!")
return f(x)
return g
'''
Syntactic Sugar of decorator as follows
1. Simple decorators here.
2. @trace is euqal to
var_func = trace(square) - returns the refernce to square.
var_func(value) - returns the square value
'''
@trace
def square(x):
return x*x
@trace
def add(x):
return x+x
@trace
def difference(x):
return x-x
'''
Lets try some here as it is tasting good :)
1. Passing multiple arguments to decorator functions.
2. So use *args to perform this.
'''
def trace2(f):
def g(*args):
print(f.__name__, args)
return f(*args)
return g
@trace2
def square2(x):
return x*x
@trace2
def sum_of_squares(x,y):
return square2(x)+square2(y)
def main():
print("Checking if decorators execution is done at import time or not")
print(sum_of_squares(4,9))
print(square(4))
print(add(4))
print(difference(10))
if __name__ == '__main__':
main()
| true |
bf5a57816608353f402c38cbb0f0294fbad96731 | cintax/dap_2019 | /areas_of_shapes.py | 944 | 4.21875 | 4 | #!/usr/bin/env python3
import math
def circle():
radius = int(input("Give radius of the circle: "))
print(f"The area is {math.pi*(radius**2):6f}")
def rectangle():
width = int(input("Give width of the rectangle: "))
height = int(input("Give height of the rectangle: "))
print(f"The area is {height*width:6f}")
def triangle():
base = int(input("Give base of the triangle: "))
height = int(input("Give height of the triangle: "))
print(f"The area is {0.5*base*height:6f}")
def main():
# enter you solution here
while True:
choice = input("Choose a shape (triangle, rectangle, circle): ")
if choice == "triangle":
triangle()
elif choice == "circle":
circle()
elif choice == "rectangle":
rectangle()
elif choice == "":
break
else:
print("Unknown shape!")
if __name__ == "__main__":
main()
| true |
b6d75f871bb2a85f93d87234fd97c73cd7350ecf | hiSh1n/learning_Python3 | /Day_02.py | 1,249 | 4.3125 | 4 | #This is day 2
#some variable converters int(),str(), bool(), input(), type(), print(), float(), by default everything is string.
#Exercise 03-
#age finder
birth_year = input("what's your Birth Year:")
age = (2021 - int(birth_year))
print("your are " + str( age) + " years old !")
print(" ")
#Exercise 04-
#pound to kilo weight convertor-
your_weight = input("Enter the weight in pounds: ")
a_kilo = (int(your_weight) / 2.20)
print(str(your_weight) + ' Pound is equal to ' + str(a_kilo) + " kg")
print(" ")
#python indexing
#python indexes strints like 'APPLE'
# 01234
#there's also negitive indexing line 'A P P L E'
# ...-2 -1
#index printing
dummy = 'jojo'
print(dummy[0])
#output = j, 0
print(dummy[0:3])
#output = joj, 0,1,2
print(" ")
#formatted strings, use f'{placeholder for variable} no concatenation needed.
first_name = 'jonny'
last_name = 'jake'
message = f'{first_name} {[last_name]} is our secret agent! '
#without f'string I have to write it as
#message = first_name + ' [' + last_name + ' ]' + 'is our secret agent!'
print(message)
print(" ")
#TO BE CONTINUE...
| true |
a61941a1d02f0fe26da9dfb3586341bcaa5cb419 | joshuaabhi1802/JPython | /class2.py | 793 | 4.125 | 4 | class mensuration:
def __init__(self,radius):
self.radius=radius
self.pi= 22/7
def area_circle(self):
area = self.pi*self.radius**2
return area
def perimeter_circle(self):
perimeter = 2*self.pi*self.radius
return perimeter
def volume_sphere(self):
volume= 4/3*self.pi*self.radius**3
return volume
if __name__ == "__main__":
print("Enter the radius")
a=int(input())
print("Please select the options given below-\n1.Area of circle\n2.Perimeter of circle\n3.Volume of sphere")
b=int(input())
s= mensuration(a)
if b==1:
print('Area is:',s.area_circle())
if b==2:
print('Perimeter is:',s.perimeter_circle())
if b==3:
print('Volume is:',s.volume_sphere())
| true |
abd5cb0421cd452bdb1405cca6a680f7f7f2ead3 | mthompson36/newstuff | /codeacademypractice.py | 856 | 4.1875 | 4 |
my_dict = {"bike":1300, "car":23000, "boat":75000}
"""for number in range(5):
print(number, end=',')"""
d = {"name":"Eric", "age":26}
for key in d:
print(d.items()) #list for each key and value in dictionary
for key in d:
print(key, d[key]) #list each key and value in dictionary just once(not like above example)
for letter in "Eric":
print(letter)
for key in my_dict:
print(key, my_dict[key])
#List comprehensions
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print(evens_to_50)
even_squares = [x**2 for x in range(12) if x % 2 == 0]
print(even_squares)
cubes_by_four = [x**3 for x in range(11) if x % 4 ==0] #not sure why x%4 w/o parenthesis doesn't work see example below
print(cubes_by_four)
cubes_by_four1 = [x**3 for x in range(1,11) if ((x**3) % 4 ==0)]
print(cubes_by_four1)
l = [x**2 for x in range(1,11)]
print(l[2:9:2])
| true |
b3b88fe8ea17fd2a5d32e6ca796633d9855c7aa4 | Izaya-Shizuo/lpthw_solutions | /ex9.py | 911 | 4.5 | 4 | # Here's some new strange stuff, remember type it exactly
# Assigning the days variable with a string containing the name of all the 7 days in their short form
days = "Mon Tue Wed Thu Fri Sat Sun"
# Assigning the month variable with the name of the months from Jan to Aug in their short forms. After ech month's name there is a new line character which while printing place the cursor on the next line.
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# These two print commands print the days and months variable values as they are stored in the variables
print "Here are the days: ", days
print "Here are the months: ", months
# This print statement can print multiple lines if use 3 double-quotes at the starting and the end of the print statement.
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
| true |
d1608587d280fd2ed388aaa71241f856421f7648 | todaatsushi/python-data-structures-and-algorithms | /algorithms/sort/insertion_sort.py | 1,025 | 4.40625 | 4 | """
Insertion sort.
Sort list/array arr of ints and sort it by iterating through and placing each element
where it should be.
"""
def insertion_sort(arr, asc=True):
"""
Inputs:
- Arr - list of ints to be sorted. Assumes arr
is longer than 1 element long.
- asc - True for ascending, False for descending
"""
final = list(arr)
# Iterate through list
for i in range(1, len(final)):
current = final[i]
# Compare current to every preceding element
for n in range(0, i):
# If smaller, place before and remove current from current location
if current < final[n]:
final.pop(i)
final.insert(n, current)
break
# Reverse list for descending order
if not asc:
return [final[i] for i in range(len(final) - 1, -1, -1)]
return final
import random
unsorted = [random.randint(0, 1000) for i in range(0, 10)]
print(insertion_sort(unsorted))
print(insertion_sort(unsorted, False))
| true |
453fc0baf0163d84d4b0b26ffa2164826bec58cf | fslichen/Python | /Python/src/main/java/Set.py | 207 | 4.34375 | 4 | # A set is enclosed by a pair of curly braces.
# Set automatically removes duplicate elements.
set = {'apple', 'pear', 'banana', 'apple'}
print(set)
if 'apple' in set:
print('Apple is in the set.') | true |
41bac5b84ed3e03a44faaf6a3cdcb39649e8ba0d | shubhamjain31/demorepo | /Python_practice/Practice_10.py | 330 | 4.125 | 4 | from collections import Counter
str = 'In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.'
count = Counter(str).most_common(10)
print(count) | true |
ad947590ffed3dcfe73337bea8ffe8e68b6910ef | sky-bot/Interview_Preparation | /Educative/Permutation_in_a_String_hard/sol.py | 1,806 | 4.40625 | 4 | # Given a string and a pattern, find out if the string contains any permutation of the pattern.
# Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations:
# abc
# acb
# bac
# bca
# cab
# cba
# If a string has ‘n’ distinct characters it will have n!n! permutations.
# Example 1:
# Input: String="oidbcaf", Pattern="abc"
# Output: true
# Explanation: The string contains "bca" which is a permutation of the given pattern.
# Example 2:
# Input: String="odicf", Pattern="dc"
# Output: false
# Explanation: No permutation of the pattern is present in the given string as a substring.
# Example 3:
# Input: String="bcdxabcdy", Pattern="bcdyabcdx"
# Output: true
# Explanation: Both the string and the pattern are a permutation of each other.
# Example 4:
# Input: String="aaacb", Pattern="abc"
# Output: true
# Explanation: The string contains "acb" which is a permutation of the given pattern.
# Sol
def find_permutation(str, pattern):
print("str => {} pattern => {}".format(str, pattern))
pat_dict = dict()
for i in pattern:
if i in pat_dict.keys():
pat_dict[i] = pat_dict[i] + 1
else:
pat_dict[i] = 1
for i in range(len(str)):
if str[i] in pat_dict.keys():
pat_dict[str[i]] = pat_dict[str[i]]-1
else:
return False
for i in pat_dict.values():
if i != 0:
return False
return True
def main():
str = "bcdxabcdy"
pattern = "bcdyabcdx"
for i in range(len(str)):
if i+len(pattern)<=len(str):
temp_val = find_permutation(str[i:i+len(pattern)], pattern)
# print(temp_val)
if temp_val:
return True
return False
print(main()) | true |
a1ff9c00543721443a49cee0b3c9ecbe1741f740 | sky-bot/Interview_Preparation | /Educative/LinkedList/Palindrome_LinkedList.py | 1,343 | 4.125 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def is_palindromic_linked_list(head):
slow = head
fast = head
tail = None
count = 1
middle = None
while(fast.next and fast.next.next):
slow = slow.next
fast = fast.next.next
count += 2
if fast.next:
count+=1
fast = fast.next
tail = fast
middle = slow
reverse_the_list(slow)
first = head
last = tail
i=0
count = int(count/2)
while(i<count):
if first.value != last.value:
return False
first = first.next
last = last.next
i = i + 1
return True
return count
def reverse_the_list(head):
# display(head)
prev = head
cur = head.next
temp = None
while(cur):
temp = cur.next
cur.next = prev
prev = cur
cur = temp
# head.next = None
return prev
def main():
head = Node(2)
head.next = Node(4)
head.next.next = Node(6)
head.next.next.next = Node(4)
head.next.next.next.next = Node(2)
print("Is palindrome: " + str(is_palindromic_linked_list(head)))
head.next.next.next.next.next = Node(2)
print("Is palindrome: " + str(is_palindromic_linked_list(head)))
main()
| true |
179576de0a97a3a2957d7cdcedf93d53e203869e | Switters37/helloworld | /lists.py | 758 | 4.25 | 4 |
#print range(10)
#for x in range (3):
# print 'x=',x
#names = [['dave',23,True],['jeff',24,False],['mark',21,True]]
#for x in names:
# print x
#print names [1][1]
#numbers in square brackets above will index over in the list. So in this case, the list will index over 1 list, and then 1 space in the second list.
# thus giving 24, which is the second value in the second list.
#use a number sign to comment out stuff....
#for x in range (3):
# y = x**2
# print y
# for-loops:
# so for the range(4) [0, 1, 2, 3], for i = the range(4), it will loop and produce the array of [0, 1, 4, 9]
#x = range (4)
#y = [i**2 for i in x]
#print y
y = list()
for x in range(3):
y.append(x**2)
print y
y = [i+3 for i in y]
print y
| true |
1260a7849253566d81c9d5c8d0836f3c20b71bac | NihalSayyad/python_learnigs | /51DaysOfCode/017/Enumerator_in_py.py | 221 | 4.15625 | 4 | '''
In we are interested in an index of a list, we use enumerate.
'''
countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
for index, i in enumerate(countries):
print(f"country {i} is at index {index}") | true |
465380ce5b174a59245d0691e8394672def2d779 | devanbenz/PythonStuff | /MIT OCW/LectureSix/lectureSix.py | 2,618 | 4.40625 | 4 | ## Recursion -
# **Process of repeating items in a self-similar way
# '''Droste effect''' - picture within a picture
# Divide and conquer
# Decrease and conquer
# Algorithmically we reduce a problem into smaller parts in
#order to solve problems
# Semantically it is a function that is called within the body
#of the function
def recursionOne(x):
x -= 1
if x == 1:
print('Done!')
return x
else:
recursionOne(x)
print(x)
#recursionOne(5)
##Recursive reduction
# a * a == a + a + a..... + a
# for recursion this is a + a * (b - 1)
def mult(a,b):
if b == 1:
return a
else:
return a + mult(a, b -1)
#print(mult(3,4))
def factorial(n):
if n == 1:
return 1
else:
print(n)
return n * factorial(n-1)
#print(factorial(5))
#when writing recursive code once we hit the base case think
#of the function back tracking and performing the return sequences
#backwards
##MATHEMATICAL INDUCTION
#If I want to prove a statement is true on all integers
#I prove it is true for the smallest value of n and 'n+1'
def fib(x):
if x == 0 or x == 1:
return 1
else:
return fib(x - 1) + fib(x - 2)
print(fib(5))
def isPalindrome(s):
def toChars(s):
s = s.lower()
ans = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
ans = ans + c
return ans
def isPal(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and isPal(s[1:-1])
return isPal(toChars(s))
###############################################
#Dictionary data-type
#way to store data in a key:value pair
grades = {'Devan': ['A', 6.001], 'Carl': ['B',2.001]}
print(grades)
for e in grades.values():
print(e)
def lyricFrequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
#####CHAPTER 4.3 IN ICS#####
#Recursion is made up of two parts a base case that specifies the result
#for a special case and a recursive (inductive) case
#A classic Inductive definition :
# 1! = 1 <---- base case
# (n + 1)! = (n + 1) * n!
# Due to when you are back tracking in recursion we need to have the base case as the first possible
#return value and work towards it, so in factorial so n is going to be multiplied by n - 1 during each turn
#Lets do a factorial recursion
def factorialICS(n):
if n == 1:
return 1
else:
return n * factorialICS(n - 1)
#print(factorialICS(n=20))
#Basic summation recursion - adds from n to 1
def summation(n):
if n == 1:
return 1
else:
return n + summation(n - 1)
print(summation(10))
| true |
bb17f15513d9e77d524d9396beabff0470adab0e | sejalg1019/project-97 | /guessingGame.py | 559 | 4.3125 | 4 | import random
print("Number guessing game!")
number = random.randint(1,9)
chances = 0
print("Guess a number between 1-9 (You only have 5 chances to guess correctly)")
while chances < 5:
guess = int(input("Enter your guess:"))
if guess == number:
print("Congratulations, you won!")
break
elif guess < number:
print("Your guess is too low, guess again", guess)
else:
print("Your guess is too high, guess again", guess)
chances += 1
if not chances < 5:
print("You lose! The number is: ", number) | true |
19bc00052a6249859a29cbd57b55e1ac2821c175 | Nsk8012/TKinter | /1.py | 426 | 4.34375 | 4 | from tkinter import * #import Tkinter lib
window = Tk() #Creating window
window.title("Print") #Giving name of the window
l1 = Label(window, text="Hello World!",font=('Arial Bold',50)) #label is used to print line of text on window gui
l1.grid(column=0,row=0) #grid set the position of label on window
window.geometry('500x500') #sets the size of window
window.mainloop() #Runs the event loop untill x button is clicked
| true |
83119fa61c4da7286fba5de1586d2df40a5bcb7f | SW1992/100-Days-Of-Code | /Forty-third-day.py | 1,271 | 4.625 | 5 | # Day Forty Three
# Python Range & Enumerate
# range() function
# the python range function can be thought of as a form of loop
# it loops through & produces list of integer values
# it takes three parameters, start, end & step
# if you specify only an end value, it will loop up to the number (exclusive)
# starting from 0, as start defaults at 0 if it's omitted
for w in range(3):
print("w range:", w)
# prints 0, 1, 2
# if you specify an start value & end value it will start from start & loop up to end
for x in range(0,3):
print("x range:", x)
# prints 0, 1, 2
# if you specify a step value, it will use that to decide the incremental difference between each number it produces
for y in range(3,15,3):
print("y range:", y)
# prints 3, 6, 9, 12
# you can also count downwards with range, aswell as upwards
for z in range(5,-1,-1):
print("z range:", z)
# prints 5, 4, 3, 2, 1, 0
# enumerate() function
# the native enumerate function will display the associative index & item, for each item in a list
fruits = ["Apple", "Mango", "Orange"]
print("Enumerate:", end = " ")
for item in enumerate(fruits):
print(item, end = " ")
# Enumerate: (0, "Apple") (1, "Mango") (2, "Orange")
| true |
c3a81e455e13111e4f3d39301727e1b8a20ae464 | codingandcommunity/intro-to-python | /beginner/lesson7/caesar.py | 494 | 4.15625 | 4 | '''
Your task is to create a funcion that takes a string and turns it into a caesar cipher.
If you do not know what a caesar cipher is, here's a link to a good description:
https://learncryptography.com/classical-encryption/caesar-cipher
'''
def makeCipher(string, offset):
# Your code here
return string
s = input("Enter a string to be turned into a cipher: ")
o = input("Enter an offset for your cipher: ")
cipher = makeCipher(s, o)
print("You're new cipher is: {}".format(cipher))
| true |
b530e63e5290ca037d25b0d547fee2f963b91a26 | codingandcommunity/intro-to-python | /beginner/lesson7/piglatin.py | 655 | 4.28125 | 4 | '''
Write a function translate that translates a list of words to piglatin
ex) input = ['hello', 'world']
output = ['ellohay', 'orldway']
remember, you can concactenate strings using +
ex) 'hello' + ' ' + 'world' = 'hello world'
'''
def translate( ):
# Your code here
phrase = (input("Enter a phrase -> ")).split() # takes a string as input and splits it into a list of strings; ex: hello world becomes ['hello', 'world']
piglatin = translate(phrase) # write the function translate
print(' '.join(piglatin)) # takes a list of strings and make them into one string with a space between each item; ex: ['hello', 'world'] becomes 'hello world' | true |
6f5b4a260426de11c79686367fc4d854d3d2c10a | carlosarli/Learning-python | /old/str_methods.py | 458 | 4.21875 | 4 | name = 'lorenzo' #this is a string object
if name.startswith('lo'):
print('yes')
if name.find('lo') != -1: #.find finds the position of a string in a string, and returns -1 if it's not succesfull in finding the string in the string
print('yes')
delimiter = '.'
namelist = ['l', 'o', 'r', 'e', 'n', 'z', 'o']
print('imma the new florida: ', delimiter.join(namelist))#.join substitutes commas and spaces between strings in a list with a given string
| true |
e7ce661b78ca1fb34ee44f025de804f0fc4cec29 | AkshayGulhane46/hackerRank | /15_string_split_and_join.py | 512 | 4.28125 | 4 | # Task
# You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
#
# Input Format
# The first line contains a string consisting of space separated words.
#
# Output Format
# Print the formatted string as explained above.
def split_and_join(line):
a = line.split(" ") # a is converted to a list of strings.
a = "-".join(a)
return a
# write your code here
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) | true |
625abfb54078aa303cfc1e7d9f358a0fc1b6528d | kolodziejp/Learning-Part-1 | /Smallest_Value.py | 343 | 4.28125 | 4 | # Finding the smallest value in a range
small = None
print ("Let us look for the smallest value")
for number in [21, 42, 13, 53, -5, 2, 56, 119, -23, 99, 2, 3, 9, 87]:
if small is None:
small = number
elif number < small:
small = number
print (small, number)
print ("The smallest number is", small)
| true |
c5f22e3b607f0af078e1506feb80d6d81041862c | kolodziejp/Learning-Part-1 | /Ex_5_1.py | 480 | 4.1875 | 4 | # entered numbers are added, counted and average computed
count = 0
total = 0
while True:
num = input ("Enter a number: ")
if num == "done":
break
try:
fnum = float(num) #convert to floating number
except:
print ("Invalid Data!")
continue # should only consider valid numbers continue and ignore error
count = count + 1
total = total + fnum
avg = total / count
print (total, count,avg)
| true |
e925e128a91016a06b95f1c88d3c9a7f8c1628f8 | ApurvaW18/python | /Day 3/Q2.py | 377 | 4.25 | 4 | '''
2.From a list containing ints, strings and floats,make three lists to store
them separately.
'''
l=['aa','bb','cc',1,2,3,1.45,14.51,2.3]
ints=[]
strings=[]
floats=[]
for i in l:
if (type(i))==int:
ints.append(i)
elif (type(i))==float:
floats.append(i)
else:
strings.append(i)
print(ints)
print(strings)
print(floats)
| true |
0ccd24589fd5833bd9dd205fe3bf34a315f533eb | ApurvaW18/python | /Day 6/Q2.py | 678 | 4.125 | 4 | '''
2.Write program to implement Selection sort.
'''
a = [16, 19, 11, 15, 10, 12, 14]
i = 0
while i<len(a):
s=min(a[i:])
print(s)
j=a.index(s)
a[i],a[j] = a[j],a[i]
i=i+1
print(a)
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx], array[step])
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)
| true |
9fef6a6753a7fc3f577a737d811d5179fe0d1435 | oski89/udemy | /complete-python-3-bootcamp/my-files/advanced_lists.py | 398 | 4.25 | 4 | l = [1, 2, 3, 3, 4]
l.append([5, 6]) # appends the list as an item
print(l)
l = [1, 4, 3, 3, 2]
l.extend([5, 6]) # extends the list
print(l)
print(l.index(3)) # returns the index of the first occurance of the item
l.insert(2, 'inserted') # insertes at index
print(l)
l.remove(3) # removes the first occurance
print(l)
l.remove('inserted')
l.sort() # removes the first occurance
print(l)
| true |
800319d01235504239ac6011970662a0b9dc7a76 | Tduncan14/PythonCode | /pythonGuessGame.py | 834 | 4.21875 | 4 | #Guess my number
##
#The computer picks a random number between 1 and 100
#The player tries to guess it and the computer lets
#The player on guessing the numner is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\n I'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible. \n")
# set the intial values
the_number = random.randint(1,4)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("guess lower")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you:" ,tries ," tries")
input("press enter to exit the code")
| true |
4741931113c64c098b5d06449bceafc4949bab1f | seen2/Python | /workshop2019/secondSession/function.py | 415 | 4.1875 | 4 | # without parameter
def func():
a, b = 10, 20
c = a+b
print(c)
# func()
def funcP(a, b):
'''
takes two integer and print its sum
'''
c = a+b
print(c)
# default argument comes last in parameter sequence.
def funcDefaultP(a, b=1, c=1):
'''
takes three integer and print its sum or print default sum
'''
c = a+b
print(c)
# funcP(10, 30)
funcDefaultP(10, 30)
| true |
e90d7ae10791ac7dd407d940ed3e444770d087c1 | seen2/Python | /bitwiseOperators/bitwiseLogicalOperators.py | 406 | 4.125 | 4 | def main():
a=2 # 2=ob00000010
b=3 # 3=ob00000011
# logical operations
print(f"{a} AND {b}={a&b}")
print(f"{a} OR {b}={a|b}")
# takes binary of a and flips its bits and add 1 to it.
# whilch is 2 's complement of a
print(f"2's complement of {a} ={~a}")
# exclusive OR (X-OR)
print(f"{a} X-OR {b}={a^b}")
if __name__=="__main__":
main()
| true |
78c62c8944c81c10e80cc64673aab404ff0f4bd5 | GeorgeMohammad/Time2ToLoseWeightCalculator | /WeightLossCalculator.py | 1,081 | 4.3125 | 4 | ####outputs the amount of time required to lose the inputted amount of weight.
#computes and returns the amount of weight you should lose in a week.
def WeeklylbLoss(currentWeight):
return (currentWeight / 100)
#Performs error checking on a float.
def NumTypeTest(testFloat):
errorFlag = True
while(errorFlag):
try:
float(testFloat)
except:
testFloat = input("Invalid Type. Enter a decimal")
else:
testFloat = float(testFloat)
errorFlag = False
return testFloat
weight2Lose = input("How many pounds do you want to lose: ")
weight2Lose = NumTypeTest(weight2Lose)
#Gathering weight input
weight = -1
while (weight < weight2Lose):
weight = input("How much do you weigh: ")
weight = NumTypeTest(weight)
weightLost = 0
weekCount = 0
#Subtracts weight week by week.
while ((weightLost < weight2Lose) and (weight2Lose <= weight)):
weightLost += WeeklylbLoss(weight)
weight -= WeeklylbLoss(weight)
weekCount += 1
print("The weight loss will take", weekCount, "week/s.")
| true |
b7df58e4d45c16fc5fe35e2ba028378c9cf227d8 | rcreagh/network_software_modelling | /vertex.py | 606 | 4.125 | 4 | #! usr/bin/python
"""This script creates an object of class vertex."""
class Vertex(object):
def __init__(self, name, parent, depth):
"""Initialize vertex.
Args:
name: Arbitrary name of the node
parent: Parent vertex of the vertex in a tree.
depth: Number of edges between the vertex itself and the root vertex.
"""
self.name = name
self.parent = parent
self.depth = depth
def __repr__(self):
"""Change print format to show name, parent and depth of vertices."""
return '\n' + str(
self.name) + ', ' + str(self.parent) + ', ' + str(self.depth)
| true |
8c2e4e8110aa53f0b5ecffce8b2b80ba2bbeb1aa | gittangxh/python_learning | /io_input.py | 364 | 4.3125 | 4 | def reverse(text):
return text[::-1]
def is_palindrome(text):
newtext=''
for ch in text:
if ch.isalpha() and ch.isnumeric():
newtext+=ch.lower()
return newtext == reverse(newtext)
something = input('Enter text:')
if is_palindrome(something):
print('yes, it is palindrome')
else:
print('no, it is not a palindrome')
| true |
b54ece015da6564cd0c5c839f67149774f0e0888 | niteshsrivats/IEEE | /Python SIG/Classes/Class 6/regularexp.py | 2,377 | 4.375 | 4 | # Regular expressions: Sequence of characters that used for
# searching and parsing strings
# The regular expression library 're' should be imported before you use it
import re
# Metacharacters: characters with special meaning
# '.' : Any character "b..d"
# '*' : Zero or more occurrences "bal*"
# '+' : One or more occurrences "bal+"
# '^' : Starts with "^bald"
# '$' : Ends with "bald$"
# '{}' : Exactly the specified number of occurrences "al{3}"
# '()' : Capture and group
# '|' : Either or "bald|ball"
# '\' : Signals a special sequence "\d"
# Special Sequences: A special sequence is a '\' followed by one of the
# characters which has a special meaning
# \d : Returns a match if string contains digits
# \D : Returns a match if string DOES NOT contain digits
# \s : Returns a match for a white space character
# \S : Match for non white space character
# \w : Match for word character(a-z,A-Z,0-9,_)
# \W : Returns a match if it DOES NOT contain word characters
# search function: Searches for first occurrence of pattern within a string.
# Returns a match object if there is a match
# Syntax: re.search(pattern,string)
line = "Message from anjali@gmail.com to nitesh@gmail.com"
mailId = re.search('\S+@\S+', line)
print("The first mail id is at position:", mailId.start())
# If the pattern is not present it returns None
line = "Message from anjali@gmail.com to nitesh@gmail.com @ 3:00"
time = re.search("\d{2}:\d{2}", line)
print(time)
# Returns none as no such pattern
# findall function: Returns a list containing all matches
line = "Message from anjali@gmail.com to nitesh@gmail.com"
mailId = re.findall('\S+@\S+', line)
print(mailId)
# Search for lines that start with From and have an at sign
"""
hand = open('example.txt')
for line in hand:
line = line.rstrip()
if re.search('^From:.+@', line):
print(line)
"""
# Escape characters: A way to indicate special characters by using backslash
line = "I received $1000 as a scholarship"
amount = re.findall("\$\d{4}", line)
print(amount)
# Since we prefix dollar sign with backslash it matches dollar sign and not
# end of string
| true |
77f86f9689a16c3a8d9438a24b5d13b67bd6c6f0 | alanvenneman/Practice | /Final/pricelist.py | 614 | 4.125 | 4 | items = ["pen", "notebook", "charge", "scissors", "eraser", "backpack", "cap", "wallet"]
price = [1.99, .5, 4.99, 2.99, .45, 9.99, 7.99, 12.99]
pricelist = zip(items, price)
for k, v in pricelist:
print(k, v)
cart = []
purchase = input("Enter the first item you would like to buy: ")
cart.append(purchase)
second = input("Enter another item: ")
cart.append(second)
third = input("Enter one last item: ")
cart.append(third)
prices = []
for k, v in pricelist:
if k in cart:
prices.append(v)
# print(v)
total = 0
for p in prices:
total += p
# print(cart)
# print(prices)
print(total)
| true |
4e7693939c6098c938fce30f8915f19b80dc2ecd | SteveWalsh1989/Coding_Problems | /Trees/bst_branch_sums.py | 2,265 | 4.15625 | 4 | """
Given a Trees, create function that returns a list of it’s branch sums
ordered from leftmost branch sums to the rightmost branch sums
__________________________________________________________________
0 1
/ \
1 2 3
/ \ / \
2 4 5 6 7
/ \ /
3 8 9 10
Here there are 5 branches ending in 8,9,10,6,7
SO sums would be:
1+2+4+8 =15
1+2+4+9 = 16
1+2+5+10 = 18
1+3+6 = 10
1+3+7 = 11
result being : [15, 16, 18, 10, 11]
__________________________________________________________________
- Need to keep runing total passed into recursive function,
- when no more children it can be added to an array of branch values
- Sum up values within the array
__________________________________________________________________
Space and Time Complexity
Space: O(N)
- impacted by list of branch sums
- impacted by recurisve nature of function
Time: O(N)
- need to traverse all nodes
"""
def get_branch_sum(root):
"""sums values of all branches within a Trees"""
sums = []
branch_sum_helper(root, 0, sums)
return sums
def branch_sum_helper(node, total_sum, sums):
# return if none
if node is None:
return
# update branch total
updated_sum = total_sum + node.value
# check if need to continue
if node.left is None and node.right is None:
sums.append(updated_sum)
return
branch_sum_helper(node.left, updated_sum, sums)
branch_sum_helper(node.right, updated_sum, sums)
def main():
""" Main function"""
# create Trees
root = BinaryTree(1)
root.left = BinaryTree(2)
root.left.left = BinaryTree(4)
root.left.left.left = BinaryTree(8)
root.left.left.right = BinaryTree(9)
root.left.right = BinaryTree(5)
root.left.right.right = BinaryTree(10)
root.right = BinaryTree(3)
root.right.left = BinaryTree(6)
root.right.right = BinaryTree(7)
sums = get_branch_sum(root)
print(f" The list of all sums of each branches within Trees is {sums}")
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
''' Run Program '''
main()
| true |
a21b1e8a04826d5391cfa5eac83e0d4b12d22859 | SteveWalsh1989/Coding_Problems | /Arrays/sock_merchant.py | 634 | 4.3125 | 4 |
def check_socks(arr, length):
""" checks for number of pairs of values within an array"""
pairs = 0
# sort list
arr.sort()
i = 0
# iterate
while i < (length - 1):
# set values
current = arr[i]
next = arr[i + 1]
# check if the same sock or different
if next == current:
pairs += 1
i += 2
else:
i += 1
return pairs
def main():
""" Main function"""
arr = [2, 3, 3, 1, 2, 1, 4, 2, 2, 2, 1]
res = check_socks(arr, len(arr) )
print(f"The array {arr} has {res} pairs")
''' Run Program '''
main()
| true |
70ed3e204149399b43259d4fa675d705cc4d9121 | yueranwu/CP1404_prac06 | /programming_language.py | 946 | 4.125 | 4 | """CP1404/CP5632 Practical define ProgrammingLanguage class"""
class ProgrammingLanguage:
"""represent a programming language"""
def __init__(self, name, typing, reflection, year):
"""Initiate a programming language instance
name: string, the name of programming language
typing: string, the typing of programming language is dynamic or static
reflection: string,
year:
"""
self.name = name
self.typing = typing
self.reflection = reflection
self.year = year
def __str__(self):
return "{}, {}, Reflection = {}, First appeared in {}".format(self.name, self.typing, self.reflection, self.year)
def is_dynamic(self):
"""
returns True/False if the programming language is dynamically typed or not
"""
if self.typing == "Dynamic":
return True
else:
return False
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.