blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
58f99618238ebedc92e013c8b47b259e1fb2b197 | ryadav4/Python-codes- | /EX_05/Finding_largestno.py | 263 | 4.28125 | 4 | #find the largest number :
largest = -1
print('Before',largest)
for i in [1,45,67,12,100] :
if i>largest :
largest = i
print(largest , i)
else :
print(i , 'is less than',largest)
print('largest number is :', largest)
| true |
6faa436ab98bac3d2f6c556f8cb239c48ba72b0f | BusgeethPravesh/Python-Files | /Question6.py | 1,549 | 4.15625 | 4 | """Write a Python program that will accept two lists of integer.
Your program should create a third list such that it contain only odd numbers
from the first list and even numbers from the second list."""
print("This Program will allow you to enter two list of 5 integers "
"\nand will then print the odd numbers from list 1 and even numbers from list 2. ")
tryagain="yes"
while tryagain=="yes":
count=0
list1=[]
print("\nLIST 1:")
while count<=4:
addintegers=input("Enter integer:")
list1.append(addintegers)
count+=1
print("\nList 1:",list1)
count=0
list2=[]
print("\nLIST 2:")
while count<=4:
addintegers=input("Enter integer:")
list2.append(addintegers)
count+=1
print("\nList 1:",list1)
print("List 2:",list2)
even_numbers=[]
odd_numbers=[]
for addintegers in (list1):
if int(addintegers)% 2 != 0:
odd_numbers.append(addintegers)
#else:
# print("No Odd Number in LIST 1")
for addintegers in (list2):
if int(addintegers) % 2 == 0:
even_numbers.append(addintegers)
# else:
# print("No Even Number in LIST 2")
# print("\nOdd Numbers in List 1:", odd_numbers)
# print("Even Numbers in List 2", even_numbers)
print("\nOdd Numbers from List 1 and Even Numbers from List 2:",odd_numbers,even_numbers)
tryagain = input("\nContinue? Yes/No?")
if tryagain == " no ":
break | true |
04890c636e097a33fdad2ff75e9c00be0da9ee06 | Oluyosola/micropilot-entry-challenge | /oluyosola/count_zeros.py | 544 | 4.15625 | 4 | # Write a function CountZeros(A) that takes in an array of integers A, and returns the number of 0's in that array.
# For example, given [1, 0, 5, 6, 0, 2], the function/method should return 2.
def countZeros(array):
# count declared to be zero
count=0
# loop through array length and count the number of zeros
for m in range(0,len(array)):
if array[m] == 0:
count=count+1
return count
# testing the function
A = [1, 0, 5, 6, 0, 2]
zeros_count=countZeros(A)
print("Number of zeros is", zeros_count)
| true |
d9504458070080dca24cf9736564196369483c82 | salmonofdoubt/TECH | /PROG/PY/py_wiki/wiki_code/w8e.py | 1,551 | 4.125 | 4 | #!/usr/bin/env python
#8_Lists - test of knowledge
def get_questions(): #Note that these are 3 lists
return [["What color is the daytime sky on a clear day? ", "blue"],
["What is the answer to life, the universe and everything? ", "42"],
["What is a three letter word for mouse trap? ", "cat"]]
def check_question(question_and_answer): #what element is the q, which one the a
question = question_and_answer[0]
answer = question_and_answer[1]
given_answer = input(question) #give the question to the user
if answer == given_answer: #compare the user's answer to the testers answer
print("Correct")
return True
else:
print("Incorrect, correct was:", answer)
return False
def run_test(questions): #runs through all the questions
if len(questions) == 0:
print("No questions were given.")
return #the return exits the function
index = 0
right = 0
while index < len(questions):
if check_question(questions[index]): # Check the question, it extracts a q and a list from the lists of lists.
right = right + 1
index = index + 1 # go to the next question
print("You got", right * 100 / len(questions), # order of the computation, first multiply, then divide
"% right out of", len(questions))
run_test(get_questions()) #let's run the questions
| true |
df7cfa7f74c9ac6d00ee5f0cb1c059aeac69febb | salmonofdoubt/TECH | /PROG/PY/dicts/ex40.py | 800 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Discription: dicts
Created by André Baumann 2012 Copyright (c) Google Inc. 2012. All rights reserved.
"""
import sys
from sys import exit
import os
def find_city(which_state, cities):
if which_state in cities:
return cities[which_state]
else:
return "Not found."
def main():
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Oregon'
for key in cities:
print key
cities[key]()
while True:
print "State?: / ENTER to quit",
which_state = raw_input("> ")
if not which_state: break
print find_city(which_state, cities)
# simply calls find_city() with cities (the dict)
# and the state (entered), prints the return value
if __name__ == '__main__':
main()
| true |
3de44b016d5b45e0670397bfe59d69aedb9bef33 | salmonofdoubt/TECH | /PROG/PY/classes/dog.py | 1,881 | 4.53125 | 5 | #!/usr/bin/env python
# encoding: utf-8
'''
How to use classes and subclasses
- classes are templates
Created by André Baumann on 2011-12-11.
Copyright (c)2011 Google. All rights reserved.
'''
import sys
import os
class Dog(object): # means Dog inherits from 'object'
def __init__(self, name, breed): # __init__ is class constructor method
self.name = name # initilizing the instance vars
self.breed = breed
#print self.name + ' created this Dog instance'
def Bark(self): # classes also provide certain methods
return 'barking!'
def Greet(self):
return 'Woof, I am ' + self.name
def Rename(self, new_name):
self.name = new_name
return self.name
def Owner(self, owner_id):
self.owner = owner_id
return 'Who owns '+ self.name +'? '+ self.owner +' does.'
class Puppy(Dog): # creates a subclass of (now) superclass Dog
def Bark(self):
return 'Puppy wiff'
# --- lets play with this ---------------------------------------------------:
my_dog = Dog('Lou', 'Malti') # - instantiate Dog object, calling the
# contructor method. Ignore 1st var 'self'.
# - my_dog = Dog(breed='Malti', name='Lou')
print my_dog.name # let'see this Dog's properties
print my_dog.breed
print my_dog.Bark() # let's use this Dog's methods
print my_dog.Greet()
my_dog.Rename('Lou2')
print my_dog.Greet()
print my_dog.Owner(u'André') # this method adds an instance variable that
# was not previously defined in the class.
# --- lets play with subclass -----------------------------------------------:
my_puppy = Puppy('Louchen', 'Malti')
print my_puppy.name
print my_puppy.breed
print my_puppy.Bark() # uses the new bark method from subclass
# so subclasses EXTEND the superclass
| true |
2f3e14bec17b97afd523081d2e116dea6ddcd6d8 | salmonofdoubt/TECH | /PROG/PY/py_wiki/wiki_code/w12a.py | 434 | 4.125 | 4 | #!/usr/bin/env python
# 12_Modules
import calendar
year = int(input('Type in the bloody year: '))
calendar.setfirstweekday(calendar.SUNDAY)
calendar.prcal(year) # Prints the calendar for an entire year as returned by calendar().
from time import time, ctime
prev_time = ""
while True:
the_time = ctime(time())
if prev_time != the_time:
print("The time is:", ctime(time()))
prev_time = the_time
| true |
cb7e18fd05f7cb9b2bedb14e80ceef0c9d5591ea | molusca/Python | /learning_python/speed_radar.py | 955 | 4.15625 | 4 | '''
A radar checks whether vehicles pass on the road within the 80km/h speed limit.
If it is above the limit, the driver must pay a fine of 7 times the difference between the speed that he was
trafficking and the speed limit.
'''
def calculate_speed_difference(vehicle_speed, speed_limit):
return (vehicle_speed - speed_limit)
def calculate_fine_value(speed_difference, base_multiplier):
return (speed_difference * base_multiplier)
print('\nSPEED RADAR')
vehicle_speed = int(input('\nVehicle speed (Km/h): '))
speed_limit = 80
base_multiplier = 7
speed_difference = calculate_speed_difference(vehicle_speed, speed_limit)
fine_value = calculate_fine_value(speed_difference, base_multiplier)
if vehicle_speed > speed_limit:
print(f'\nThe vehicle was {speed_difference}Km/h above the speed limit and got fined!')
print(f'The fine value is ${fine_value} !\n')
else:
print('\nThe vehicle was trafficking within the speed limit!\n')
| true |
18fa6287bdfec727517bb2073845c911f1494b2f | swatha96/python | /preDefinedDatatypes/tuple.py | 928 | 4.25 | 4 | ## tuple is immutable(cant change)
## its have index starts from 0
## enclosed with parenthesis () - defaultly it will take as tuple
## it can have duplicate value
tup=(56,'swe',89,5,0,-6,'A','b',89)
t=56,5,'swe'
print(type(t)) ## it will return as tuple
print(tup)
print(type(tup)) ## it will return datatype as tuple
print(tup[3]) ## print3rd index - 4th value
tup[6]=45 ## cant assign (error : does not support item assignment)
del tup[2] ## cant del (error : 'tuple' object does not support item deletion)
s="asd",'swe','swe is a good girl',5,5
d=5,5,6,9,10
print(d) ## will print enclosed with parenthesis- it will considered as type tuple
print(d[4])
print(type(d)) ## return type as tuple
print(s) ## will print enclosed with parenthesis- it will considered as type tuple
print(s[2])
print(type(s)) ## return - tuple
del s[1] ## error :'tuple' object doesn't support item deletion
| true |
4205c5ca3e4edd81809135f9aa3f79323a0db129 | swatha96/python | /numberDatatype.py | 327 | 4.3125 | 4 | #int
#float
#complex - real and imaginary number: eg:5 : it will return 5+0j
#type() - to get the datatype - predefined function
#input()- predefined function - to get the inputs from the user
a=int(input("enter the number:"))
b=float(input("enter the number:"))
c=complex(input("enter the number:"))
print(a,b,c)
| true |
317b17c8ac8c70a11950599c1c150feadf2cf034 | swatha96/python | /large_number_list.py | 478 | 4.1875 | 4 | """
number=[23,98,56,26,96,63]
number.sort()
maxi=len(number)
minus=maxi-1
for i in range(maxi):
if(i==minus):
print("the largest number is :",number[i])
"""
number=[]
n=int(input("how many numbers you wants to add:"))
for i in range(n):
num=int(input("enter the number:"))
number.append(num)
number.sort()
maxi=len(number)
minus=maxi-1
for i in range(maxi):
if(i==minus):
print("the largest number is :",number[i])
| true |
fc551bda83861e5a5f921668fc08d3e98b76307e | c344081/learning_algorithm | /01/48_Rotate_Image.py | 1,544 | 4.3125 | 4 | '''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly.
DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
'''
'''
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
13, 14, 15, 16
->
1, 5, 9, 13
2, 6, 10, 14
3, 7, 11, 15
4, 8, 12, 16
->
13, 9, 5, 1
14, 10, 6, 2
15, 11, 7, 3
16, 12, 8, 4
'''
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix: return
if len(matrix) == 0: return
n = len(matrix[0])
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n):
for j in range(int(n * 0.5)):
matrix[i][j] , matrix[i][n - j - 1] = matrix[i][n - j - 1], matrix[i][j]
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
s = Solution()
s.rotate(matrix)
print(matrix)
| true |
f1251d29d364dd65a74150dcdd1c7b4e5a906bbc | 009shanshukla/tkinter_tut_prog | /tkinter3.py | 433 | 4.125 | 4 | from tkinter import*
root = Tk()
######making lable #######
one = Label(root, text="one", bg="red", fg="white") #bg stands for background color
one.pack() #static label
two = Label(root, text="two", bg="green", fg="black")
two.pack(fill=X) #label that streches in x-dir
three = Label(root, text="one", bg="red", fg="white")
three.pack(side=LEFT, fill=Y) #label that streches in y-dir
root.mainloop()
| true |
6f8af959758fad53d3a36b7da1fb1ea9aeca3777 | einian78/The-Complete-Python-3-Course-Beginner-to-Advanced-Udemy-Course | /Section 3 (Programming Basics)/3. Built-in Functions.py | 706 | 4.21875 | 4 | # print(): prints whatever inside
print("hi!") # hi!
# str(): Converts any type into a string
str(5) # 5
str(True) # True
# int(): Converts any type into a integer
int("5")
# float(): Converts any type into a float
float("5.6")
print(float(1)) # 1.0
# bool(): Converts any type into a boolean
bool("True")
# len(): returns the length
len("Hello There!")
len([1,2,3,4,5,6,7])
len(["Hello", "Muiz"])
print(len(["Hello", "Muiz"])) # 2
# sorted(): sort an array/list in accending order
arr = [16, 3,8,6,9,133,435,21,823,45]
arr = sorted(arr)
print(arr) # [3, 6, 8, 9, 16, 21, 45, 133, 435, 823]
Str = ["A", "Z", "d", "c", "5.5", "1"]
Str = sorted(Str)
print(Str) # ['1', '5.5', 'A', 'Z', 'c', 'd']
| true |
91945d3b7d3fd6939c0d44e0a08fb8a5e6627af5 | msheikomar/pythonsandbox | /Python/B05_T1_Dictionaries.py | 420 | 4.21875 | 4 | # Dict:
# Name is String, Age is Integer and courses is List
student = {'name':'John', 'age':25, 'courses':['Math', 'CompSys']}
# To get value by using key
print(student['name'])
# To get value by using key
print(student['courses'])
# If you look at the keys are currently being string. But actually it can be any immutable data type
#student = {1:'John', 'age':25, 'courses':['Math', 'CompSys']}
#print(student[1]) | true |
8b393455be6e85cc3825b98fe857d7147c7c1806 | msheikomar/pythonsandbox | /Python/B04_T1_Lists_Tuples_Sets.py | 974 | 4.5 | 4 | # Lists and Tuples allows us to work with sequential data
# Sets are unordered collections of values with no duplicate
# List Example
courses = ['History', 'Math', 'Physics', 'ComSys'] # Create List with elements
print(courses) # To print lists
print(len(courses)) # To print length of list
print(courses[0]) # To access first value from the list
print(courses[3]) # To access last value from the list
# We can use -ve index too to access last value of the list
print("-ve index example")
print(courses[-1]) # So zero is the first item of the list -1 is the last item of the list
# List index error
# print(courses[4]) # **List index out of range
# Get first two values/items from the list
print("Get first two values/items from the list")
print(courses[0:2])
print(courses[:2]) # Alternative approach. You can leave off the start index as empty
# Get values/items from the mid of the list and all the way end
print(courses[2:]) # Leave the end index empty
| true |
d5c7efe1c7f1345be4b3fa2bdc3c1cb218c532e7 | riya1794/python-practice | /py/list functions.py | 815 | 4.25 | 4 | list1 = [1,2,3]
list2 = [4,5,6]
print list1+list2 #[1,2,3,4,5,6]
print list1*3 #[1,2,3,1,2,3,1,2,3]
print 3 in list1 #True
print 3 in list2 #False
print "length of the list : "
print len(list1)
list3 = [1,2,3]
print "comparsion of the 2 list : "
print cmp(list1,list2) # -1 as list1 is smaller
print cmp(list2,list1) # 1 as list2 is bigger
print cmp(list1,list3) # 0 as same
print max(list1)
print min(list1)
new_list = []
for i in range(6):
new_list.append(i)
print new_list
new_list.append(3)
print "list after appending 3", new_list
print new_list.count(3) #count number of 3 in the list
print new_list.index(2)
print new_list.pop(0)
print new_list.pop(-1)
new_list.remove(2)
print new_list
new_list.reverse()
print new_list
list4 = [2,3,2,31,1,0]
list4.sort()
print list4 | true |
c6e4fa1d487e0c922865c44fa8042aad78cf6a96 | crazymalady/Python-Exercises | /ielect_Meeting10/w10_e1fBC_ListOperations_Delete Elements.py | 508 | 4.40625 | 4 | def display():
try:
# We can change the values of elements in a List. Lets take an example to understand this.
# list of nos.
list = [1,2,3,4,5,6]
# Deleting 2nd element
#del list[1]
# Deleting elements from 3rd to 4th
#del list[2:4]
#print(list)
# Deleting the whole list
del list
print(list)
#if(list == -1):
# print("EMPTY!")
except:
print("Something went wrong")
display()
| true |
d63aa167926b91a246b0219af06e6ffec803a944 | SahityaRoy/get-your-PR-accepted | /Sorting/Python/Insertion_Sort.py | 532 | 4.21875 | 4 | # Python program to implement Insertion Sort
def insertion_sort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = key
# Driver function
if __name__ == '__main__':
nums=list(map(int,input().split()))
insertion_sort(nums) # Calling the insertion_sort function by passing the 'nums' list
# Printing the sorted list
print(nums)
| true |
db188733063d2315b9ba8b8906b24576fc5883cc | SourabhSaraswat-191939/ADA-BT-CSE-501A | /Assignment-2/Insertion_Sort.py | 1,740 | 4.5 | 4 | #Insertion sort is used when number of elements is small. It can also be useful when input array
# is almost sorted, only few elements are misplaced in complete big array.
import time, random, sys
sys.setrecursionlimit(3010)
def insertionSortRecur(arr,n):
if n<=1:
return
insertionSortRecur(arr,n-1)
val = arr[n-1]
j = n-2
while j>=0 and val<arr[j]: #compare value with its predecissors till we get the right position.
arr[j+1] = arr[j] # performing swap here.
j-=1
arr[j+1] = val # placing the value at right position.
return arr
def insertionSort(arr):
# we are starting from 1 because there is no sense to compare value at 0 index with none.
for i in range(1,len(arr)):
val = arr[i]
j = i-1
while j>=0 and val<arr[j]: #compare value with its predecissors till we get the right position.
arr[j+1] = arr[j] # performing swap here.
j-=1
arr[j+1] = val # placing the value at right position.
return arr
N = int(input("Enter the number of values you want to sort --> "))
numbers = []
for i in range(N):
numbers.append(random.randint(0,N))
print(numbers)
start = time.time()
numbers = insertionSortRecur(numbers,N)
end = time.time()
print(numbers)
print(f"Runtime of the program is {end - start}")
# Time Complexity (Worst Case): O(n^2)
# Time Complexity (Best Case): O(n)
# Number of comparisons in Normal Insertion sort can be decreased by using Binary Search.
# Insertion sort takes "n" comaprisons for "n-th interation" in worst case.
# With the use of Binary Search with Insertion Sort, we can decrease comparison for "n-th interation" to "log(n)" in worst case.
| true |
279eaa1adb84a6362e50c16cbcf77fdb96b8c710 | parinita08/Hacktoberfest2020_ | /Python/wordGuess.py | 1,664 | 4.3125 | 4 | import random
# This lib is used to choose a random word from the list of word
# The user can feed his name
name = input("What's your Name? ")
print("Good Luck ! ", name)
words = ['education', 'rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condition',
'reverse', 'water', 'board', 'hacktoberfest']
# Our function will choose a random from the give list
word = random.choice(words)
print("Guess the characters")
guesses = ''
# You can reduce/increase the number of turns
turns = 10
while turns > 0:
# This holds the number of times a user fails
failed = 0
# The letter you feed is taken as input one at a time
for char in word:
# Comparing that character with our set
if char in guesses:
print(char)
else:
print("_")
# For every failure 1 will be added in failed count
failed += 1
if failed == 0:
# The User will win the game if failure is 0
print("You Win")
# This prints the correct word
print("The word is: ", word)
break
# If user has input the wrong alphabet then the user is given a next chance
guess = input("guess a character:")
# Every input character will be stored in guesses
guesses += guess
# Check input with the character in word
if guess not in word:
turns -= 1
# if the character doesn’t match the word then “Wrong” will be given as output
print("Wrong")
# this will print the number of turns left
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")
| true |
e9958c2817a63419482cd59df408a156cd3264ae | SwiftBean/Test1 | /Name or Circle Area.py | 656 | 4.40625 | 4 | #Zach Page
#9/13
#get a users name
##def get_name():
### step one: ask user for name
## name = input("what's your name")
###step two: display the name back for user
## print("the name you entered was", name)
###step three: verify the name
## input("is this correct? yes or no")
##
##print("this is our function")
##get_name()
#calculate the area of a circle
#radius*radius*pi
def areaofCircle():
pi=3.141592653
#1: Get a radius
radius = input("what is the radius")
#2: Calculate the area
radius = float(radius)
area = radius*radius*pi
#3: Display the area
print("the area of the circle is: ", area)
areaofCircle()
| true |
297443115f368f6f74954748aea31cf38fdb3aad | abhikrish06/PythonPractice | /CCI/CCI_1_09_isSubstring.py | 732 | 4.15625 | 4 | # Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one
# call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat").
def isRotation(str1, str2):
if len(str1) != len(str2):
return False
return isSubstring(str1 + str1, str2)
def isSubstring(str1, str2):
if len(str2) > len(str1):
return False
for i in range(len(str1) - len(str2) + 1):
isSubstringexists = True
for j in range(len(str2)):
if str1[i + j] != str2[j]:
isSubstringexists = False
break
if isSubstringexists:
return True
return False
print(isRotation("abhikrish", "ishabhikr"))
| true |
ac98777c509e0e92d030fd29f9fc9e33e175d948 | morvanTseng/paper | /TestDataGeneration/data_generation.py | 2,653 | 4.125 | 4 | import numpy as np
class DataGenerator:
"""this class is for two dimensional data generation
I create this class to generate 2-D data for testing
algorithm
Attributes:
data: A 2-d numpy array inflated with 2-D data
points has both minority and majority class
labels: A 1-D numpy array inflated with 0 or 1
0 represent majority class, whereas 1 represent
minority class
"""
def __init__(self, total_number, ratio):
"""init this class instance
:param total_number: a int, indicating how many number of points you want to generate
:param ratio: a float number, between 0 and 1, the ratio of majority against minority
"""
self.total_number = total_number
self.ratio = ratio
self.data = []
self.labels = []
def _generate_majority(self)->np.array:
"""this is for majority creation
:return: a 2-D numpy array
"""
num_of_majority = self.total_number * self.ratio
return np.random.random((int(num_of_majority), 2)) * 100
def _generate_minority(self)->np.array:
"""this is for minority creation
:return: a 2-D numpy array
"""
num_of_minority = self.total_number - self.ratio * self.total_number
center = num_of_minority * 0.2
left_bottom = num_of_minority * 0.25
right_bottom = num_of_minority * 0.05
left_top = num_of_minority * 0.2
right_top = num_of_minority * 0.3
center_area = 50 + (np.random.random((int(center), 2)) - 0.5) * 10
left_bottom_area = np.array([20, 15]) - (np.random.random((int(left_bottom), 2)) - np.array([0.5, 0.5])) * 10
right_bottom_area = np.array([90, 0]) + np.random.random((int(right_bottom), 2)) * 10
left_top_area = (np.random.random((int(left_top), 2)) * [2, 1]) * 10 + np.array([10, 70])
right_top_area = np.array([100, 100]) - np.random.random((int(right_top), 2)) * 15
return np.concatenate((right_top_area, center_area, left_bottom_area, right_bottom_area, left_top_area), axis=0)
def generate(self)->np.array:
"""generate both majority class instances and minority class instances
:return: a 2-d numpy array
"""
majority = self._generate_majority()
for i in range(len(majority)):
self.labels.append(0.)
minority = self._generate_minority()
for i in range(len(minority)):
self.labels.append(1.)
self.data, self.labels = np.concatenate((majority, minority), axis=0), np.array(self.labels)
return self.data, self.labels
| true |
193ba136e0c667b84dcff683355aee443607c556 | olessiap/glowing-journey-udacity | /6_drawingturtles.py | 1,179 | 4.15625 | 4 | # import turtle
#
# def draw_square():
# window = turtle.Screen()
# window.bgcolor("white")
#
# brad = turtle.Turtle()
# brad.shape("turtle")
# brad.color("green")
# brad.speed(2)
# count = 0
# while count <= 3:
# brad.forward(100)
# brad.right(90)
# count = count + 1
# angie = turtle.Turtle()
# angie.shape("arrow")
# angie.color("red")
# angie.circle(100)
#
# tom = turtle.Turtle()
# tom.color("blue")
# tom.shape("circle")
# count = 0
# while count <= 2:
# tom.forward(320)
# tom.left(120)
# count = count + 1
#
# window.exitonclick()
#
# draw_square()
###draw a circle from a bunch of squares (with better code)###
import turtle
def draw_shapes(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("white")
#create square brad
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("red")
brad.speed(10)
for i in range(1,37):
draw_shapes(brad)
brad.right(10)
window.exitonclick()
draw_art()
| true |
820b6dc8f092a7128bfd1b55d0db7f3b239d3f9a | olessiap/glowing-journey-udacity | /2_daysold.py | 2,007 | 4.375 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
##breaking down the problem ##
#PSEUDOCODE for daysBetweenDates (3)#
#
# days = 0
# while date1 is before date2: #<--dateIsBefore (2)
# date1 = day after date1 #<-- nextDay (1)
# days = days + 1
# return days
## 1. nextDay - find next day assuming month has 30 days##
def nextDay(year, month, day):
if day < 30:
return year, month, day + 1
else:
if month < 12:
return year, month + 1, 1
else:
return year + 1, 1, 1
# print nextDay(2016, 10, 30)
# print nextDay(2016, 12, 06)
# print nextDay(2015, 12, 30)
## 2. helper procedure##
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""returns True if year1-month1-day1 is before
year2-month2-day2. otherwise, returns False"""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
return day1 < day2
return False
print dateIsBefore(2016, 10, 06, 2016, 10, 07) # True
print dateIsBefore(2016, 10, 06, 2016, 11, 06) # True
print dateIsBefore(2018, 10, 06, 2017, 10, 06) # False
## 3. daysBetweenDates - approximate answers using the above nextDay procedure ###
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
days = 0
while dateIsBefore(year1, month1, day1, year2, month2, day2):
year1, month1, day1 = nextDay(year1, month1, day1)
days += 1
return days
print daysBetweenDates(2016, 10, 06, 2016, 10, 07) #>>1
print daysBetweenDates(2016, 10, 06, 2016, 11, 06) #>>30
print daysBetweenDates(2016, 10, 06, 2017, 10, 06) #>>360
print daysBetweenDates(2013, 1, 24, 2013, 6, 29) #>>155
print daysBetweenDates(2015, 1, 24, 2013, 6, 29) #>> 0
| true |
a9ab2e591e65123d33deb79ffc5467f5199a2f39 | TeeGeeDee/adventOfCode2020 | /Day4/day4.py | 2,221 | 4.125 | 4 |
from typing import List
def parse_records(records_raw:List[str]):
"""Turn list of raw string records (each record across multiple list entries)
to list of dict structured output (one list entry per record)
Parameters
----------
records_raw : List[str]
List of records. Records are seperated by '' entries.
strings of the form: 'key1:value1 key2:value2' for any number of key-value pairs
Returns
-------
records : List[dict]
List of dicts, structuring the key-value pairs in the records
"""
records,my_record = [],''
for r in records_raw:
if len(r)>0:
my_record += ' '+r
else:
records += [dict([p.split(':') for p in my_record.split()])]
my_record = ''
return records
def validate1(record: dict):
return all([(fld in set(record.keys())) for fld in ['byr','iyr','eyr','hgt','hcl','ecl','pid']])
def validate2(record: dict):
is_valid = validate1(record)
if not is_valid:
return False
is_valid &= record['byr'].isnumeric() and 1920<=int(record['byr'])<=2002
is_valid &= record['iyr'].isnumeric() and 2010<=int(record['iyr'])<=2020
is_valid &= record['eyr'].isnumeric() and 2020<=int(record['eyr'])<=2030
is_valid &= ((record['hgt'][-2:]=='cm'
and 150<=int(record['hgt'][:-2])<=193)
or
(record['hgt'][-2:]=='in'
and 59<=int(record['hgt'][:-2])<=76)
)
is_valid &= (record['hcl'][0]=='#'
and len(record['hcl'][1:])==6
and all([c in 'abcdef0123456789' for c in record['hcl'][1:]])
)
is_valid &= record['ecl'] in ('amb','blu','brn','gry','grn','hzl','oth')
is_valid &= record['pid'].isnumeric() and len(record['pid'])==9
return is_valid
if __name__ == "__main__":
with open("data.txt", "r") as f:
records = [r.rstrip('\n') for r in f.readlines()]
print('Number of valid records is {0}'.format(sum([validate1(r) for r in parse_records(records)])))
print('Number of valid records using second rule is {0}'.format(sum([validate2(r) for r in parse_records(records)])))
| true |
ad3564d330aba2b298de30d2f8b41ab2ca6891da | TeeGeeDee/adventOfCode2020 | /Day3/day3.py | 1,066 | 4.125 | 4 |
from typing import List
from math import prod
def traverse(down: int,right: int,terrain: List[str]):
""" Counts number of trees passed when traversing terrane with given step sizes
Parameters
----------
down: int
number of steps to take down each iteration
right: int
number of steps to take right each iteration
terrain: list of str
representing terrain. '#' represents tree
Returns
-------
number of trees the traveral goes through
"""
y_pos,x_pos,num_trees = down,right,0
while y_pos<=len(terrain)-1:
num_trees += terrain[y_pos][x_pos % len(terrain[y_pos])]=='#'
y_pos += down
x_pos += right
return num_trees
if __name__ == "__main__":
with open("data.txt", "r") as f:
slope = [x.rstrip('\n') for x in f.readlines()]
params = [(1,1),(1,3),(1,5),(1,7),(2,1)]
print('Number of trees his is {0}'.format(traverse(1,3,slope)))
print('Product of trees seen is {0}'.format(prod([traverse(*p,slope) for p in params])))
| true |
9e72a3b63a392aff565a4cd4bbad93a433a4a29f | matthijskrul/ThinkPython | /src/Fourth Chapter/Exercise7.py | 375 | 4.1875 | 4 | # Write a fruitful function sum_to(n) that returns the sum of all integer numbers up to and including n.
# So sum_to(10) would be 1+2+3...+10 which would return the value 55.
def sum_to(n):
s = 0
for i in range(1, n+1):
s += i
return s
def sum_to_constant_complexity(n):
return ((n*n)+n)/2
total = sum_to_constant_complexity(3242374)
print(total)
| true |
90e3aa20ceca89debc99ef5b009ad413dd57c625 | matthijskrul/ThinkPython | /src/Seventh Chapter/Exercise15.py | 2,718 | 4.5 | 4 | # You and your friend are in a team to write a two-player game, human against computer, such as Tic-Tac-Toe
# / Noughts and Crosses.
# Your friend will write the logic to play one round of the game,
# while you will write the logic to allow many rounds of play, keep score, decide who plays, first, etc.
# The two of you negotiate on how the two parts of the program will fit together,
# and you come up with this simple scaffolding (which your friend will improve later) - see below.
# 1) Write the main program which repeatedly calls this function to play the game,
# and after each round it announces the outcome as “I win!”, “You win!”, or “Game drawn!”.
# It then asks the player “Do you want to play again?” and either plays again, or says “Goodbye”, and terminates.
# 2) Keep score of how many wins each player has had, and how many draws there have been.
# After each round of play, also announce the scores.
# 3) Add logic so that the players take turns to play first.
# 4) Compute the percentage of wins for the human, out of all games played. Also announce this at the end of each round.
def play_once(human_plays_first):
"""
Must play one round of the game. If the parameter
is True, the human gets to play first, else the
computer gets to play first. When the round ends,
the return value of the function is one of
-1 (human wins), 0 (game drawn), 1 (computer wins).
"""
# This is all dummy scaffolding code right at the moment...
import random # See Modules chapter ...
rng = random.Random()
# Pick a random result between -1 and 1.
result = rng.randrange(-1,2)
print("Human plays first={0}, winner={1} "
.format(human_plays_first, result))
return result
def play_game():
wincount_player = 0
wincount_comp = 0
drawcount = 0
player_turn = True
while True:
result = play_once(player_turn)
if result == -1:
wincount_player += 1
print("You win!")
elif result == 0:
drawcount += 1
print("Game drawn!")
else:
wincount_comp += 1
print("I win!")
player_turn = not player_turn
print(f"Player wins: {wincount_player}, Computer Wins: {wincount_comp}, Draws: {drawcount}")
print(f"Player wins percentage: {100*(wincount_player/(wincount_player + drawcount + wincount_comp))}%")
while True:
response = input("Do you want to play again? Type y or n")
if response == "n":
print("Goodbye!")
return
if response == "y":
break
play_game()
| true |
4da17d0305a8c7473bd24624d04fb148a271bc7e | AbelCodes247/Google-Projects | /Calculator.py | 1,240 | 4.375 | 4 | #num1 = input("Enter a number: ")
#num2 = input("Enter another number: ")
#result = int(num1) + int(num2)
#print(result)
#Here, the calculator works the same way but the
#Arithmetic operations need to be changed manually
print("Select an operation to perform:")
print("1. ADD")
print("2. SUBTRACT")
print("3. MULTIPLY")
print("4. DIVIDE")
operation = input()
if operation == "1":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is " + str(int(num1) + int(num2)))
elif operation == "2":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is " + str(int(num1) - int(num2)))
elif operation == "3":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is " + str(int(num1) * int(num2)))
elif operation == "4":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is " + str(int(num1) / int(num2)))
else:
print("Invalid Entry")
#Here is a more complex calulator where it can accept
#User input and can choose between the addition,
#Subtraction, multiplication and division
#If no input is entered, then it returns ("Invalid Entry") | true |
49d4ae16fba58eaa1ebfeb45553eb575b6962b0a | EJohnston1986/100DaysOfPython | /DAY9 - Secret auction/practice/main.py | 1,283 | 4.65625 | 5 | # creating a dictionary
student = {}
# populating the dictionary with key value pairs
student = {"Name": "John",
"Age": 25,
"Courses": ["Maths", "Physics"]
}
# printing data from dictionary
print(student) # prints all key, value pairs
print(student["name"]) # prints only value of named key
# accessing key value pair using get method
print(student.get("name"))
# adding new key value pair to a dictionary
student["phone"] = "01738 447385"
# searching a dictionary for a key named "phone", returns not found if no result
print(student.get("phone", "not found"))
# changing information in a dictionary
student["Name"] = "Jane"
# using update function to update more than one piece of information, dictionary as argument
student.update({"Name": "Steve", "Age": 27, "Courses": "Geology", "Phone": "2342145435"})
# deleting a dictionary key value pair
del student["age"]
# looping through keys and values of dictionary
print(len(student)) # displays number of keys
print(student.keys()) # displays all the keys
print(student.values()) # displays all the values
print(student.items()) # displays all key and value pairs
for key, value in student.items(): # prints all key value pairs from loop
print(key, value)
| true |
ed583b5475071835db5ac8067ccae943e10c432a | LavanyaJayaprakash7232/Python-code---oops | /line_oop.py | 844 | 4.40625 | 4 | '''
To calculate the slope of a line and distance between two coordinates on the line
'''
#defining class line
class Line():
def __init__(self, co1, co2):
self.co1 = co1
self.co2 = co2
#slope
def slope(self):
x1, y1 = self.co1
x2, y2 = self.co2
return (y2 - y1)/(x2 - x1)
#distance
def distance(self):
x1, y1 = self.co1
x2, y2 = self.co2
return ((x2 - x1)**2 + (y2 -y1)**2)**(1/2)
#User input of coordinates in the form of tuples
co1 = tuple(int(a) for a in input("Enter the coordinate point 1\n").split())
co2 = tuple(int(b) for b in input("Enter the coordinate point 2\n").split())
myline = Line(co1, co2)
slope = myline.slope()
distance = myline.distance()
print(f"The slope is {slope} and the distance is {distance}")
| true |
4d386f77d415e5e9335763ebb49bc683af7c0fbf | pbeata/DSc-Training | /Python/oop_classes.py | 2,087 | 4.40625 | 4 | import turtle
class Polygon:
def __init__(self, num_sides, name, size=100, color="black", lw=2):
self.num_sides = num_sides
self.name = name
self.size = size # default size is 100
self.color = color
self.lw = lw
self.interior_angles_sum = (self.num_sides - 2) * 180
self.single_angle = self.interior_angles_sum / self.num_sides
# print details about the attributes
def print(self):
print("\npolygon name:", self.name)
print("number of sides:", self.num_sides)
print("sum of interior angles:", self.interior_angles_sum)
print("value for single angle:", self.single_angle)
# draw the polygon shape
def draw(self):
turtle.color(self.color)
turtle.pensize(self.lw)
for i in range(self.num_sides):
turtle.forward(self.size)
turtle.right(180 - self.single_angle)
turtle.done()
# PART 1: The Basics
# plaza = Polygon(4, "Square", 200, color="blue", lw=5)
# plaza.print()
# plaza.draw()
# building = Polygon(5, "Pentagon")
# building.print()
# # building.draw()
# stop_sign = Polygon(6, "Hexagon", 150, color="red", lw=5)
# stop_sign.print()
# stop_sign.draw()
# PART 2: Inheritance and Subclassing
class Square(Polygon):
def __init__(self, size=100, color="black", lw=2):
# Polygon is the "super" class
super().__init__(4, "Square", size, color, lw)
# overriding the member function from Polygon
def draw(self):
turtle.begin_fill()
super().draw()
turtle.end_fill()
# square = Square(color="blue", size=200)
# print(square.num_sides)
# print(square.single_angle)
# square.draw()
# turtle.done()
# PART 3: Operator Overloading
import matplotlib.pyplot as plt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Point):
x = self.x + other.x
y = self.y + other.y
else:
x = self.x + other
y = self.y + other
return Point(x,y)
def pplot(self):
plt.plot(self.x, self.y, 'kx')
plt.show()
point1 = Point(4, 5)
print(point1.x, point1.y)
# point1.pplot()
a = Point(1, 1)
b = Point(2, 2)
c = a + b
print(c.x, c.y)
d = a + 5
print(d.x, d.y) | true |
0e087f65ba7b781cda0568712dee4975a49a1bd1 | OkelleyDevelopment/Caesar-Cipher | /caesar_cipher.py | 1,258 | 4.21875 | 4 | from string import ascii_letters
def encrypt(message, key):
lexicon = ascii_letters
result = ""
for char in message:
if char not in lexicon:
result += char
else:
new_key = (lexicon.index(char) + key) % len(lexicon)
result += lexicon[new_key]
return result
def decrypt(message, key):
return encrypt(message, (key * -1))
def main():
while True:
print("\n============ Menu ============")
print(*["1.Encrpyt", "2.Decrypt", "3.Quit"], sep="\n")
user_choice = input("Choose an option: ").strip() or "3"
if user_choice not in ("1", "2", "3"):
print("ERROR: Please enter a valid choice!")
elif user_choice == "1":
message = input("Please enter the string to be encrypted: ")
key = int(input("Please enter off-set: ").strip())
print(encrypt(message, key))
elif user_choice == "2":
message = input("Please enter the string to be decrypted: ")
key = int(input("Please enter off-set: ").strip())
print(decrypt(message, key))
elif user_choice == "3":
print("Farewell.")
break
if __name__ == "__main__":
main()
| true |
f194918b18cd8728d7f5ec5854152b8d5bc4cc2e | rarezhang/ucberkeley_cs61a | /lecture/l15_inheritance.py | 987 | 4.46875 | 4 | """
lecture 15
inheritance
"""
# inheritance
# relating classes together
# similar classes differ in their degree of specialization
## class <name>(<base class>)
# example: checking account is a specialized type of account
class Account:
interest = 0.04
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return 'insufficient funds'
self.balance = self.balance - amount
return self.balance
class CheckingAccount(Account):
withdraw_fee = 1
interest = 0.01
def withdraw(self, amount):
return Account.withdraw(self, amount + self.withdraw_fee)
ch = CheckingAccount('Tom') # calls Account.__init__
print(ch.interest) # can be found in CheckingAccount class
print(ch.deposit(20)) # can be found in Account class
print(ch.withdraw(5)) # can be found in CheckingAccount class | true |
21964a6a9150ffc373599207402aef774f5917a8 | rarezhang/ucberkeley_cs61a | /lecture/l10_data_abstraction.py | 1,233 | 4.4375 | 4 | """
lecture 10
Data Abstraction
"""
# data
print(type(1))
## <class 'int'> --> represents int exactly
print(type(2.2))
## <class 'float'> --> represents real numbers approximately eg. 0.2222222222222222 == 0.2222222222222227 True
print(type(1+1j))
## <class 'complex'>
print(type(True))
## <class 'bool'>
print(1+1.2)
## <class 'float'>
# object
# represent information
# (1) data (2) behavior --> abstraction
# object-oriented programming
from datetime import date
today = date(2016, 2, 29)
freedom = date(2016, 5, 20)
print(str(freedom - today))
print(today.year)
print(today.day)
print(today.strftime("%A %B %d")) # a method for the object 'today' string format of time
print(type(today))
## <class 'datetime.date'>
# data abstraction
# compound objects combine objects together
## parts -> how data are represented
## units -> how data are manipulated
# data abstraction: enforce an abstraction barrier between (1) representation (2) use
# pair representation
## normal way
def pair_1(x, y):
return [x, y]
def select_1(p, i):
return p[i]
## functional pair representation
def pair_2(x, y):
def get(index):
if index == 0:
return x
elif index == 1:
return y
return get
def select_2(p, i):
return p(i) | true |
efd57652ea766f2eead4561e8d9737163de0ef8a | cIvanrc/problems | /ruby_and_python/2_condition_and_loop/check_pass.py | 905 | 4.1875 | 4 | # Write a Python program to check the validity of a password (input from users).
# Validation :
# At least 1 letter between [a-z] and 1 letter between [A-Z].
# At least 1 number between [0-9].
# At least 1 character from [$#@].
# Minimum length 6 characters.
# Maximum length 16 characters.
# Input
# W3r@100a
# Output
# Valid password
import re
def check_pass():
passw = input("say a password: ")
if is_valid(passw):
print("Valid pass")
else:
print("wrong pass")
def is_valid(passw):
is_valid = True
if not (len(passw) >= 6 and len(passw) <= 16):
is_valid = False
if not re.search("[a-z]", passw):
is_valid = False
if not re.search("[A-Z]", passw):
is_valid = False
if not re.search("[0-9]", passw):
is_valid = False
if not re.search("[$#@]", passw):
is_valid = False
return is_valid
check_pass()
| true |
5ca2ba498860e710f44477f96523c0413ed54cbe | cIvanrc/problems | /ruby_and_python/12_sort/merge_sort.py | 1,497 | 4.40625 | 4 | # Write a python program to sort a list of elements using the merge sort algorithm
# Note: According to Wikipedia "Merge sort (also commonly spelled mergesort) is an 0 (n log n)
# comparasion-baed sortgin algorithm. Most implementations produce a stable sort, which means that
# the implementation preserves the input order of equal elements on the sorted output.
# Algorithm:
# Concepcually, a merge sort works as follows:
# Divide the unsorted list into n sublist, each containing 1 element (a list of 1 element is considered sorted).
# Repeatedly merge sublist to produce new sorted sublist until there only 1 sublist remaining. This will be the sorted list"
def merge_sort(nlist):
print("Splitting ", nlist)
if len(nlist)>1:
mid = len(nlist)//2
left_half = nlist[:mid]
right_half = nlist[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
nlist[k] = left_half[i]
i+=1
else:
nlist[k] = right_half[j]
j+=1
k+=1
while i < len(left_half):
nlist[k] = left_half[i]
i+=1
k+=1
while j < len(right_half):
nlist[k] = right_half[j]
j+=1
k+=1
print("Merging: ",nlist)
nlist = [4,12,5,82,1,43,73,84,24,51,35,12]
merge_sort(nlist)
print(nlist)
| true |
68456f7fa3638ae327fc6874c22b74099b28f351 | cIvanrc/problems | /ruby_and_python/3_list/find_max.py | 648 | 4.28125 | 4 | # Write a Python program to get the smallest number from a list.
# max_num_in_list([1, 2, -8, 0])
# return 2
def find_max():
n = int(input("How many elements you will set?: "))
num_list = get_list(n)
print(get_max_on_list(num_list))
def get_list(n):
numbers = []
for i in range(1, n+1):
number = int(input("{}.-Say a number: ".format(i)))
numbers.append(number)
return numbers
def get_max_on_list(num_list):
max = num_list[0]
for i in range(1, len(num_list)):
if max < num_list[i]:
max = num_list[i]
return "The max value in the list is: {}".format(max)
find_max()
| true |
9600319f92cf09f3eef5ec5e5cdfbe80c2c8e81a | asingleservingfriend/PracticeFiles | /regExpressions.py | 1,796 | 4.125 | 4 | import re
l = "Beautiful is better than ugly"
matches = re.findall("beautiful", l, re.IGNORECASE)
#print(matches)
#MATCH MULTIPLE CHARACTERS
string = "Two too"
m = re.findall("t[wo]o", string, re.IGNORECASE)
#print(m)
#MATCH DIGITS
line = "123?34 hello?"
d = re.findall("\d", line, re.IGNORECASE)
#print(d)
#NON GREEDY REPITITION MATCHING
# the quesiton mark makes the expression non-greedy.
t= "__one__ __two__ __three__"
found = re.findall("__.*?__", t)
#print (found)
#ESCAPING
line2 = "I love $"
l = re.findall("\\$", line2, re.IGNORECASE)
#print(l)
#PRACTICE
txt="""
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
match = re.findall("Dutch", txt)
#print(match)
string2 = "Arizona 479, 501, 870. California 209, 213, 650"
dig = re.findall("\d", string2, re.IGNORECASE)
#print(dig)
sent = "The ghost that says boo haunts the loo"
doubla = re.findall("[bl]oo", sent, re.IGNORECASE)
print(doubla)
| true |
10a1d131ff6eb33d0f12d8aa67b3e9fd93e05153 | christianmconroy/Georgetown-Coursework | /ProgrammingStats/Week 8 - Introduction to Python/myfunctions.py | 2,006 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 18:33:25 2018
@author: chris
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 07 18:29:10 2018
@author: chris
"""
# refer slide 41
# Program with functions
# Name this program withfunctions.py
# the entire program; there is one small change
# that small change is that the file name is not
# hard coded into the function
def get_input(filename):
"""Reads a file and returns the file contents.
Args:
filename: the name of the file including the path
Returns:
a list with the file contents
"""
myList = []
with open(filename) as f:
for line in f:
myList.append(int(line))
return myList
def getMean(myList):
"""returns the mean of numbers in a list
Args:
myList (list): contains numbers for which mean is calculated
Returns:
(float) the mean of numbers in myList
"""
mysum = 0.0
for i in range(len(myList)):
mysum = mysum + myList[i]
mymean = mysum/len(myList)
return mymean
def getSD(myList):
"""returns the standard deviation of numbers in a list
Args:
myList (list): contains numbers for which standard deviation is calculated
Returns:
(float) the standard deviation of numbers in myList
"""
import math
n = len(myList)
mean = sum(myList) / n
dev = [x - mean for x in myList]
dev2 = [x*x for x in dev]
mysd = math.sqrt( sum(dev2) / (n-1))
return mysd
def print_output(myList, mymean, mysd):
"""prints the output
Args:
myList (list): contains numbers to be counted
mymean (float): contains value of mean for numbers in myList
mysd (list): contains value of standard deviation for numbers in myList
"""
print ("The size of the sample is {:d}".format(len(myList)))
print ("The sample mean is {:10.2f} ".format(mymean))
print ("The sample standard deviation is {:<16.2f}".format(mysd))
| true |
3608552cce91138d629a3ad9cb2208b2b8f15b2f | Latoslo/day-3-3-exercise | /main.py | 617 | 4.1875 | 4 | # 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
# > `on every year that is evenly divisible by 4
# > **except** every year that is evenly divisible by 100
# > **unless** the year is also evenly divisible by 400`
#Write your code below this line 👇
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print('line12: This is a leap year')
else:
print('line14: This is not a leap year')
else:
print('line16: This is a leap year')
else:
print('line18: This is not a leap year')
| true |
80b2020aeabd82d5390c8ef044523e6d3fb616c4 | shubhamkanade/all_language_programs | /Evenfactorial.py | 363 | 4.28125 | 4 | def Evenfactorial(number):
fact = 1
while(number != 0):
if(number % 2 == 0):
fact = fact * number
number -= 2
else:
number = number-1
return fact
number = int(input("Enter a number"))
result = Evenfactorial(number)
print("the factorial is ", result) | true |
e0461c90da83c9b948352e729a91c80b24ed2817 | shubhamkanade/all_language_programs | /checkpalindrome.py | 460 | 4.21875 | 4 | import reverse
def checkpalindrome(number):
result = reverse.Reverse_number(number)
if(result == number):
return True
else:
return False
def main():
number = int(input("Enter a number\n"))
if(checkpalindrome(number)== True):
print("%d number is palindrome" % number)
else:
print("%d is not a palindrome number" % number)
if __name__ == "__main__":
main() | true |
a1a1c971e1fa7008b457aa67d8d784b054f0b671 | workwithfattyfingers/testPython | /first_project/exercise3.py | 553 | 4.40625 | 4 | # Take 2 inputs from the user
# 1) user name
# 2) any letter from user which we can count in SyntaxWarning
# OUTPUT
# 1) user's name in length
# 2) count the number of character that user inputed
user_name=input(print("Please enter any name"))
char_count=input(print("Please enter any character which you want to count"))
#name_count = len(user_name)
#Output
print("String/Name input by you:\t" + user_name)
print("Length of your name is:\t" + str(len(user_name)))
print("Characters which you want to count:\t" + str(user_name.count(char_count))) | true |
8ca6c553c9d2fcf7d142b730e5b455a781cf22da | Phone5mm/MDP-NTU | /Y2/SS/MDP/NanoCar (Final Code)/hamiltonianPath.py | 2,928 | 4.125 | 4 | # stores the vertices in the graph
vertices = []
# stores the number of vertices in the graph
vertices_no = 0
graph = []
#Calculate Distance
def distance(p1, p2):
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5
#Add vertex to graph
def add_vertex(v):
global graph
global vertices_no
global vertices
if v in vertices:
print("Vertex ", v, " already exists")
else:
vertices_no = vertices_no + 1
vertices.append(v)
if vertices_no > 1:
for vertex in graph:
vertex.append(0)
temp = []
for i in range(vertices_no):
temp.append(0)
graph.append(temp)
# Add edge between vertex v1 and v2 with weight e
def add_edge(v1, v2, e):
global graph
global vertices_no
global vertices
# Check if vertex v1 is a valid vertex
if v1 not in vertices:
print("Vertex ", v1, " does not exist.")
# Check if vertex v1 is a valid vertex
elif v2 not in vertices:
print("Vertex ", v2, " does not exist.")
else:
index1 = vertices.index(v1)
index2 = vertices.index(v2)
graph[index1][index2] = e
graph[index2][index1] = e
# Print the graph
def print_graph():
global graph
global vertices_no
for i in range(vertices_no):
for j in range(vertices_no):
if graph[i][j] != 0:
print(vertices[i], " -> ", vertices[j], \
" edge weight: ", graph[i][j])
def shortestPath(obstacle_android):
obstacle_number = len(obstacle_android)
print('No. of obstacles:',obstacle_number)
origin = [0,0]
obstacle_list = []
visited_vertex = [0] * obstacle_number
obstacle_distance = []
list = []
for i in range(0, obstacle_number):
obstacle_list.append ([obstacle_android[i][0],obstacle_android[i][1]])
for i in range(0, obstacle_number):
obstacle_distance.append(distance(origin,obstacle_list[i]))
add_vertex(i) # Add vertices to the graph
first_vertex = obstacle_distance.index(min(obstacle_distance))
# Add the edges between the vertices with the edge weights.
for i in range(0, obstacle_number-1):
for j in range(i+1, obstacle_number):
add_edge(i, j, round(distance(obstacle_list[i],obstacle_list[j]),2))
# Update the current vertex
current_vertex = first_vertex
shortest_path = [400] * obstacle_number
for i in range(0, obstacle_number):
shortest_path[i] = current_vertex
minimum = 200
min_index = 0
visited_vertex[current_vertex] = 1
for j in range (0, obstacle_number):
if graph[current_vertex][j]<minimum and current_vertex!=j:
if visited_vertex[j] == 0 :
minimum = graph[current_vertex][j]
min_index = j
current_vertex = min_index
for i in range(len(shortest_path)):
list.append(obstacle_android[shortest_path[i]])
return list
| true |
863817a9ec431234468b53402deaccd657227c15 | brianabaker/girlswhocode-SIP2018-facebookHQ | /data/tweet-visualize/data_vis_project_part4.py | 2,586 | 4.25 | 4 | '''
In this program, we will generate a three word clouds from tweet data.
One for positive tweets, one for negative, and one for neutral tweets.
For students who finish this part of the program quickly,
they might try it on the larger JSON file to see how much longer that takes.
They might also want to try subjective vs objective tweets.
'''
import json
from textblob import TextBlob
import matplotlib.pyplot as plt
from wordcloud import WordCloud
#Wrap this in a function because we'll use it several times
def get_filtered_dictionary(tweetblob, tweet_search):
#Filter Words
words_to_filter = ["about", "https", "in", "the", "thing", "will", "could", tweet_search]
filtered_dictionary = dict()
for word in tweetblob.words:
#skip tiny words
if len(word) < 2:
continue
#skip words with random characters or numbers
if not word.isalpha():
continue
#skip words in our filter
if word.lower() in words_to_filter:
continue
#don't want lower case words smaller than 5 letters
if len(word) < 5 and word.upper() != word:
continue;
#Try lower case only, try with upper case!
filtered_dictionary[word.lower()] = tweetblob.word_counts[word.lower()]
return filtered_dictionary
#Wrap this in a function so we can use it three times
def add_figure(filtered_dictionary, plotnum, title):
wordcloud = WordCloud().generate_from_frequencies(filtered_dictionary)
plt.subplot(plotnum)
plt.imshow(wordcloud, interpolation='bilinear')
plt.title(title)
plt.axis("off")
#Search term used for this tweet
#We want to filter this out!
tweet_search = "automation"
#Get the JSON data
tweet_file = open("tweets_small.json", "r")
tweet_data = json.load(tweet_file)
tweet_file.close()
#Combine All the Tweet Texts
positive_tweets = ""
negative_tweets = ""
neutral_tweets = ""
for tweet in tweet_data:
tweetblob = TextBlob(tweet['text'])
#Play with the numbers here
if tweetblob.polarity > 0.2:
positive_tweets += tweet['text']
elif tweetblob.polarity < -0.2:
negative_tweets += tweet['text']
else:
neutral_tweets += tweet['text']
#Create a Combined Tweet Blob
positive_blob = TextBlob(positive_tweets)
negative_blob = TextBlob(negative_tweets)
neutral_blob = TextBlob(neutral_tweets)
#Create a matplotlib figure
plt.figure(1)
#Create the three word clouds
add_figure(get_filtered_dictionary(negative_blob, tweet_search), 131, "Negative Tweets")
add_figure(get_filtered_dictionary(neutral_blob, tweet_search), 132, "Neutral Tweets")
add_figure(get_filtered_dictionary(positive_blob, tweet_search), 133, "Positive Tweets")
#Show all at once
plt.show()
| true |
f0e1863b39362db65c98698eff2b6c7150984475 | G-Radhika/PythonInterviewCodingQuiestions | /q5.py | 1,469 | 4.21875 | 4 | """
Find the element in a singly linked list that's m elements from the end.
For example, if a linked list has 5 elements, the 3rd element from the end is
the 3rd element. The function definition should look like question5(ll, m),
where ll is the first node of a linked list and m is the "mth number from the
end". You should copy/paste the Node class below to use as a representation of
a node in the linked list. Return the value of the node at that position.
e.g. 10->20->30->40->50
"""
head = None
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a new node at the beginning
def push(new_data):
global head
new_node = Node(new_data)
new_node.next = head
head = new_node
def question5(ll, m):
main_ptr = ll
ref_ptr = ll
count = 0
if(head is not None):
while(count < m ):
if(ref_ptr is None):
print "%d is greater than the no. of nodes in list" %(m)
return
ref_ptr = ref_ptr.next
count += 1
while(ref_ptr is not None):
main_ptr = main_ptr.next
ref_ptr = ref_ptr.next
return main_ptr.data
# Main program
def main():
global head
# Make linked list 10->20->30->40->50
push(50)
push(40)
push(30)
push(20)
push(10)
print question5(head, 4)
print question5(head, 2)
print question5(head, 7)
if __name__ == '__main__':
main() | true |
6ed2cd27f06b2bb4f00f0b14afd94e42e7173164 | MichaelAuditore/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 706 | 4.40625 | 4 | #!/usr/bin/python3
def add_integer(a, b=98):
"""
Add_integer functions return the sum of two numbers
Parameters:
a: first argument can be integer or float
b: Second argument initialized with value 98, can be integer or float
Raises:
TypeError: a must be an integer or float
TypeError: b must be an integer or float
Returns:
int:Sum of a + b
"""
if type(a) != int and type(a) != float:
raise TypeError("a must be an integer")
if type(b) != int and type(b) != float:
raise TypeError("b must be an integer")
if type(a) == float:
a = int(a)
if type(b) == float:
b = int(b)
return (a + b)
| true |
a30bd99e44e61f3223dfa2ba64adb89dc19ad0b2 | Debu381/Conditional-Statement-Python-Program | /Conditional Statement Python Program/Guss.py | 213 | 4.125 | 4 | #write a python program to guess a number between 1 to 9
import random
target_num, guess_num=random.randint(1,10), 0
while target_num !=guess_num:
guess_num=int(input('Guess a number'))
print('Well guessed') | true |
b6ace974b9b55f653fe3c45d35a1c76fd3322f7e | lucasloo/leetcodepy | /solutions/36ValidSudoku.py | 1,530 | 4.1875 | 4 | # Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
# The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
# A partially filled sudoku which is valid.
# Note:
# A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
# check rows
for i in range(len(board)):
containMap = {}
for k in range(len(board[i])):
if board[i][k] != '.' and board[i][k] in containMap:
return False
containMap[board[i][k]] = 1
# check columns
for i in range(len(board[0])):
containMap = {}
for k in range(len(board)):
if board[k][i] != '.' and board[k][i] in containMap:
return False
containMap[board[k][i]] = 1
# check square
i = 0
while i < len(board):
k = 0
while k < len(board[0]):
containMap = {}
for x in range(3):
for y in range(3):
if board[i + x][k + y] != '.' and board[i + x][k + y] in containMap:
return False
containMap[board[x + i][k + y]] = 1
k += 3
i += 3
return True
| true |
98c092348ce916622847924b48967ef75ce99d9e | SaralKumarKaviti/Problem-Solving-in-Python | /Day-3/unit_convert.py | 1,738 | 4.25 | 4 | print("Select your respective units...")
print("1.centimetre")
print("2.metre")
print("3.millimetre")
print("4.kilometre")
choice= input("Enter choice(1/2/3/4)"
unit1=input("Enter units from converting:")
unit2=input("Enter units to coverting:")
number=float(input("Enter value:"))
if choice == '1':
if unit1 == 'centimetre' and unit2 == 'metre':
value=number/100
print("Metre value is {}".format(value))
elif unit1 == 'metre' and unit2 == 'centimetre':
value=number*100
print("Centimetre value is {}".format(value))
else:
print("Please enter the valid units...")
elif choice == '2':
if unit1 == 'millimetre' and unit2 == 'centimetre':
value=number/10
print("Millimetre value is {}".format(value))
elif unit1 == 'centimetre' and unit2 == 'millimetre':
value=number*10
print("Centimetre value is {}".format(value))
else:
print("Please enter the valid units...")
elif choice == '3':
if unit1 == 'millimetre' and unit2 == 'metre':
value=number/1000
print("Millimetre value is {}".format(value))
elif unit1 == 'metre' and unit2 == 'millimetre':
value=number*1000
print("Metre value is {}".format(value))
else:
print("Please enter the valid units...")
elif choice == '4':
if unit1 == 'kilometre' and unit2 == 'metre':
value=number*1000
print("Kilometre value is {}".format(value))
elif unit1 == 'metre' and unit2 == 'kilometre':
value=number/1000
print("Metre value is {}".format(value))
elif unit1 == 'millimetre' and unit2 == 'kilometre':
value=number/1000000
else:
print("Please enter the valid units...")
| true |
2d082dda2f464f6da9d9a043a90ca7599a4b92bd | anikanastarin/Learning-python | /Homework session 4.py | 1,516 | 4.375 | 4 | '''#1. Write a function to print out numbers in a range.Input = my_range(2, 6)Output = 2, 3, 4, 5, 6
def my_range(a,b):
for c in range(a,b+1):
print (c)
my_range(2,6)
#2. Now make a default parameter for “difference” in the previous function and set it to 1. When the difference value is passed, the difference between the numbers should change accordingly.
def increment(a,b,diff=1):
w=a;
while w<=b:
print(w)
w=w+diff
increment(2,6)
#3. Write a Python program to reverse a string. Go to the editor Sample String: "1234abcd" Expected Output: "dcba4321"
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "123abcd"
print ("Sample String: ",end="")
print (s)
print ("Reverse Output: ",end="")
print (reverse(s))
#4. Write a function to return the factorial of an input. Assign the value to a new variable and print it.
def factorial(x):
a=1;
for c in range (0,x):
a=a*(x-c)
return a
z=int(input("Input Number:"))
factorial(z)
w=factorial(z)
print("value of new variable:",w)
#5. Write a Python function that takes a number as a parameter and check the number is prime or not. Return True or False.
def prime(y):
f=0;
for x in range(2,y):
if y%x==0:
f=f+1
if f>=1:
return False
else:
return True
c=int(input("Enter any prime integer:"))
print(prime(c))'''
| true |
6ae607ac50b7fe370e6257fd083fc369a5ac7a14 | Dcnqukin/A_Byte_of_Python | /while.py | 383 | 4.15625 | 4 | number=23
running=True
while running:
guess=int(input("Enter an integer:"))
if guess==number:
print("Congratulation, you guessd it.")
running=False #this causes the while loop to stop
elif guess<number:
print("No, it is a little higher")
else:
print("No, it is a little lower")
else:
print("the while loop is over")
print("done")
| true |
b5cf0e1ec9d8ad7f5f60e89891ee08ef6e3bc6f9 | marieramsay/IT-1113 | /Miles_To_Kilometers_Converter.py | 2,618 | 4.5625 | 5 | # Marie Ramsay
# Prompts the user to select whether they want to convert Miles-to-Kilometers or Kilometers-to-Miles, then asks the user
# to enter the distance they wish to convert. Program converts value to the desired unit.
# Program will loop 15x.
import sys
# converts input from miles to kilometers
def convert_miles_to_km(amount):
the_answer = amount / 0.6214
return the_answer
# converts input from kilometers to miles
def convert_km_to_miles(amount):
the_answer = amount * 0.6214
return the_answer
print("Welcome to the conversion calculator. This program will run 15 times.")
# use for in loop to run the procedure below 15X
for x in range(15):
# keep track of what data set the process is on
data_number = x + 1
data_number = str(data_number)
# ask user which conversion they want to do
print("Please enter which conversion you need to be done for conversion " + data_number + ":")
print("A. Miles-to-Kilometers")
print("B. Kilometers-to-Miles")
# save the user's selection to a variable
conversion_selection = input()
# decide which unit the input will be in
if (conversion_selection == "A") or (conversion_selection == "a"):
unit_name = "miles"
elif (conversion_selection == "B") or (conversion_selection == "b"):
unit_name = "kilometers"
else:
sys.exit('Your input is invalid. Please enter A or B. The program will restart.')
# ask the user for the value they want to convert
print("Please enter how the amount of " + unit_name + " you want to convert:")
# save the value to a variable
convert_this = input()
# change string to float
convert_this = float(convert_this)
# decide which function to send the variable to
if unit_name == "miles":
converted_amount = convert_miles_to_km(convert_this)
converted_amount = str(converted_amount)
convert_this = str(convert_this)
print(convert_this + " " + unit_name + " converts to " + converted_amount + " kilometers.")
print(" ")
else:
converted_amount = convert_km_to_miles(convert_this)
converted_amount = str(converted_amount)
convert_this = str(convert_this)
print(convert_this + " " + unit_name + " converts to " + converted_amount + " miles.")
print(" ")
# if this is the last conversion, let the user know.
if data_number == "15":
print("You have converted 15 values.")
print("Thank you for using the Conversion Calculator!")
| true |
e07ac75e79a257241d4a467320e113247db4df8b | calebwest/OpticsPrograms | /Computer_Problem_2.py | 2,211 | 4.40625 | 4 | # AUTHOR: Caleb Hoffman
# CLASS: Optics and Photonics
# ASSIGNMENT: Computer Problem 2
# REMARKS: Enter a value for the incident angle on a thin lens of 2.0cm, and
# the focal length. A plot will open in a seperate window, which will display
# light striking a thin lens, and the resulting output rays. This program uses
# a derived ray transfer matrix equation to compute the ouput angle of a thin
# lens.
# DISCLAIMER: This program will be further developed to compute a series of
# lenses to achieve other various tasks.
import matplotlib.pyplot as plt
import math
from math import tan
from math import pi
# The primary function of this program is to compute the result of light
# striking a thin lens of a specific angle and focal length
def main():
d = 2.0 # centimeters
input_angle = float(input("Enter Incident Angle: "))*(pi/180)
f = float(input("Enter Focal Length: "))
# Declares domain for both sides of the lens as a list constrained to f input
xDomain = [x for x in range(int(-f*1.3), 1)]
xDomain_Output = [x for x in range(0, int(f*1.3))]
# The slope of the line is the tangent of the input angle
m = tan(input_angle)
# Chart labels
plt.title("Thin Lens-Object at Infinity")
plt.xlabel("Optical Axis (cm)")
plt.ylabel("Ray Elevation (cm)")
# Imposes a grid making the plot easier to read
plt.grid(color='black', linestyle=':', linewidth = 0.5)
# vlines (x=0, ymin, ymax) draws out the lens (in black)
plt.vlines(0, (-d/2), (d/2), color = 'black')
# This loop computes three identical rays striking
# the lens. Followed by the output
for i in range(3):
# This section computes incidents rays
zRange = [m*x+((1-i)*(d/2)) for x in xDomain]
plt.plot(xDomain, zRange, color = 'red')
# This section computes transmitted rays
output_angle = (input_angle) - (((1-i)*(d/2))/f)
m_Output = tan(output_angle)
zRange_Output = [m_Output*x+((1-i)*(d/2)) for x in xDomain_Output]
plt.plot(xDomain_Output, zRange_Output, color = 'blue')
# This displays the generated plot (ray trace display)
plt.show()
# Invokes main
main()
| true |
756a096e6c156f1f5be7347067903a3135008535 | 22fansje/python | /modb_challenge.py | 1,034 | 4.21875 | 4 | def main():
#Get's info on the user's name than greets them
first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
print("Hello, %s %s!"%(first_name,last_name))
print()
#Lists the foods avaliable
food = ['Cookie', 'Steak', 'Ice cream', 'Apples']
for food in food:
print (food)
#showing age in days, weeks and months
print()
age_in_years = float(input("How old are you?: "))
days_in_years = age_in_years * 365
weeks_in_years = age_in_years * 52.143
months_in_years = age_in_years * 12
print("You're at least",days_in_years,"days old.")
print("You,re at least",weeks_in_years,"weeks old.")
print("You're at least",months_in_years,"months old.")
#Makes a humorous statement
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
adjective = input("Enter a adjective: ")
place = input("Enter a place: ")
print("Take your %s %s and %s it at the %s"%(adjective, noun, verb, place))
main() | true |
19eb4be275bd3a0477a42ec205be2596a5c459db | harry990/coding-exercises | /trees/tree-string-expression-balanced-parenthesis.py | 1,107 | 4.15625 | 4 |
from collections import defaultdict
"""
Given a tree string expression in balanced parenthesis format:
(A(B(C)(D))(E)(F))
A
/ | \
B E F
/ \
C D
The function is to return the root of the tree you build, and if you can please
print the tree with indentations like above.
You can print in the simplified format.
A
B E F
C D
"""
def parse_string(s):
levels = defaultdict(list) # dict of lists
level_count = 0
for i, c in enumerate(s):
if c == '(':
level_count += 1
elif c == ')':
level_count -= 1
else:
levels[level_count].append(c)
return levels
def print_levels(levels):
for level in levels:
for c in levels[level]:
print c,
print
def main():
#tree = "(A(B(C))"
#tree = "(A(B(C)D)"
tree = "(A(B(C)(D))(E)(F))"
levels = parse_string(tree)
# TODO make sure that levels are accesed in order
# sort the dict into a list
print_levels(levels)
if __name__ == "__main__":
main()
| true |
1c90e6c43a74e92dc37477692317ae008d9ec415 | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/Lynda - Python 3 Essential Training/11 Functions/generator_01_sequence_tuple_with_yield.py | 1,411 | 4.59375 | 5 | #!/usr/bin/python3
# A generator function is function that return an iterator object.
# So this is how you create functionality that can be used in a for loop or any
# place an iterator is allowable in Python
def main():
print("This is the functions.py file.")
for i in inclusive_range(2, 125, 4):
print(i, end =' ')
def inclusive_range(*args): # we make an inclusive range function
numargs = len(args)
if numargs < 1: raise TypeError('requires at least one argument')
elif numargs == 1:
start = 0
step = 1
stop = args[0]
elif numargs == 2:
(start, stop) = args
step = 1
elif numargs == 3:
(start, stop, step) = args
else: raise TypeError('inclusive_range expected at most 3 arguments, got {}'.format(numargs))
i = start
while i <= stop:
yield i # yield does it return 'i' but because we are using yield instead of return
i += step # the next time the function is called execution will continue right after
# the yield statement. It will get incremented with step.
# Difference between yield and return :
# as the function gets called over and over again, each time execution begins right after
# the yield and continues as if the function were running continually
if __name__ == "__main__": main()
| true |
89c5785788e5171d33ef0e2cc34622b8781004af | btrif/Python_dev_repo | /BASE SCRIPTS/Logic/basic_primes_generator.py | 980 | 4.125 | 4 | #!/usr/bin/python3
# comments.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
for n in primes(): #generate a list of prime numbers
if n > 100: break
print(n, end=' ')
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n=1):
while(True):
if isprime(n): yield n
n += 1
print(isprime(31) == True)
#############################################
# from MITx.6.00.1x Course
# A Different Version :
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
if __name__ == "__main__": main()
| true |
6c9a13d67dea2ce2672fc0dad170207bdfce715f | btrif/Python_dev_repo | /BASE SCRIPTS/module bisect pickle.py | 2,002 | 4.46875 | 4 | import bisect, pickle
print(dir(bisect))
########################
# The bisect() function can be useful for numeric table lookups.
# This example uses bisect() to look up a letter grade for an exam score (say)
# based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on:
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
print( [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] )
#################################
# The above bisect() functions are useful for finding insertion points but
# can be tricky or awkward to use for common searching tasks.
# The following five functions show how to transform them into the standard lookups for sorted lists:
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
raise ValueError
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect.bisect_right(a, x)
if i:
return a[i-1]
raise ValueError
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect.bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError
def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect.bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError
print('\n-------------------pickle module---------------------\n')
print(dir(pickle))
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.txt", "wb" ) )
# Load the dictionary back from the pickle file.
favorite = pickle.load( open( "save.txt", "rb" ) )
print(favorite,'\nWOW ! That was nice !') | true |
2dbae09466384658d5906425b8aeb6095495ac1a | btrif/Python_dev_repo | /BASE SCRIPTS/searching.py | 1,535 | 4.75 | 5 | # ### Python: Searching for a string within a list – List comprehension
# The simple way to search for a string in a list is just to use ‘if string in list’. eg:
list = ['a cat','a dog','a yacht']
string='a cat'
if string in list:
print ('found a cat!')
# But what if you need to search for just ‘cat’ or some other regular expression and return a list of the list
# items that match, or a list of selected parts of list items that match.
# Then you need list comprehension.
import re
list = ['a cat','a dog','a yacht','cats']
regex=re.compile(".*(cat).*")
print([m.group(0) for l in list for m in [regex.search(l)] if m])
print([m.group(1) for l in list for m in [regex.search(l)] if m])
# Lets work through that. Firstly we’re going to use the regular expression library so we import that. re.compile
# lets us create a regular expression that we can later use for search and matching.
#
# Now lets look at a simpler comprehension line:
print([m for l in list for m in [regex.search(l)]])
# This is creating a list of the results of running regex.search() on each item in l.
# Next we want to exclude the None values. So we use an if statement to only include the not None values:
print([m for l in list for m in [regex.search(l)] if m ])
# Lastly rather than returning just a list of the m’s, which are RE match objects, we get the information we want from them.
print([m.group(0) for l in list for m in [regex.search(l)] if m])
print([m.group(1) for l in list for m in [regex.search(l)] if m]) | true |
a42127989a11eabe0a112f58ec1e6ca0a4be9bcd | btrif/Python_dev_repo | /BASE SCRIPTS/OOP/static_variables.py | 2,037 | 4.5 | 4 | # Created by Bogdan Trif on 17-07-2018 , 3:34 PM.
# I noticed that in Python, people initialize their class attributes in two different ways.
# The first way is like this:
class MyClass:
__element1 = 123 # static element, it means, they belong to the class
__element2 = "this is Africa" # static element, it means, they belong to the class
def __init__(self):
pass
# pass or something else
# The other style looks like:
class MyClass:
def __init__(self):
self.__element1 = 123
self.__element2 = "this is Africa"
# Which is the correct way to initialize class attributes?
# ANSWER :
'''
Both ways aren't correct or incorrect, they are just two different kind of class elements:
1. Elements outside __init__ method are static elements, it means, they belong to the class.
2. Elements inside the __init__ method are elements of the object (self ), they don't belong to the class.
You'll see it more clearly with some code:
'''
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
print('# Initial values of both elements')
print( ' c1 class : ',c1.static_elem, c1.object_elem)
# 123 456
print( ' c2 class : ', c2.static_elem, c2.object_elem )
# 123 456
# Nothing new so far ...
# Let's try changing the static element
print('\n# Lets try changing the static element')
MyClass.static_elem = 999
print( ' c1 class : ',c1.static_elem, c1.object_elem)
# 999 456
print( ' c2 class : ', c2.static_elem, c2.object_elem )
# 999 456
# Now, let's try changing the object element
print('\n# Now, let s try changing the object element')
c1.object_elem = 888
print( ' c1 class : ',c1.static_elem, c1.object_elem)
# 999 888
print( ' c2 class : ', c2.static_elem, c2.object_elem )
# 999 456
# As you can see, when we changed the class element, it changed for both objects. But, when we
# changed the object element, the other object remained unchanged.
| true |
0b4eae1855d2a62e6152419526c4f49d08c1085d | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/EDX - MIT - Introduction to Comp Science I/bank_credit_account.py | 844 | 4.65625 | 5 | '''
It simulates a credit bank account. Suppose you have a credit. You pay each month a monthlyPaymentRate
and each month an annualInterestRate is calculated for the remaining money resulting in a remaining balance
each month.
'''
balance = 5000 # Balance
monthlyPaymentRate = 2/100 # Monthly payment rate, %
annualInterestRate = 18/100 # Annual Interest Rate, %
#def bank_account(balance , annualInterestRate , monthlyPaymentRate ):
for i in range(1,13):
balance = balance - (monthlyPaymentRate * balance)
balance = balance + (balance * annualInterestRate /12)
print(round(balance , 2),' ; ', round(-monthlyPaymentRate*balance ,2) , ' ; ', round((balance * annualInterestRate /12),2))
print ('\nRemaining balance after a year : ',round(balance, 2))
#print(bank_account(484, 0.2, 0.04)) | true |
53958a00677713402c549640639d87442b94d9d2 | btrif/Python_dev_repo | /plots exercises/line_animation.py | 1,087 | 4.40625 | 4 | __author__ = 'trifb' #2014-12-19
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure() #defining the figure
ax = plt.axes(xlim=(0, 10), ylim=(-8, 8)) # x-axes limits and y-axes limits
line, = ax.plot([], [], lw=4, ) # establishing two lists and lw = linewidth
# initialization function: plot the background of each frame
def init():
# line.set_data([], [])
return line,
'''The next piece is the animation function.
It takes a single parameter, the frame number i, and draws a sine wave with a shift that depends on i:'''
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 1+ 0.09*i, 100)
y = (1 - 0.02 * i) # the 'i' variable makes the sine function flow
line.set_data(x, y)
return line,
print(line)
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.grid(); plt.show() | true |
24e78bf77cad25af185baf4fd71d6953e86620c7 | fransikaz/PIE_ASSIGNMENTS | /homework8.py | 2,880 | 4.5 | 4 | import os
# import os.path
from os import path
'''
HOMEWORK #8:
Create a note-taking program. When a user starts it up, it should prompt them for a filename.
If they enter a file name that doesn't exist, it should prompt them to enter the text they want to write to the file.
After they enter the text, it should save the file and exit.
If they enter a file name that already exists, it should ask the user if they want:
A) Read the file
B) Delete the file and start over
C) Append the file
'''
# Notebook as existing file. For testing code
with open("Notebook.txt", "w") as existingFile:
for i in range(5):
notes = "This is a note for existing filename\n"
existingFile.write(notes)
def Notes():
Filename = input("Please enter the filename: ")
if path.exists("{}.txt".format(Filename)): # Do if filename already exists
print("The filename already exists. What what you like to do with this file?")
option = input(
"Enter 'r' to read, 'd' to delete, 'a' to append to file \n or 's' to replace a line in the file: ")
if option == "r": # if user wants to read from existing file
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
elif option == "a": # If user wants to append new notes
with open("{}.txt".format(Filename), "a") as NoteFile:
notesTaken = input(
"Type your notes and hit enter when done: \n")
NoteFile.write("\n" + notesTaken)
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
elif option == "s": # replacing a single line
with open("{}.txt".format(Filename), "r") as NoteFile:
lineNum = int(
input("Please enter line number you want to replace: "))
notesTaken = input(
"Type your notes and hit enter when done: \n")
NoteFileList = NoteFile.readlines()
NoteFileList[lineNum] = notesTaken + "\n"
with open("{}.txt".format(Filename), "w") as NoteFile:
for List in NoteFileList:
NoteFile.write(List)
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
elif option == "d": # if user wants to delete existing file
os.remove("{}.txt".format(Filename))
Notes()
else: # Do if filename does not exist
with open("{}.txt".format(Filename), "w") as NoteFile:
notesTaken = input("Type your notes and hit enter when done: \n")
NoteFile.write(notesTaken)
with open("{}.txt".format(Filename), "r") as NoteFile:
print(NoteFile.read())
Notes()
| true |
d20f44d4150c21a96b178b3aac74b45e25c5fab1 | AndersenDanmark/udacity | /test.py | 2,516 | 4.5 | 4 | def nextDay(year, month, day):
"""
Returns the year, month, day of the next day.
Simple version: assume every month has 30 days.
"""
# YOUR CODE HERE
if day+1>30:
day=1
if month+1>12:
month=1
year=year+1
else:
month=month+1
else:
day=day+1
return (year,month,day)
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before
year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
return day1 < day2
return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second. Assertation added for date order"""
# YOUR CODE HERE!
assert(dateIsBefore(year1, month1, day1, year2, month2, day2)==True),"the first date is not before the second date!"
dayCount=1
currentDay=nextDay(year1,month1,day1)
while currentDay[0]<year2:
currentDay=nextDay(currentDay[0],currentDay[1],currentDay[2])
dayCount=dayCount+1
while currentDay[1]<month2:
currentDay=nextDay(currentDay[0],currentDay[1],currentDay[2])
dayCount=dayCount+1
while currentDay[2]<day2:
currentDay=nextDay(currentDay[0],currentDay[1],currentDay[2])
dayCount=dayCount+1
return dayCount
def test():
"""This is a test function for the daysBetweenDates function"""
test_cases = [((2012,9,30,2012,10,30),30),
((2012,1,1,2013,1,1),360),
((2012,9,1,2012,9,4),3),
((2013,1,1,1999,12,31), "AssertionError")]
for (args, answer) in test_cases:
try:
result = daysBetweenDates(*args)
if result != answer:
print ("Test with data:", args, "failed")
else:
print ("Test case passed!")
except AssertionError:
if answer == "AssertionError":
print ("Nice job! Test case {0} correctly raises AssertionError!\n".format(args))
else:
print ("Check your work! Test case {0} should not raise AssertionError!\n".format(args))
test()
| true |
14389832de4c1e1317bd88f01b2686a83eb36017 | KeelyC0d3s/L3arning | /squareroot.py | 1,126 | 4.375 | 4 | # Keely's homework again.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
# Now, time to figure out how to get the square root of 14.5
#import math
#math.sqrt(14.5)
#print( "math.sqrt(14.5)", math.sqrt(14.5))
#Trying Newton Method.
#Found code here: https://tinyurl.com/v9ob6nm
# Function to return the square root of
# a number using Newtons method
def squareRoot(n, l) :
# Assuming the sqrt of n as n only
x = n
# To count the number of iterations
count = 0
while (1) :
count += 1
# Calculate more closed x
root = 0.5 * (x + (n / x))
# Check for closeness
if (abs(root - x) < l) :
break
# Update root
x = root
return root
# Driver code
if __name__ == "__main__" :
n = 14.5
l = 0.00001
print(squareRoot(n, l))
#I'll be honest, I still don't completely understand this.
#I searched the internet for Newton Method, square root Python
#and the above program is what I found. I'll need to spend more time with it.
| true |
8aaf6cd5b8634dfdcd5a6e6923dbea448100b983 | carlanlinux/PythonBasics | /9/9.6_ClonningLists.py | 418 | 4.25 | 4 | '''
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the
list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of
the word copy.
The easiest way to clone a list is to use the slice operator.
'''
a = [81,82,83]
b = a[:] # make a clone using slice
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b) | true |
ce9a774c06363afc1f03da671d9276d5ae11b758 | MalteMagnussen/PythonProjects | /week2/objectOriented/Book.py | 974 | 4.21875 | 4 | from PythonProjects.week2.objectOriented import Chapter
class Book():
"""A simple book model consisting of chapters, which in
turn consist of paragraphs."""
def __init__(self, title, author, chapters=[]):
"""Initialize title, the author, and the chapters."""
self.title = title
self.author = author
self.chapters = chapters
def __repr__(self):
return 'Book(%r, %r, %r)' % (self.title, self.author, self.chapters)
def __str__(self):
return '{name} by {by} has {nr_chap} chapters.'.format(
name=self.title, by=self.author, nr_chap=len(self.chapters))
def read(self, chapter=1):
"""Simulate reading a chapter, by calling the reading
method of a chapter."""
self.chapters[chapter - 1].read()
def open_book(self, chapter=1) -> Chapter:
"""Simulate opening a book, which returns a chapter
object."""
return self.chapters[chapter - 1]
| true |
fdde0b3b81e7987289e4134ff4a523f5b6544587 | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/sqrt.py | 1,075 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/125/template-i/950/
#Description
"""
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of
the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or
x ** 0.5.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is
returned.
Constraints:
0 <= x <= 231 - 1
"""
def mySqrtImpl(x, start, end):
if end - start <= 1:
sq_end = end * end
if sq_end == x:
return end
else:
return start
mid = (start + end)//2
sq_mid = mid * mid
if sq_mid == x:
return mid
elif sq_mid > x:
return mySqrtImpl(x, start, mid)
else: # sq_mid < x
return mySqrtImpl(x, mid, end)
def mySqrt(x):
assert x >= 0
if x == 0:
return 0
if x == 1:
return 1
return mySqrtImpl(x, 1, x) | true |
7ff689c4e4d6f95ad27413579ee15919eee29e15 | saurabh-pandey/AlgoAndDS | /leetcode/bst/sorted_arr_to_bst.py | 1,129 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/143/appendix-height-balanced-bst/1015/
#Description
"""
Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node
never differs by more than one.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order.
"""
from bst.node import Node
def createBST(nums, start, end):
if start >= end:
return None
else:
mid = (start + end)//2
node = Node(nums[mid])
node.left = createBST(nums, start, mid)
node.right = createBST(nums, mid + 1, end)
return node
def sortedArrayToBST(nums):
return createBST(nums, 0, len(nums)) | true |
c5361ad406f3da27f7960150fb6afbd44bbae03e | saurabh-pandey/AlgoAndDS | /leetcode/queue_stack/stack/target_sum.py | 2,326 | 4.1875 | 4 | #URL: https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1389/
#Description
"""
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each
integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them
to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input: nums = [1], target = 1
Output: 1
Constraints:
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
"""
add = lambda x, y: x + y
sub = lambda x, y: x - y
def checkTargetSumMatch(target, stackSum):
targetSum = target + stackSum
targetDiff = target - stackSum
count = 0
if targetSum == 0:
count += 1
if targetDiff == 0:
count += 1
return count
def findTargetSumRec(sz, nums, target, runningSum, stackSum, i, action):
newStackSum = action(stackSum, nums[i])
if i == sz - 1:
return checkTargetSumMatch(target, newStackSum)
sumRemainStack = runningSum[i + 1]
maxPositiveSum = newStackSum + sumRemainStack
minPositiveSum = newStackSum - sumRemainStack
minNegativeSum = -newStackSum - sumRemainStack
maxNegativeSum = -newStackSum + sumRemainStack
isTargetInPosRange = (target <= maxPositiveSum) and (target >= minPositiveSum)
isTargetInNegRange = (target <= maxNegativeSum) and (target >= minNegativeSum)
if isTargetInPosRange or isTargetInNegRange:
count = 0
count += findTargetSumRec(sz, nums, target, runningSum, newStackSum, i + 1, add)
count += findTargetSumRec(sz, nums, target, runningSum, newStackSum, i + 1, sub)
return count
else:
return 0
def findTargetSumWays(nums, target):
if len(nums) == 0:
return 0
sz = len(nums)
nums.sort(reverse=True)
runningSum = [sum(nums[i:]) for i in range(sz)]
return findTargetSumRec(sz, nums, target, runningSum, 0, 0, add)
| true |
72d27e13ba30f9d65f0e0b4e105389f80d2fcd03 | loolu/python | /CharacterString.py | 830 | 4.15625 | 4 | #使用字符串
#字符串不可改变,不可给元素赋值,也不能切片赋值
website = 'http://www.python.org'
website[-3] = 'com'
#
format = "Hello, %s. %s enough for ya?"
values = ('world', 'hot')
print(format % values)
from string import Template
tmpl = Template("Hello, $who! $what enough for ya?")
print(tmpl.substitute(who='Mars', what='Dusty'))
print("{}, {} and {}".format("first", "second", "third"))
print("{0}, {1} and {2}".format("first", "second", "third"))
print("{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to"))
from math import pi
print("{name} is approximately {value:.2f}.".format(value=pi, name="π"))
print("{name} is approximately {value}.".format(value=pi, name="π"))
from math import e
print(f"Euler's constant is roughly {e}.")
print("Euler's constant is roughly {e}.".format(e=e)) | true |
61bb1f7871db613627d1edd50128a7c5c88d0b4b | Stemist/BudCalc | /BudgetCalculatorCLI.py | 1,577 | 4.28125 | 4 | #!/usr/bin/env python3
people = []
class Person:
def __init__(self, name, income):
self._name = name
self._income = income
self.products = {}
def add_product():
try:
product = str(input("Enter product name: "))
cost = float(input("Enter product cost ($): "))
products[product] = price
except:
print("Error: Invalid entry format. Make sure cost is a number, e.g. '3.50'.")
def return_total_cost():
pass
def main():
start_menu()
# User enters people to be considered in the calculation.
while making_people == True:
try:
check = str(input("Add a person to the calculation? (y/n)"))
if check == 'y' or 'Y':
generate_person()
else:
break
except:
print("Error: Please enter 'y' or 'n'.")
# User enters items and prices.
while adding_items == True:
for person in people:
display_totals()
def start_menu():
print("### Monthly Budget Calculator. ###\n\n")
expected people =
def display_totals():
for each_person in people:
print("Name: ", each_person._name, ", Monthly income: $", each_person._income)
print("Items: ", each_person.products)
def generate_person():
try:
person_name = str(input("Enter the first person's name: "))
person_income = float(input("Enter their monthly income ($)"))
# Generate a new person with the above values.
person_instance = Person(person_name, person_income)
# Add them to the list of people.
people.append(person_instance)
except:
print("Input Error: Must input a name and a number value.")
if __name__ == '__main__':
main() | true |
4b67eb4c4a802e7980142f6a8ee644f1bda6d867 | huyilong/python-learning | /fibo_module.py | 720 | 4.25 | 4 | #fibonacci numbers module
#could directly input python3 on mac terminal to invoke version 3
def fib(n):
a, b = 0, 1
while b < n:
print( b),
#there is a trailing comma "," after the print to indicate not print output a new line
a, b = b, a+b
print #this is print out a empty line
#if you use print() then it will actually output a () rather than a new line
def fib2(n):
result = []
a, b =0, 1
while b<n:
result.append(b)
a, b = b, a+b
return result
if __name__=="__main__":
#here the __name__ and __main__ all have two underlines! not only one _!
import sys
fib(int(sys.argv[1]))
print("hello, this is my first module for fibonacci numbers generator")
print("Usage: fibo_module.fib(1000)") | true |
6d70e720d4424c0b948c20561fdec80afae21701 | gregxrenner/Data-Analysis | /Coding Challenges/newNumeralSystem.py | 1,752 | 4.46875 | 4 | # Your Informatics teacher at school likes coming up with new ways to help
# you understand the material. When you started studying numeral systems,
# he introduced his own numeral system, which he's convinced will help clarify
# things. His numeral system has base 26, and its digits are represented by
# English capital letters - A for 0, B for 1, and so on.
# The teacher assigned you the following numeral system exercise:
# given a one-digit number, you should find all unordered pairs of one-digit
# numbers whose values add up to the number.
# Example
# For number = 'G', the output should be
# newNumeralSystem(number) = ["A + G", "B + F", "C + E", "D + D"].
# Translating this into the decimal numeral system we get:
# number = 6, so it is ["0 + 6", "1 + 5", "2 + 4", "3 + 3"].
# Assume input is "A" <= number <= "Z".
def newNumeralSystem(number):
# Initialize and empty solution list
solution = []
# Define the number system.
system = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'I':8, 'J':9, 'K':10, 'L':11, 'M':12,
'N':13, 'O':14, 'P':15, 'Q':16, 'R':17, 'S':18, 'T':19, 'U':20, 'V':21, 'W':22, 'X':23, 'Y':24, 'Z':25}
# Invert the dict for reverse lookups.
system_inv = dict((v, k) for k, v in system.items())
print('System[number]=', system[number])
# Find unordered pairs of one-digit numbers that add up to 'number'.
for i in range(0, system[number]):
for j in range(i, system[number]+1):
if (i + j) == system[number]:
success = str(system_inv[i] + ' + ' + system_inv[j])
solution.append(success)
# Handle case where number = 'A'
if number == 'A': return ['A' + ' + ' + 'A']
return solution
newNumeralSystem('A')
| true |
23de8de49110b4db71833b1b54041bd41fae2b43 | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-6.py | 436 | 4.3125 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates miles walked and calories lost for a specific day of the week.
dayWalked = input('Enter the day of the week you walked: ')
stepsTaken = int(input('Enter the number of steps taken that day: '))
milesWalked = (stepsTaken/2000)
caloriesLost = (stepsTaken/2000)*65
print ('You walked', milesWalked, 'miles on', dayWalked, 'and lost', caloriesLost, 'calories.')
| true |
2c2cd04d5893ebb5e05d463729a999f80e55266c | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-4.py | 580 | 4.1875 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates how many credits are left until graduation.
studentName = input('Enter student name. ')
degreeName = input('Enter degree program name. ')
creditsDegree = int(input('Enter the number of credits needed for the degree. '))
creditsTaken = int(input('Enter the number of credits taken so far. '))
creditsLeft = creditsDegree - creditsTaken
print ('The student\'s name is', studentName)
print ('The degree program name is', degreeName)
print ('There are', creditsLeft, 'credits left until graduation. ')
| true |
3434b25d66c2edefe39cc30ecc20b8a886d45639 | kundaMwiza/dsAlgorithms | /source/palindrome.py | 869 | 4.1875 | 4 | def for_palindrome(string):
"""
input: string
output: True if palindrome, False o/w
implemented with a for loop
"""
for i, ch in enumerate(string):
if ch != string[-i-1]:
return False
return True
def rec_palindrome(string):
"""
input: string
output: True if palidrome, False o/w
implemented with recursion
"""
string = string.lower()
n = len(string)
start = 0
stop = n-1
def is_palindrome(string, stop, start):
if stop == start:
return True
elif (stop - start) == 1 or (stop - start) == 2:
return string[start] == string[stop]
else:
x = string[start] == string[stop]
return x and is_palindrome(string, stop-1, start+1)
return is_palindrome(string, stop, start)
print(rec_palindrome('ara'))
| true |
5c30a3093ad4fca9ef738d7901f659eff9698700 | ase1590/python-spaghetti | /divide.py | 254 | 4.1875 | 4 | import time
print('divide two numbers')
# get the user to enter in some integers
x=int(input('enter first number: '))
y=int(input('enter number to divide by: '))
print('the answer is: ',int(x/y)),
time.sleep(3) #delay of a few seconds before closing
| true |
5cfd561fc32a028223208019bde4c60736e786a5 | ndvssankar/ClassOf2021 | /Operating Systems/WebServer/test_pipe.py | 1,316 | 4.3125 | 4 | # Python program to explain os.pipe() method
# importing os module
import os
import sys
# Create a pipe
pr, cw = os.pipe()
cr, pw = os.pipe()
stdin = sys.stdin.fileno() # usually 0
stdout = sys.stdout.fileno() # usually 1
# The returned file descriptor r and w
# can be used for reading and
# writing respectively.
# We will create a child process
# and using these file descriptor
# the parent process will write
# some text and child process will
# read the text written by the parent process
# Create a child process
pid = os.fork()
# pid greater than 0 represents
# the parent process
if pid > 0:
# This is the parent process
# Closes file descriptor r
# os.close(pr)
os.close(cw)
os.close(cr)
# print("Parent process is writing")
os.dup2(pw, stdout)
text = "n=10"
print(text)
os.close(pw)
os.dup2(pr, stdin)
st = input()
print(st)
# print("Written text:", text.decode())
else:
# This is the parent process
# Closes file descriptor w
# os.close(pw)
# os.close(pr)
# Read the text written by parent process
# print("\nChild Process is reading")
# print(open("scripts/odd.py").read())
os.dup2(cr, stdin)
os.dup2(cw, stdout)
exec(open("scripts/odd.py").read())
| true |
564be3d797b4993009205db721f2fb1c1513c820 | koussay-dellai/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 415 | 4.125 | 4 | #!/usr/bin/python3
class Square:
'''defining a sqaure'''
def __init__(self, size=0):
'''initialize an instance'''
self.__size = size
if type(size) is not int:
raise TypeError("size must be an integer")
elif (size < 0):
raise ValueError("size must be >= 0")
def area(self):
'''defining a public method'''
return (self.__size ** 2)
| true |
99f7f46430267a6ee17e0288b14511e3cbef57fc | koussay-dellai/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 350 | 4.1875 | 4 | #!/usr/bin/python3
"""
module to print lines of a file
"""
def read_lines(filename="", nb_lines=0):
"""
function to print n lines of a file
"""
number = 0
with open(filename, encoding="UTF8") as f:
for i in f:
number += 1
print(i, end="")
if nb_lines == number:
break
| true |
fce2be88790287f25b5d6cf863720bbf172f772c | katealex97/python-programming | /UNIT2/homework/hw-1.py/hw-3.py | 394 | 4.21875 | 4 | odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar',
'123451' , '0.0', 'papa', '-pq-']
count = 0
for string in odd_strings:
#find strings greater than 3 and have same
#first and last character
first = string[0]
last = string[len(string) - 1] #python allows neg. indexes last = string[-1]
if len(string) > 3 and first = last:
count += 1
print(count)
| true |
cde77dfa50a8a370bf1c589bc8d262488dc81e29 | thecipherrr/Assignments | /New Project/Number1.py | 488 | 4.25 | 4 | # Main Function
def convert_to_days():
hours = float(input("Enter number of hours:"))
minutes = float(input("Enter number of minutes:"))
seconds = float(input("Enter number of seconds:"))
print("The number of days is:", get_days(hours, minutes, seconds))
# Helper Function
def get_days(hours, minutes, seconds):
days = (hours / 24) + (minutes / (24 * 60)) + (seconds / (24 * 3600))
days_final = round(days, 4)
return days_final
convert_to_days() | true |
1414aef6db7b039b2f065d68376d903c79e7ba3f | seangrogan-archive/datastructures_class | /TP2/BoxClass.py | 1,691 | 4.28125 | 4 | class BoxClass:
"""class for easy box handling"""
def __init__(self, name, width, height):
"""init method"""
self._name = name
self._width = width
self._height = height
self._rotate = False
def __lt__(self, other):
"""for sorting"""
return self._name < other.name()
def __gt__(self, other):
"""for sorting"""
return self._name > other.name()
def __eq__(self, other):
"""for sorting"""
return self._name == other.name()
def __str__(self):
"""pretty printing"""
pp = '(' + self._name + ',' + str(self._width) + ',' + str(self._height) + ')'
return pp
def rotate_box(self):
"""class to rotate the box"""
self._rotate = not self._rotate
def reset_rotate(self):
"""rotates the box to original"""
self._rotate = False
def is_rotated(self):
"""class to tell if a box is rotated"""
return self._rotate
def name(self):
"""return thy name"""
return self._name
def height(self):
"""returns the height"""
if self._rotate:
return self._width
else:
return self._height
def width(self):
"""returns the width"""
if self._rotate:
return self._height
else:
return self._width
# unit testing
if __name__ == '__main__':
print('unit testing')
box = BoxClass('A', 5, 3)
print(box.height())
print(box.is_rotated())
box.rotate_box()
print(box.height())
print(box.is_rotated())
print(box) | true |
a761dad436a049421f7e6fa8b0bf3c478df6b8aa | pavanjavvadi/leet_code_examples | /anagram.py | 1,681 | 4.3125 | 4 | """
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
"""
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
# create a default dictionary using collections module
# defaultdict keys must be immutable and unique
res = defaultdict(list)
# looping the list elements using for loop
for s in strs:
# sort the value of the each element using sorted() function
sorted_values = sorted(s)
# this assigns values to the key where keys are unique
# here the keys are sorted ones but the values are original elements
res[''.join(sorted_values)].append(s)
# print the defaultdict values() elements for printing the group anagrams
print(res.values())
solution = Solution()
strs = ["eat","tea","tan","ate","nat","bat"]
solution.groupAnagrams(strs)
"""
detailed explaination:
_2d_list_value = [] , eg: [[a, b], [c, d]]
for s i strs:
values = [''.join(sorted(s)), s]
_2d_list_value.append(values)
result = defaultdict(list)
for k, v in _2d_list_value:
result[k].append(v)
print(result.values())
""" | true |
66d180a6bfbc522549ac68db6d3b04d940455159 | Rinatik79/PythonAlgoritms | /Lesson 1/lesson1-7.py | 609 | 4.21875 | 4 | sides = input("Enter length of every side of triangle, separated by ';' : ")
sides = sides.split(";")
sides[0] = float(sides[0])
current = sides[0]
sides[1] = float(sides[1])
if sides[1] > sides[0]:
sides[0] = sides[1]
sides[1] = current
current = sides[0]
sides[2] = float(sides[2])
if sides[2] > sides[0]:
sides[0] = sides[2]
sides[2] = current;
if sides[0] > sides[1] + sides[2]:
print("Triangle with given sides doesn't exist.")
elif sides[1] == sides[2]:
print("This is isosceles triangle.")
if sides[0] == sides[1] == sides[2]:
print("This is equilateral triangle.")
| true |
4977a7a7e99f1f571ade665a927e97a059287ae4 | AtharvBagade/Python | /Question7.py | 304 | 4.28125 | 4 | string=input("Enter the string")
def Most_Duplicate_Character(str1):
count = 0
for i in str1:
count2 = str1.count(i)
if(count2 > count):
count = count2
num = i
print(num,"Count:",count)
Most_Duplicate_Character(string)
| true |
cf05f6410b6878b34067ecb3b89b38bef59f59b5 | Design-Computing/me | /set3/exercise2.py | 1,216 | 4.5 | 4 | """Set 3, Exercise 2.
An example of how a guessing game might be written.
Play it through a few times, but also stress test it. What if your lower bound
is 🍟, or your guess is "pencil", or "seven"
This will give you some intuition about how to make exercise 3 more robust.
"""
import random
def exampleGuessingGame():
"""Play a game with the user.
This is an example guessing game. It'll test as an example too.
"""
print("\nWelcome to the guessing game!")
print("A number between 0 and _ ?")
upperBound = input("Enter an upper bound: ")
print(f"OK then, a number between 0 and {upperBound} ?")
upperBound = int(upperBound)
actualNumber = random.randint(0, upperBound)
guessed = False
while not guessed:
guessedNumber = int(input("Guess a number: "))
print(f"You guessed {guessedNumber},")
if guessedNumber == actualNumber:
print(f"You got it!! It was {actualNumber}")
guessed = True
elif guessedNumber < actualNumber:
print("Too small, try again :'(")
else:
print("Too big, try again :'(")
return "You got it!"
if __name__ == "__main__":
exampleGuessingGame()
| true |
03f695385e9a5b6dd258029d10e11b9bb6ffa371 | ahmedzaabal/Beginner-Python | /Dictionary.py | 606 | 4.28125 | 4 | # Dictionary = a changeable, unorderd collecion of unique key:value pairs
# fast because they use hashing, allow us to access a value quickly
capitals = {'USA': 'Washington DC',
'India': 'New Delhi',
'China': 'Beijing',
'Russia': 'Moscow'}
capitals.update({'Germany': 'Berlin'})
capitals.update({'USA': 'Las Vegas'})
capitals.pop('China')
capitals.clear()
# print(capitals['Germany'])
# print(capitals.get('Germany'))
# print(capitals.keys())
# print(capitals.values())
# print(capitals.items())
for key, value in capitals.items():
print(key, value)
| true |
c5d91ba52a45b61a4442201fc22f7a20aa575c63 | malay1803/Python-For-Everybody-freecododecamp- | /files/findLine.py | 1,218 | 4.375 | 4 | # Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
#X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
fName = input("Enter your file name : ")
try:
fHand = open(fName)
except:
print("Invalid file name")
quit()
sum = 0
count=0
for line in fHand :
if line.startswith("X-DSPAM-Confidence:") :
rmNewLine = line.strip() #to remove /n from the end of each line
pos = rmNewLine.find(":") #to find the position of : in a line
num = float(rmNewLine[pos+1:]) #to select convert the string into number
sum = sum + num #to find sum of the numbers
count = count +1 #to count the number of lines
print(f'Average spam confidence: {sum/count}') #to print the output | true |
53c6e9853a06f737c8c43009c4ed2c154e11e107 | vmysechko/QAlight | /metiz/files_and_exceptions/file_writer.py | 720 | 4.21875 | 4 | filename = "programming.txt"
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
# 'w' argument tells Python that we want to open a file in write mode.
# In the write mode Python will erase the content of the file.
# 'r' - read mode
# 'a' - append mode
# 'r+' - read/write mode
with open(filename, 'a') as file_object:
file_object.write("That should be the only stroke in the file.\n")
file_object.write("I also love finding meaning in large data-sets. \n")
file_object.write("I also love creating apps that can run in a browser. \n")
guest_name = input("Write your name, please: ")
with open(filename, 'a') as file_object:
file_object.write(guest_name + "\n")
| true |
7f26b982dd0543a277216ca671b882f9d1c1f3a1 | calder3/BCA_Project- | /hang_man2.py | 1,186 | 4.15625 | 4 | '''
This will play the game hangman. Need to have the random word modual installed.
'''
from random_word import RandomWords
r = RandomWords()
word = r.get_random_word(hasDictionaryDef = 'true')
word = word.lower()
space = list(word)
dash = []
dash.extend(word)
#print(word)
for i in range(len(dash)):
dash[i] = "_"
print(' '.join(dash))
print()
turns = 10
already_guessed = []
while turns > 0:
guess = input('If you think you know the word enter word. Other wise guess a letter: ')
guess = guess.lower()
if guess in space:
for i in range(len(space)):
if space[i] == guess:
dash[i] = guess
print('You got a letter right!')
elif guess == "word":
word_guess = input("\n What is the word? ")
word_guess = word_guess.lower()
if word_guess == word:
print(f'You win! \n The word was {word}')
break
else:
print("Wrong! \n")
already_guessed.append(guess)
print('You have wrongly guessed', already_guessed,'\n')
turns = turns - 1
print(f'You have {turns} fails before you lose.')
print(" ".join(dash))
print()
if turns == 0:
print('You lose!')
print(f'The word was {word}')
| true |
028e73aab6a25145064048c00eb5d9f35d8037c1 | PriyaRcodes/Threading-Arduino-Tasks | /multi-threading-locks.py | 995 | 4.375 | 4 | '''
Multi Threading using Locks
This involves 3 threads excluding the main thread.
'''
import threading
import time
lock = threading.Lock()
def Fact(n):
lock.acquire()
print('Thread 1 started ')
f = 1
for i in range(n,0,-1):
f = f*i
print('Factorial of',n,'=',f)
lock.release()
def Square(n):
lock.acquire()
print('Thread 2 started ')
sq = n*n
print('Square of',n,'=',sq)
lock.release()
def Task():
print('Thread 3 started ')
time.sleep(1) #represents any task that takes 1 sec
print('Task done')
print('This is the main thread')
n = int(input('Enter a number: '))
start_time = time.time()
T1 = threading.Thread(target=Fact,args=(n,))
T2 = threading.Thread(target=Square,args=(n,))
T3 = threading.Thread(target=Task)
T1.start()
T2.start()
T3.start()
T1.join()
T2.join()
T3.join()
print('All threads have been closed')
print('Processing time taken: ',time.time()-start_time,'seconds')
| true |
6fe40fec45477da49060eb84fc699ce68e6075c7 | ant0nm/reinforcement_exercise_d23 | /exercise.py | 818 | 4.375 | 4 | def select_cards(possible_cards, hand):
for current_card in possible_cards:
print("Do you want to pick up {}?".format(current_card))
answer = input()
if answer.lower() == 'y':
if len(hand) >= 3:
print("Sorry, you can only pick up 3 cards.")
else:
hand.append(current_card)
return hand
available_cards = ['queen of spades', '2 of clubs', '3 of diamonds', 'jack of spades', 'queen of hearts']
new_hand = select_cards(available_cards, [])
while len(new_hand) < 3:
print("You have only picked up {} cards.\nYou are required to have 3 cards.\nPlease choose again.".format(len(new_hand)))
new_hand = select_cards(available_cards, [])
display_hand = "\n".join(new_hand)
print("Your new hand is: \n{}".format(display_hand))
| true |
28789e85fe5a651088aed96262a4ba1c9bb97bed | ntuong196/AI-for-Puzzle-Solving | /Week7-Formula-puzzle/formula_puzzle.py | 1,095 | 4.34375 | 4 | #
# Instructions:
#
# Complete the fill_in(formula) function
#
# Hints:
# itertools.permutations
# and str.maketrans are handy functions
# Using the 're' module leads to more concise code.
import re
import itertools
def solve(formula):
"""Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None."""
for f in fill_in(formula):
if valid(f):
return f
def fill_in(formula):
''' Return a generator that enumerate all possible fillings-in
of letters in formula with digits.'''
# INSERT YOUR CODE HERE
def valid(f):
"""Formula f is valid if and only if it has no
numbers with leading zero, and evals true."""
try:
return not re.search(r'\b0[0-9]', f) and eval(f) is True
except ArithmeticError:
return False
print(solve('ODD + ODD == EVEN'))
print(solve('A**2 + BC**2 == BD**2'))
# Should output
# >>>
## 655 + 655 == 1310
## 2**1 + 34**1 == 36**1
#print (re.split('([A-Z]+)', 'A**2 + BC**2 == BD**2'))
| true |
1c44fed92ef5e6e7c986f79a0f2473de31325184 | hansweni/UBC_PHYS_Python-crash-course | /2. Arduino for Data Collection/RGB_LED.py | 1,311 | 4.28125 | 4 | '''
Program to demonstrate how to flash the three colors of a RGB diode
sequentially using the Arduino-Python serial library.
'''
# import libraries
from Arduino import Arduino
import time
board = Arduino() # find and connect microcontroller
print('Connected') # confirms the microcontroller has been found
# give pins names, so they are easy to reference
RED = 3
GREEN = 5
BLUE = 6
# configure the pins as outputs
board.pinMode(RED, "OUTPUT")
board.pinMode(GREEN, "OUTPUT")
board.pinMode(BLUE, "OUTPUT")
# turn all LEDs off
board.analogWrite(RED, 0)
board.analogWrite(GREEN, 0)
board.analogWrite(BLUE, 0)
try:
while True:
board.analogWrite(RED, 255) # set RED to full brightness
time.sleep(1) # wait 1 second
board.analogWrite(RED, 0) # turn RED off
board.analogWrite(GREEN, 255) # set GREEN to full brightness
time.sleep(1) # wait 1 second
board.analogWrite(GREEN, 0) # turn RED off
board.analogWrite(BLUE, 255) # set GREEN to full brightness
time.sleep(1) # wait 1 second
board.analogWrite(BLUE, 0) # turn GREEN off
# press ctrl+c while the console is active to terminate the program
except:
board.close() # close the serial connection
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.