blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a6b7095bdf942c083324dc7d49dc2835d651bdb9 | RileyMathews/nss-python-exercises-classes | /employees.py | 1,597 | 4.1875 | 4 | class Company(object):
"""This represents a company in which people work"""
def __init__(self, company_name, date_founded):
self.company_name = company_name
self.date_founded = date_founded
self.employees = set()
def get_company_name(self):
"""Returns the name of the company"""
return self.company_name
# Add the remaining methods to fill the requirements above
def get_employees(self):
print(f'Employee report for {self.company_name}')
for employee in self.employees:
employee.print_information()
def hire_employee(self, employee):
self.employees.add(employee)
class Employee:
""" this class represent the people which work at companies """
def __init__(self, fn, ln, job_title, start_date):
self.first_name = fn
self.last_name = ln
self.job_title = job_title
self.start_date = start_date
def print_information(self):
print(f'{self.first_name} {self.last_name} started working as {self.job_title} on {self.start_date}')
# create a company
galactic_empire = Company("The Galactic Empire", "-10 BBY")
# declare employee objects
vader = Employee("Darth", "Vader", "Sith Lord", "-10 BBY")
sidious = Employee("Darth", "Sidious", "Emperor", "-10 BBY")
thrawn = Employee("Mithrando", "Thrawn", "Admiral", "-6 BBY")
# add employees to galactic empire
galactic_empire.hire_employee(vader)
galactic_empire.hire_employee(sidious)
galactic_empire.hire_employee(thrawn)
# call employee report for galactic empire
galactic_empire.get_employees()
| true |
eec5d6c8cb0b850addb2f043eb56b93787cb123f | peterjoking/Nuevo | /Ejercicios_de_internet/Ejercicio_22_Readfile.py | 897 | 4.53125 | 5 | """
Opening a file for reading is the same as opening for writing, just using a different flag:
with open('file_to_read.txt', 'r') as open_file:
all_text = open_file.read()
Note how the 'r' flag stands for “read”. The code sample from above
reads the entire open_file all at once into the all_text variable.
But, this means that we now have a long string in all_text that
can then be manipulated in Python using any string methods you want.
Another way of reading data from the file is line by line:
with open('file_to_read.txt', 'r') as open_file:
line = open_file.readline()
while line:
print(line)
line = open_file.readline()
"""
"""with open('Docuprueba.txt', 'r') as open_file:
all_text = open_file.read()
print(all_text)
"""
ruta = '/Users/Pedro/Nuevo/fichero1.txt'
with open(ruta, 'r') as open_file:
all_text = open_file.read()
print(all_text) | true |
f3b36b0d425a27a84edce61bd93de52c69ec90fe | ceejtayco/python_starter | /longest_strings.py | 455 | 4.125 | 4 | #Given an array of strings, return another array containing all of its longest strings.
def longest_string(inputList):
newList = list()
longest = len(inputList[0])
for x in range(len(inputList)-1):
if longest < len(inputList[x+1]):
longest = len(inputList[x+1])
for x in inputList:
if len(x) == longest:
newList.append(x)
return newList
print(longest_string(["aba", "ab", "ababa", "ab"])) | true |
eab7db0160e4e7dfc0da0690f114d51b49cbd69a | Haris-HH/CP3-Haris-Heamanunt | /Exercise_5_2_Haris_Heamanunt.py | 262 | 4.28125 | 4 | distance = int(input("Distance (km) : "))
time = int(input("Time (h) : "))
if(distance < 1):
print("Distance can not be less than 1 km")
elif(time < 1):
print("Time can not be less than 1 hour")
else:
result = distance / time
print(result,"km/h") | true |
383cd867c393b32c6655c8c5bfbbd8baba60ad6a | LeilaRzazade/python_projects | /guess_number.py | 802 | 4.1875 | 4 | #This is random number generator program.
#You should guess the random generated number.
import random
random_num = random.randint(1,100)
user_input = int(input("Guess the number: "))
if (user_input == random_num):
print("Congratulations! Guessed number is: ", user_input)
while(user_input != random_num):
if(user_input == random_num):
print("Congratulations! Guessed number is right.")
break
else:
if(user_input > random_num):
print("Your number is not right. It's too high.")
user_input = int(input(("Enter a new number: ")))
else:
print("Your number is not right. It's too low.")
user_input = int(input(("Enter a new number: ")))
print("Congratulations! Guessed number is: ", user_input)
| true |
4f8686f815a0f47d40b96cd5d9f6491d490a6159 | jlast35/hello | /python/data_structures/queue.py | 1,905 | 4.34375 | 4 | #! /usr/bin/env python
# Implementation of a Queue data structure
# Adds a few non-essential convenience functions
# Specifically, this is a node intended for a queue
class Node:
def __init__(self, value):
self.value = value
self.nextNode = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enq(self, value):
# Create an empty node
node = Node(value)
# If it's the first node, make it the head
if self.tail == None: self.head = node
# Make its next node the current tail of the queue
node.nextNode = self.tail
# Update the tail to now be the new node
self.tail = node
def deq(self):
# Special case: Empty
if self.is_empty():
#print "Deq empty!"
pass
# There is at least one node
else:
#print "Deq", self.head.value
# Special case: only one node
if self.is_singleton():
# After we deq, head and tail are None
self.tail = None
self.head = None
# There is more than one node
else:
penult = self.tail
while penult.nextNode != self.head:
penult = penult.nextNode
#print "Penult is", penult.value
penult.nextNode = None
del self.head
self.head = penult
self.print_q()
# ----- Convenience functions for testing -------
def print_q(self):
if self.tail == None:
#print "Empty queue!"
pass
else:
current = self.tail
while current != None:
print current.value,
current = current.nextNode
print
def from_list(self, qList):
for node in qList:
self.enq(node)
self.print_q()
def is_empty(self):
if (self.head == None) and (self.tail == None): return True
else: return False
def is_singleton(self):
if (self.head == self.tail) and (self.head != None): return True
else: return False
def deq_all(self):
while not self.is_empty(): self.deq()
# ---------- TEST ----------------
q = Queue()
q.from_list(range(10))
q.deq_all()
| true |
2bb03b26a4554f78c897815138c6bf675ddfe96e | YuliiaAntonova/leetcode | /reverse integer.py | 786 | 4.125 | 4 | # Given a signed 32-bit integer x, return x with its digits reversed.
# If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
class Solution(object):
def reverse(self,n):
y = str(abs(n)) # Create a variable and convert the integer into a string
y = y.strip() #Strip all the leading zeros
y = y[::-1] #reversed str
rev = int(y) #Input reverse as an integer
if rev >= 2 **31 -1 or rev <= -2**31: #check the conditions
return 0
elif n < 0: #display negative numbers
return -1 * rev
else:
return rev
if __name__ == '__main__':
solution = Solution()
print(solution.reverse(-123))
print(solution.reverse(1234))
| true |
cc54a0283f674a4091d9d3a26f3b70459245119e | JaffarA/ptut | /python-4.py | 1,626 | 4.4375 | 4 | # introduction to python
# 4 - io, loops & functions cont..
# functions can take multiple arguments, default arguments and even optional arguments (part of *args)
def introduce(name='slim shady', age, hobby='fishing'):
return print(f'Hi, my name is {name}. Hi, my age is {age}. Hi, i like this "{hobby}"')
# this code will by default work with only 1 variable passed.
introduce(8)
# we can even be explicit and say exactly what we want to pass
introduce(age=23, hobby='tacos')
# for-based iteration, previously we used while-based iteration but this option is more popular
# a for loop iterates a finite amount of times in what is called a count-controlled loop
# below are two examples of types of for-loops
items = ['eggs', 'cheese', 'milk']
for i in items: # we can iterate over a list object using each element as the i value
print(f'Buying {i}\n') # \n adds a newline
# fixed-length for loop
for i in range(1, 100): # range technically creates a list object with every number between two points
print(i, end='\n')
# exercise 1
# fill in the blanks (#) below to make the code run 3 times and stop if the password is correct with a for loop
def password_program(password):
for # insert an i control statement
if get_name('Please enter the password: ') == password:
print('Access Granted') # fill this in to say 'Access Granted after {i} attempts'
break # escape from the for loop
else:
print() # fill this in to say 'Access Denied. {i}/3 attempts left'
password_program('cheese')
# exercise 2
# write a function which asks for someone's name and uses a default greeting parameter
| true |
f9f86abfd5bab24edac6d6149fefd15b451f438e | anvarknian/preps | /Heaps/min_heap.py | 2,621 | 4.1875 | 4 | import sys
# defining a class min_heap for the heap data structure
class min_heap:
def __init__(self, sizelimit):
self.sizelimit = sizelimit
self.cur_size = 0
self.Heap = [0] * (self.sizelimit + 1)
self.Heap[0] = sys.maxsize * -1
self.root = 1
# helper function to swap the two given nodes of the heap
# this function will be needed for heapify and insertion to swap nodes not in order
def swapnodes(self, node1, node2):
self.Heap[node1], self.Heap[node2] = self.Heap[node2], self.Heap[node1]
# THE MIN_HEAPIFY FUNCTION
def min_heapify(self, i):
# If the node is a not a leaf node and is greater than any of its child
if not (i >= (self.cur_size // 2) and i <= self.cur_size):
if (self.Heap[i] > self.Heap[2 * i] or self.Heap[i] > self.Heap[(2 * i) + 1]):
if self.Heap[2 * i] < self.Heap[(2 * i) + 1]:
# Swap the node with the left child and then call the min_heapify function on it
self.swapnodes(i, 2 * i)
self.min_heapify(2 * i)
else:
# Swap the node with right child and then call the min_heapify function on it
self.swapnodes(i, (2 * i) + 1)
self.min_heapify((2 * i) + 1)
# THE HEAPPUSH FUNCTION
def heappush(self, element):
if self.cur_size >= self.sizelimit:
return
self.cur_size += 1
self.Heap[self.cur_size] = element
current = self.cur_size
while self.Heap[current] < self.Heap[current // 2]:
self.swapnodes(current, current // 2)
current = current // 2
# THE HEAPPOP FUNCTION
def heappop(self):
last = self.Heap[self.root]
self.Heap[self.root] = self.Heap[self.cur_size]
self.cur_size -= 1
self.min_heapify(self.root)
return last
# THE BUILD_HEAP FUNCTION
def build_heap(self):
for i in range(self.cur_size // 2, 0, -1):
self.min_heapify(i)
# helper function to print the heap
def Print(self):
for i in range(1, (self.cur_size // 2) + 1):
print(" PARENT : " + str(self.Heap[i]) +
" LEFT CHILD : " + str(self.Heap[2 * i]) +
" RIGHT CHILD : " + str(self.Heap[2 * i + 1]))
def __repr__(self):
return str(self.Heap[1:])
minHeap = min_heap(10)
minHeap.heappush(15)
minHeap.heappush(7)
minHeap.heappush(9)
minHeap.heappush(4)
minHeap.heappush(13)
print(minHeap)
# minHeap.Print()
minHeap.heappop()
print(minHeap)
| true |
643bb8a4c5100d1f22dbd60132317b66f6fb3b06 | Vinaypatil-Ev/aniket | /1.BASIC PROGRAMS/4.fahrenheit_to_degree.py | 286 | 4.40625 | 4 | # WAP to convert Fahrenheit temp in degree Celsius
def f_to_d(f):
return (f - 32) * 5 / 9
f = float(input("Enter Fahrenheit temprature: "))
x = f_to_d(f)
print(f"{f} fahreheit is {round(x, 3)} degree celcius")
# round used above is to round the decimal values upto 3 digits
| true |
3211aaae0cdbca9324479483fb2206519ccf8ca2 | TonyPwny/cs440Ass1 | /board.py | 1,614 | 4.1875 | 4 | # Thomas Fiorilla
# Module to generate a Board object
import random #import random for random generation
def valid(i, j, size):
roll = random.randint(1, max({(size - 1) - i, 0 + i, (size - 1) - j, 0 + j}))
return roll
# function to generate the board and place the start/end points
# returns the built board and its size
class Board:
def __init__(self, boardSize):
# checks to see if the user input board size is valid; if not...
# generate a random number between 1 and 4, map 1:5, 2:7, 3:9, assign the boardSize variable
# if 4 or any other number not 1,2,3, catch and map as 11
# also assigns boardMax, which is the maximum number that will fit in ANY tile
if int(boardSize) > 4:
roll = int(boardSize)
else:
roll = random.randint(0,3)
if roll == 0:
self.boardSize = 5
elif roll == 1:
self.boardSize = 7
elif roll == 2:
self.boardSize = 9
elif roll == 3:
self.boardSize = 11
else:
self.boardSize = roll
self.boardBuilt = [[0 for x in range(self.boardSize)] for y in range(self.boardSize)] # create a 2D array of size "size"x"size" all initialised to 0
i = 0
j = 0
# code to generate the board, starting with iterating through each row
while (i < self.boardSize):
# iterates through each column of one row, rolling dice and checking if there are too many walls
while (j < self.boardSize):
if (i == self.boardSize-1) and (j == self.boardSize-1):
self.boardBuilt[i][j] = 'G'
break
else:
roll = valid(i, j, self.boardSize)
self.boardBuilt[i][j] = roll
j += 1
j = 0
i += 1
| true |
30b85504154a9a22042c416955ca643818f45e63 | psarangi550/PratikAllPythonRepo | /Python_OOS_Concept/Monkey_Pathching_In_Python.py | 2,149 | 4.4375 | 4 | #changing the Attribute of a class dynamically at the runtime is called Monkey Patching
#its a common nature for dynamically typed Language
#lets suppose below example
class Test:#class Test
def __init__(self):#constructor
pass#nothing to initialize
def fetch_Data(self):#instance method
#remeber that function is also a object and function name is the variable which been pointing to the function object that
#that means:-function object has some id and function name variable pointing to that function object
#address of function object and function reference variable being same as of now
print("lets suppose its been fetching the data from DB")
#after this data Fetched from DB we want to perform some activity using another function
def f1(self):#instance method
self.fetch_Data()#calling the instance method
#now we realized that we should not deal with the live DB but we have to pre store test dat with which we need to test
#which is
def fetch_new_data(x):#here we are taking x as args as it will replace the ond live DB Data and we know self is not a keyword hence we cantake any args and PVM will provide the value for the same
print("lets suppose its been fetching the data from Test DB")
#so we can change the data fetching from the old DB to the New DB Using the Monkey Patching at runtime
#we can write as below:-
Test.fetch_Data=fetch_new_data
#here the fetch_new_data function object referred by variable fetch_new_data same like fetch_data
#as function is the object and which is referred by the function reference variable
#here you can see we are not calling the method we are assigning the reference variable fetch_new_data reference to
# fetch data reference
#now the fetch_data is now not refer its old function object but its now pointing to the new function object as we assign the fetch_new_Data reference variable to fetch_data
#now if we try to access the fetch_data it will provide the new Fetch_new_Data info
Test().fetch_Data()#creating Test class Object and calling the instance method
#lets suppose its been fetching the data from Test DB
| true |
1bbc38978d15042164c2a458952ea34ba30853db | yuliia11882/CBC.Python-Fundamentals-Assignment-1 | /Yuliia-py-assignment1.py | 1,380 | 4.21875 | 4 | #Canadian Business College.
# Python Fundamentals Assignment 1
#PART 1:-------------------------------
#enter how many courses did he/she finish
# the input value (which is string) is converted into number with int()
num_of_courses = int(input("How many courses have you finished? "))
print(num_of_courses)
#Declare an empty list
course_marks = []
#while loop
count = 1
while count <= num_of_courses:
# the append() method used to add user's input into course_marks = []
course_marks.append (int(input("Enter your MARK for the COURSE #{count} is: ")))
#increment the loop count
count += 1
print(course_marks)
#PART 2:-------------------------
#find the total of all the courses marks inside the list with loop
total = 0
for number in course_marks :
total += number
# find the average for all the courses
for numb in course_marks :
average = total / num_of_courses
print(f"The average of your {num_of_courses} is: {average}"))
#PART 3:------------------------
if average >= 90 and average <=100:
print("your grade is A+")
if average >= 80 and average <=89:
print("your grade is B")
if average >= 70 and average <=79:
print("your grade is C")
if average >= 60 and average <=69:
print("your grade is D")
if average < 60:
print("your grade is F")
| true |
6e3568a6057b0d88393120ad65238b14834d53ba | samiCode-irl/programiz-python-examples | /Native_Datatypes/count_vowels.py | 273 | 4.125 | 4 | # Python Program to Count the Number of Each Vowel
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
sent = ip_str.casefold()
count = {}.fromkeys('vowels', 0)
for letter in sent:
if letter in count:
count[letter] += 1
print(count)
| true |
f19151fce2c14be35efad14a418a87e724286aa0 | bryanlie/Python | /HackerRank/lists.py | 1,198 | 4.46875 | 4 | '''
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands where each command will be of the types listed above.
Iterate through each command in order and perform the corresponding operation on your list.
No switch case in Python...
'''
if __name__ == '__main__':
n = int(input())
arr = []
for _ in range(n):
line = list(input().split())
if line[0] == 'insert':
arr.insert(int(line[1]), int(line[2]))
elif line[0] == 'print':
print(arr)
elif line[0] == 'remove':
arr.remove(int(line[1]))
elif line[0] == 'append':
arr.append(int(line[1]))
elif line[0] == 'sort':
arr.sort()
elif line[0] == 'pop':
arr.pop()
elif line[0] == 'reverse':
arr.reverse()
else:
break
| true |
c270f4865da343415ea72349627c690b2bd5ad54 | dipikakhullar/Data-Structures-Algorithms | /coding_fundamentals.py | 772 | 4.125 | 4 | def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)
import queue
# From class queue, Queue is
# created as an object Now L
# is Queue of a maximum
# capacity of 20
L = queue.Queue(maxsize=20)
# Data is inserted into Queue
# using put() Data is inserted
# at the end
L.put(5)
L.put(9)
L.put(1)
L.put(7)
# get() takes data out from
# the Queue from the head
# of the Queue
print(L.get())
print(L.get())
print(L.get())
print(L.get())
#OUTPUT:
"""
5
9
1
7
"""
L.put(9)
L.put(10)
print("Full: ", L.full())
print(L.get())
print(L.get())
print(L.get())
# Return Boolean for Empty
# Queue
print("Empty: ", L.empty())
| true |
28a982b392e5a1c3e5ecc287f78d63b506349c2a | Aparna768213/Best-Enlist-task-day3 | /day7task.py | 794 | 4.34375 | 4 | def math(num1,num2):
print("Addition of two numbers",num1+num2)
print("Subtraction of two numbers",num1-num2)
print("Multiplication of two numbers",num1*num2)
print("Division of two numbers",num1/num2)
num1 = float(input("Enter 1st number:"))
num2 = float(input("Enter 2nd num:"))
math(num1,num2)
#Create a function covid()& it should accept patient name ,and body temperature ,by default the body temparature should be 98 degree.
def covid(patient_name, body_temperature):
if body_temperature < str(0):
default=str(98)
print("Patient name is",patient_name," Body temperature is",default)
else:
print("Patient name is",patient_name," Body temperature is",body_temperature)
covid("Aparna","")
covid("Aparna","99")
| true |
c28bc62bc1b7a68b6a73b36cceada5cf8f07cd0c | rishikumar69/all | /average.py | 239 | 4.21875 | 4 | num = int(input("Enter How Many Number you want:"))
total_sum = 0
for i in range(num):
input = (input("Enter The Number:"))
total_sum += input
ans = total_sum/num
line = f"Total Average of {total_sum}is{ans}"
print(line)
| true |
d6ab91f6579ec619a681ab8f0d6f31240773a194 | Gaurav716Code/Python-Programs | /if else if/ph value..py | 288 | 4.125 | 4 | def phvalue():
num = float(input("Enter number : "))
if num > 7 :
print(num," is acidic in nature.")
elif num<7:
print(num," is basic in nature.")
else:
print(num,"is neutral in nature.")
print("~~~~ End of Program ~~~~~~")
phvalue()
| true |
d22f4ce6a9cff8d04db8fca268a56a52bb2092e3 | ridwan098/Python-Projects | /multiplication table.py | 220 | 4.21875 | 4 | # This program displays the multiplication table
loop = 1 == 1
while loop == True:
n= input('\nenter an integer:')
for i in range(1, 13):
print ("%s x %s = %s" %(n, i, i*int(n)))
| true |
e4d00925b6e7d22f3f36a97fe670119419ffc614 | ridwan098/Python-Projects | /fibonacci sequence(trial 1).py | 361 | 4.15625 | 4 |
# This program prints out the fibonacci sequence(up to 100)
loop = 1 == 1
while loop == True:
number = 1
last = 0
before_last = 0
num = int(input("\nHow many times should it list? "))
for counter in range(0, num):
before_last = last
last = number
number = before_last + last
print(number)
| true |
26f0f0fdbbe45e57831f01a07ccdcf501e11515c | kelleyparker/Python | /grades.py | 512 | 4.3125 | 4 | print("This program calculates the averages of five students' grades.\n\n")
# Define a list of tuples containing the student names and grades
students = []
for i in range(5):
name = input(f"Insert student {i+1}'s name: ")
grade = float(input(f"Insert {name}'s grade: "))
students.append((name, grade))
# Calculate the average grade
total = sum([grade for name, grade in students])
average = total / len(students)
# Print the results
print(f"The class average for the five students is {average}.")
| true |
19387fd2d7095b98e0492d1e93bd8f98001d8cf1 | MaiShantanuHu/Coursera-Python-3-Programming | /Python-Basics/Week-2/Lists and Strings.py | 1,622 | 4.21875 | 4 | '''Q-1: What will the output be for the following code?'''
let = "z"
let_two = "p"
c = let_two + let
m = c*5
print(m)
#Answer:
# pzpzpzpzpz
'''Q-2: Write a program that extracts the last three items in the list sports and assigns it to the variable last.
Make sure to write your code so that it works no matter how many items are in the list.'''
sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey']
last=sports[-3:]
print(last)
'''Q-3: Write code that combines the following variables so that the sentence “You are doing a great job, keep it up!” is assigned to the variable message.
Do not edit the values assigned to by, az, io, or qy.'''
by = "You are"
az = "doing a great "
io = "job"
qy = "keep it up!"
message=by+" "+az+io+","+" "+qy
print(message)
'''Q-4: What will the output be for the following code?
ls = ['run', 'world', 'travel', 'lights', 'moon', 'baseball', 'sea']
new = ls[2:4]
print(new)'''
#Answer :
# ['travel', 'lights']
'''Q-5: What is the type of m?
l = ['w', '7', 0, 9]
m = l[1:2]'''
#Answer :
# list
'''Q-6: What is the type of m?
l = ['w', '7', 0, 9]
m = l[1]'''
#Answer :
# string
'''Q-7: What is the type of x?
b = "My, what a lovely day"
x = b.split(',')'''
#Answer :
# list
'''Q-8: What is the type of a?
b = "My, what a lovely day"
x = b.split(',')
z = "".join(x)
y = z.split()
a = "".join(y)'''
#Answer :
# string
| true |
88aa8d4f5e4c0db6bc03e01b37b1b81e5419b3fa | dtulett15/5_digit_seperator | /3digit_seperator.py | 300 | 4.28125 | 4 | #seperate three digits in a three digit number entered by user
#get number from user
num = int(input('Enter a 3 digit number: '))
#set hundreds digit
num1 = num // 100
#set tens digit
num2 = num % 100 // 10
#set ones digit
num3 = num % 10
#seperate digits
print(num1, ' ', num2, ' ', num3) | true |
9c2987a4dc6565034ae0ee703a4af1175d409d22 | shahzeb-jadoon/Euclids-Algorithm | /greatest_common_divisor.py | 691 | 4.375 | 4 | def greatest_common_divisor(larger_num, smaller_num):
"""This function uses Euclid's algorithm to calculate the Greatest Common Divisor
of two non-negative integers
pre: larger_num & smaller_num are both non-negative integers, and larger_num > smaller_num
post: returns the greatest common divisor of larger_num & smaller_num
"""
while smaller_num != 0:
remainder = larger_num % smaller_num
larger_num, smaller_num = smaller_num, remainder
return larger_num
def main():
larger_num = 60
smaller_num = 24
print(greatest_common_divisor(larger_num, smaller_num))
if __name__ == "__main__":
main() | true |
873a3801db68683d1551df016016074821335284 | Meghna-U/posList.py | /posList.py | 215 | 4.125 | 4 | list=[]
s=int(input("Enter number of elements in list:"))
print("Enter elements of list:")
for x in range(0,s):
element=int(input())
list.append(element)
for a in list:
if a>0:
print(a)
| true |
7e97f790d96abf42d0220cb1fe537834a50d0796 | shikhaghosh/python-assigenment1 | /assignment2/question10.py | 284 | 4.15625 | 4 | print("enter the length of three side of the triangle:")
a,b,c=int(input()),int(input()),int(input())
if a==b and a==b and a==c:
print("triangle is equilateral")
elif a==b or b==c or a==c:
printf("triangle is a isoscale")
else:
printf("triangle is a scalene")
| true |
143f78b793a0772073bcc3239ce361d2735339d4 | IbroCalculus/Python-Codes-Snippets-for-Reference | /Set.py | 1,592 | 4.21875 | 4 |
#Does not allow duplicate, and unordered, but mutable.
#It is faster than a list
#Python supports the standard mathematical set operations of
# intersection, union, set difference, and symmetric difference.
#DECLARING EMPTY SET
x= set() #NOTE: x = {} is not an empty set, rather an empty dictionary
s = {10,10,10,3,2}
print(s, end='\n\n')
L = ['Ibrahim','Ibrahim','Ibrahim',"Musa"]
print(L,end='\n')
S = set(L)
print(S)
#Counting characters using set
testT = "Ibrahim Musa Suleiman"
print(f'CHARACTERS PRESENT: {set(testT)}, NUMBER OF CHARACTERS: {len(set(testT))}')
#Add elements to a set
y = set()
y.add("One")
y.add("Two")
y.add("Three")
y.add("Four")
print(y)
print(f'ADDED ELEMENT: {y}')
#Remove element from a set
y.remove("Three") #OR y.discard("Three")
print(f'ROM0VED ELEMENT: {y}')
#y.pop() removes the last element in the tuple, but tuple is unordered, ie: removes any element
#Clear a set
y.clear()
#Delete a tuple
del y
#JOIN TWO SETS
#Assume Set1 and Set2 are defined, use the Set1.update(Set2). print(Set1)
#SET OPERATIONS
#UNION A|B
#INTERSECTION A&B
#SET DIFFERENCE A-B ELEMENTS IN A BUT NOT IN B
#SYMETRIC DIFFERENCE A^B ELEMENTS IN A OR B, BUT NOT IN BOTH
#Check reference for more
A = {"IBRAHIM", "IBRAHIM", "MUSA"}
B = {"SULEIMAN", "20s", "IBRAHIM"}
print(f'THE UNION: {A|B}')
print(f'THE INTERSECT: {A&B}')
print(f'THE DIFFERENCE: {A-B}')
print(f'THE SYMETRIC DIFFERENCE: {A^B}')
x = (A|B) - (A&B)
print(f'SIMILARLY: {x}')
#SET QUANTIFICATION WITH ALL AND ANY
#Check reference | true |
b27175e1a40f491c0ef12308615e1fc946b694e6 | IbroCalculus/Python-Codes-Snippets-for-Reference | /Regex2.py | 902 | 4.4375 | 4 | import re
#REGULAR EXPRESSIONS QUICK GUIDE
'''
^ - Matches the beginning of a line
$ - Matches the end of a line
. - Matches any character
\s - Matches whitespace
\S - Matches any non-whitespace character
* - Repeats a character zero or more times
*? - Repeats a character zero or more times (non-greedy)
+ - Repeats a character one or more times.
+? - Repeats a character one or more times (non-greedy)
[aeiou] - Matches a single character in the listed set
[^XYZ] - Matches a single character not in the listed set
[a-z0-9] - The set of characters can include a range
( - Indicates where string extraction is to start
) - Indicates where String extraction is to end
'''
st = "This is a string statement, this is a this is which is a this. Just for testing regex"
#USING re.find and re.search
if re.search("is", st):
print("Match found")
print(f'{re.search("is", st)}')
| true |
fd9adb7ebb5603760577526aa16ab7d83555be5d | ParulProgrammingHub/assignment-1-mistryvatsal | /Program8.py | 241 | 4.15625 | 4 | # WPP TO TAKE INPUT BASE AND HEIGHT OF THE TRIANGLE AND PRINT THE AREA OF THE TRIANGLE
base = int(input('ENTER THE BASE OF THE TRIANGLE :'))
height = int(input('ENTER THE HEIGHT OF THE TRIANGLE :'))
print('AREA IS : ', 0.5 * height * base)
| true |
c26f6b50cf1d5469dbd3cc97838e12ec9893e8ba | johnlev/coderdojo-curriculum | /Week2/activity.py | 633 | 4.34375 | 4 | # We are going to be making a guessing game, where the user guesses your favorite number
# Here we define a variable guess which holds the user's response to the question
# The input function asks the user the question and gives back the string the user types in.
# The int(...) syntax converts the string into an integer if it can
guess = int(input("What is my favorite number? "))
# =======================
# You write the following
my_favorite_number = 42
# If the guess is less than your favorite number, tell the user
# If the guess is more than your favorite number, ...
# If the guess is your favorite number, ...
| true |
f83050b30754d73714f4382103ec3499635b7eb2 | GiantPanda0090/Cisco_Toolbox | /regex/remove_dup_words.py | 695 | 4.46875 | 4 |
###################################################
# Duplicate words
# The students will have to find the duplicate words in the given text,
# and return the string without duplicates.
#
###################################################
import re
def demo():
print(remove_duplicates("the bus bus will never be a bus bus in a bus bus bus"))
def remove_duplicates(text):
#write here
exression_0=r"\b(\w+)(?!\s+\1)\b"
text_with_no_dup_list=re.findall(exression_0,text)
text_with_no_dup=""
for word in text_with_no_dup_list:
text_with_no_dup=text_with_no_dup+" "+word
return text_with_no_dup
##main class trigger
if __name__ == "__main__":
demo() | true |
7b23940e3907b14467adeec77e52d3713ae5ad87 | jtylerroth/euler-python-solutions | /1-100/14.py | 1,219 | 4.125 | 4 | # The following iterative sequence is defined for the set of positive integers:
#
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
#
# Using the rule above and starting with 13, we generate the following sequence:
#
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
#
# Which starting number, under one million, produces the longest chain?
#
# NOTE: Once the chain starts the terms are allowed to go above one million.
# Dictionary will hold all the known answers to speed up calculations
lengths = {}
def collatzSequence(n):
length = 1
while n != 1:
if n % 2 == 0: # even
n = n/2
else: # odd
n = 3*n+1
length += 1
if n in lengths:
length += lengths[n]
break # already solved
return length
# Question example
# print(collatzSequence(13))
max_n = 1
max_val = 1
for i in range(1,1000000):
seq = collatzSequence(i)
lengths[i] = seq # Save the answer
if seq > max_val:
max_n = i
max_val = seq
print("Longest chain: {0} with length {1}".format(max_n,max_val))
| true |
086a9d173ed3e63778658acb1b08f31c5adacf90 | leo-sandler/ICS4U_Unit_4_Algorithms_Leo_Sandler | /Lesson_4.1/4.1_Recursion_and_Searching.py | 1,826 | 4.21875 | 4 | import math
# Pseudo code for summing all numbers from one to 100.
# Initialize count variable, at 1
# for 101 loops
# Add loop number to the count, with reiterating increase
# Real code
count = 0
for x in range(101):
count += x
# print(count)
# Recursion is calling the same function within itself.
# Recursion pseudo code
def recursionexample(tracker):
if tracker > 4:
return True
else:
return recursionexample(tracker + 1) # Increases forever, automatically returning True.
print("\nRecursive programming: ")
print(recursionexample(6)) # If higher than 4, it returns True.
print(recursionexample(-992)) # If lower than 4, continually adds up until it is bigger than four, then returns True.
# Searches can be done in binary, or through linear searching.
# Linear searching:
# pseudo code below.
# define function
# search data is set to 12
# for loop, number in numbers(which is a list of numbers)
# if searchdata is number then
# Return true
def list_searching(numbers): # Pseudo code in python
searchdata = 12
for number in numbers:
if searchdata == number:
return True
return False
print("\nList searching: ")
print(list_searching([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(list_searching([2, 4, 6, 8, 10, 12, 14]))
# Binary is faster, but data must be sorted first.
# Binary will be slower for extremely large lists.
# The list is split into halves, which are searched. The list cuts from the middle.
def binarySearch(a, value, left, right):
if right < left:
return False
mid = math.floor((right - left) / 2)
if a[mid] == value:
return value
if value < a[mid]:
return binarySearch(a, value, left, mid-1)
else:
return binarySearch(a, value, left+1, right)
| true |
83971e63972f9a21edf9f355529cab109502a54d | sanketha1990/python-basics | /pythonHelloWorld/com/python/learner/ComparisionOperatorInPython.py | 410 | 4.46875 | 4 | temperature=30
if temperature > 30: # == , !=,
print('its hot day !')
else:
print('it is not hot day !')
print('=============================================')
name=input('Please enter your name .. ')
name_len=len(name)
if name_len <= 3:
print('Name should be gretter thant 3 charecter !')
elif name_len >=50:
print('Name length should be less than 50')
else:
print('Name looks Good !!!')
| true |
bc0237b5b7ad679068c608b10a522c79423ca44a | alexisfaison/Lab1 | /Programming Assignment 1.py | 1,021 | 4.1875 | 4 | # Name: Alexis Faison
# Course: CS151, Prof. Mehri
# Date: 10/5/21
# Programming Assignment: 1
# Program Inputs: The length, width, and height of a room in feet.
# Program Outputs: The area and the amount of paint and primer needed to cover the room.
import math
#initialize variables
width_wall = 0.0
length_wall = 0.0
height_wall = 0.0
print("\nPaint your room! Enter the dimensions of the room in feet.")
length_wall = float(input("\n\tEnter desired length:"))
width_wall = float(input("\n\tEnter desired width:" ))
height_wall = float(input("\n\tEnter desired height:" ))
#Calculate the area, gallons of primer & gallons of paint
area = (length_wall + width_wall) + 2 * ((length_wall * height_wall) + (width_wall * height_wall))
primer = math.ceil(area/200)
paint = math.ceil(area/350)
print("\nThe total area of the four walls and ceiling is", area, "feet.")
print("\nThe gallons of primer needed to coat the area is", primer, "gallons.")
print("\nThe gallons of paint needed to cover the area is", paint, "gallons.") | true |
0f662c6750f4e56b67eb4c73f495dc70b96c1bf7 | pallavibhagat/Problems | /problem2.py | 376 | 4.4375 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The
sum of these multiples is 23. Write a program to find the sum of all the multiples of 3 or 5 below
1000.
"""
def multiple():
sum = 0
for i in range(1,1000):
if i%3==0 or i%5==0:
sum +=i
print sum
if __name__ == '__main__':
multiple() | true |
2133af4c52bba08fd49755539e15512f1ee865e5 | DipakTech/Python-basic | /app.py | 2,827 | 4.15625 | 4 | # print('hello world')
# python variables
# one=1
# two=2
# some_number=1000
# print(one,two,some_number)
# booleans
# true_boolean=True
# false_boolean=False
# # string
# my_name='diapk'
# # float
# book_price=12.3
# print(true_boolean,false_boolean,my_name,book_price)
# if True:
# print('Hello python learners:')
# if 3>1:
# print('3 is greater than 1')
# control flow and conditional statements
# if 1>2:
# print('1 is greater than 2')
# elif 2>1:
# print('2 is greater than 1')
# else:
# print('1 is equal to 2')
# looping and iterator
# num=1
# while num<=100:
# print(num)
# num+=1
# another basic bit of code to better understand it :
# loop_condition=True
# while loop_condition:
# print('loop condition keeps: %s' %(loop_condition))
# loop_condition=False
# for looping
# for i in range(1,11):
# print(i)
# list collection |array and data structure
# my_integers=[1,2,3,4,5,6,7,8,9]
# print(my_integers[0])
# print(my_integers[2])
# print(my_integers[3])
# print(my_integers[5])
# print(my_integers[4])
# print(my_integers[6])
# relatives_names=[
# 'bipana',
# 'dipak',
# 'jagat',
# 'ananda',
# 'premlal',
# 'saraswati'
# ]
# for i in range(0,len(relatives_names)):
# print(relatives_names[i])
# appending the list in to the empty array
# book_list=[]
# book_list.append('The effective enginners')
# book_list.append('money heist')
# book_list.append('the mekemoney dev')
# book_list.append('the python study')
# book_list.append('the javascript learners')
# print(book_list[4])
# for i in range(0,len(book_list)):
# print(book_list[i])
# dictoionary_example
# dictoionary_example={
# "key1":"value1",
# "key2":"value2",
# "key3":"value3"
# }
# print(dictoionary_example)
# print(dictoionary_example["key1"])
# print(dictoionary_example["key2"])
# printting the dictoionary in the formatted way
# dictoionary_tk={
# "name":"DIPAK",
# "age":21,
# "education":"bachelore"
# }
# dictoionary_tk["age"]=23;
# print(dictoionary_tk)
# bookshef=[
# "the effective engineer",
# "The 4 hours of social network",
# "zero to mestry",
# "the Hero"
# ]
# for book in bookshef:
# print(book)
# dictionary = { "some_key": "some_value" }
# for key in dictionary:
# print("%s --> %s" %(key, dictionary[key]))
# dictionary = { "some_key": "some_value" }
# for key, value in dictionary.items():
# print("%s --> %s" %(key,value))
# dictoionary_tk={
# "name":"DIPAK",
# "age":21,
# "education":"bachelore"
# }
# for attribute, value in dictoionary_tk.items():
# print('my %s is %s' %(attribute,value)) | true |
104fac3bec6c7975673715d7a3d2594d6d8e9d63 | AlphaCoderX/MyPythonRepo | /Assignment 1/RecipeConverter.py | 1,157 | 4.125 | 4 | #Programmer Raphael Heinen
#Date 1/19/17
#Version 1.0
print "-- Original Recipe --"
print "Enter the amount of flour (cups): ",
flour = raw_input()
print "Enter the amount of water (cups): ",
water = raw_input()
print "Enter the amount of salt (teaspoons): ",
salt = raw_input()
print "Enter the amount of yeast (teaspoons): ",
yeast = raw_input()
print "Enter the loaf adjustment factor (e.g. 2.0 double the size): ",
factor = raw_input()
#adjusts recipe based on user input factor
flour = float(flour) * float(factor)
water = float(water) * float(factor)
salt = float(salt) * float(factor)
yeast = float(yeast) * float(factor)
print " "
print "-- Modified Recipe --"
print "Bread Flour: %s cups." % flour
print "Water: %s cups." % water
print "Salt: %s teaspoons." % salt
print "Yeast: %s teaspoons." % yeast
print "Happy Baking!",
print " "
#converts current cup(s) measurement(s) to grams
flour2 = flour * 120
water2 = water * 237
salt2 = salt * 5
yeast2 = yeast * 3
print "-- Modified Recipe in Grams --"
print "Bread Flour: %s g." % flour2
print "Water: %s g." % water2
print "Salt: %s g." % salt2
print "Yeast: %s g." % yeast2
print "Happy Baking!",
| true |
463fab4b59fd21609889666840b14b98e01a80bf | helloallentsai/leetcode-python | /1295. Find Numbers with Even Number of Digits.py | 958 | 4.21875 | 4 | # Given an array nums of integers, return how many of them contain an even number of digits.
# Example 1:
# Input: nums = [12,345,2,6,7896]
# Output: 2
# Explanation:
# 12 contains 2 digits (even number of digits).
# 345 contains 3 digits (odd number of digits).
# 2 contains 1 digit (odd number of digits).
# 6 contains 1 digit (odd number of digits).
# 7896 contains 4 digits (even number of digits).
# Therefore only 12 and 7896 contain an even number of digits.
# Example 2:
# Input: nums = [555,901,482,1771]
# Output: 1
# Explanation:
# Only 1771 contains an even number of digits.
# Constraints:
# 1 <= nums.length <= 500
# 1 <= nums[i] <= 10^5
from typing import List
class Solution:
def findNumbers(self, nums: List[int]) -> int:
nums = list(map(lambda num: str(num), nums))
evens = list(filter(lambda num: len(num) % 2 == 0, nums))
return len(evens)
x = Solution()
print(x.findNumbers([12, 345, 2, 6, 7896]))
| true |
6c0da654abdc01986b10d70f380f02b0f7800d29 | seekindark/helloworld | /python/py-study/testlist.py | 1,968 | 4.375 | 4 | #
# define a function to print the items of the list
#
def showlist(team):
i = 0
for item in team:
# end= "" will not generate '\n' automatically
print("list[%d]=%s" % (i, item), end=" ")
i += 1
print("\n-------------------")
team = ['alice', 'bob', 'tom']
print(team)
print("size = ", len(team))
print("team[0]=%s, [1]=%s, [2]=%s, || [-1]=%s, [-2]=%s, [-3]=%s" %
(team[0], team[1], team[2], team[-1], team[-2], team[-3]))
showlist(team)
# append
team.append(4) # there is no type limited in a list !!
team.append("last-one")
showlist(team)
# insert
team.insert(0, 'insert0')
team.insert(-1, 'insert-1')
showlist(team)
# pop
team.pop()
team.pop(0)
team.pop(1) # pop out the item of the given index
showlist(team)
# replace
team[2] = 'jack' #直接赋值替换
team[3] = 'last'
showlist(team)
# list as one element of another list
team[-1] = team
print(team) # ['alice', 'tom', 'jack', [...]]
showlist(team) # list[0]=alice list[1]=tom list[2]=jack list[3]=['alice', 'tom', 'jack', [...]]
team[-1] = [1, 2, 3, 4]
print(team)
showlist(team)
print("team[-1][-1] = ", team[-1][-1])
"""
this is comment
this is comment
"""
print("""-----------------""")
team1, team2 = [1, 2, 3, 4], ['a', 'b', 'c', 'd']
team = team1 + team2
team1x = team1*3
print('team1={0}'.format(team))
print('team1x={0}'.format(team1x))
print('team[2:-1]=', team[2:-1])
print("""---------xx--------""")
print(team)
print(team[0::2]) # 每隔两步截取一个列表
print(team[0:4:2]) # 每隔两步截取一个列表
print(team[-1::-1]) # 如果步长为负数,那么就反向截取
print(team[-1::-2]) # 如果步长为负数,那么就反向截取
print("""---------xx end--------""")
if __name__ == '__main__':
print("""---------xxx--------""")
team = [1 ,2, 3]*2
showlist(team)
print("""---------xxx end--------""")
| true |
8fb063a77d24fc0a4e30759ca867b24d4c448a56 | sabbirDIU-222/Learb-Python-with-Sabbu | /loopExercize.py | 1,483 | 4.46875 | 4 | # for loop exersize in the systamatic way
# so we first work with the list
party = ['drinks','chicken','apple','snow','ice','bodka','rma','chess board']
for p in party[:4]:
print(p)
print(len(p))
print(sorted(p))
for n in "banana":
print(n)
# break statement to break the loop in our specifed item
alist = ["sabbir","mamun","ibrahim","moti","sagor","ridwan","yasin","nemo"]
#With the break statement we can stop the loop before it has looped through all the items
for l in alist:
print(l)
if l=="moti":
break
# for loop in range
# alll that time we should not use list
# so we need to contain a range to stop our loop
for x in range(10):
print(x)
# it is printing to strat 0 to 9
# so it has no start limit>?
# yah it have a start and stop limit
print("range method thake three perametr ")
print("one take start value , second take range or finishing point , and last want increment")
print("")
for c in range(1,6): # the range function default value is 0
print(c)
# 1 to 5 printing
print("\n")
print("range function start with 0 so need to print extended level that you desire")
for d in range(5,10,1):
print(d)
# 5 to 9 print
# nested for loop
# suppose we have two different type of list
print("\n")
print("nested for loop")
point = ["*",'**']
for i in point:
for j in alist:
print(i,j)
i = 1
while i<6:
print(i)
i += 1
| true |
7d20e78c33f560812eac4f0f420b3035bdc6b322 | sabbirDIU-222/Learb-Python-with-Sabbu | /Unpacking Arguments.py | 928 | 4.21875 | 4 | # so what is unpacking ugument
# i am surprised to know about the horriable things
# and that is , what i learn about the arbetery argument \
# or can i call it paking and unpaking
# so what i learn aboout variable argument \
'''
def _thisFunction(*args):
sum = 0
for n in range(0,len(args)):
sum = sum+args[n]
return sum
print(_thisFunction(10,20,30,40,50))
print(_thisFunction(1,2,3,4,5))
'''
# so this called packing to packing
# now the things
def helth_calculator(age,eatingapple,tosingCigr):
res = (100-age) + (eatingapple*3.25) - (tosingCigr * 2)
if res <= 100:
print("your condition is not good")
elif res>=100:
print("your health condition is goood")
print(res)
sabbuInfo = [23,2,14]
moonInfo = [22,10,0]
helth_calculator(*sabbuInfo) # that is called unpacking sequence
helth_calculator(*moonInfo)
| true |
e76737fb088ea69b73e34bf61037610d30e869d1 | ccccclw/molecool | /molecool/measure.py | 1,252 | 4.15625 | 4 | """
This module is for functions
"""
import numpy as np
def calculate_distance(rA, rB):
"""
Calculate the distance between two points.
Parameters
----------
rA, rB : np.ndarray
The coordinates of each point.
Return
------
distance : float
The distance between the two points
Examples
--------
>>> r1 = np.array([0.0,0.0,0.0])
>>> r2 = np.array([0.0,0.0,0.0])
>>> calculate_dist(r1, r2)
1.0
"""
if isinstance(rA, np.ndarray) is False or isinstance(rB, np.ndarray) is False:
raise TypeError("input should be numpy array")
d=(rA-rB)
distance=np.linalg.norm(d)
if distance == 0.0:
raise Exception("Two atoms are in the same point")
return distance
def calculate_angle(rA, rB, rC, degrees=False):
"""
Calculate the angle given three coordinates.
Parameter
---------
rA, rB, rC : np.ndarray
The coordinates of each point.
Return
______
angle : float
The angle given three coordinates
"""
AB = rB - rA
BC = rB - rC
theta=np.arccos(np.dot(AB, BC)/(np.linalg.norm(AB)*np.linalg.norm(BC)))
if degrees:
return np.degrees(theta)
else:
return theta
| true |
6433e495fd2d47ee50910d166821502eab388856 | mdk7554/Python-Exercises | /MaxKenworthy_A2P4.py | 2,537 | 4.25 | 4 | '''
Exercise: Create program that emulates a game of dice that incorporates betting and multiple turns. Include a functional
account balance that is updated with appropriate winnings/losses.
'''
import random
#function to generate a value from dice roll
def roll():
return int(random.randrange(1,7))
#function to get bet amount as input from user and update balance or exit game
def get_bet(bal):
while True:
bet = input("Current balance is ${}. Enter 'x' to exit or place your bet: ".format(bal))
if bet == 'x':
return 0,0
try: #try/except clause to catch invalid input from user
bet=int(bet)
if bet in range(0,bal+1):
new_bal=bal-int(bet)
return bet,new_bal
else:
print("Invalid amount. Try again.")
except ValueError:
print("Invalid amount. Try again.")
#function to control third roll option
def opt_roll(roll_sum,bal,bet):
while True:
opt=input("No luck. Do you want to double your bet for a third roll? Enter 1 for yes or 0 for no ")
try: #try/except to catch invalid input from user
opt=int(opt)
if opt==0:
return None
elif bal<bet:
print('Sorry you dont have enough for this bet.')
return None
elif opt==1:
return roll_sum + roll()
else:
print("Invalid entry. Try again.")
except ValueError:
print("Invalid entry. Try again.")
#initial balance
bal = 100
while bal>0: #begin game with while loop that ends when the users balance = 0
bet,bal = get_bet(bal) #get input bet from user
if bet==0 and bal==0: #exit game if user chooses
break
roll1= roll()+roll()
print('You rolled a {}'.format(roll1))
if roll1 == 7 or roll1==12:
print('You win!')
bal = bal+bet*3
elif roll1 != 7 and roll!=12:
roll2 = opt_roll(roll1,bal,bet) #third roll option
if roll2 == 7 or roll2 == 12:
print('You rolled a {}'.format(roll2))
print('You win!')
bal = bal+bet*4
elif roll2==None:
pass #pass and restart loop if user elects not to roll 3rd time
else:
print('You rolled a {}'.format(roll2))
print('Sorry, better luck next time.')
bal= bal-bet
else:
pass
print('Thanks for playing. Goodbye!')
| true |
11a0db557909161e59c03ab75726f02e4275be5a | gammaseeker/Learning-Python | /old_repo/6.0001 Joey/sanity_check2.py | 848 | 4.15625 | 4 | annual_salary = 120000
portion_saved = .1
total_cost = 1000000
monthly_salary = (annual_salary / 12.0)
portion_down_payment = 0.25 * total_cost
current_savings = 0
returns = (current_savings * 0.4) / 12
overall_savings = returns + (portion_saved * monthly_salary)
months = 0
# Want to exit the loop when there is enough savings for a down payment
while current_savings < portion_down_payment:
current_savings += current_savings * (0.4 / 12) # Monthly interest
current_savings += portion_saved # Monthly savings
months += 1
print("It will take {} months to save!".format(months))
current_Saving=0
rate=0.04/12
monthly_savings = monthly_salary*0.1
i=0
while (current_Saving <= portion_down_payment):
current_Saving = current_Saving+(monthly_savings)*rate + monthly_savings
i=i+1
print(i) | true |
c5f3dcab578ef708da59fc2be131ef86cf6660e1 | gammaseeker/Learning-Python | /old_repo/6.0001 Joey/sanity_check.py | 623 | 4.15625 | 4 | annual_salary = 120000
portion_saved = .1
total_cost = 1000000.0
monthly_salary = (annual_salary / 12.0)
portion_down_payment = 0.25 * total_cost
current_savings = 0
returns = (current_savings * 0.04) / 12
overall_savings = returns + (portion_saved * monthly_salary)
months = 0
# Want to exit the loop when there is enough savings for a down payment
while current_savings < portion_down_payment:
current_savings += current_savings * (0.04 / 12) # Monthly interest
current_savings += portion_saved # Monthly savings
months += 1
print("It will take {} months to save!".format(months)) | true |
e0a5c95ec996fd314a829b8f41043a0f3aaa9d4c | JanDimarucut/cp1404practicals | /prac_06/car_simulator.py | 1,397 | 4.125 | 4 | from prac_06.car import Car
MENU = "Menu:\nd) drive\nr) refuel\nq) quit"
def main():
print("Let's drive!")
name = input("Enter your car name: ")
my_car = Car(name, 100)
print(my_car)
print(MENU)
menu_choice = input(">>>").lower()
while menu_choice != "q":
if menu_choice == "d":
distance_to_driven = int(input("How many km do you wish to drive? "))
while distance_to_driven < 0:
print("Distance must be >= 0")
distance_to_driven = int(input("How many km do you wish to drive? "))
distance_driven = my_car.drive(distance_to_driven)
print("The car drove {}".format(distance_driven))
if my_car.fuel == 0:
print("and ran out of fuel")
elif menu_choice == "r":
print(my_car)
add_fuel = int(input("How many units of fuel do you wan to add to the car? "))
while add_fuel <= 0:
print("Fuel amount must be > 0")
add_fuel = int(input("How many units of fuel do you wan to add to the car? "))
my_car.add_fuel(add_fuel)
print("Added {} units of fuel".format(add_fuel))
else:
print("Invalid choice")
print(my_car)
print(MENU)
menu_choice = input(">>>")
print("Good bye {}'s driver".format(name))
main()
| true |
210105f313227d23381e8ce2e0511df1ffec2637 | JanDimarucut/cp1404practicals | /prac_04/list_exercises.py | 2,647 | 4.40625 | 4 | # 1
numbers = []
for i in range(5):
number = int(input("Number: "))
numbers.append(number)
# print("The first number is: ", numbers[0])
# print("The last number is: ", numbers[-1])
# print("The smallest number is: ", min(numbers))
# print("The largest number is: ", max(numbers))
# print("The average of the numbers is: ", sum(numbers) / len(numbers))
# 2
user_names = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn', 'Command', 'ExerState', 'InteractiveConsole', 'InterpreterInterface',
'StartServer', 'bob']
user_input = input("Please enter your username")
if user_input in usernames:
print("Access granted")
else:
print("Access denied")
# 3
names = ["Bob", "Angel", "Jimi", "Alan", "Ada"]
full_names = ["Bob Martin", "Angel Harlem", "Jimi Hendrix", "Alan Turing",
"Ada Lovelace"]
# for loop that creates a new list containing the first letter of each name
first_initials = []
for name in names:
first_initials.append(name[0])
print(first_initials)
# list comprehension that does the same thing as the loop above
first_initials = [name[0] for name in names]
print(first_initials)
# list comprehension that creates a list containing the initials
# splits each name and adds the first letters of each part to a string
full_initials = [name.split()[0][0] + name.split()[1][0] for name in
full_names]
print(full_initials)
# one more example, using filtering to select only the names that start with A
a_names = [name for name in names if name.startswith('A')]
print(a_names)
# use a list comprehension to create a list of all of the full_names
# Names printed in all capital letters
capital_names = []
all_full_names = [name.upper() for name in full_names]
capital_names.append(all_full_names)
print(capital_names)
# in lowercase format
lowercase_full_names = [name.lower() for name in full_names]
print(lowercase_full_names)
almost_numbers = ['0', '10', '21', '3', '-7', '88', '9']
# use a list comprehension to create a list of integers
# Numbers sorted from smallest to biggest
sorted_int = []
almost_numbers.sort()
sorted_int += almost_numbers
print(sorted_int)
# from the above list of strings
numbers = [int(almost_number) for almost_number in almost_numbers]
print(numbers)
# use a list comprehension to create a list of only the numbers that are
over_nine = []
bigger_number = [number for number in numbers if number > 9]
over_nine.append(bigger_number)
print(over_nine)
# greater than 9 from the numbers (not strings) you just created
big_numbers = [number for number in numbers if number > 9]
print(big_numbers)
| true |
a00f702483bab4e505f2c2cb7b7bc790d01beeeb | Zach-Wibbenmeyer/cs108 | /lab05/spirograph.py | 2,909 | 4.125 | 4 | '''Using Python to draw a spirograph
March 5, 2015
Lab05 Exercise 2
Zach Wibbenmeyer (zdw3)'''
#Gains access to the turtle module
import turtle
#Gains access to the math module
import math
#Prompts the user to enter a choice if they would like to draw or not
choice = str(input('Would you like to draw a spirograph? (Y/n): '))
#Forever while loop
while True:
#If statement checking if choice is no
if choice == 'n' or choice == 'N':
print('Okay! Maybe some other time')
break
#Else if statement checking if choice is yes
elif choice == 'Y' or choice == 'y':
#Create a variable named window and make it the turtle screen
window = turtle.Screen()
#Create a turtle and name it zach
zach = turtle.Turtle()
#Prompts the user to enter the moving radius
mov_rad = float(input('Please enter a moving radius: '))
#Prompts the user to enter the fixed radius
fix_rad = float(input('Please enter a fixed radius: '))
#Prompts the user to enter the pen offset
pen_offset = float(input('Please enter the pen offset: '))
#Prompts the user to enter the color
color = str(input('Please enter the color: '))
#Creates a variable of the current time and initializes it to 0
current_time = 0.0
#Finds the x value
x = (fix_rad * mov_rad) * math.cos(current_time) + pen_offset * math.cos((((fix_rad + mov_rad) * current_time))/mov_rad)
#Finds the y value
y = (fix_rad * mov_rad) * math.sin(current_time) + pen_offset * math.sin((((fix_rad + mov_rad) * current_time))/mov_rad)
#Tells zach to change the speed to 10
zach.speed(10)
#Tells zach to pick the pen up
zach.penup()
#Tells zach to go to the x and y points
zach.goto(x,y)
#Tells zach to put the pen down
zach.pendown()
#Tells zach to change the pen color to what the user enters
zach.pencolor(color)
#While loop checking if current_time is less than 100
while current_time < 100:
#Redefines the x variable
x = (fix_rad * mov_rad) * math.cos(current_time) + pen_offset * math.cos((((fix_rad + mov_rad) * current_time))/mov_rad)
#Redefines the y variable
y = (fix_rad * mov_rad) * math.sin(current_time) + pen_offset * math.sin((((fix_rad + mov_rad) * current_time))/mov_rad)
#Tells zach to go to the new x and y points
zach.goto(x,y)
#Increments the current time
current_time += .1
#Tell the turtle window to remain open until clicked on
window.exitonclick()
#Else if statement checking if choice is something other than yes
elif choice != 'y' or choice != 'Y':
choice = str(input('Would you like to draw a spirograph? (Y/n): ')) | true |
703a6f099c981601b87743d254d6b6661626fa6f | mronowska/python_code_me | /zadania_domowe/zadDom3.py | 945 | 4.28125 | 4 | men_name = input("Male name: ")
feature_positive = input("Positive feature of this man: ")
feature_negative = input("Negative feature of this man: ")
day_of_the_week = input("Day of the week: ")
place = input("Place: ")
animal = input("Animal: ")
print(
f"There was a man called {men_name}. In one hand he was {feature_positive}, but on the other hand also a little {feature_negative}.\nOne day, I think it was {day_of_the_week}, {feature_negative} lost him. When he was walking on the {place}, he met {animal}, which ate people for being {feature_negative}. That's how he died.")
print("\n\n")
print(
f"There was a man called {men_name}. In one hand he was {feature_positive}, but on the other hand also a little {feature_negative}.\nOne day, I think it was {day_of_the_week}, {feature_negative} lost him. When he was walking on the {place}, he met {animal}, which ate people for being {feature_negative}. That's how he died."[::-1]) | true |
8df97a9d1609a30896b0a3342a44b11cc7fcce90 | Mannuel25/py-projects | /all-python-codes/e-mail-scrapper/email.py | 502 | 4.25 | 4 | # file input for users
fname = input('Enter file name: ')
# if the enter key is pressed 'emailfile.txt' is the file automatically
if (len(fname) < 1): fname = 'emailfile.txt'
#file handle
fh = open(fname)
# a loop that prints out the email
for line in fh:
# parsing through
if not line.startswith('From '): continue
pieces = line.split()
email = pieces[1]
info1 = email.find('@')
info2 = email.find(' ', info1)
org = email[info1 + 1:info2]
print (org)
| true |
f1e0b7caafb0e93735eeb2b8fda8ba152076607d | Mannuel25/py-projects | /all-python-codes/password-generator/password-generator-2/generate_password.py | 1,523 | 4.34375 | 4 | import secrets, string
def password_generator():
"""
A program that generates a secure random password
: return: None
"""
try:
# get the length of alphabets to be present in password
length_of_alphabets = int(input('\nEnter the length of alphabets (upper and lower case inclusive): '))
# get the length of digits to be present in password
length_of_digits = int(input('Enter the length of digits: '))
# get the length of special characters to be present in password
length_of_special_characters = int(input('Enter the length of special characters: '))
except ValueError:
print('Invalid Input!')
else:
# get the total password length
passwordLength = length_of_alphabets + length_of_digits + length_of_special_characters
# generate a password for user based on the total password length
securePassword = ''.join(secrets.choice(string.ascii_letters) for i in range(length_of_alphabets))
securePassword += ''.join(secrets.choice(string.digits) for i in range(length_of_digits))
securePassword += ''.join(secrets.choice(string.punctuation) for i in range(length_of_special_characters))
# make a list with the password
generated_password = list(securePassword)
# shuffle generated password
secrets.SystemRandom().shuffle(generated_password)
print('Your password of length {} is {}'.format(passwordLength,''.join(generated_password)))
password_generator() | true |
8abed6121ee7847b3d076fa7c555db089ec3f483 | wajdm/ICS3UR-5-05-Python | /addressing_mails.py | 1,866 | 4.46875 | 4 | # !/usr/bin/env python3
# Created by: Wajd Mariam
# Created on: December 2019
# This program formats the mailing address using given input.
def format_address(first_name, last_name, street_add, city,
province, postal_code, apt_number=None):
# returns formatted mailing address
if apt_number is not None:
address = first_name + " " + last_name + "\n" + apt_number + "-" \
"" + street_add + "\n" + city + " " + province + " " + postal_code
else:
address = first_name + " " + last_name + "\n" + street_add + "\n" + \
city + " " + province + " " + postal_code
return address
def main():
# this function gets user input and fromats it into mailing address.
# welcome statement.
print("")
print("This program formats your mailing address using given input")
print("Make sure all of your input is in upper case!")
print("")
apt_number = None
# getting input from user
first_name = input("Enter the first name: ")
last_name = input("Enter the last name: ")
question = input("Does your receiver have an apartment number? (y/n): ")
if question.upper() == "Y" or question.upper() == "YES":
apt_number = input("Enter the apartment number: ")
street_add = input("Enter the street address: ")
city = input("Enter the city: ")
province = input("Enter the province: ")
postal_code = input("Enter the postal code: ")
# process
if apt_number is not None:
address = format_address(first_name, last_name, street_add, city,
province, postal_code, apt_number)
else:
address = format_address(first_name, last_name, street_add,
city, province, postal_code)
# output
print("")
print(address)
if __name__ == "__main__":
main()
| true |
ac566079a1f0b1c8b05a921253df65872f4d2201 | tryingtokeepup/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,387 | 4.34375 | 4 | # TO-DO: Complete the selection_sort() function below
def swapping_helper(index_a, index_b, arr):
# cool_dude = array
temp = arr[index_a]
arr[index_a] = arr[index_b]
arr[index_b] = temp
return arr
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
if cur_index != smallest_index:
arr = swapping_helper(smallest_index, cur_index, arr)
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# call my swap function
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# well, aggghhhhhh. i suck at variable names, so here. let's just assume that at the beginning, we are still wanting to swap.
swap_actually_happened = True
while swap_actually_happened:
swap_actually_happened = False
for i in range(0, len(arr) - 1): # remember to minus 1 so we don't go out of bounds
if arr[i] > arr[i+1]:
arr = swapping_helper(i, i+1, arr)
swap_actually_happened = True
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true |
9a718e4a71ef9f2a19f9decc472d6fba57a5cb51 | czwartaoslpoj/book-review-project | /templates/house_hunting.py | 736 | 4.1875 | 4 | //calculating how many months I need to save the money fo portion_down_payment
total_cost = int(input("The cost of your dream house: "))
portion_down_payment = total_cost/4
current_savings = 0
annual_salary= int(input("Your annual salary: "))
portion_saved = float(input("Portion of your salary to save as a decimal: "))
monthly_salary = annual_salary/12
percent_of_monthly_salary_to_save = monthly_salary * portion_saved
months=0
while current_savings < portion_down_payment:
investment_savings = (current_savings * 0.04) / 12
current_savings= current_savings+ percent_of_monthly_salary_to_save+ investment_savings
months +=1
if current_savings >= portion_down_payment:
print(months)
| true |
e1a42bb8d1b00666fe1a9d2022d116fc879630eb | markellisdev/bangazon-orientationExercises1-6 | /bangazon.py | 2,605 | 4.15625 | 4 | class Department(object):
"""Parent class for all departments
Methods: __init__, get_name, get_supervisor
"""
def __init__(self, name, supervisor, employee_count):
self.name = name
self.supervisor = supervisor
self.size = employee_count
def get_name(self):
"""Returns the name of the department"""
return self.name
def get_supervisor(self):
"""Returns the name of the supervisor"""
return self.supervisor
class HumanResources(Department):
"""Class representing Human Resources department
Methods: __init__, add_policy, get_policy, etc.
"""
def __init__(self, name, supervisor, employee_count):
super().__init__(name, supervisor, employee_count)
self.policies = set()
def add_policy(self, policy_name, policy_text):
"""Adds a policy, as a tuple, to the set of policies
Arguments:
policy_name (string)
policy_text (string)
"""
self.policies.add((policy_name, policy_text))
def get_policy(self):
return self.policies
class InformationTechnology(Department):
def __init__(self):
super().__init__(self, name, supervisor, employee_count)
self.languages = ()
def add_devLanguage(self, language_name):
"""Adds a language to the set of languages"""
class Marketing(Department):
"""Class representing Marketing department
Methods: __init__, add_materials, get_materials
"""
def __init__(self, name, supervisor, employee_count):
super().__init__(name, supervisor, employee_count)
self.materials = ()
def add_material(self, material_type):
self.materials.add(material_type)
marketing_department = Marketing("Marketing", "Jami Jackson", 3)
print("{0} is the head of the {1} Department, which has {2} employees".format(marketing_department.supervisor, marketing_department.name, marketing_department.size))
human_resources_dept = HumanResources("Human Resources", "Val Hovendon", 1)
human_resources_dept.add_policy("Code Of Conduct", "Covers employees, board members and volunteers")
human_resources_dept.add_policy("Hours Of Work", "Describes the number of hours full time employees are required to work")
print(human_resources_dept.policies)
CodeOfConduct_policy = {x: y for x, y in human_resources_dept.policies if "Code Of Conduct" in x}
print(type(CodeOfConduct_policy))
for k, v in CodeOfConduct_policy.items():
print("Please see {0}, to view our {1} policy which has the following desription: {2}".format(human_resources_dept.name, k, v))
| true |
24f6feeda30f66fddf433d9d4c0cd388b6509763 | MrDeshaies/NOT-projecteuler.net | /euler_042.py | 1,597 | 4.125 | 4 | # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
# so the first ten triangle numbers are:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# By converting each letter in a word to a number corresponding to its alphabetical position and
# adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10.
# If the word value is a triangle number then we shall call the word a triangle word.
#
# Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand
# common English words, how many are triangle words?
import re
def load_words(filename):
f = open(filename, "r")
data = f.readline()
f.close()
# file looks like "BOB","MARY","JANE"
# split will keep an empty token at the front and end. Get rid of them
words = re.split(r'\W+',data)
words = words[1:len(words)-1]
return words
def compute_score(word):
A = ord("A")
return sum(ord(x.upper()) - A + 1 for x in word)
def generate_triangle(upper_limit):
triangle_numbers = []
i = 1
while True:
n = int((i * (i+1)) / 2)
triangle_numbers.append(n)
i += 1
if n > upper_limit:
break
return triangle_numbers
# compute the score for each word
words = load_words("p042_words.txt")
word_scores = [compute_score(x) for x in words]
# find the relevant triangle numbers
triangle_numbers = generate_triangle(max(word_scores))
# count how many words have a triangle score...
print(len([x for x in word_scores if x in triangle_numbers])) | true |
542759df80baa3bdc951931364e72aea52226305 | amitkumar-panchal/ChQuestiions | /python/q01/Contiguous.py | 1,558 | 4.28125 | 4 | """
Fiels: _items is a list of items
_size is number of items that can be stored
"""
## Contiguous(S) produces contiguous memory of size s
## and initializes all entries to None.
## Requires: s is positive
class Contiguous:
def __init__(self, s):
self._items = []
self._size = s;
for index in range(self._size):
self._items.append(None)
## repr(self) produces a strinng with the sequence of values.
## __repr__: contiguous -> Str
def __repr__(self):
to_return = "("
for index in range(self._size - 1):
if self.access(index) == None:
to_print = "None"
else:
to_print = self.access(index)
to_return = to_return + str(to_print) + ","
if self.access(self._size - 1) == None:
to_print = "None"
else:
to_print = self.access(self._size - 1)
return to_return + str(to_print) + ")"
## self == other produces the size of self
## size. Contiguous -> Int
def size(self):
return self._size
def __eq__(self, other):
if(self.size() != other.size()):
return False
else:
for pos in range(self.size()):
if self.access(pos) != other.access(pos):
return False
else:
return True
def access(self, index):
return self._items[index]
def store(self, index, value):
self._items[index] = value | true |
164e6ece6af8f27d2f6154414be81e602fc2c53b | Anushadsilva/python_practice | /List/list.pg5.py | 489 | 4.21875 | 4 | '''Write a Python program to extract specified size of strings from a give list of string values. Go to the editor
Original list:
['Python', 'list', 'exercises', 'practice', 'solution']
length of the string to extract:
8 '''
#Solution:
if __name__ == '__main__':
list1 = ['Python', 'list', 'exercises', 'practice', 'solution']
list2 = []
usr = input("choose the length of string 6 or 4 or 9 or 8")
for ch in list1:
if len(ch) == int(usr):
list2.append(ch)
print(list2) | true |
d68786a9942542808767b47b11919d0f7f7eaa6a | Anushadsilva/python_practice | /Functions/func_pg3.py | 305 | 4.28125 | 4 | #Write a Python function to find the Max of three numbers
def mx(x,y,z):
return max(x,y,z)
if __name__ == '__main__':
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
c =int(input("Enter the third number"))
print("max of the given numbers is: ", mx(a,b,c))
| true |
579d6046604626afd901e8885bcce6de1a8fb09c | SinghReena/TeachPython3 | /SayNamesMultipleTimes.py | 591 | 4.21875 | 4 | # SayNamesMultipleTimes.py - lets everybody print their name on the screen
# Ask the user for their name
name = input("Can I know your name please: ")
# Keep printing names until we want to quit
while name != "":
# Print their name 35 times
for x in range(35):
# Print their name followed by a space, not a new line
print(name, end = " ")
print() # After the for loop, skip down to the next line
# Ask for another name, or quit
name = input("Type another name, or just hit [ENTER] to quit: ")
print("Thanks for printing names 35 times!")
| true |
ac96cf0e2ab8e77a576743b00c938e0d259aa089 | TanmoyX/CodeStore-Cracking_The_Coding_Interview | /Chap2/2.1 - RemoveDuplicates/n2-sol.py | 936 | 4.125 | 4 | class Node:
def __init__(self, val):
self.data = val
self.next = None
def printLL(node):
while node != None:
print(node.data)
node = node.next
def insertNode(node, val):
if node == None:
return None
while node.next != None:
node = node.next
node.next = Node(val)
node.next.next = None
def removeDuplicates(node):
#This method has a time complexity of O(N^2) and space complexity of O(1) without using any temporary buffer
head = node
while node != None:
runner = node
while (runner.next != None):
if runner.next.data == node.data:
runner.next = runner.next.next
else:
runner = runner.next
node = node.next
return head
n = Node(4)
insertNode(n, 8)
insertNode(n, 1)
insertNode(n, 1)
insertNode(n, 5)
insertNode(n, 9)
printLL(n)
print()
printLL(removeDuplicates(n))
| true |
7f8be46a01d986de37906424a7c6e7e186ca30c3 | Shivani3012/PythonPrograms | /conditional ass/ques33.py | 484 | 4.375 | 4 | #Write a Python program to convert month name to a number of days.
print("Enter the list of the month names:")
lname=[]
for i in range(0,12):
b=input()
lname.append(b)
#print(lname)
m=input("Enter the month name:")
ind=lname.index(m)
#print(ind)
if ind==0 or ind==2 or ind==4 or ind==6 or ind==7 or ind==9 or ind==11:
print("number of days in "+ m +" is 31")
elif ind==1:
print("number of days in febraury is 28/29")
else:
print("number of days "+m+" is 30")
| true |
21d89fe0a3fbf5d59124847acd307845da9205ce | Shivani3012/PythonPrograms | /guessing a number.py | 876 | 4.15625 | 4 | print(" Welcome to the Guessing a Number Game ")
print("You have to guess a number if the number matches the random number")
print("you win the game else you will only get three chances")
name=input("Enter the user name")
import random
for i in range (1,4):
print("Chance",i)
r=random.randint(10,50)
h=int(input("Guess the number between the range 10 to 50:"))
if r>h:
print("Guessed number is",r)
print("The number you guessed is smaller then the number we guess.")
print("So sorry, you are losser .")
elif r<h:
print("The guessed number is",r)
print("The number you guessed is higher then the number we guess.")
print("So sorry, you are losser .")
else:
print("Guessed number is",r)
print("The number you guessed is equal to the number we guess.")
print("You win")
| true |
53ca55ed41ad6b133f43f1951a52320980eed50d | Shivani3012/PythonPrograms | /conditional ass/ques6.py | 419 | 4.15625 | 4 | #Write a Python program to count the number of even and odd numbers from a series of numbers.
a=int(input("Enter the number of elements in the list"))
print("Enter the list")
l=[]
countev=0
countodd=0
for i in range(a):
b=int(input())
l.append(b)
for i in range(a):
if l[i]%2==0:
countev+=1
else:
countodd+=1
print("No. of even elements:",countev)
print("No. of odd elements:",countodd)
| true |
52a686724c000189abcae44a27fc2e0eda9f4b70 | Shivani3012/PythonPrograms | /conditional ass/ques35.py | 212 | 4.40625 | 4 | #Write a Python program to check a string represent an integer or not.
s=input("Enter the string")
a=s.isdigit()
#print(a)
if a==True:
print("This is an integer.")
else:
print("This is not an integer.")
| true |
4112f792af4b4e1cd696891ebaa81dcd6868a4c1 | KaanSerin/python_side_projects | /rock_paper_scissors_game.py | 2,879 | 4.28125 | 4 |
import random
def welcomeMessage():
print("Welcome to my very basic rock, paper, scissors game!")
print('You can play as long as you want.')
print('Whenever you want to quit, just enter -1 and the game will end immediately.')
#Implementing the rules of rock paper scissors with if-else blocks
def decider(player_action, ai_action):
#Rock beats scissors
if player_action == '1' and ai_action == '3':
#player_score = player_score + 1
return True
elif ai_action == '1' and player_action == '3':
#ai_score = ai_score + 1
return False
#Paper beats Rock
elif player_action == '2' and ai_action == '1':
#player_score = player_score + 1
return True
elif ai_action == '2' and player_action == '1':
#ai_score = ai_score + 1
return False
#scissors beats paper
elif player_action == '3' and ai_action == '2':
#player_score = player_score + 1
return True
elif ai_action == '3' and player_action == '2':
#ai_score = ai_score + 1
return False
#Display the welcome messages
welcomeMessage()
#Possible actions
actions = {'1': 'Rock', '2': 'Paper', '3': 'Scissors'}
player_action = input('Enter a number | Rock(1), Paper(2), or Scissors(3): ')
#Scores of player an AI
player_score = 0
ai_score = 0
#Action of AI will be defined in the while loop
ai_action = None
#Game will continue until the user enters '-1' as their choice.
while player_action != '-1':
ai_action = str(random.randint(1, 3))
#Actions performed when the player wins
if decider(player_action, ai_action) == True:
player_score += 1
print('You won!')
print('Your move:', actions[player_action], "| AI's move:", actions[ai_action])
#Actions performed when the AI wins
elif decider(player_action, ai_action) == False:
ai_score += 1
print('AI won :(')
print('Your move:', actions[player_action], "AI's move:", actions[ai_action])
#Actions performed when it's a tie
else:
print("It's a tie!")
print('Your move:', actions[player_action], "AI's move:", actions[ai_action])
print("Your score:", player_score, "\nAI's score:", ai_score, "\n")
player_action = input('Enter a number | Rock(1), Paper(2), or Scissors(3): ')
#Ending the game
print("Game stopped.")
print("Your final score:", player_score, "\nAI's final score:", ai_score)
#End game messages
if player_score > ai_score:
print("You won the game! Thanks for playing! I hope you had a fun time.")
elif player_score == ai_score:
print("You tied! Feel free to try your luck later.")
else:
print("Thanks for playing! I hope you had a fun time... Even though you lost(hehehe)")
| true |
d43a964b2eddddbfd01ad71ee356b7711f7945fd | s-ajensen/2017-18-Semester | /knockKnock/blackbelt.py | 1,857 | 4.21875 | 4 | # Samuel Jensen, Knock Knock Joke Blackbelt, 9/28/2017
# Checks user input, gets frustrated when user doesn't go with the joke, unnecessary recursion
# Get user's name
name = input("Hi what's your name?")
# Ask user if they want to hear a joke
hearJoke = input("Nice to meet you " + name + ", would you like to hear a knock knock joke?")
# Define asking function
def askJoke(response):
# If user says 'yes' continue joke
if response == "yes":
whoThere = input("Knock knock")
# Convert whoThere to lowercase in case user capitalized
whoThere = whoThere.lower()
# If user continues the joke, continue
if whoThere == "who's there" or whoThere == "who is there":
inquisition = input("The Spanish inquisition")
# Convert inquisition to lowercase in case user capitalized
inquisition = inquisition.lower()
# Check if user input continues the joke
if inquisition == "the spanish inquisition who" or inquisition == "the spanish inquisition who?":
print("No one expects the Spanish Inquisition!")
# If not, ragequit
else:
print("I don't think you really understand how these jokes work")
# Otherwise start again
else:
misunderstandJoke = input("Do you know how a knock knock joke works?")
askJoke(misunderstandJoke)
# If not, commend them, and quit
elif response == "no":
print("Good, anyone with any sense of humor wouldn't want to hear a knock knock joke")
return "no"
# If neither, chastise them for not being straightforward
else:
misunderstandYesNo = input("Please answer yes or no. Would you like to hear a knock knock joke?")
askJoke(misunderstandYesNo)
# Call function using user input
askJoke(hearJoke)
| true |
f7b353f903f773892c834561b89e06b732cb61ca | x223/cs11-student-work-ibrahim-kamagate | /april11guidedpractice.py | 861 | 4.25 | 4 | # what does this function return ? This prints the x*2 which is 7*2
def print_only(x):
y = x * 2
print y
# how is this one different ? This does the same thing as the print function but you dont see it
def return_only(x):
y = x * 2
return y
# let's try to use our 2 functions
print "running print_only ..."# This prints whatever is in the quotes and it does the equation that is given an gives you the sum
print_only(7)
print "running return_only ..."# It does the samething as the one on line 12 but it doesn't print the sum
return_only(7)
print "printing print_only ..."# adding print mkes it also print none
print print_only(7)
print "printing return_only ..."#it only print whats n the quotes
return_only(7)
print "using print_only ..."#you can't add those two numbers
print_only(7) + 6
print "using return_only ..."
return_only(7) + 6
| true |
90e995d7a410da9d546f1c3a2f687c9e12c74995 | prasanth-vinnakota/python-gvp | /generator-fibonacci.py | 358 | 4.125 | 4 | def fibonacci(n):
a = 0
b = 1
for i in range(n):
yield a
a, b = b, a + b
size = None
try:
size = int(input("Enter size of fibonacci series: "))
if size == 0:
raise ValueError
except ValueError:
print("input must be a number and greater than 0")
exit(0)
for j in fibonacci(size):
print(j, end=" ")
| true |
2cfe7c91405ec313dfed83e864bf6e18f5d8e276 | jing1988a/python_fb | /900plus/FractionAdditionandSubtraction592.py | 2,718 | 4.1875 | 4 | # Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.
#
# Example 1:
# Input:"-1/2+1/2"
# Output: "0/1"
# Example 2:
# Input:"-1/2+1/2+1/3"
# Output: "1/3"
# Example 3:
# Input:"1/3-1/2"
# Output: "-1/6"
# Example 4:
# Input:"5/3+1/3"
# Output: "2/1"
# Note:
# The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
# Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
# The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
# The number of given fractions will be in the range [1,10].
# The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
class Solution:
def fractionAddition(self, expression):
"""
:type expression: str
:rtype: str
"""
eFormat=self.myFormat(expression)
l=len(eFormat)
if l ==0:
return 0
a, b = eFormat[0].split('/')
a = int(a)
b = int(b)
i=1
while i<l:
op=eFormat[i]
c , d=eFormat[i+1].split('/')
c=int(c)
d=int(d)
newA=0
if op=='+':
newA=a*d+c*b
else :
newA=a*d-c*b
newB=b*d
temp = self.maxDivide(a, b)
a=newA//temp
b=newB//temp
i+=2
temp=self.maxDivide(a , b)
a//=temp
b//=temp
return str(a)+'/'+str(b)
def myFormat(self , expression):
ans=[]
cur=[]
for e in expression:
if e in ['-' , '+']:
if cur:
ans.append(''.join(cur))
cur=[]
ans.append(e)
else:
cur.append(e)
else:
cur.append(e)
if cur:
ans.append(''.join(cur))
return ans
def maxDivide(self , a , b ):
if a>b:
a , b = b , a
i=b
while i>1:
if a%i==0 and b%i==0:
return i
i-=1
return 1
test=Solution()
print(test.fractionAddition("-1/2+1/2"))
| true |
1e4e214385a54a8e225977e90172fe154dd2300a | jing1988a/python_fb | /lintcode_lyft/ReverseInteger413.py | 558 | 4.125 | 4 | # Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
#
# Example
# Given x = 123, return 321
#
# Given x = -123, return -321
class Solution:
"""
@param n: the integer to be reversed
@return: the reversed integer
"""
def reverseInteger(self, n):
# write your code here
flag=1
if n<0:
flag=-1
n=-n
# return int(str(n)[::-1])*flag
ans=0
while n:
ans=ans*10+n%10
n//=10
return ans*flag | true |
f8aef6ac6c5f8838b8fed96f3f36437c6560a423 | Almr1209/idk | /ex32.py | 1,001 | 4.59375 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a loop
for number in the_count:
print(f"This is count {number}")
# same as above, basically it's using the same format but different varaibles
for fruit in fruits:
print(f"A fruit of type: {fruit}s")
# also we can go through mixed lisits too
# notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print(f"Element was: {i}")
# I don't know how to explain this, so sorry.
# New for me; therefore I cannot explain much besides what the book says | true |
e5db03cd5cde605a6fda0837ae334bfb247d231f | sarahoeri/Giraffe | /window.py | 1,229 | 4.15625 | 4 | # Tuples...don't change like in lists
even_numbers = (2, 4, 6, 8, 10, 12)
print(even_numbers[5])
# Functions
def sayhi(name, age) :
print("Hello " + name + " you are " + age)
sayhi("Nancy", "25")
sayhi("Christine", "27")
# Return Statement
def square(num) :
return num*num
print(square(8))
def cube(num) :
return num*num*num # return breaks out of the function
result = cube(8) # variable
print(result)
# If Statements
is_single = True
if is_single:
print("Head on to Tinder app")
else:
print("Meet your partner")
is_male = False
is_tall = True
if is_male and is_tall: # or tall
print("You are either male or tall or both")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
print("You are not a male but are tall")
else:
print("You are neither male or tall")
# Count number of even and odd numbers from a series of numbers
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
count_even = 0
count_odd = 0
for x in numbers:
if x % 2 :
count_even += 1
else:
count_odd += 1
print("Number of even numbers is: " + str(count_even))
print("Number of odd numbers is: " + str(count_odd))
| true |
9391c201f98ce42de5efc3c74cf6a32887901013 | hyperskill/hs-test | /src/test/java/projects/python/coffee_machine/stage3/machine/coffee_machine.py | 1,127 | 4.25 | 4 | # Write your code here
water_amount = int(input('Write how many ml of water the coffee machine has:'))
milk_amount = int(input('Write how many ml of milk the coffee machine has:'))
coffee_amount = int(input('Write how many grams of coffee beans the coffee machine has:'))
N = int(water_amount / 200)
if N > milk_amount / 50:
N = int(milk_amount / 50)
if N > coffee_amount / 15:
N = int(coffee_amount / 15)
number_cups = int(input("Write how many cups of coffee you will need: "))
if number_cups == N:
print("Yes, I can make that amount of coffee")
elif N > number_cups:
print("Yes, I can make that amount of coffee (and even ", N-1," more than that)")
else:
print("No, I can make only ", N," cups of coffee")
#print("""Starting to make a coffee
#Grinding coffee beans
#Boiling water
#Mixing boiled water with crushed coffee beans
#Pouring coffee into the cup
#Pouring some milk into the cup
#Coffee is ready!""")
#
#
#print("For ", number_cups, " cups of coffee you will need:")
#print(200 * number_cups, " ml of water")
#print(50 * number_cups, " ml of milk")
#print(15 * number_cups, " g of coffee beans") | true |
8cd722978b4902fd1f5e803d37358ac481741a54 | mybatete/Python | /seqBinSearch.py | 1,873 | 4.25 | 4 | """
Program: seqBinSearch.py
Author : Charles Addo-Quaye
E-mail : caaddoquaye@lcsc.edu
Date : 01/31/2018
Description:
This program implements demo for both
sequential and binary search algorithms.
The program generates a random list of integers
and provides a menu for searching for numbers
in the list.
Input variables: List
Output variables: match, found
"""
import random
def main():
NUM=100
List = []
for num in xrange(NUM):
value = random.randint(0,50000)
List.append(value)
size = len(List)
print List
List.sort()
#print List
print "\n\nListed Database contains %d Records\n\n" % len(List)
#Create a List to store the returned Found item:
match = []
done = False
while not done:
response = raw_input("Exit Records Database? 'Y/N': ")
if response.upper() == "Y":
done = True
else:
query = input("Enter a Number: ")
found = seqSearch(List,size,query,match)
#found = binarySearch(List,size,query,match)
if found:
print "Query Number (%d) Found: %d at Position: %d\n" % (query, match[0],match[1])
else:
print "\n\n***No Record of the Number %s in Database***\n\n" % query
def binarySearch(List,size,query,match):
i = 0
first = 0
last = size - 1
found = False
while first <= last :
mid = (last + first)/2
print "Search iteration: %d\tMid-point: %d" % (i,mid)
i = i + 1
if query > List[mid]:
first = mid + 1
elif query < List[mid]:
last = mid - 1
else:
break
#first = last + 1
#last = first - 1
if query == List[mid]:
found = True
match.insert(0,List[mid])
match.insert(1,mid)
return found
def seqSearch(List,size,query,match):
i = 0
found = False
while i < size and query != List[i]:
print "Search iteration: %d" % (i)
i = i + 1
if i < size and query == List[i]:
found = True
match.insert(0,List[i])
match.insert(1,i)
return found
main()
| true |
dff114f7caa3b803d85a634807ae4e38aa70a4e0 | krissmile31/documents | /Term 1/SE/PycharmProjects/pythonProject/Tut2/Most Frequent Character.py | 263 | 4.28125 | 4 | from collections import Counter
#ask user input a string
stringCount = input("Enter a string: ")
#count char appearing most in that string
count = Counter(stringCount).most_common(1)
print("Character that appears most frequently in the string: " )
print(count) | true |
8dfcd3b7339f271409fa64ae63b4357c8692e990 | adinimbarte/codewayy_python_series | /Python_Task6/Q.4/Q.4.py | 283 | 4.15625 | 4 | # taking string input
string = input("Enter the string from which you want to count number of 'at': ")
# counting occurence of "at" and printing
count=string.count("at")+ string.count("At")+ string.count("At") + string.count("AT")
print("'at'occured %d times in string." % count )
| true |
c94fe10616b30c1291d5675772810fc0374fbc69 | KeithWilliamsGMIT/Emerging-Technologies-Python-Fundamentals | /03-fizzbuzz.py | 506 | 4.34375 | 4 | # Author: Keith Williams
# Date: 21/09/2017
# This script iterates between the numbers 1 and 100.
# For each iteration there is a condition for each of the following:
# 1) For numbers which are multiples of both three and five print "FizzBuzz".
# 2) For multiples of three print "Fizz".
# 3) For multiples of five print "Buzz".
# 4) Otherwise print the number.
for i in range(1, 101):
if i%3 == 0 and i%5 == 0:
print("FizzBuzz")
elif i%3 == 0:
print("Fizz")
elif i%5 == 0:
print("Buzz")
else:
print(i) | true |
a406961c86682d5d15c0b6eaa25a187a33a8ae59 | scoffers473/python | /uneven_letters.py | 564 | 4.28125 | 4 | #!/usr/bin/python3
"""
This takes an input word and prints out a count of uneven letters
for example in aabbc we have one uneven letter (c). In hello we have 3 (hme and o)
"""
import sys
from collections import Counter
def solution (S):
removal=0
counter = Counter(S)
for letters in S:
if counter[letters]%2 != 0:
removal += 1
return removal
def main (S):
ans = solution(S)
print(" For the word ",S, " we would have to remove ", ans," letters to make it even")
if __name__ == "__main__":
main(sys.argv[1])
| true |
680528fefc54b25668e4e7fdb1ebc2cfc752f1ff | scoffers473/python | /days_offset.py | 1,197 | 4.25 | 4 | #!/usr/bin/python3
"""
This take an input number and works out the offset day based on this number
Days are Mon:1
Tue:2
Wed:3
Thu:4
Fri:5
Sat:6
Sun:7
So if i passwd an offset of 7 this would be a Sunday, a 5 a Friday, a 13 a Saturday, etc
"""
import sys
def solution (D,S):
# define tuple array - use day as day-1 so that it works easily with the modulus
days = ([0,"Sun"],[1,'Mon'],[2,"Tue"],[3,"Wed"],[4,"Thu"],[5,"Fri"],[6,"Sat"])
# Work out which day equates to this
which_day = S % 7
newday=0
# Find the starting day Integer
# (If Sun, add 7)
# Then add the day offset and get the modulus
# in order to determine the final day
for day in days:
if day[1] == D:
starting_day = day[0]
if starting_day == 0:
starting_day = 7
which_day = (S+starting_day)%7
break
# Now we have the final day, work out the day name
for day in days:
if day[0] == which_day:
return day[1]
def main (D,S):
ans = solution(D,S)
print(ans)
if __name__ == "__main__":
main(sys.argv[1],int(sys.argv[2]))
| true |
0e55bc414b576a4a6962eaac939dd1709fcb04de | ksu-is/Congrats | /test_examples.py | 269 | 4.125 | 4 | # Python code to pick a random
# word from a text file
import random
# Open the file in read mode
with open("MyFile.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
# print random string
print(random.choice(words)) | true |
3b4d4944bfe4a170225e0d213f327c89d890905d | lttviet/py | /bitwise/count_bits.py | 337 | 4.15625 | 4 | def count_bits(x: int) -> int:
"""Returns the number of bits that are 1.
"""
num_bit: int = 0
while x:
# if odd, right most bit is 1
num_bit += x & 1
# shift to the right 1 bit
x >>= 1
return num_bit
if __name__ == '__main__':
for i in (1, 2, 11):
print(i, count_bits(i)) | true |
b81c76ba7cc637017c0432b6d9b0e527cd624fd3 | tvanrijsselt/file-renamer | /main.py | 1,058 | 4.15625 | 4 | """This main module calls the helper functions in the main-function, such that the right files in the right folder are changed."""
import os
from helperfunctions import ask_input_for_path, ask_input_base_filename, files_ending_with_chars
def main():
"""Main function to call the helper functions and
rename the files at the destination"""
path = ask_input_for_path()
base_filename = ask_input_base_filename()
file_end = files_ending_with_chars()
for count, filename in enumerate(os.listdir(path)):
if file_end is None or filename.endswith(file_end):
file_extension = filename.split('.')[-1]
full_name = f"{base_filename}_{count}.{file_extension}"
source = path + filename # Actual name of the file
destination = path + full_name # New name of the file
os.rename(source, destination) #rename function will rename the files
print("The filenames are changed. End of script")
if __name__ == '__main__':
main() # Calling main() function
| true |
caedf25abc2fcbb1677d8743b9f50e254447bdd9 | ahathe/some-a-small-project | /MyPython/test/StrBecome.py | 320 | 4.15625 | 4 | #!/usr/bin/env python
'make string become largest to smallest orade! '
num = list(raw_input("plaese input number!thank you!:"))
choice = raw_input("input you choice!,one or two:")
one = 'one'
two = 'two'
if choice == one:
num.sort()
print num
elif choice == two:
num.sort()
for x,i in enumerate(num):
print x,i
| true |
950c8785a6fe4cec2e491a1e1ca90a1651cae86d | ahathe/some-a-small-project | /MyPython/test/NumTest.py | 1,626 | 4.25 | 4 | #!/usr/bin/env python
'is input number to count mean and total'
empty = []
def Input():
while True:
num = raw_input("input you number to count mean!,input 'q' is going to quit!:")
if num == ('q' or 'Q'):
print 'rechoice input type,input or to count or remove or view!'
Choice()
else:
try:
number = float(num)
except ValueError:
print 'is not number,reinput!'
else:
if type(number) == type(1.2):
empty.append(number)
print empty
def Count():
length = len(empty)
total = sum(empty)
mean = float(total) / float(length)
print "is working!"
print 'the mean is %s' % mean
def Remove():
print 'what number you want to remove?!'
while True:
print 'make you choice ,input you want to remove that number! %s' % empty
remove = raw_input("input you want to remove float value!:")
if remove == ('q' or 'Q'):
Choice()
break
try:
move = float(remove)
except ValueError:
print 'invalid value ,plaese input int or float type!,thank you!'
else:
if move in empty:
empty.remove(move)
print 'is been removed %s' % move
print 'new number total is %s' % empty
break
else:
print "plaese input float type value!"
def View():
Count()
print 'the mean list is %s' % empty
def Choice():
while True:
choice = raw_input("input you choice,count or input or remove or view:").strip().lower()
string = ["input","count","remove","view"]
dict1 = {"input":Input,"count":Count,"remove":Remove,"view":View}
if choice not in string:
print "is invalid option,plaese choice input or count to make mean!"
else:
dict1[choice]()
Choice()
| true |
1298ec09dc5cf5bbbe9ad19dd9a691e60e384b2c | JaclynStanaway/PHYS19a | /tutorial/lesson00/numpy-histograms.py | 2,352 | 4.53125 | 5 | """
Author: Todd Zenger, Brandeis University
This program gives a first look at Numpy and
we plot our first plot.
"""
# First, we need to tell Python to bring in numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# np and plt are the standard shortcut names we give it
x = np.array([0,2,4,5])
# Some basic modifications
print(x)
print(x+5)
print(x**2)
# Now let's do some slicing to get specific elements
print("Without the first element")
print(x[1:])
print("Without the last two elements")
print(x[:4])
print(x[:-2]) # Negative index values means that we start going backwards
# There are also useful mathematical operations available to us
sinx = np.sin(x) # numpy uses radians
print("sin(x) is:")
print(sinx)
np.random.seed(900835)
# Now, let's turn our attention to plotting a histogram
# First, let's generate some random data
# See documentation online for this, but loc is the mean,
# scale is the standard deviation, and size is number of values
data = np.random.normal(loc=5.0, scale=1.0, size=20)
# Let's get some statistical information from this
mean_data = np.mean(data)
std_data = np.std(data, ddof=1) #ddof is set to 1 for the sample standard deviation
# Now let's get to plotting
# First we tell python to open up a figure
plt.figure()
plt.grid()
# Make the histogram
n, bins, patches = plt.hist(data, bins=5, ec="black")
# Now add labels for a presentable chart
plt.xlabel("Data Points")
plt.ylabel("Frequency")
plt.title("Histogram of Random Data")
# Now tell python to show this plot
plt.show()
print(mean_data)
print(std_data)
# Now, we can save it offline
#plt.savefig("firsthisto.png")
# Now what if we want a Gaussian fit?
# We will copy and paste, but notice there are changes at the histogram
# options and added a pdf below it
# First we tell python to open up a figure
plt.figure()
plt.grid()
# Make the histogram
n, bins, patches = plt.hist(data, bins=5, density=True, ec="black")
# We need to sort the data for statistics
sorted_data = np.sort(data)
# Add a fit to the histogram
data_pdf = norm.pdf(sorted_data, mean_data, std_data)
plt.plot(sorted_data, data_pdf, 'r--')
# Now add labels for a presentable chart
plt.xlabel("Data Points")
plt.ylabel("Frequency")
plt.title("Histogram of Random Data")
# Now tell python to show this plot
plt.show() | true |
ba522adf755c38008a07ac70acb9effcc2dafe1e | sonushakya9717/Hyperverge__learnings | /dsa_step_10/power_of_number.py | 238 | 4.15625 | 4 | def power_of_number(n,x):
if x==0:
return 1
elif x==1:
return n
else:
return n*power_of_number(n,x-1)
n=int(input("enter the number"))
x=int(input("enter the degree of no."))
print(power_of_number(n,x)) | true |
b732cda25aed23b3a2f629b89bccf286cf16c62c | mrvrbabu/MyPycode | /Python Developer Bootcamp/Section5-Python_Loops/1.for_loops_pt-1.py | 472 | 4.4375 | 4 | # ----------------------------------------------------------------------- #
# --------------- ** For Loops ** -------------------------- #
# Example 1 - DRY - Do not repeat yourself
# n = 3
# for (i=0, i<=n,):
# print(i)
# i += 1
for x in range(10):
print(x + 1)
print("\n")
for number in range(5):
print(f"The code has ran for {number} times")
print("\n")
for a in range(5, 15):
print(a)
print("\n")
for b in range(100, 200, 10):
print(b)
| true |
24a8c11de8abacaf180b9e99452ddf3e7adc17d6 | mrvrbabu/MyPycode | /Python Developer Bootcamp/Section4-Python_Logic-Control_Flow/21.Conditional_statements.py | 621 | 4.46875 | 4 | # ----------------------------------------------------------------------- #
# --------------- ** Control Statements ** ---------------------------- #
"""
if (boolean expression):
execute the statements
"""
# ******************** Example Check for a single condition *******************
temperature = int(input("Pleae enter the current temperature: "))
print("You have entered the temperature as : ", temperature)
if temperature > 32:
print("Temperature is high")
else:
print("The tempature is low and it is ", temperature)
# ************ Checking for two conditions *********************************
| true |
d0d29d933e69c997308480233cd114b6e10e188d | mrvrbabu/MyPycode | /Python Developer Bootcamp/Section5-Python_Loops/4.iterables.py | 342 | 4.125 | 4 | # ----------------------------------------------------------------------- #
# --------------- ** Iterables ** -------------------------------------- #
# *** Example 1
print(type(range(4)))
for char in "Welcome Home":
print(char)
# *** Example 2
for somethin in ["Coffee", "Play with the cat", "Walk the dog"]:
print(somethin)
| true |
7a3d476958d7a43f3545000557bd7c66990e2ab6 | faustfu/hello_python | /def01.py | 1,281 | 4.5 | 4 | # 1. Use "def" statement with function name, parameters and indented statements to declare a function.
# 2. Use "return" statement with data to return something from the function.
# 3. If there is no "return" statement, the function will return "None".
# 4. All parameters are references.
# 5. Parameters could be assigned by locations or by names.
# 6. Papameters could have defaults.
# 7. Default values of parameters are calculated when declaration.
# 8. Use "*<name>" to collect dynamic parameters as a tuple.
# 9. Use "**<name>" to collect dynamic naming parameters as a dictionary.
# 10. First string statement of a function is its description(docstring).
# 11. Docstring could be accessed by help() or <function name>.__doc__
def do_nothing():
pass
def agree():
return True
def echo(anything):
anything.append("go")
return ",".join(anything)
def attack(a, b = "me"):
return a + ' attacked ' + b
def print_more(req, *args):
'First parameter is required!'
print("required parameter", req)
print("rest parameters", args)
do_nothing()
yes = ["ok"]
if agree():
print(echo(yes))
else :
print("not ok")
print(yes)
print(attack("Bob", "Ada"))
print(attack(b = "Bob", a = "Ada"))
print(attack("Bob"))
print_more(1,2,3)
help(print_more) | true |
e240fabceddd8c71f1a81d400582a996bbd0ac07 | avbpk1/learning_python | /circle_area.py | 251 | 4.4375 | 4 | # Program to accept radius and calculate area and circumference
radius = float(input("Please Enter Radius:"))
pi = 22/7
area = pi * radius**2
circumference = pi * 2 * radius
print(f"Area is : {area}")
print(f"Circumference is : {circumference}") | true |
2c95c3f1109bd296b05896f637a61c155f2ef6d8 | avbpk1/learning_python | /assignments.py | 476 | 4.125 | 4 | # This is assignment 1
# Program to take input from user until 0 is entered and print average. Negative input to be ignored
total = 0
cnt = 0
while True:
num = int(input("Please enter a number (Entering Zero will terminate) : "))
if num == 0:
break
elif num < 0:
continue
else:
total += num
cnt += 1
if cnt == 0:
print(f"No numbers entered.")
else:
print(f"Average of the entered numbers is {total/cnt}") | true |
9f1190f69f2799fd18d2e86845f794643761d4c2 | avbpk1/learning_python | /20May_ass4.py | 568 | 4.1875 | 4 | # -- ass4 -- use map to extract all alphabets from each string in a list. Use map and a function
def ext_alpha(word_str):
new_word = ''
for c in word_str:
if c.isalpha():
new_word += c
return new_word
words = ['Ab12c','x12y2','sdfds33&']
for word in words:
alpha_extract = map(ext_alpha,word)
print(alpha_extract)
# gives following output -- please explain
# <map object at 0x000001C3B608ED90>
# <map object at 0x000001C3B608ED30>
# <map object at 0x000001C3B608EDC0>
#
# Process finished with exit code 0
| true |
43aa1410040d47341dab6e09813c0820f38d3f97 | LalithaNarasimha/Homework2 | /Solution2.py | 1,062 | 4.21875 | 4 | # Code that compute the squares and cubes for numbers from 0 to 5,
# each cell occupies 20 spaces and right-aligned
numbers = [ 0, 1, 2, 3, 4, 5]
place_width = 20
header1 = 'Number'
header2 = 'Square'
header3 = 'Cube'
print('\nSolution 1\n')
print(f' {header1: >{place_width}} {header2: >{place_width}} {header3: >{place_width}}')
for num in numbers:
print(f' {num: >{place_width}} {num ** 2: >{place_width}} {num**3: >{place_width}} ')
# Code that use the formula to calculate and print the Fahrenheit temperature
celsius_value = [-40, 0, 40, 100]
f = 0
print('\nSolution 2\n')
for value in celsius_value:
f = (9/5 * value) + 32
print(f'Fahrenheit temperature for Celsius scale {value} is {f}')
# Code that input three integers from the user and print the sum and average of the numbers
input_seq = [1000, 2000, 4000]
total = 0
seq = 0
average = 0
print('\nSolution 3\n')
for input in input_seq:
total = total + input
seq = seq + 1
average = total/seq
print(f'The sum {total:,d} ')
print(f'The average is {average:,.2f}')
| true |
ef47c071219b5964290c6802f8006a639abf1955 | amylearnscode/CISP300 | /Lab 8-5.py | 2,270 | 4.1875 | 4 | #Amy Gonzales
#March 21, 2019
#Lab 8-5
#This program uses while loops for input validation and calculates
#cell phone minute usage
def main():
endProgram = "no"
minutesAllowed = 0
minutesUsed = 0
totalDue = 0
minutesOver = 0
while endProgram=="no":
minutesAllowed = getAllowed(minutesAllowed)
minutesUsed = getUsed(minutesUsed)
totalDue, minutesOver = calcTotal(minutesAllowed, minutesUsed, totalDue, minutesOver)
printData(minutesAllowed, minutesUsed, totalDue, minutesOver)
endProgram = raw_input("Do you want to end the program? yes or no")
while not (endProgram=="yes" or endProgram=="no"):
print "Please enter a yes or no"
endProgram = raw_input("Do you want to end the program? (Enter no to process a new set of scores): ")
def getAllowed(minutesAllowed):
minutesAllowed = input("Enter minutes allowed between 200 and 800: ")
while minutesAllowed < 200 or minutesAllowed > 800:
print "Minutes must be between 200 and 800. "
minutesAllowed= input("Enter minutes allowed between 200 and 800: ")
return minutesAllowed
def getUsed(minutesUsed):
minutesUsed = input("Enter number of minutes used: ")
while minutesUsed < 0:
print "Please enter minutes of at least 0"
print "How many minutes were used?"
return minutesUsed
def calcTotal(minutesAllowed, minutesUsed, totalDue, minutesOver):
extra = 0
if minutesUsed <= minutesAllowed:
totalDue = 74.99
minutesOver = 0
print "You were not over your minutes"
elif minutesUsed>= minutesAllowed:
minutesOver = minutesUsed - minutesAllowed
extra = minutesOver*.20
totalDue = 74.99 + extra
print "You were over your minutes by ", minutesOver
return totalDue, minutesOver
def printData(minutesAllowed, minutesUsed, totalDue, minutesOver):
print "----Monthly Use Report-----"
print "Minutes allowed were: ", minutesAllowed
print "Minutes used were: ", minutesUsed
print "Minutes over were: ", minutesOver
print "Total due is: ", totalDue
main()
| true |
82fc95d5d86f08c337f3823f0bd147c142f8c69e | floydnunez/Project_Euler | /problem_004.py | 852 | 4.21875 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import math
def check_palindrome(number):
is_palindrome = True
str_num = str(number)
size = len(str_num)
half_size = math.floor(size/2)
for index in range(0, half_size + 1):
char_1 = str_num[index]
char_2 = str_num[size - index-1]
if char_1 != char_2:
is_palindrome = False
return is_palindrome
print(check_palindrome(21923))
all = []
for xx in range(999, 1, -1):
for yy in range(999, 1, -1):
val = xx * yy
if check_palindrome(val):
print("first:", xx, "second:", yy, "=", val)
all.append(val)
print(max(all))
#answer: 906609 | true |
9b6ed13e70dcb0706ea37b9c4d36b8e838d7965a | swaroopsaikalagatla/Python | /python5.py | 267 | 4.125 | 4 | def maximum(a,b,c):#function
list=[a,b,c]#statement 1
return max(list)#statement 2
x=int(input("Enter the first number : "))
y=int(input("Enter the second number :"))
z=int(input("Enter the third number :"))
print("biggest number is :",maximum(x,y,z)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.