blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
382a8915e11e58f68d73b4451e9efaa294ff1ffb | niranjan2822/List | /Iterating two lists at once.py | 1,777 | 4.65625 | 5 | # Iterating two lists at once
# Sometimes, while working with Python list, we can have a problem in which we have to iterate over two list elements.
# Iterating one after another is an option, but it’s more cumbersome and a one-two liner is always recommended over
# that
'''
Input 1 : [4, 5, 3, 6, 2]
Input 2 : [7, 9, 10, 0]
The paired list contents are :
4 5 3 6 2 7 9 10 0
'''
# Method #1 : Using loop + “+” operator
# Python3 code to demonstrate working of
# Iterating two lists at once
# using loop + "+" operator
# initializing lists
test_list1 = [4, 5, 3, 6, 2]
test_list2 = [7, 9, 10, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Iterating two lists at once
# using loop + "+" operator
# printing result
print("The paired list contents are : ")
for ele in test_list1 + test_list2:
print(ele, end=" ")
# output : Output :
# The original list 1 is : [4, 5, 3, 6, 2]
# The original list 2 is : [7, 9, 10, 0]
# The paired list contents are :
# 4 5 3 6 2 7 9 10 0
# Method #2 : Using chain()
# This is the method similar to above one, but it’s slightly more memory efficient as the chain() is used to
# perform the task and creates an iterator internally.
# Python3 code to demonstrate working of
# Iterating two lists at once
# using chain()
from itertools import chain
# initializing lists
test_list1 = [4, 5, 3, 6, 2]
test_list2 = [7, 9, 10, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Iterating two lists at once
# using chain()
# printing result
print("The paired list contents are : ")
for ele in chain(test_list1, test_list2):
print(ele, end=" ")
| true |
4ffa4b3471cedec80b47c6408b8bf1318c28dc40 | siddbose97/maze | /DFS/maze.py | 1,240 | 4.15625 | 4 | #logic inspired by Christian Hill 2017
#create a cell class to instantiate cells within the grid which will house the maze
#every cell will have walls and a coordinate pair
class cell:
# create pairs of walls
wallPairs = {"N":"S", "S":"N", "E":"W", "W":"E"}
def __init__(self, x, y):
#give a wall coordinates xy and then give it walls (all bool true)
self.xCoord = x
self.yCoord = y
self.walls = {"N": True, "S": True, "E": True, "W": True}
def checkWalls(self):
#check if all walls are still present
for key in self.walls:
if self.walls[key] == True:
continue
else:
return False
return True
def removeWall(self, neighbor, wall):
#if removing one wall for a cell, remove corresponding wall in other cell
if self.walls[wall] == False:
neighborWall = cell.wallPairs[wall]
neighbor.walls[neighborWall] = False #use corresponding wall to remove accordingly
class maze:
#initialize a maze as cells in rows and columns based on input values
#initialize by taking input row and column and then using 0,0 as a starting cell
pass
| true |
8b589bdd3f9299888080234f814c617e111817c1 | Purushotamprasai/Python | /Rehaman/001_Basic_understanding/001_basic_syntax.py | 1,023 | 4.125 | 4 | #!/usr/bin/python
# the above line is shabang line ( path of python interpreter)
#single line comment ( by using hash character '#'
'''
We can comment multiple lines at a time
by using triple quotes
'''
# the below code understand for statement concept
'''
1---> single statemnt
'''
# a line which is having single executable instruction
print " this is single statement example "
'''
2----> multiple statement
'''
# a single line which is having more than one executable instruction
print "hello " ; print "hai" ; print "bye"
'''
3 ---> multiline statement
'''
# a single instruction which may contine more than one line
print "hello \
hai \
bye "
'''
4---> compound statement / indentation statement
in othe preogramming language syntax
block_name
{
st1
---
---
}
in python syntax:
block_name :
st1
st2
st3
st4
'''
if(__name__ == "__main__"):
print " i am in if block"
print " i am very happy for learning python"
print "hai i am error statement"
| true |
efe69eec4380f3041992e4b82eb1252f32876859 | Purushotamprasai/Python | /Rohith_Batch/Operator/Logical Operator/001_understand.py | 908 | 4.3125 | 4 | # this file is understand for logical operators
'''
Logical AND ---> and
---------------------
Defination :
-----------
if 1st input is false case then output is 1st input value
other wise 2nd input value is the output
Logical OR---> or
---------------------
Defination :
-----------
if 1st input is false case then output is 2st input value
other wise 1st input value is the output
Logicakl not ---> not
---------------------
Defination :
-----------
if 1st input is false case then output is True boolean data
other wise False boolean data as on output
'''
def main():
a = input("enter boolean data") # True
b = input("enter boolean daata") # False
print a ," logical and", b," is ", a and b
print a , "logical or ",b, " is ", a or b
print " logical not ", b ,"is " , not b
if(__name__ =="__main__"):
main()
| true |
ad53e27408916456b808dea9bdc0662692a5fd24 | Purushotamprasai/Python | /Z.R/files/002_write.py | 355 | 4.125 | 4 | file_obj = open("readfile.txt","w")
'''
file opened as write mode
if the file is not existed 1st create then open it"
file is existed then removes previous data
and open as fresh file
if the is open as write mode
we cant use read methodes
'''
data =input("enter some data")
file_obj.write(data)
d =file_obj.read()
file_obj.close()
| true |
72a0cc33029ff768a219bfe8517ed7793abfe467 | Purushotamprasai/Python | /Rohith_Batch/Operator/Relational/Bitwise_Even or Odd.py | 299 | 4.34375 | 4 | '''
Program : Find the Given number is Even or Odd using bitwise operator
Programmer : Rohit
'''
def main():
a = input('Enter a value: ')
if a&1==0:
print "Number is Even"
else:
print "Number is Odd"
if (__name__=="__main__"):
main()
| true |
e1194fa52edbd9f140b0d048833b2fd13e6517ff | Purushotamprasai/Python | /hussain_mani/python_introduction/003_Python Basic Built-in function/Built_in_function_info.py | 1,541 | 4.21875 | 4 | # python Basic Built -in Function
'''
Function :-
---------------
-----> Function is a set of instructions for doing any one task
-----> there are two types
1. User Defined Function :-
---------------------------
The programmer can define function
def ----> user defined function
2. Built-in function :-
---------------------------
----> the functions are already available in python interpreter
---> Basic Built Function
---------------------------
---> Input function
---> Output function
---> type and id
---> Data type convertions function
---> Number system conversion function
'''
#Input function :-
#----------------
----> Are used for to read the data from keyword by user/ client / programmer
In python we have two input functions
1. raw_input()
2. input()
# Output function:-
--------------------
----> To display the data on monitor
we can use print keyword
----> print keyword we can use in 2 ways
1. print "statement"
2. print("function")
#type
-----
----> type is a function which is return type of data
type(obj)
# id
----> to know the memory location od any variable / object
id(obj)
# data type conversion function:-
--------------------------------
---> we can convert one datatype element to targeted datatype
int ()
float()
complex()
bool()
str()
list()
tuple()
set()
dict()
---> we can use with in raw_input
| true |
a57998b659eb1ad0d09749a74eb54a6a7db0e58c | TomiMustapha/Shleep | /week.py | 623 | 4.15625 | 4 | ## Week class
##
## Each week is a list of fixed size 7 of positive ints
## Represents a week in which we log hours of sleep
## We can then combine weeks into a matrix to be represented graphically
import numpy as np
class Week():
def __init__(self):
self.nodes = np.array([])
def insert_node(self, node):
if (not type(node) == int):
raise TypeError("Not an int.")
elif (self.nodes.size >= 7):
raise ValueError("Week has exceeded 7")
else:
self.nodes = np.append(self.nodes, node)
| true |
97487f7c395f37af614556864394127eeeb006b7 | parker57/210CT | /week4/adv2_qs.py | 1,754 | 4.25 | 4 | ## Adapt the Quick Sort algorithm to find the mth smallest element out of a list of n integers, where m is
## read from the standard input.
## For example, when m = 5, your version of Quick Sort will output the 5th smallest element out of your
## input list.
import random
def quickselect(array, m):
def sort(array, left, right, index):
if left == right:
return array[left] #Found/ base case.
#If return array is only one long, will leave stack
pivot = left #Primitive pivot selection/ not ideal.
wall = pivot
for i in range(left+1, right+1):
if array[i] < array[left]:
wall += 1
array[wall], array[i] = array[i], array[wall]
array[wall], array[left] = array[left], array[wall]
if index>wall:
#If index is greater than wall, sort larger
return sort(array, wall+1, right, index)
elif index<wall:
#If index is less than wall, sort smaller
return sort(array, left, wall-1, index)
else:
#If index is equal to wall, mth smallest found.
return array[wall]
if len(array) < 1:
return
if m not in range(0, len(array)):
raise IndexError('Index searched is out of range, remember index uses zero-based numbering')
return sort(array, 0, len(array) - 1, m)
if __name__ == '__main__':
array_size = int(input('How many integers should the list be? '))
m = int(input('Finding the Mth smallest, what is m? '))
test_list = [random.randint(0,99) for i in range(array_size)]
print('List: ',test_list)
print(m,'th element is: ',quickselect(test_list,m))
print('Sorted list: ',sorted(test_list))
| true |
521e916bcc367920ddb63aedcd90e84e38ac7f42 | Anshul-GH/jupyter-notebooks | /UdemyPythonDS/DS_BinarySearchTree/Node.py | 2,982 | 4.46875 | 4 | # Defining the class Node
class Node(object):
# Construction for class Node
def __init__(self, data):
self.data = data
# defining both the child nodes as NULL for the head node
self.leftChild = None
self.rightChild = None
# Defining the insert function.
# 'data' contains the new value to be inserted within the tree.
# 'self' designates the node which is calling this function
def insert(self, data):
# If the new data value is less than calling node's data the new value has to go to left branch of the tree
if data < self.data:
if not self.leftChild: # if there are no nodes on the left
self.leftChild = Node(data) # assign the new node as the left child
else: # if there are nodes on the left
self.leftChild.insert(data) # call the insert function again with the immediate left child node
# If the new data value is greater than calling node's data the new value has to go to right branch of the tree
else:
if not self.rightChild: # if there are no nodes on the right
self.rightChild = Node(data) # assign the new node as the right child
else: # if there are nodes on the right
self.rightChild.insert(data) # call the insert function again with the immediate right child node
# Defining the remove function
# Parameters: self, data and parent node
def remove(self, data, parentNode):
if data < self.data:
if self.leftChild is not None:
self.leftChild.remove(data, self)
elif data > self.data:
if self.rightChild is not None:
self.rightChild.remove(data, self)
else:
if self.leftChild is not None and self.rightChild is not None:
self.data = self.rightChild.getMin()
self.rightChild.remove(self.data, self)
elif parentNode.leftChild == self:
if self.leftChild is not None:
tempNode = self.leftChild
else:
tempNode = self.rightChild
parentNode.leftChild = tempNode
elif parentNode.rightChild == self:
if self.leftChild is not None:
tempNode = self.leftChild
else:
tempNode = self.rightChild
parentNode.rightChild = tempNode
def getMin(self):
if self.leftChild is None:
return self.data
else:
self.leftChild.getMin()
def getMax(self):
if self.rightChild is None:
return self.data
else:
self.rightChild.getMax()
def traverseInOrder(self):
if self.leftChild is not None:
self.leftChild.traverseInOrder()
print(self.data)
if self.rightChild is not None:
self.rightChild.traverseInOrder() | true |
99467384dfdee08e2f5794af6db8e964807ccc95 | JFarina5/Python | /password_tester.py | 1,107 | 4.25 | 4 | """
This program takes a given user password and adds 'points' to that password,
then calculates the total amount of 'points'. The program will take the total
amount of points and then inform the user if they have a strong password or a
weak password.
"""
import re
def password_test():
value = 0
user_pass = input("Please enter a password for testing: ")
if re.search('[a-z]', user_pass):
value = value + 1
if re.search('[A-Z]', user_pass):
value = value + 1
if re.search('[0-9]', user_pass):
value = value + 1
if re.search('[!@#$%^&*()~_+":?<>.,;-=]', user_pass):
value = value + 1
if len(user_pass) < 10:
print("Your password should contain more than 10 characters\n")
password_score(value)
def password_score(value):
if value == 4:
print("Strong Password")
if value == 3:
print("Medium Password")
if value == 2:
print("Weak Password")
if value == 1:
print("Very Weak Password, consider changing your password now.")
return 0
if __name__ == '__main__':
password_test()
| true |
8f8505622fbd3ab77638a28c71d98133d5980fa7 | JFarina5/Python | /palindrome_tester.py | 623 | 4.4375 | 4 | """
The purpose of this program is to test a string of text
and determine if that word is a palindrome.
"""
# Palindrome method, which disregards spaces in the user's input and reverses that string
# in order to test the input to see if it is a palindrome.
def palindrome():
string = input("Please insert a palindrome: ").lower()
if ' ' in string:
string = string.replace(' ', '')
elif str(string) == str(string)[::-1]:
print("The following string is a palindrome.\n")
else:
print("The following string is not a palindrome.\n")
if __name__ == '__main__':
palindrome()
| true |
18b0a035d045cfdb818ecabd0c29fad2a166fa70 | ImLeosky/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,164 | 4.28125 | 4 | #!/usr/bin/python3
"""
the class Square that inherits from Rectangle
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""
Class Square inherits from Rectangle
"""
def __init__(self, size, x=0, y=0, id=None):
"""
Class constructor
"""
width = size
height = size
super().__init__(width, height, x, y, id)
self.size = self.width
def __str__(self):
"""
he overloading __str__ method should return
"""
str1 = "[{}] ({}) ".format(Square.__name__, self.id)
str2 = "{}/{} - {}".format(self.x, self.y, self.size)
return(str1 + str2)
@property
def size(self):
"""
the getter
"""
return(self.width)
@size.setter
def size(self, value):
"""
The setter should assign (in this order) the width
and the height - with the same value
"""
self.width = value
self.height = value
def update(self, *args, **kwargs):
"""
*args is the list of arguments - no-keyworded arguments
**kwargs can be thought of as a double pointer to a dictionary:
key/value (keyworded arguments)
**kwargs must be skipped if *args exists and is not empty
"""
if len(args) > 0:
self.id = args[0]
if len(args) > 1:
self.size = args[1]
if len(args) > 2:
self.x = args[2]
if len(args) > 3:
self.y = args[3]
if args is None or len(args) == 0:
for key, value in kwargs.items():
if key == "id":
self.id = value
if key == "size":
self.size = value
if key == "x":
self.x = value
if key == "y":
self.y = value
def to_dictionary(self):
"""
that returns the dictionary representation of a Rectangle:
"""
dicts = {
"x": self.x,
"y": self.y,
"id": self.id,
"size": self.size}
return(dicts)
| true |
830e2ac7c2d5a8e558877538c644ff87a2747f3b | alammahbub/py_begin_oct | /5. list.py | 1,402 | 4.53125 | 5 | # list in python start with square brackets
# list can hold any kind of data
friends = ["asib","rony","sajia"]
print(friends)
# accessing list item with there index
print(friends[2]+" has index 2")
# accessing list from back or, as negative index
print(friends[-1]+" has index -1")
# Asigning new item in list by using index
friends[2] = "Borhan"
print(friends[0:2])
# list function
lucky_number = [4,8,9,32,23]
friends = ["Asib","Rony","Sajia","Borhan","Rakib"]
print(friends)
# extend function combine one list with another
friends.extend(lucky_number)
print(friends)
# append add new item at the end
friends.append("Maksud")
print(friends)
# insert can insert data item into any choosen location
friends.insert(4,"Sumon")
print(friends)
# remove delete data item as there index
friends.remove(4)
print(friends)
# pop remove a single item from back or index -1
friends.pop()
print(friends)
# index of an item can be accessed by index function
print(friends.index(9))
friends.append("Borhan")
print(friends.count("Borhan"))
# sort function will sort data in ascending order if there is only same type of data
lucky_number.sort()
print(lucky_number)
# Reverse function rearrenge data item as index 0 = index -1
lucky_number.reverse()
print(lucky_number)
#copy function of a list return all data to a new list
friends2 = friends.copy()
print(friends2) | true |
2a6f7cbc33008d2a22ba3974e0e90201caab553a | marko-despotovic-bgd/python | /EndavaExercises/1_3_stringoperations.py | 381 | 4.34375 | 4 | # 1. Strings and Numbers
# 1.3. Write a console program that asks for a string and outputs string length
# as well as first and last three characters.
print('Please enter some string: ')
string = (input())
print('Length: {}\nFirst 3 chars: {}\nLast 3 chars: {}'.format(len(string),
string[:3],
string[-3::1]))
| true |
e21afb700a8297f49dc193bd9f7d5c72b5c95c07 | 4Empyre/Bootcamp-Python | /35python_bike/bike.py | 780 | 4.21875 | 4 | class Bike(object):
def __init__ (self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print "Price:",self.price,"Max Speed:",self.max_speed,"Miles:", self.miles
def ride(self):
self.miles += 10
print "Riding"
return self
def reverse(self):
if self.miles >= 5: # Prevents miles from going negative.
self.miles -= 5
print "Reversing"
return self
bike1 = Bike("$200", "25mph")
bike2 = Bike("$250", "27mph")
bike3 = Bike("$350", "29mph")
bike1.ride().ride().ride().reverse().displayInfo()
bike2.ride().ride().reverse().reverse().displayInfo()
bike3.reverse().reverse().reverse().displayInfo()
| true |
c2b4a96ee434e18f2be2f2758478331919d65582 | brucekaushik/basicblog | /apps/hello-world/valid-month.py | 1,189 | 4.4375 | 4 | # -----------
# User Instructions
#
# Modify the valid_month() function to verify
# whether the data a user enters is a valid
# month. If the passed in parameter 'month'
# is not a valid month, return None.
# If 'month' is a valid month, then return
# the name of the month with the first letter
# capitalized.
#
months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
# build dictionary
month_abbrs = dict((m[:3].lower(), m) for m in months)
def valid_month(month):
if month:
cap_month = month.capitalize();
if cap_month in months:
return cap_month
def valid_month_short(month):
if month:
short_month = month[:3].lower() # get first 3 letters of input
return month_abbrs.get(short_month) # check if short_month exists in the dictionary
print valid_month("january")
print valid_month("jan")
print valid_month_short("january")
print valid_month_short("jan")
print valid_month_short("janasfasfaf")
print valid_month_short("jjjj")
| true |
6dad3d3891bda5551a6e6a3f03a442236cf2a9ae | cameronww7/Python-Workspace | /Python-Bootcomp-Zero_To_Hero/Sec-14-Py-Adv_Modules/113-Py-ZippingAndUnzippingFiles.py | 2,175 | 4.1875 | 4 | from __future__ import print_function
import zipfile
import shutil
import os
"""
Prompt 113-Py-ZippingAndUnzippingFiles
"""
print("113-Py-ZippingAndUnzippingFiles")
"""
Unzipping and Zipping Files
As you are probably aware, files can be compressed to a zip format.
Often people use special programs on their computer to unzip these
files, luckily for us, Python can do the same task with just a few
simple lines of code.
"""
print("\n113-Py-ZippingAndUnzippingFiles")
print("- - - - - - - - - - ")
# Create Files to Compress
# slashes may need to change for MacOS or Linux
f = open("new_file.txt", 'w+')
f.write("Here is some text")
f.close()
# slashes may need to change for MacOS or Linux
f = open("new_file2.txt", 'w+')
f.write("Here is some text")
f.close()
"""
Zipping Files
The zipfile library is built in to Python, we can use it to compress
folders or files. To compress all files in a folder, just use the
os.walk() method to iterate this process for all the files in a
directory.
"""
comp_file = zipfile.ZipFile('comp_file.zip', 'w')
comp_file.write("new_file.txt", compress_type=zipfile.ZIP_DEFLATED)
comp_file.write('new_file2.txt', compress_type=zipfile.ZIP_DEFLATED)
comp_file.close()
"""
Extracting from Zip Files
We can easily extract files with either the extractall() method to
get all the files, or just using the extract() method to only grab
individual files.
"""
zip_obj = zipfile.ZipFile('comp_file.zip', 'r')
print(zip_obj.extractall("extracted_content"))
"""
Using shutil library
Often you don't want to extract or archive individual files from a
.zip, but instead archive everything at once. The shutil library
that is built in to python has easy to use commands for this:
"""
print(os.getcwd())
"""
directory_to_zip = ""
# Creating a zip archive
output_filename = 'example'
# Just fill in the output_filename and the directory to zip
# Note this won't run as is because the variable are undefined
shutil.make_archive(output_filename, 'zip', directory_to_zip)
# Extracting a zip archive
# Notice how the parameter/argument order is slightly different here
shutil.unpack_archive(output_filename, directory_to_zip, 'zip')
"""
| true |
ec0cbb2d72776eedda8618778e642c7944080959 | cameronww7/Python-Workspace | /Python-Bootcomp-Zero_To_Hero/Sec-14-Py-Adv_Modules/106-Py-Date_Time.py | 1,964 | 4.40625 | 4 | from __future__ import print_function
import datetime
"""
Prompt 106-Py-Date_Time
"""
print("106-Py-Date_Time")
"""
datetime module
Python has the datetime module to help deal with timestamps in
your code. Time values are represented with the time class.
Times have attributes for hour, minute, second, and microsecond.
They can also include time zone information. The arguments to
initialize a time instance are optional, but the default of 0
is unlikely to be what you want.
time
Let's take a look at how we can extract time information from
the datetime module. We can create a timestamp by specifying
datetime.time(hour,minute,second,microsecond)
"""
print("\ndatetime.time(4, 20, 1)")
print("- - - - - - - - - - ")
t = datetime.time(4, 20, 1)
# Let's show the different components
print(t)
print('hour :', t.hour)
print('minute:', t.minute)
print('second:', t.second)
print('microsecond:', t.microsecond)
print('tzinfo:', t.tzinfo)
print('Earliest :', datetime.time.min)
print('Latest :', datetime.time.max)
print('Resolution:', datetime.time.resolution)
"""
Dates
datetime (as you might suspect) also allows us to work with date
timestamps. Calendar date values are represented with the date
class. Instances have attributes for year, month, and day. It is
easy to create a date representing today’s date using the today()
class method.
"""
print("\ndatetime.date.today()")
print("- - - - - - - - - - ")
today = datetime.date.today()
print(today)
print('ctime:', today.ctime())
print('tuple:', today.timetuple())
print('ordinal:', today.toordinal())
print('Year :', today.year)
print('Month:', today.month)
print('Day :', today.day)
print('Earliest :', datetime.date.min)
print('Latest :', datetime.date.max)
print('Resolution:', datetime.date.resolution)
print("\ndatetime.date(2015, 3, 11)")
print("- - - - - - - - - - ")
d1 = datetime.date(2015, 3, 11)
print('d1:', d1)
d2 = d1.replace(year=1990)
print('d2:', d2)
| true |
47226b0ba22174336343d4f6fe2648d053ec8612 | cameronww7/Python-Workspace | /Python-Bootcomp-Zero_To_Hero/Sec-8-Py-OOP/66-OOP-Challenge.py | 2,257 | 4.3125 | 4 |
from __future__ import print_function
import math
"""
Prompt 66-OOP-Challenge
"""
print("66-OOP-Challenge")
"""
Object Oriented Programming Challenge
For this challenge, create a bank account class that has two attributes:
owner
balance
and two methods:
deposit
withdraw
As an added requirement, withdrawals may not exceed the available balance.
Instantiate your class, make several deposits and withdrawals, and test to
make sure the account can't be overdrawn.
"""
print("\n66-OOP-Challenge\n")
print("- - - - - - - - - - ")
class Account:
def __init__(self, xName, xBalance):
self.name = xName
self.curBalance = xBalance
def owner(self):
print("The Account Holder Name is : {}".format(self.name))
return self.name
def balance(self):
print("Your Current Balance is : {}".format(self.curBalance))
return self.curBalance
def deposit(self, xDepositAmount):
print("Processing Deposit of {}".format(xDepositAmount))
self.curBalance = self.curBalance + xDepositAmount
print("Deposit Accepted, Your new Balance is : {}".format(self.curBalance))
return True
def withdraw(self, xWithdrawAmount):
print("Processing Withdraw of {}".format(xWithdrawAmount))
if xWithdrawAmount > self.curBalance:
print("Error : Do not have enough Balance")
return False
else:
self.curBalance = self.curBalance - xWithdrawAmount
print("Withdraw Accepted, Your new Balance is : {}".format(self.curBalance))
return True
# 1. Instantiate the class
acct1 = Account('Jose', 100)
# 2. Print the object
print("\n# 2. Print the object")
print(acct1)
# 3. Show the account owner attribute
print("\n# 3. Show the account owner attribute")
print(acct1.owner())
# 4. Show the account balance attribute
print("\n# 4. Show the account balance attribute")
print(acct1.balance())
# 5. Make a deposit
print("\n# 5. Make a deposit")
print(acct1.deposit(50))
# 6. Make a withdrawal
print("\n# 6. Make a withdrawal")
print(acct1.withdraw(75))
# 7. Make a withdrawal that exceeds the available balance
print("\n# 7. Make a withdrawal that exceeds the available balance")
print(acct1.withdraw(500))
| true |
6e8687c78e8198d41807ef3bd1652efcf16bffe9 | romanitalian/romanitalian.github.io | /sections/python/spiral_matrix/VH7Isb3mRqUaaHCc_spiral-matrix-in-python.py | 1,751 | 4.28125 | 4 | #!/usr/bin/env python3
# http://runnable.com/VH7Isb3mRqUaaHCc/spiral-matrix-in-python
def change_direction(dx, dy):
# not allowed!3
if abs(dx+dy) != 1:
raise ValueError
if dy == 0:
return dy, dx
if dx == 0:
return -dy, dx
def print_spiral(N=5, M=6):
if N < 0 or M < 0:
return None
dx, dy = 1, 0 # direction
x, y = 0, 0 # coordinate
start = 0 # initial value for the matrix
max_digits = len(str(N*M-1)) # for pretty printing
left_bound, right_bound = 0, N-1
upper_bound, bottom_bound = 1, M-1
# zero filled 2d array
matrix = [[0 for i in range(N)] for j in range(M)]
for not_use in range(N*M):
matrix[y][x] = start
if (dx > 0 and x >= right_bound):
dx, dy = change_direction(dx, dy)
right_bound -= 1
if (dx < 0 and x <= left_bound):
dx, dy = change_direction(dx, dy)
left_bound += 1
if (dy > 0 and y >= bottom_bound):
dx, dy = change_direction(dx, dy)
bottom_bound -= 1
if (dy < 0 and y <= upper_bound):
dx, dy = change_direction(dx, dy)
upper_bound += 1
x += dx
y += dy
start += 1
print('\n'.join([' '.join(['{:0{pad}d}'.format(val, pad=max_digits) for val in row]) for row in matrix]))
if __name__ == '__main__':
print_spiral()
# def spiral(X, Y):
# x = y = 0
# dx = 0
# dy = -1
# for i in range(max(X, Y)**2):
# if (-X/2 < x <= X/2) and (-Y/2 < y <= Y/2):
# print (x, y)
# # DO STUFF...
# if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):
# dx, dy = -dy, dx
# x, y = x+dx, y+dy
| true |
dff98da96027c42420440cdae33e55c3dcab539b | kelvinadams/PythonTheHardWay | /ex11.py | 386 | 4.40625 | 4 | # Python the Hard Way - Exercise 11
# prompts user for their age, height, and weight
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("What is your weight?", end=' ')
weight = input()
# prints out the input in a new format
print(
f"Alrighty, so you're {age} years old, {height} tall, and weigh {weight}.")
| true |
b7fc72d816e4fbf3dad343eb6f7f2cf47847a7e7 | SujeethJinesh/Computational-Physics-Python | /Jinesh_HW1/Prob1.py | 414 | 4.1875 | 4 | import math
def ball_drop():
height = float(input("please input the height of the tower: ")) #This is how many meters tall the tower is
gravity = 9.81 #This is the acceleration (m/s^2) due to gravity near earth's surface
time = math.sqrt((2.0*height)/gravity) #derived from h = 1/2 gt^2 to solve for time
print("It will take the ball ", time, " seconds to fall to earth.") #Final output statement. | true |
f6146b7e9826f07bc27579b30a5b48abbc35be7a | SujeethJinesh/Computational-Physics-Python | /Jinesh_HW1/Prob2.py | 870 | 4.21875 | 4 | import math
def travel_time():
distance_from_planet = float(input("Enter distance from planet in light years: ")) #gets user input for light year distance
speed_of_craft = float(input("please enter speed as a fraction of c: ")) #gets speed of craft in terms of c from user
stationary_observer_time_years = distance_from_planet/speed_of_craft #calculates time according to stationary observer
moving_observer_time_years = stationary_observer_time_years*math.sqrt(1 - pow(speed_of_craft, 2.0)) #Time dilation equation solved for observer's time
print("It will take ", stationary_observer_time_years, " years according to the stationary observer's reference frame.") #output for stationary observer
print("It will take ", moving_observer_time_years, " years according to the travelling observer's reference frame.") #output for moving observer
| true |
a037cc7c52fa60741d40e9ac8f715b9e3bd7cc02 | carolinemascarin/LPTHW | /ex5.py | 714 | 4.21875 | 4 | #Exercise 5
myname = 'Caroline Mascarin'
myage = 27
myheight = 175
myeyes = 'Black'
myteeth = 'White'
myhair = 'Brown'
print "Lets talk about %s." % myname
print "She is %d centimeters tall" %myheight
print "She's got %s eyes and %s hair" % (myeyes, myhair)
print "if I add %d and %d I get %d" % (myage, myheight, myage + myheight)
print "my name is %s" % myname
print "my name is %r" % myname
print "my age is %o" % myage
""" 4. Try to write some variables that convert the inches and pounds to centimeters and kilos.
Do not just type in the measurements. Work out the math in Python. """
#converting km to pounds
x = 20 #kg
y = 2.2 # pounds
print x * y
#converting cm to inch
x = 175 #cm
y = 2.54 #inch
print x / y
| true |
99af0848e395225fbdfa555324a93e1f03ede662 | nlscng/ubiquitous-octo-robot | /p100/problem-196/MostOftenSubtreeSumBST.py | 1,563 | 4.125 | 4 | # This problem was asked by Apple.
#
# Given the root of a binary tree, find the most frequent subtree sum. The subtree sum of a node is the sum of all values under a node, including the node itself.
#
# For example, given the following tree:
#
# 5
# / \
# 2 -5
# Return 2 as it occurs twice: once as the left leaf, and once as the sum of 2 + 5 - 5.
"""
Another variation of BST traversal that should benefit from bubbling things back up to root.
"""
from common.treenode.MyBST import IntNode
from collections import defaultdict
def most_frequent_sum_bst(root: IntNode) -> int:
# This should be O(n) in time and space, n being the number of nodes in the tree, since we visit
# each node one time before passing back up.
assert root
counts: defaultdict = defaultdict(int) # a dictionary of sum:count key-value pairs
def traverse(node: IntNode) -> int:
left_sum = traverse(node.left) if node.left is not None else 0
right_sum = traverse(node.right) if node.right is not None else 0
my_sum = node.val + left_sum + right_sum
counts[my_sum] += 1
return my_sum
traverse(root)
return max([v for (k, v) in counts.items()])
c = IntNode(-5)
b = IntNode(2)
a = IntNode(5, b, c)
# assert most_frequent_sum_bst(a) == 2
# -3
# -2 -1
# 4 1 2 2
# 4 1 2 2, 3, 3, 3
g = IntNode(2)
f = IntNode(2)
e = IntNode(1)
d = IntNode(4)
c = IntNode(-1, f, g)
b = IntNode(-2, d, e)
a = IntNode(-3, b, c)
assert most_frequent_sum_bst(a) == 3, "Actual: {}".format(most_frequent_sum_bst(a))
| true |
43dc120d758dd3a1d5c60582ce1df81c0a6a8459 | nlscng/ubiquitous-octo-robot | /p100/problem-188/PythonFunctionalDebug.py | 782 | 4.15625 | 4 | # This problem was asked by Google.
#
# What will this code print out?
#
# def make_functions():
# flist = []
#
# for i in [1, 2, 3]:
# def print_i():
# print(i)
# flist.append(print_i)
#
# return flist
#
# functions = make_functions()
# for f in functions:
# f()
# How can we make it print out what we apparently want?
##Google
# Very interesting problem, worthy of the google sticker, although in the end it's so simple
def make_functions():
flist = []
for i in [1, 2, 3]:
def print_i(statement):
# Remember none of the func body is executed in declaration
print(statement)
flist.append((print_i, i))
return flist
functions = make_functions()
for f, a in functions:
f(a)
| true |
62ebf7681cc0f040b0ccb64d4c2218a1d2c5c7ad | nlscng/ubiquitous-octo-robot | /p000/problem-98/WordSearchPuzzle.py | 2,521 | 4.21875 | 4 | # This problem was asked by Coursera.
#
# Given a 2D board of characters and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those
# horizontally or vertically neighboring. The same letter cell may not be used more than once.
#
# For example, given the following board:
#
# [
# ['A','B','C','E'],
# ['S','F','C','S'],
# ['A','D','E','E']
# ]
# exists(board, "ABCCED") returns true, exists(board, 'SEE') returns true, exists(board, "ABCB") returns false.
def snake_word_search(board: list, word: str) -> bool:
# This is dfs looking for the first character match in given word, if found, we dfs explore and find following
# matches.
# Assume width of the board is n, height of the board is m, and size of target word is s, then this solution is
# O(n*m) in time and O(s) in space
if not board or not word:
return False
def find_neighbor_locs(bd: list, row: int, col: int) -> list:
res = []
width, height = len(bd[0]), len(bd)
if row > 0:
res.append((row - 1, col))
if col > 0:
res.append((row, col - 1))
if row < height - 1:
res.append((row + 1, col))
if col < width - 1:
res.append((row, col + 1))
return res
def explore_and_mark(bd: list, target: str, row: int, col: int, visited: set) -> bool:
if len(target) == 0:
return True
neighbor_locs = find_neighbor_locs(bd, row, col)
for neighbor_r, neighbor_c in neighbor_locs:
if (neighbor_r, neighbor_c) not in visited and bd[neighbor_r][neighbor_c] == target[0]:
visited.add((neighbor_r, neighbor_c))
if explore_and_mark(bd, target[1:], neighbor_r, neighbor_c, visited):
return True
return False
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == word[0]:
visited = {(r, c)}
found = explore_and_mark(board, word[1:], r, c, visited)
if found:
return True
return False
test_board = [
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
]
assert not snake_word_search([], 'some')
assert not snake_word_search(test_board, '')
assert snake_word_search(test_board, 'ABCCED')
assert snake_word_search(test_board, 'SEE')
assert not snake_word_search(test_board, 'ABCB')
| true |
70bf93d87d438fffa829d69fb3b1eb615a5322a0 | nlscng/ubiquitous-octo-robot | /p000/problem-88/DivisionWithoutOperator.py | 546 | 4.21875 | 4 | # This question was asked by ContextLogic.
#
# Implement division of two positive integers without using the division, multiplication, or modulus operators.
# Return the quotient as an integer, ignoring the remainder.
def raw_division(n: int, m: int) -> int:
if n < m:
return raw_division(m, n)
quot, cur_sum = 0, 0
while cur_sum <= n:
quot += 1
cur_sum += m
return quot - 1
assert raw_division(1, 1) == 1
assert raw_division(2, 1) == 2
assert raw_division(10, 3) == 3
assert raw_division(11, 7) == 1 | true |
5a75a95a3a659a9a970c94aebfc13950730718a1 | nlscng/ubiquitous-octo-robot | /p000/problem-6/XorLinkedList.py | 1,961 | 4.1875 | 4 | # An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev
# fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR
# linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at
# index.
#
# If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and
# dereference_pointer functions that converts between nodes and memory addresses.
##Google
def get_pointer(object):
return 1234
def dereference_pointer(address):
return 4321
class XorLinkedListNode:
# I guess this xor linked list rely on the special fact
# that A xor B = C => A xor C = B, B xor C = A
def __init__(self, value: int, prev_add):
self.value = value
self.ptr = prev_add ^ 0
def set_pointer(self, new_ptr):
self.ptr = new_ptr
class XorLinkedList:
def __init__(self):
self.head = None
self.tail = None
def add(self, value):
if self.head is None:
self.head = XorLinkedListNode(value, 0)
else:
node = self.head
prev_add = 0
while node.ptr is not None:
cur_add = get_pointer(node)
node = dereference_pointer(prev_add ^ node.ptr)
prev_add = cur_add
new_node = XorLinkedListNode(value, get_pointer(node))
node.set_ptr(prev_add ^ get_pointer(new_node))
def get(self, index):
if index <= 0:
return None
node = self.head
prev_add = 0
while node.ptr is not None and index > 0:
cur_add = get_pointer(node)
node = dereference_pointer(prev_add ^ cur_add)
prev_add = cur_add
index -= 1
return node.value
# hmm, how do I test this with the fake get_pointer and dereference ...
| true |
ede2ca2fec4c1156fb877811d1f5274749299ea2 | nlscng/ubiquitous-octo-robot | /p000/problem-58/SearchInRotatedSortedArray.py | 1,415 | 4.15625 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Amazon.
#
# An sorted array of integers was rotated an unknown number of times.
#
# Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't
# exist in the array, return null.
#
# For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array).
#
# You can assume all the integers in the array are unique.
'''
left ... mid ... right
b: > left or < mid => left, else go right
b: > left and < mid go left, go right
so both scenario relies on the value of left to decide which half to go
'''
def rotated_binary_search(nums: list, k: int) -> int:
# GG: this is a very interesting binary search exercise
if not nums:
return None
if len(nums) < 2 and nums[0] != k:
return None
left = 0
right = len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] == k:
return mid
if k >= nums[left]:
right = mid
else:
left = mid
return None
assert rotated_binary_search([], 3) is None
assert rotated_binary_search([1], 3) is None
assert rotated_binary_search([1], 1) == 0
assert rotated_binary_search([1, 3], 3) == 1
assert rotated_binary_search([12, 18, 25, 2, 8, 10], 8) == 4
| true |
c6d5c270f8a215c1b8d8060d15e4073d6339a8bb | nlscng/ubiquitous-octo-robot | /p000/problem-68/AttackingBishop.py | 1,467 | 4.28125 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Google.
#
# On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops
# that have another bishop located between them, i.e. bishops can attack through pieces.
#
# You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the
# number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered
# the same as (2, 1).
#
# For example, given M = 5 and the list of bishops:
#
# (0, 0)
# (1, 2)
# (2, 2)
# (4, 0)
# The board would look like this:
#
# [b 0 0 0 0]
# [0 0 b 0 0]
# [0 0 b 0 0]
# [0 0 0 0 0]
# [b 0 0 0 0]
# You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4.
def find_attacking_bishops(board_width: int, bishop_locs: list):
count = 0
for i in range(len(bishop_locs)):
for j in range(i+1, len(bishop_locs)):
if abs(bishop_locs[i][0] - bishop_locs[j][0]) == abs(bishop_locs[i][1] - bishop_locs[j][1]):
count += 1
return count
assert find_attacking_bishops(5, [(0, 0), (1, 2), (2, 2)]) == 1, \
"actual: {}".format(find_attacking_bishops(5, [(0, 0), (1, 2), (2, 2)]))
assert find_attacking_bishops(5, [(0,0), (1,2), (2,2), (4,0)]) == 2, \
"actual: {}".format(find_attacking_bishops(5, [(0,0), (1,2), (2,2), (4,0)]))
| true |
5b4735c804aafaa74f3a0461bc53fb5befbc6093 | chandrikakurla/implementing-queue-with-array-space-efficient-way-in-python- | /qu_implement queue using array.py | 2,962 | 4.1875 | 4 | #class to implement queue
class Queue:
def __init__(self,size):
self.queue=[None] *size
self.front=-1
self.rear=-1
self.size=size
#function to check empty stack
def isEmpty(self):
if self.front==-1 and self.rear==-1:
return True
else:
return False
#function to check full stack
def isFull(self):
#if next of rare is front then stack is full
if ((self.rear+1)%(self.size))==self.front:
print("queue is full")
return True
else:
return False
#function to insert element into queue in rear side
def Enqueue(self,data):
if self.isFull():
return
elif (self.isEmpty()):
self.front=0
self.rear=0
self.queue[0]=data
else:
#increment rear
#use of array in circular fashion to effeciently use space in array
self.rear=(self.rear+1)%(self.size)
self.queue[self.rear]=data
#function to remove element from front
def Dequeue(self):
if (self.isEmpty()):
print("queue is empty")
return
#if queue contains single element after removing make queue empty
elif self.front==self.rear:
temp=self.queue[self.front]
self.front=-1
self.rear=-1
return temp
else:
temp=self.queue[self.front]
#update front of queue
self.front=(self.front+1)%(self.size)
return temp
#function to return front element of queue
def Front(self):
if self.isEmpty():
print("Queue is empty")
else:
print("Front item is", self.queue[self.front])
#function to return last element of queue
def Rear(self):
if self.isEmpty():
return
else:
print("rear item is",self.queue[self.rear])
#function to print elements of queue in inserted order
def print_queue(self):
if self.isEmpty():
print("queue is empty")
return
if self.front==0 and self.rear==0:
print(self.queue[0])
return
current=self.front
print("front element is"+str(self.queue[current]))
while(True):
print(self.queue[current])
current=(current+1)%(self.size)
if(current==self.rear):
print(self.queue[current])
break
if __name__=="__main__":
que=Queue(10)
que.Enqueue(1)
que.Enqueue(2)
que.Enqueue(3)
que.Enqueue(4)
que.Enqueue(5)
que.print_queue()
print("dequed element is"+str(que.Dequeue()))
print("dequed element is"+str(que.Dequeue()))
que.print_queue()
que.Front()
que.Rear()
| true |
041e238b857fa33960c8f51c95e21d5fd2e4cf0d | lindajaracuaro/My-Chemical-Polymorphism | /My chemical polymorphism.py | 782 | 4.28125 | 4 | # Chemical polymorphism! In this program you'll have fun using chemistry and polymorphism. Add elements and create molecules.
class Atom:
def __init__(self, label):
self.label = label
def __add__(self, other):
# Return as a chemical composition
return self.label + other.label
def __repr__(self):
return self.label
class Molecule:
def __init__(self, atoms):
if type(atoms) is list:
self.atoms = atoms
def __repr__(self):
# Return as a list of molecules
return self.atoms
sodium = Atom("Na")
chlorine = Atom("Cl")
# Salt chemical composition using label AND using Polymorphism
salt_pol = sodium + chlorine
print(salt_pol)
# Salt Molecule as a list
salt = Molecule([sodium, chlorine])
print(salt.atoms) | true |
6b0f193dc597b8d5f02db807376a3a7f4f39bcdd | rowens794/intro-to-cs | /ps1/ps1.py | 599 | 4.125 | 4 |
portion_down_payment = .25
r = .04
annual_salary = float(input('what is your annual salary? '))
portion_saved = float(input('what portion of your salary will you save? '))
total_cost = float(input('how much does your dream house cost? '))
current_savings = 0
months = 0
print('pre loop')
print(current_savings)
print(total_cost * portion_down_payment)
while current_savings < total_cost * portion_down_payment:
months = months + 1
current_savings = current_savings + current_savings * \
r / 12 + annual_salary / 12 * portion_saved
print('in loop')
print(current_savings)
| true |
f18337a4c73ad850e323599b21a91263b75ce1d9 | JKH2124/jnh-diner-project-py | /diner_project.py | 2,157 | 4.40625 | 4 | # J & K's Diner
dinnerMenu = ['STEAK', '15', 'CHICKEN', '12', 'PORK', '11', 'SALAD', '12']
sidesMenu = ['FRIES', 'RICE', 'VEGGIES', 'SOUP', '1']
dinnerSelect = input("Please select an entree: ").upper()
if dinnerSelect == dinnerMenu[0]:
print("Excellent choice! The price for that entree is {}".format(dinnerMenu[1]))
input("And how would you like your steak?")
dinner_main = [dinnerMenu[0], dinnerMenu[1]]
elif dinnerSelect == dinnerMenu[2]:
print("Wonderful! The price for that entree is {}".format(dinnerMenu[3]))
dinner_main = [dinnerMenu[2], dinnerMenu[3]]
elif dinnerSelect == dinnerMenu[4]:
print("Tasty! The price for that entree is {}".format(dinnerMenu[5]))
dinner_main = [dinnerMenu[4], dinnerMenu[5]]
elif dinnerSelect == dinnerMenu[6]:
print("One of our most popular! The price for that entree is {}".format(dinnerMenu[7]))
dinner_main = [dinnerMenu[6], dinnerMenu[7]]
else:
print("Please make a valid selection")
sidesSelect = input("You also have your choice of two sides to go with your meal. What is the first side you would like? ").upper()
if sidesSelect == sidesMenu[0] or sidesSelect == sidesMenu[1] or sidesSelect == sidesMenu[2] or sidesSelect == sidesMenu[3]:
print("Ok.")
first_side_price = sidesMenu[4]
else:
print("We currently do not offer that on our menu.")
sidesSelect = input("And what would you like for your second side?").upper()
if sidesSelect == sidesMenu[0]:
print("Very good! The price for those sides is {}".format(sidesMenu[4]))
side_price = sidesMenu[4]
elif sidesSelect == sidesMenu[1]:
print("Super! The price for those sides is {}".format(sidesMenu[4]))
side_price = sidesMenu[4]
elif sidesSelect == sidesMenu[2]:
print("Nice! The price for those sides is {}".format(sidesMenu[4]))
side_price = sidesMenu[4]
elif sidesSelect == sidesMenu[3]:
print("Sounds good! The price for those sides is {}".format(sidesMenu[4]))
side_price = sidesMenu[4]
else:
print("We currently do not offer that on our menu.")
dinnerTotal = int(dinner_main[1]) + int(side_price) + int(first_side_price)
print("The total cost for your dinner comes to {}".format(dinnerTotal)) | true |
e645165c06b68fadc275ab51ed701a00887f5688 | Gaurav-Pande/DataStructures | /leetcode/graphs/add_search_trie.py | 1,636 | 4.15625 | 4 | # link: https://leetcode.com/problems/add-and-search-word-data-structure-design/
class TrieNode(object):
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.is_word=False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
current = self.root
for letter in word:
current = current.children[letter]
current.is_word=True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
current = self.root
self.result = False
self.dfs(current, word)
return self.result
def dfs(self,current, word):
if not word:
if current.is_word:
self.result = True
return
else:
if word[0] == '.':
for children in current.children.values():
self.dfs(children, word[1:])
else:
current = current.children.get(word[0])
if not current:
return
self.dfs(current,word[1:])
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word) | true |
5cc638d480d73a33a413a565f0375a43e51f1606 | DeekshaKodieur/python_programs | /python/factorial_num.py | 263 | 4.3125 | 4 | fact=1
num=int(input("Enter the number to find its factorial : "))
#for i in range(1,(num+1)):
#fact = fact * i
i=1
while(i<=num):
fact = fact * i
i = i+1
print("Factorial of a number",num,"is",fact)
input("press enter to exit")
| true |
8f6cf04a3d8692607547aa336b7e4f1d370cdb2f | kazinayem2011/python_problem_solving | /reverse_number.py | 209 | 4.21875 | 4 | number=int(input("Please Enter Your Number : "))
reverse=0
i=0
while i<number:
last_num=number%10
reverse=(reverse*10)+last_num
number=number//10
print("The Reverse of numbers are : ", reverse) | true |
768a3e44b3d7e5389f0f30c459ff852808e02642 | Adriannech/phyton-express-course | /Greatest_no#.py | 693 | 4.46875 | 4 | print("Description: This program will pick the biggest value from string of numbers")
nums = input("Please input number (coma separated):")
nums = nums.split(",")
if len(nums) == 0:
print("There's no input numbers")
exit(0)
for i in range(len(nums)):
if not nums[i].is_numeric():
nums[i] = float(nums[i])
max_num = nums[0]
for num is nums:
if num > max_num:
max_num = num
print(f"Max value: {max_num}")
number1 = input("Please enter first number:")
number2 = input("Please enter second number:")
number1 = float(number1)
number2 = float(number2)
if number1 > number2:
max_number = number1
info = "first number is greater than second number" | true |
6dc92fcd7d63fded3c67a6ea9a5ae6d8abd8f5ee | Li-congying/algorithm_python | /LC/String/string_compression.py | 2,062 | 4.21875 | 4 | '''
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2:
Input:
["a"]
Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
Explanation:
Nothing is replaced.
Example 3:
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
Note:
All characters have an ASCII value in [35, 126].
1 <= len(chars) <= 1000.
'''
class Solution(object):
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
total = 0
cur_char = ''
cur_count = 0
chars.append('')
for char in chars:
if cur_char != char:
# print cur_char, cur_count
chars[total] = cur_char
if cur_count == 1:
total += 1
if cur_count > 1:
str_c = str(cur_count)
for i in range(len(str_c)):
chars[total+1+i] = str_c[i]
total += (1+len(str(cur_count)))
cur_char = char
cur_count = 0
cur_count += 1
print chars[:total]
return total
obj = Solution()
print obj.compress(["a","b","b","b","b","b","b","b","b","b","b","b","b"]) | true |
89bb52bd6f25cd45531546efc8b5474f6a57ab56 | gittygupta/Python-Learning-Course | /Tutorials/error_exception.py | 650 | 4.25 | 4 | # Exception handling
while True:
try:
x = int(input('Enter your fav number: \n'))
print(8/x) # it can cause a ZeroDivisionError
break
except ValueError: # "ValueError" means an exception
print("ok dude you gotta try again")
except ZeroDivisionError:
print("Dude dont use 0")
except:
# this basically exits your program. Used in a wider angle to handle exceptions. Takes all exceptions
break
finally: # the prog executes this line every time no matter what exception it encounters
print("sorry dude you're dumb")
| true |
ddcd9d1fb9864438fdb3a1017b7798c2beca0311 | gittygupta/Python-Learning-Course | /Tutorials/download_image.py | 577 | 4.125 | 4 | import urllib.request
import random
def download_image_file(url):
name = random.randrange(1, 1000)
full_name = str(name) + ".png"
urllib.request.urlretrieve(url, full_name) # used to retrive url to download the image
# it also stores the name of the file and saves the image in the same directory as the program
# .jpg / .png is written at the end of full_name because python stores images as numbers
download_image_file("https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Sunflower_from_Silesia2.jpg/800px-Sunflower_from_Silesia2.jpg") | true |
95c3a925e8eb187fadaeffb4c6daef30b1f0af77 | jmachcse/2221inPython | /newtonApproximation.py | 905 | 4.40625 | 4 | # Jeremy Mach
# Function to approximate a square root using Newton's algorithm
def sqrt(x):
estimate = float(x)
approximation = 1.0
while abs(approximation - (estimate / approximation)) > (0.0001 * approximation):
approximation = 0.5 * (approximation + (float(x) / approximation))
# When the approximation is less than 0.0001 * approximation,
# the approximation will be returned as the guess for the square root
return approximation
userAns = input("Would you like to calculate a square root? : ")
while userAns == "Y" or userAns == "y":
userNum = input(
"Please enter the number you would like to calculate the square root of: ")
float(userNum)
sqrt = sqrt(userNum)
print("The square root of your number using Newton Iteration is " + str(sqrt))
userAns = input("Would you like to calculate another square root? (Y/N): ")
print("Goodbye!")
| true |
18bdaade58490386dcfc47784443ad2c3f871af6 | K-Maruthi/python-practice | /variables.py | 635 | 4.3125 | 4 | # variables are used to assign values , variables are containers for storing values
x = 7
y = "Hello World"
print(x)
print(y)
#multiple values to multiple variables (no.of variables should be = no.of values)
a,b,c = "orange",22,34.9
print(a)
print(b)
print(c)
# mutliple variables same value
p=q=r=2
print(p)
print(q)
print(r)
#unpack a collection
colours = ["blue","Red","white","black"]
x,y,z,memine= colours
print(x)
print(y)
print(z)
print(memine)
#global variables created outside of a function and can be used globally
x = "awesome"
def myfunc():
x = "fantastic"
print("python is " +x)
myfunc()
print("python is " +x)
| true |
f20631d07fb9ce2dfcbb9c79114d497f9920011a | anhnguyendepocen/100-pythonExercises | /66.py | 369 | 4.15625 | 4 | # Exercise No.66
# Create an English to Portuguese translation program.
# The program takes a word from the user and translates it using the following dictionary as a vocabulary source.
d = dict(weather="clima", earth="terra", rain="chuva")
# Solution
def translate(w):
return d[w]
word = input("Enter the word 'earth'/'weather'/'rain': ")
print(translate(word))
| true |
af7d4d3637bf4ad38004e1fc1eae269ec73698cf | jeremy-wickman/combomaximizer | /combinationmaximizer.py | 913 | 4.375 | 4 | # A Python program to print all combinations of items in a list, and minimize based on target
#Import
from itertools import combinations
import pandas as pd
#Set your list of numbers and the target value you want to achieve
numbers = [49.07, 122.29, 88.53, 73.02, 43.99]
target = 250
combo_list = []
#Create a list of combinatorial tuples
for i in range(len(numbers)):
comb=combinations(numbers,i+1)
combs = list(comb)
combo_list.extend(combs)
#Create a list of the sums of those tuples
combo_sum = [sum(tup) for tup in combo_list]
#Create a dataframe with them both
df = pd.DataFrame({'Combo': combo_list, 'Sum': combo_sum})
#Add a column showing the difference between the target and the sum
df['Difference']=target-df['Sum']
#Remove all rows which go over the target price is right style
df = df[df['Difference']>=0]
df = df.sort_values(by='Difference', ascending=True)
df
| true |
6c3f8a7b460c383133353a966a5aea62b71db49c | sunilmummadi/Hashing-1 | /groupedAnagram.py | 1,572 | 4.15625 | 4 | # Leetcode 149. Group Anagrams
# Time Complexity : O(nk) where n is the size of the array and k is the size of each word in the array
# Space Complexity : O(nk) where n is the size of the array and k is the size of each word in the array
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Assign first 26 prime numbers to a letter. The product of prime numbers is unique.
# All the annagrams will have same product.
# Using a hashmap we can store the product as key and anagrams list as value. Iterate through hashmap and append
# the anagrams to the list if the product is already present. Else add it. Return hashmap values as a list
# Your code here along with comments explaining your approach
class Solution:
# Function to calcuate character prime product
def calculatePrime(self, word):
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
count = 1
for letter in word:
# ascii value of the letter - ascii value of a i.e 97 gives index of prime number for that letter
index = ord(letter)-ord('a')
count = primes[index]*count
return count
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashmap = dict()
for word in strs:
temp = self.calculatePrime(word)
if temp not in hashmap:
hashmap[temp] = []
hashmap[temp].append(word)
return list(hashmap.values())
| true |
c661a44b75f35b7599fe3964f8808e57acbd5ed8 | AlanOkori/Metodos-Numericos | /FuncPar.py | 219 | 4.125 | 4 | def even(Num):
if Num % 2 == 0 :
print("Is an even number.")
else :
print("Isn't an even number.")
x = int(input("Please, insert a number: "))
even(x)
input("Press key to continue.") | true |
296c0ee856471edba71b14b43931c1219abf4ea2 | sacobera/practical-python-project | /movie_schedule.py | 601 | 4.1875 | 4 | current_movies = {'The Grinch' : "11:00 am",
'Rudolph' : "1:00 pm",
'Frosty the snowman' : "3:00 PM",
'Christmas Vacation': "5:00 PM"}
print ("We're showing the following movies:")
for key in current_movies: #this loops over the list of objects
print(key)
movie = input("what movie would you like the showtime for?\n")
showtime = current_movies.get(movie) #if the movie exists, it will get the movie from the list
if showtime == None:
print("Requested showtime isn't playing")
else:
print(movie, "is playing at", showtime )
| true |
78cbcdd59219ad25f80c5ee6a7ae9dc9cf4d9d51 | Gindy/Challenges-PCC | /Challenges_PCC/Playing_cards/Playing_cards_3-1.py | 1,196 | 4.28125 | 4 | # A standard deck of cards has four suites: hearts, clubs, spades, diamonds.
# Each suite has thirteen cards:
# ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen and king
cards = []
suits = ['Hearts']
royals = ["Jack", "Queen", "King", "Ace"]
deck = []
# We start with adding the numbers 2 through 10.
# Since there are only 4 royals and 9 'regular card'
# Which makes 13 card in total per suit.
def Creating_deck():
for i in range(2, 11):
cards.append(str(i))
# Added the roys to to list
for r in range(4):
cards.append(royals[r])
# Now we attach the suits
for r in range(1):
for c in range(13):
card = (cards[c] + " of " + suits[r])
# Let's add the cards to the deck
deck.append(card)
# Perfect we have a full deck of cards
# print(deck)
# Now we get to the actual assignment, namely printing the list
# and show the heart cards
# Actually, only printing the first 3 cards is already adequate
print("The first 3 items in the list:", deck[:3])
# You can print them as 'strings' as well:
print("The first 3 cards printed as strings: ")
for item, value in enumerate(deck):
if item == 3:
break
print(value)
Creating_deck() | true |
5a55a167f68f2c9cdb2431d6b6f17f6edab23fec | athwalh/py4e_ch9_solutions | /ex_94.py | 897 | 4.125 | 4 | #Exercise 4: Add code to the above program to figure out who has the most messages in the
#file. After all the data has been read and the dictionary has been created, look
#through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum loops) to
#find who has the most messages and print how many messages the person has.
f1 = input("Enter File: ")
emails = []
counts = dict()
maxima = None
try:
fhand = open(f1)
except:
print("File could not be processed")
exit()
for line in fhand:
line = line.rstrip()
if not line.startswith("From "): continue
word = line.split()
emails.append(word[1])
for mail in emails:
if mail not in counts:
counts[mail] = 1
else:
counts[mail] += 1
for key in counts:
if maxima is None or counts[key] > maxima :
maxima = counts[key]
largestMail = key
print(largestMail,maxima)
| true |
7bbf4efdaa89805899f195843f69704c034f7eb5 | AadityaDeshpande/TE-Assignments | /SDL/pallindrome.py | 366 | 4.4375 | 4 | #input a string and check it is pallindrome or not
#enter a word in a input and submit..!!
s=input("Enter the string that is to be checked:")
print(s)
a=s
t=False
lnth=len(a)
z=lnth-1
for i in range(len(a)):
if a[z]!=a[i] or z<0:
print("given string is not pallindrome")
t=True
break
z=z-1
if t==False:
print("Given string is pallindrome..!!")
| true |
9172ed8eb8747a678eb0809c3024adba350657bc | phuclhv/DSA-probs | /absolute_value_sort.py | 828 | 4.28125 | 4 | '''
Absolute Value Sort
Given an array of integers arr, write a function absSort(arr), that sorts the array according to the absolute values of the numbers in arr. If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers.
Examples:
input: arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]
Constraints:
[time limit] 5000ms
[input] array.integer arr
0 ≤ arr.length ≤ 10
[output] array.integer
'''
from functools import cmp_to_key
def absSort(arr):
def compare_abs(value1, value2):
if abs(value1) <= abs(value2):
return -1
return 1
compare_abs_key = cmp_to_key(compare_abs)
arr.sort(key=compare_abs_key)
return arr
arr = [2, -7, -2, -2, 0]
print(absSort(arr)) | true |
c7c65f4e20a88881f77348987187501afd310887 | jdst103/OOP-basics | /animal_class.py | 1,469 | 4.125 | 4 | # class Animal():
# # characterstics
# def __init__(self, name, legs, eyes, claws, tasty): # if we dont follow order, use dictionary to define.
# self.name = name
# self.legs = legs
# self.eyes = eyes
# self.claws = claws
# self.tasty = tasty
class Animal():
# characterstics
def __init__(self, name, legs): #if we dont follow order, use dictionary to define.
self.name = name
self.legs = legs
# behaviours - methods
# methods - which are like functions that belong to a class
# what it would be called
def eat(self, food=''): # makes the arguement optional
return 'nom' * 3 + food
def sleep(self):
return 'zzzz'
def potty(self):
return 'O_0 ...... HUMMMM!!!! ---- O_o ---- SPLOSH!'
def hunt(self):
return 'ATTACK'
# Let us create an instance of an Animal object, (also lets assign it to a variable)
animal_1 = Animal('Randy Marsh', 10, )
animal_2 = Animal('Cartman', 8, )
#checking attributes
# print(animal_1) #when run the instance changes every time (look at the number) # cant do much with it
# print(type(animal_1))
#
# print(animal_1.legs) #how tasty it is
# print(animal_2.legs)
# call methods on object of class Animal:
# print(animal_1.eat('chicken and salad'))
# print(animal_1.eat('dunno'))
# print(animal_1.sleep())
# print(animal_1.hunt())
# print(animal_1.potty()) | true |
103e97a7fe67e1ead44bc00582b08e3013962273 | sungfooo/pythonprojects | /hello.py | 528 | 4.5 | 4 | print "hello"
variable = "value of the variable"
data types
#integers
123421
#float (with decimal)
123.23
#boolean
True
False
#array (group of data types)
[1,True,"string"]
#dictionary or object
#{""}
#for loop - can be used to loop through arrays or objects one element at a time
#for x_element in x_array_or_object:
#example v
roommates = ["callie", "gary", "ari", "katie", "tim", "peter"]
for x in roommates:
print x[::-1]
def dogger(arg):
arg = arg+"dog"
print arg
for x in roommates:
dogger(x)
| true |
0e50dbf6b86984d6782b1940797eb9276c41f476 | anandjn/data-structure_and_algorithms | /algorithms/sorting/bubble_sort.py | 505 | 4.3125 | 4 | '''implementing bubble sort
TASK TIME-COMPLEXITY
1) bubbleSort O(n**2) '''
def bubbleSort(array):
#repeat below steps until there seems no change
for _ in range(len(array)):
#keep swapping
for i in range(len(array)-1):
#if first number is greater than second then swap them
if array[i] > array[i+1]:
temp = array[i]
array[i] = array[i+1]
array[i+1] = temp
return(array)
print(bubbleSort([10,12,23,40,55,2,4,5,6]))
| true |
46b83ee44a8a4645bfd9eff99dfa87be1591d587 | jihoonyou/problem-solving | /Educative/subsets/example1.py | 676 | 4.125 | 4 | """
Problem Statement
Given a set with distinct elements, find all of its distinct subsets.
Example 1:
Input: [1, 3]
Output: [], [1], [3], [1,3]
Example 2:
Input: [1, 5, 3]
Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3]
"""
def find_subsets(nums):
subsets = [[]]
for current_num in nums:
length = len(subsets)
for i in range(length):
new_set = list(subsets[i])
new_set.append(current_num)
subsets.append(new_set)
return subsets
def main():
print("Here is the list of subsets: " + str(find_subsets([1, 3])))
print("Here is the list of subsets: " + str(find_subsets([1, 5, 3])))
main()
| true |
271fe07e5cd53ad165806d4848de1913ad66354c | sashank17/MyCaptain-Python-Tasks | /task5 - function most frequent.py | 362 | 4.125 | 4 | def most_frequent(string):
string = string.lower()
letters1 = {}
for letter in string:
c = string.count(letter)
letters1[letter] = c
letters = sorted(letters1.items(), key=lambda x: x[1], reverse=True)
for i in letters:
print(i[0], "=", i[1])
str1 = input("Please enter a string: ")
most_frequent(str1)
| true |
9e4246031adc055ca31af9e82ed617cd3942f9a2 | BeijiYang/codewars | /7kyu/special_number.py | 1,763 | 4.40625 | 4 | '''
Definition
A number is a Special Number *if it’s digits only consist 0, 1, 2, 3, 4 or 5 *
Task
Given a number determine if it special number or not .
Warm-up (Highly recommended)
Playing With Numbers Series
Notes
The number passed will be positive (N > 0) .
All single-digit numbers with in the interval [0:5] are considered as special number.
Input >> Output Examples
1- specialNumber(2) ==> return "Special!!"
Explanation:
It's a single-digit number within the interval [0:5] .
2- specialNumber(9) ==> return "NOT!!"
Explanation:
Although ,it's a single-digit number but Outside the interval [0:5] .
3- specialNumber(23) ==> return "Special!!"
Explanation:
All the number's digits formed from the interval [0:5] digits .
4- specialNumber(39) ==> return "NOT!!"
Explanation:
Although , there is a digit (3) Within the interval But the second digit is not (Must be ALL The Number's Digits ) .
5- specialNumber(59) ==> return "NOT!!"
Explanation:
Although , there is a digit (5) Within the interval But the second digit is not (Must be ALL The Number's Digits ) .
6- specialNumber(513) ==> return "Special!!"
7- specialNumber(709) ==> return "NOT!!"
For More Enjoyable Katas
ALL translation are welcomed
Enjoy Learning !!
'''
# solution 1
def is_specialNum(num):
return num in [0, 1, 2, 3, 4, 5]
def special_number(num):
numList = list(map(int, str(num)))
for num in numList:
if not is_specialNum(num):
return 'NOT!!'
return 'Special!!'
# solution 2
sepcial_set = set('012345')
def special_number(num):
return 'Special!!' if set(str(num)) <= sepcial_set else 'NOT!!'
print(
# specialNumber(123)
)
set('012345') # {'2', '3', '0', '4', '1', '5'}
set([0, 1, 2, 3, 4, 5]) # {0, 1, 2, 3, 4, 5}
| true |
da6c16ba70e42bf9fd1db6578b6a116563011989 | Hassanabazim/Python-for-Everybody-Specialization | /1- Python for Everybody/Week_4/2.3.py | 389 | 4.28125 | 4 | '''
2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
You should use input to read a string and float() to convert the string to a number.
'''
hrs = float(input("Enter Hours:"))
rph = float(input("Enter the rate per hour:"))
print ("Pay:",hrs * rph)
| true |
bf9348541d0a97db5d4c63cf34a01d65b43a5468 | NathanJiangCS/Algorithms-and-Data-Structures | /SPFA.py | 810 | 4.125 | 4 | #Python implementation of shortest path faster algorithm
#Implementation for weighted graphs. Graphs can have negative values
infinity = float('inf')
#a is the adjacency list representation of the graph
#start is the initial node, end is the destination node
def spfa(a, start, end):
n = len(a)
distances = [infinity for i in range(n)]
distances[start] = 0
q = [start]
while len(q):
currentNode = q.pop(0)
for i in a[currentNode]:
nextNode, distance = i
if distances[nextNode] > distances[currentNode] + distance:
distances[nextNode] = distances[currentNode] + distance
q.append(nextNode)
return distances, distances[end]
#This code does not check for a negative cycle which would result
#in an infinite loop
| true |
716028bbd232b3c1b1ab81a8592238fb9dfc733f | ArcticSubmarine/Portfolio | /Python/hangmans_game.py | 1,263 | 4.28125 | 4 | ##
# This file contains an implementation of the hangsman's game.
# The rules are the following :
# 1) the computer choses a word (max. 8 letters) in a pre-defined list ;
# 2) the player tries to find the letters of this word : at each try, he/she chose a letter ;
# 3) if the letter is in the word, the computer displays the word making the already found letters appearing. Those that haven't been found are replaced by stars (*).
# 4) the players have only 8 chances to find the letters or he/she lose the game ;
# 5) at the begining of the game, the player enters his/her name in order to save his/her score.
# The score is calculated as following : the number of plays resting at a winning party is added to his/her current scoring. For istance, if there are 3 tries left and that the player wins, 3 is added to his/her score.
# The file "datas.py" contains the datas such as the list of words, the number of authorized tries, etc.
# The file functions.py contains the useful functions for this application.
##
# Importation of the needed files and libraries
from datas import *
from functions import *
scores = HaveScores()
user = PlayerName()
if user not in scores.keys():
scores[user] = 0
Menu(user, scores)
| true |
afcd89a627b55a754ae64c577ed0e96c724f1873 | daicorrea/my-project | /book_me_up/helpers/date_time.py | 440 | 4.25 | 4 | # Function to verify if param day is weekday or weekend
def verify_weekday(date_to_verify):
# Using regular expression to get the day of the week inside the parentheses from the inputted data
day = date_to_verify[date_to_verify.find("(") + 1:date_to_verify.find(")")]
if day in ['mon', 'tues', 'wed', 'thur', 'fri']:
return 'week'
elif day in ['sat', 'sun']:
return 'weekend'
else:
return 'error' | true |
84661d9c5549561aaf66cef611e2454a9985492d | GemmaLou/selection | /selection dev 4.py | 547 | 4.125 | 4 | #Gemma Buckle
#03/10/2014
#selection dev 4 grade check
mark = int(input("Please enter your exam mark to receive your grade: "))
if 0<=mark<=40:
print("Your grade is U.")
elif 41<=mark<=50:
print("Your grade is E.")
elif 51<=mark<=60:
print("Your grade is D.")
elif 61<=mark<=70:
print("Your grade is C.")
elif 71<=mark<=80:
print("Your grade is B.")
elif 81<=mark<=100:
print("Your grade is A!")
else:
print("The mark you have entered is unacceptable. Please enter an integer between 0 and 100.")
| true |
d833663e075a6d781691dedb79757dce251f45f3 | lifewwy/myLeetCode | /Easy/566. Reshape the Matrix.py | 1,787 | 4.1875 | 4 | # Question:
#
# In MATLAB, there is a very useful function called 'reshape', which can reshape a
# matrix into a new one with different size but keep its original data.
#
# You're given a matrix represented by a two-dimensional array, and two positive
# integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
#
# The reshaped matrix need to be filled with all the elements of the original
# matrix in the same row-traversingorder as they were.
#
# If the 'reshape' operation with given parameters is possible and legal,
# output the new reshaped matrix; Otherwise, output the original matrix.
#
# Example 1:
#
# Input:
# nums =
# [[1,2],
# [3,4]]
# r = 1, c = 4
# Output:
# [[1,2,3,4]]
# Explanation:
# The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix,
# fill it row by row by using the previous list.
# Example 2:
#
# Input:
# nums =
# [[1,2],
# [3,4]]
# r = 2, c = 4
# Output:
# [[1,2],
# [3,4]]
# Explanation:
# There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
# Note:
#
# The height and width of the given matrix is in range [1, 100].
# The given r and c are all positive.
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if r*c!=len(nums)*len(nums[0]):
return nums
x = []
ret = []
for row in nums:
for i in row:
x.append(i)
if len(x) == c:
ret.append(x)
x = []
return ret
print(Solution().matrixReshape([[1,2], [3,4]], 1, 4))
| true |
b11ee4f8692487cba17e93f741642dde1e7439d5 | lifewwy/myLeetCode | /Easy/21. Merge Two Sorted Lists.py | 2,112 | 4.1875 | 4 |
# Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
#
# Example:
#
# Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
def println(l, N = 10):
if not l:
return
print(l.val, end='\t')
cursor = l.next
nCount = 1
while cursor != None and nCount < N:
nCount += 1
print(cursor.val, end='\t')
cursor = cursor.next
print()
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
# ①②③④⑤⑥⑦⑧⑨↖↑↗←→↙↓↘
class Solution(object):
def mergeTwoLists(self, l1, l2): # curr l1① → ③ → ④
# ⑧
# :type l1: ListNode # dummy l2② → ⑤
# :type l2: ListNode ---------------------------
# :rtype: ListNode
# curr① → l1③ → ④
curr = dummy = ListNode(8) # ⑧ ↗
while l1 and l2: # dummy l2② → ⑤
if l1.val < l2.val: # --------------------------
curr.next = l1
l1 = l1.next # ① l1③ → ④
else: # ⑧ ↗ ↓
curr.next = l2 # dummy curr② → l2⑤
l2 = l2.next # --------------------------
curr = curr.next
curr.next = l1 or l2 # ① curr③ → l1④
return dummy.next # ⑧ ↗ ↓ ↗
# dummy ② l2⑤
if __name__ == "__main__":
l1 = ListNode(1)
l1.next = ListNode(3)
l1.next.next = ListNode(4)
l2 = ListNode(2)
l2.next = ListNode(5)
l = Solution().mergeTwoLists(l1,l2)
print( l )
# println( l ) | true |
93f5cd0fbbcf5fdc5d568a6a8d2e5bed8154cbbe | trizzle21/advent_of_code_2019 | /day_1/day_1.py | 1,101 | 4.3125 | 4 | """
Day 1
> Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
> For example:
> For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
> For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
> For a mass of 1969, the fuel required is 654.
> For a mass of 100756, the fuel required is 33583.
> The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
"""
from math import floor
import logging
logging.basicConfig(level=logging.DEBUG)
def calculate(value):
return floor(value/3) - 2
def run():
with open('day_1_input.txt', 'r') as f:
values = f.readlines()
values = [int(value.strip()) for value in values]
return sum([calculate(v) for v in values])
if __name__ == '__main__':
total_fuel = run()
logging.debug(total_fuel)
| true |
09526c4fc46617c708a9199e4d9baafec3aaaf0c | Chris-Cameron/SNEL | /substitution.py | 470 | 4.21875 | 4 | #Helper Functions
#"Inverts" the ASCII values of the characters in the text file, so that those at the beginning go towards the end and vice-versa
def substitute(text):
new_message = ""
for t in text:
new_message += chr(158-ord(t)) #158 is 32+126, which is why it is used for the inversion
print(new_message)
#Main Code
with open("text_files/file_2715.txt", 'r') as f:
content = f.read()
substitute(content)
| true |
82342cf39fd4969586140838a68af53bf7996ee9 | mfarooq28/Python | /Convert_C2F.py | 452 | 4.5625 | 5 | # This program will convert the Celsius Temprature into Farenheit
user_response = input (" Please Enter the Celsius Temprature :")
celsius = float (user_response)
farenheit = ((celsius*9)/5)+32
print ("The Equivalent Farenheit Temprature is :", farenheit , "degrees farenheit. ")
if farenheit < 32 :
print ("It is freezing")
elif farenheit < 50:
print("It is chilly")
elif farenheit < 90 :
print("It is OK")
else :
print("It is hot")
| true |
b41f725cced2727a6b78fc29b0ad1b7feced471a | shubham-camper/Python-Course | /8. Lists.py | 476 | 4.4375 | 4 |
friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"] #this is the list we have created
print(friends)
print(friends[0]) #this will print out the first element of the list
print(friends[1:]) #this will print out 2nd till the last element of the list
print(friends[1:3]) #this will print out 2nd till the 4 element of the list
friends[1] = "Mike" #you can also creeate the list and change the element of the list later
print(friends[1]) | true |
bcc0bb8f659c22618267ed54d24129820d78022d | EvanGottschalk/CustomEncryptor | /SortDictionary.py | 1,322 | 4.46875 | 4 | # PURPOSE - This program is for sorting dictionaries
class SortDictionary:
# This function sorts a dict alphabetically and/or from least to greatest
def sortDictByKey(self, dictionary):
# Letter characters, numeric characters, and the remaining characters are
# separated into 3 different dicts, each to be sorted individually
letter_chars = {}
number_chars = {}
symbol_chars = {}
for char in dictionary:
if str(char).isnumeric():
number_chars[char] = dictionary[char]
elif str(char).isalnum():
letter_chars[char] = dictionary[char]
else:
symbol_chars[char] = dictionary[char]
sorted_dictionary = dict(sorted(letter_chars.items()))
sorted_dictionary.update(dict(sorted(number_chars.items())))
sorted_dictionary.update(symbol_chars)
del dictionary, letter_chars, number_chars, symbol_chars
return(sorted_dictionary)
# These two function calls serve as alternative ways to call the sortDictByKey function,
# in case a user forgets the original function name
def sortDict(self, dictionary):
self.sortDictByKey(dictionary)
def sortDictionaryByKey(self, dictionary):
self.sortDictByKey(dictionary)
| true |
f87b9019600d9cd55a79e8abfbd1d5b37560f447 | Prashidbhusal/Pythonlab1 | /Lab exercises/question 7.py | 452 | 4.28125 | 4 | #Solve each of the following problems using pythone script . Makes sure you use appropriate variable names and comments.
#When there is final answer , have python is to the screen.
# A person's body mass index(BMI) is defined as:
# BMI=(mass in kg) / (height in m)^2
mass=float(input('enter the mass of person in kg'))
height=float(input('entr the height of a person in meter'))
BMI=mass/(height ** 2)
print(f"The BMI index of the person is {BMI}")
| true |
17d573930ff954e98579728f47610e0dff7b1574 | c0untzer0/StudyProjects | /PythonProblems/check_string.py | 639 | 4.21875 | 4 | #!/usr/local/bin/python3
#-*- coding: utf-8 -*-
#
# check_string.py
# PythonProblems
#
# Created by Johan Cabrera on 2/15/13.
# Copyright (c) 2013 Johan Cabrera. All rights reserved.
#
#import os
#import sys
#import re
#import random
#!/usr/local/bin/python3
#
#check_string.py
#
strng = input("Please enter an upper-case string, ending with a period: \n")
if strng.isupper() and strng.endswith("."):
print("THAT IS ACCEPTABLE")
elif not(strng.isupper() or strng.endswith(".")):
print("You didn't follow any instructions!")
elif strng.isupper():
print("Input does not end with a period")
else:
print("Input is not all upper-case")
| true |
0ee88afe44d3292f6f804dea107315db1dad55af | Payalkumari25/GUI | /grid.py | 389 | 4.40625 | 4 | from tkinter import *
root = Tk()
#creating the label widget
label1 = Label(root,text="Hello world!").grid(row=0, column=0)
label2 = Label(root,text="My name is Payal").grid(row=1, column=5)
label3 = Label(root,text=" ").grid(row=1, column=1)
# showing it into screen
# label1.grid(row=0, column=0)
# label2.grid(row=1, column=5)
# label3.grid(row=1, column=1)
root.mainloop() | true |
6a0b9a98469658afb2ed5d0f6a8ab1cc5d40509f | asiahbennettdev/Polygon-Classes | /polygon.py | 2,742 | 4.4375 | 4 | import turtle # python drawing board module
""" Define polygon by certain amount of sides or name """
class Polygon: # trianlges, squares, pentagons, hexagons, ect.
def __init__(self, sides, name, size=100, color="blue", line_thinckness=3): # initialize with parameters - whats import to a polygon?
self.sides = sides
self.name = name
self.size = size
self.color = color
self.line_thickness = line_thinckness
self.interior_angles = (self.sides - 2)*180 # find sum of all interior angles. number of sides -2 * 180 - (n-2)*180
self.angle = self.interior_angles/self.sides # EX: sum of interior angle for square is 360 each angle is 90 degrees
def draw(self): # can access parameters of Polygon class by passing in self
turtle.pensize(self.line_thickness)
turtle.color(self.color)
for i in range(self.sides):
turtle.forward(self.size)
turtle.right(180-self.angle) # defining exterior andgle insert 180-self.sides, finding supplement of interior angles
#turtle.done()
def draw_function(sides, size, angle, line_thickness, color):
turtle.pensize(line_thickness)
turtle.color(color)
for i in range(sides):
turtle.forward(size)
turtle.right(180-angle)
turtle.done()
class Square(Polygon):
def __init__(self, size=100, color="black", line_thickness=3):
super().__init__(4, "Square", size, color, line_thickness)
def draw(self):
turtle.begin_fill()
super().draw()
turtle.end_fill()
# override draw method
def draw(self):
turtle.begin_fill()
super().draw()
turtle.end_fill()
square = Square(color="#321abc", size=200)
print(square.draw())
turtle.done()
# DEFINING SHAPES
# square = Polygon(4, "Square") # based on what was initalized in __init_ pass in parameters
# pentagon = Polygon(5, "Pentagon", color="red", line_thinckness=25) # size not provided defaults to 100
# hexagon = Polygon(6, "Hexagon", 10) #size gives tiny hexagon
# print(square.sides) # prints 4
# print(square.name) # prints Square
# print(square.interior_angles) # prints 360
# print(square.angle) # prints 90
# print(pentagon.name) # prints 5
# print(pentagon.sides) # prints Pentgon
# pentagon.draw()
# hexagon.draw()
# square.draw()
# draw_function(4, 50, 90, 4, "pink") # not utilizing predefined class methods
# NOTES
# self - allows us to access everything we've intialized in the class Polygon in nice succinct manner
# inheritance - subclassing - define class specifically
# we have created a polygon class we set sides and name through __init__ method by feeding in parameters
# encapsulating information from Polygon class | true |
387e8d3706a477ba4449fd49e049f9ccf81a55ea | shivangi-prog/Basic-Python | /Day 5/examples.py | 650 | 4.1875 | 4 | # Set Integers
Temperature = int(input("Enter temperature:"))
Humidity = int(input("Enter humidity percentage:"))
# statements
if Temperature >= 100:
print("Cancel School, and recommend a good movie")
elif Temperature >= 92 and Humidity > 75:
print("Cancel schoool")
elif Temperature > 88 and Humidity >= 85:
print("Cancel school")
elif Temperature == 75 and Humidity <= 65:
print("Encourage students to skip school and enjoy the great outdoors")
elif Temperature <= -25:
print("You had better panic, because the world is clearly ending")
elif Temperature < 0:
print("Cancel school")
else:
print("School is in session")
| true |
d0bfd16ddb5208109c3e8d1f826c6f1b269836c7 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/cfff3ebc-345e-47c3-8afb-6fafaa13dae8__square_root.py | 517 | 4.21875 | 4 | # Find square root of a number
# Apply the concept of a BST
def square_root(n, precision):
low = 0.0
high = n
mid = (low+high)/2.0
# precision is the +/- error allowed in our answer
while (abs(mid*mid-n) > precision):
if (mid*mid) < n:
low = mid
elif (mid*mid) > n:
high = mid
mid = (low+high)/2.0
return mid
print square_root(1.0, 0.00001)
print square_root(3.0, 0.00001)
print square_root(4.0, 0.00001)
print square_root(49.0, 0.00001)
| true |
cb89573aca0ed58e385759b6918a1bbd090ca7ac | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/9c1ed404-f5b4-4dc0-928c-59e23d75d315__bubble_sort.py | 576 | 4.15625 | 4 | # Sorting a list by comparing it's elements two by two and putting the biggest in the end
def sort_two_by_two(ul):
for index in range(len(ul)):
try:
el1 = ul[index]
el2 = ul[index + 1]
if el1 > el2:
ul[index] = el2
ul[index +1] = el1
except IndexError:
return ul
def bubble(ul):
sorted_list = ul
copyed_list = []
while copyed_list != sorted_list:
copyed_list = sorted_list[:]
sorted_list = sort_two_by_two(sorted_list)
return sorted_list
| true |
33355877c07b4c62605de51f88829db01a0c07f0 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/8d5d2074-ace0-410b-a057-28b3eed64467__sqrt_x.py | 503 | 4.21875 | 4 | """
Implement int sqrt(int x).
Compute and return the square root of x.
"""
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# the root of x will not bigger than x/2 + 1
if x == 0:
return 0
elif x == 1:
return 1
l = 0
r = x/2 + 1
while r >= l:
mid = (r + l) /2
temp = x / mid
if temp == mid:
return mid
elif temp < mid:
r = mid - 1
else:
l = mid + 1
return r
| true |
1924d3ebb5f9043df9435f96677ac2036d775e4d | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/0385591b-6a56-4782-9052-1d9ab43f95f4__square_root.py | 995 | 4.3125 | 4 | """
Program that asks the user for a positive number and then outputs the
approximated square root of the number. Use Newton's method to find the
square root, with epsilon = 0.01. (Epsilon is the allowed error, plus or
minus, when you square your calculated square root and compare it to
your original number.)
"""
def ask_for_number():
"""Asks user for a positive number"""
number = 0
while True:
if number > 0:
return number
try:
number = int(input("Please provide a positive nuumber: "))
except:
pass
def newtons_method(num, guess=None):
"""Calculates the square root of a number."""
if guess is None:
# picked 20 out of thin air. Let me know if I should change.
guess = 20
new_guess = .5*(num/guess+guess)
if new_guess == guess:
print("The square root of {} is {}.".format(num, guess))
else:
newtons_method(num, new_guess)
newtons_method(num=ask_for_number())
| true |
d6d96a671376e09c522197179ec3e1a39e84c16e | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/117291d5-df0d-4d90-a687-2c82344d1d55__RMSE.py | 1,194 | 4.28125 | 4 | #!/usr/bin/env python
# -------
# RMSE.py
# -------
def square_of_difference(x, y) :
"""
Squares the differences between actual and predicted ratings
x is one rating from the list of actual ratings
y is one rating from the list of predicted ratings
return the difference of each actual and predicted rating squared
"""
rating_dict = {'1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5}
actual = rating_dict[x]
pred = float(y)
sd = (actual - pred) ** 2
assert type(sd) is float
return sd
def mean(a) :
"""
Calculates the average of a list
a is the list of ints or floats to average
return the average of the numbers in the input list
"""
assert type(a) is list
m = sum(a) / len(a)
assert 0 <= m <= 16
return m
def rmse(a,p) :
"""
Calculates the root mean square error between 2 lists
a is the list of actual ratings
p is the list of predicted ratings
return root mean square error between the two input lists
"""
assert type(a) is list
assert type(p) is list
assert len(a) == len(p)
r = mean(map(square_of_difference, a, p)) ** .5
assert 0 <= r <= 4
return r
| true |
5d2cfbe84e4aec18dccf9804220b0005a4d91328 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/accf931e-a4c2-45b2-b2df-c999385ff178__ex13-random.py | 528 | 4.28125 | 4 | # the following program let the user play a game where he has to guess the square of
# a random number
# modify it as follow:
# print the square of an natural number and let the player guess the square root.
# the square root should be between 1 and 20
import random
def askForNumber():
return int(raw_input("Enter square of x: "))
x = random.randint(1,10)
print "x =",x
inputValue = askForNumber()
while inputValue!=x*x:
print "Answer is wrong!"
inputValue = askForNumber()
print "Right!"
| true |
738091fc3650a91d3146a6c31aee64629a33fdd7 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/6d22552b-74ae-459d-bb4a-395727bbc2be__069-sqrt.py | 471 | 4.125 | 4 | #!/usr/bin/python
# Implement int sqrt(int x).
# Compute and return the square root of x.
import sys
# Binary search in range from 1 to x / 2. O(log(n)).
def sqrt(x):
if x == 0 or x == 1:
return x
i, j = 1, x / 2
while i <= j:
m = (i + j) / 2
if m * m > x:
j = m - 1
elif m * m < x:
i = m + 1
else:
return m
return i - 1
def main():
print sqrt(int(sys.argv[1]))
main()
| true |
ae33b275f221a81e7d91f603a22e0f44639540f8 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/73ed9c98-ac54-4356-a553-5c6e12e44eb9__forPeopleNotComputers1.py | 861 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
############ EJEMPLO 1 ############
#Don't write what code is doing, this should be left for the code to explain and can be easily done by giving class, variable and method meaningful name. For example:
t=10
#calculates square root of given number
#using Newton-Raphson method
def abc( a):
r = a / 2
while ( abs( r - (a/r) ) > t ):
r = 0.5 * ( r + (a/r) )
return r
#Above code is calculating square root using Newton-Raphson method and instead of writing comment you can just rename your method and variable as follows:
def squareRoot( num):
root = num/ 2
while ( abs(root - (num/ root) ) > t ):
r = 0.5 * (root + (num/ root))
return root
if __name__ == "__main__":
print " root abc = " + str(abc(10))
print " root squareRoot = " + str(squareRoot(10))
| true |
8cb4a22012d691a4ac812cc456464935266ed16e | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/0beb9f98-f5de-47a5-aef2-0f5af5117d90__front_x.py | 966 | 4.28125 | 4 | def front_x(words):
x_list =[]
non_x_list = []
sorted_list = []
for str in words:
if str[0].lower().startswith("x"):
x_list.append(str)
else:
non_x_list.append(str)
print x_list,
print non_x_list
print type(x_list)
print sorted(x_list)
print type(sorted(x_list))
sorted_list = sorted(x_list)+sorted(non_x_list)
# +++your code here+++
return sorted_list
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
# +++your code
sort_by = []
for item in tuples:
sort_by.append(item[-1])
sorted_index = sorted(sort_by)
print sorted_index
return sorted_index
| true |
245a22eb50b7bc37e597a13048012fd994730915 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/1a0efe9c-edb5-4b4a-9d1c-47aca8ecc3bf__main.py | 441 | 4.4375 | 4 | """This function will approximate the square root of a number using Newton's Method"""
x = float(input("Enter a positive number and I will find the square root: "))
def square_root(x):
y = x/2
count = 0
while abs((y**2) - x) > 0.01:
y = (y+x/y)/2
count += 1
print("After iterating {} times, my guess is {}.".format(count, y))
return y
print("The square root of {} is {}.".format(x, square_root(x)))
| true |
f9f788b0b38bc620286738c74daf9732a43ff3db | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/d411c458-97e1-4a17-b22a-db46445f011a__square_root.py | 485 | 4.125 | 4 | # Python Code for Square Root
num = int(input("Enter a positive number: "))
def newtonest(num):
return num ** 0.5
def estimate(num):
guess = num/3
count = 0
epsilon = 0.01
sq_guess = ((num / guess) + guess)/2
while abs(newtonest(num) - sq_guess) > epsilon:
newguess = sq_guess
sq_guess = ((num / newguess) + newguess)/2
count +=1
print("The square root of {} is {} with {} interations.".format(num,sq_guess,count))
estimate(num)
| true |
012814c4bdfb63d99d967a52027cf6d5b6ebeb8a | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/04d69a32-54b4-4e9c-b998-1c8e7e844774__newtonsMethodOfSquares.py | 253 | 4.25 | 4 | def newtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
return approx
x = float(input("what number would you like to square root?"))
print (newtonSqrt(x)) | true |
faba2172b30a6e3f2a24895770f5210ede6367c7 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/6d7d2e0c-b0a0-4f91-aad3-218cf30cf40c__sqroot.py | 750 | 4.40625 | 4 | '''
Find the square root of n.
Input: A number
Output: The square root or the integers closest to the square root
Assume: positive n
Newton's method is a popular solution for square root, but not implemented here.
'''
def sqrt(n):
for number in range(0, n):
if isSqrt(number,n):
return number
else:
if n < number * number:
return number, number - 1
def isSqrt(a,b):
'''
Helper function to use in sqrt function to calculate number squared
'''
if a * a == b:
return True
else:
return False
# Test Section
if __name__ == '__main__':
print "sqrt(25) = 5: %s" % (sqrt(25) == 5)
print "sqrt(30) = (6, 5): %s" % (sqrt(30) == (6,5))
| true |
e7ecfb257fcc00f8d2732024c7d7eccb8e188d3a | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/54adae2c-fd4c-4b83-a622-a64f867c5643__sqrt.py | 463 | 4.125 | 4 | def sqrt(x):
""" Calculate the square root of a perfect square"""
if x >= 0:
ans = 0
while ans * ans < x:
ans += 1
if ans * ans == x:
return ans
else:
print(x, "is not a perfect square")
return None
else:
print(x, "is a negative number")
return None
for i in range (-10, 11):
x = sqrt(i)
if x != None:
print("Square root of", i, "is", x)
| true |
4e9d81dd456aff5c700a0c4570c1302317bedcd3 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/ef081f79-c5e5-4dd5-9103-050da101fdfc__basic_sorts.py | 2,674 | 4.46875 | 4 | from heap import Heap
def insertion_sort(array):
"""
Standard insertion sort alogrithm
Arguments:
array - array of numbers
Returns:
array - array sorted in increasing order
"""
for i in range(1, len(array)):
j = i - 1
while j >= 0 and array[j] > array[i]:
array[i], array[j] = array[j], array[i]
i = j
j-=1
return array
def selection_sort(array):
"""
Standard selection sort algorithm.
Arguments:
array - array of numbers
Returns:
array - array sorted in increasing order
"""
for i in range(0, len(array)-1):
min_index = None
for j in range(i, len(array)):
if not min_index:
min_index = j
else:
if array[j] < array[min_index]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
return array
def merge(array1, array2):
"""
Take two sorted arrays and merge them in sorted order.
Arguments:
array1 - first array to be sorted
array2 - second array to be sorted
Returns:
sorted_array - merged arrays in sorted manner
"""
sorted_array = []
while array1 and array2:
if array1[0] < array2[0]:
sorted_array.append(array1.pop(0))
else:
sorted_array.append(array2.pop(0))
if not array1:
sorted_array.extend(array2)
elif not array2:
sorted_array.extend(array1)
return sorted_array
def merge_sort(array):
"""
Merge sort a given array in ascending order
Arguments:
array - potentially unsorted array
Returns:
sorted_array - sorted array in ascending order
"""
if len(array) == 1 or not array:
return array
else:
sorted_array = merge(merge_sort(array[0:len(array)/2]), merge_sort(array[len(array)/2:]))
return sorted_array
def quick_sort(array, start=0, end=None):
"""
Perform a quick sort in place
Arguments:
array - array to be sorted
start - starting index of array to be sorted
end - end index of array to be sorted
Returns:
array - sorted array
"""
if not array:
return
if not end:
end = len(array)-1
pivot = end
curr_index = start
while curr_index != pivot:
if array[curr_index] > array[pivot]:
array[curr_index], array[pivot-1] = array[pivot-1], array[curr_index]
array[pivot-1], array[pivot] = array[pivot], array[pivot-1]
curr_index = start
pivot-=1
else:
curr_index+=1
if pivot - start > 1:
quick_sort(array, start, pivot-1)
if pivot < end-2:
quick_sort(array, pivot + 1, end)
return array
def heap_sort(array):
"""
Performs a heap sort
Arguments:
array - array of integers to be sorted
Returns:
array - sorted array
"""
sorted_array = []
array_heap = Heap(array)
while array_heap.size > 0:
sorted_array.append(array_heap.remove())
return sorted_array | true |
6d80392cc2a2c228de03adfaa95db8a6db11742f | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/7e22a661-3c4e-4ed5-a12b-0916b621637d__Loops.py | 1,308 | 4.15625 | 4 |
from sys import float_info as sfi
def square_root (n):
'''Square root calculated using Netwton's method
'''
x = n/2.0
while True:
y = (x + n/x)/2
# As equality in floating numbers can be elusive,
# we check if the numbers are close to each other.
if abs(y-x) < sfi.epsilon:
break
x = y
return x
def factorial_new(n):
'''Factorial using for loop
'''
result = 1
if n < 0: return None
if n == 0: return 1
for i in range(1, n+1):
result = result * i
return result
def skipper01(end, start=0, step=1):
for i in range(start, end, step):
print(i, end=' ')
def skipper02(end, start=0, step=1):
i = start
while(i < end):
print(i, end=' ')
i = i + step
if __name__ == "__main__":
print("The square root of 4 = " + str(square_root(4)))
print("The square root of 9 = " + str(square_root(9)))
print("The square root of 15 = %.4f " % square_root(14))
print("The factorial of 4 = " + str(factorial_new(4)))
print("The factorial of 7 = " + str(factorial_new(7)))
print("The factorial of 10 = %d " % factorial_new(10))
skipper01(10, 5, 2)
print('\n')
skipper02(13, 3, 3)
print('\n')
skipper01(8)
print('\n')
skipper02(7)
| true |
9599518e6519acb4736f62141cc10e41d9b200e6 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/83701c06-e19a-4c7b-87a6-fa1d10a49446__squareRootBisection.py | 663 | 4.34375 | 4 | """Calculate the square cube of a float number"""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def squareRootBisection(x, precision):
'''
Calculate the square root of a float number through bisection method with given precision
:param x: Float number
:param precision: Square root precision
:return: Square root of the float number
'''
if x < 0 or precision <= 0:
return None
# x>=0
low = 0.0
high = x
value = (low+high)/2
while abs(value**2-x) > precision:
if value**2 < x:
low = value
else: # value**2 > x
high = value
value = (low+high)/2
return value | true |
9dc5ed37a27c4c98b989e3bdf2166427e52fcd9a | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/96237146-8b34-46ec-99b8-6c2b8cc9d4af__mergesort.py | 712 | 4.15625 | 4 |
def merge(a, b):
"""Merging subroutine. Meant to merge two sorted lists into a combined, sorted list."""
n = len(a) + len(b)
d = [0 for i in range(n)]
i = 0
j = 0
for k in range(n):
if a[i] < b[j]:
d[k] = a[i]
if i+1 > len(a)-1:
for l in b[j:]:
d[k+1] = b[j]
k += 1
j += 1
return d
i += 1
elif a[i] > b[j]:
d[k] = b[j]
if j+1 > len(b)-1:
for l in a[i:]:
d[k+1] = a[i]
k+=1
i+=1
return d
j += 1
def merge_sort(c):
"""Recursive merge sort. Takes non-repeating list and returns sorted version of the list."""
if len(c) == 1:
return c
else:
a = merge_sort(c[:int(len(c)/2)])
b = merge_sort(c[int(len(c)/2):])
return merge(a,b)
| true |
975976dac5dcdacbf94c3c7b5d37973ab501e3a1 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/39cf0f2e-d6c1-4606-9e97-3f60bda3a6a1__merge_sort_improved.py | 1,024 | 4.40625 | 4 | # Merge Sort
def merge(left, right):
"""Merges two sorted lists.
Args:
left: A sorted list.
right: A sorted list.
Returns:
The sorted list resulting from merging the two sorted sublists.
Requires:
left and right are sorted.
"""
items = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
items.append(left[i])
i = i + 1
else:
items.append(right[j])
j = j + 1
if i < len(left):
items.extend(left[i:])
elif j < len(right):
items.extend(right[j:])
return items
def merge_sort(items):
"""Sorts a list of items.
Uses merge sort to sort the list items.
Args:
items: A list of items.
Returns:
The sorted list of items.
"""
n = len(items)
if n < 2:
return items
m = n // 2
left = merge_sort(items[:m])
right = merge_sort(items[m:])
return merge(left, right)
| true |
0509c69d4ad62a01518607588f61468cb4aa8ada | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/d302ddc9-b885-4379-b5c8-13288906db2a__HeronsMethod.py | 1,674 | 4.40625 | 4 | #!/usr/bin/env python
"""
This script is an implementation of Heron's Method (cs.utep.edu/vladik/2009/olg09-05a.pdf), one of the oldest ways of
calculating square roots by hand.
The script asks for maximum number of iterations to run, the square root to approximate, and the initial guess
for the square root. Each successive guess is closer to the square root until either the maximum number of iterations
is reached or the actual square root is found.
"""
__author__ = 'Carlos A. Gomez'
def ask_and_approx_roots():
num_iterations = int(input("Please enter the number of iterations (an integer): "))
square_root_to_approx = int(input("Please enter the square root to approximate (an integer): "))
sq_root_guess = float(input("Please enter a guess for the square root: "))
return heron_method(num_iterations, square_root_to_approx, sq_root_guess)
def heron_method(num_iterations, square_root_to_approx, sq_root_guess):
sq_root_approximation = 1/2 * (sq_root_guess + square_root_to_approx/sq_root_guess)
result_found = False
run_counter = 0
while not result_found:
run_counter += 1
last_guess = sq_root_approximation
print("Guess number " + str(run_counter) + " is " + str(sq_root_approximation))
sq_root_approximation = 1/2 * (sq_root_approximation + square_root_to_approx/sq_root_approximation)
if abs(sq_root_approximation - last_guess) == 0 or run_counter == num_iterations:
result_found = True
print("The best guess for the square root, using " + str(run_counter) + " iterations, is "
+ str(sq_root_approximation))
if __name__ == '__main__':
ask_and_approx_roots()
| true |
1a9e104e93631dc74a90e6768991dee980bbadb8 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/f72b109f-64e1-42d5-a0ed-fcaf72e805a5__bubble_sort.py | 491 | 4.125 | 4 | from create_list import random_list, is_sorted
def bubble_sort(my_list):
"""
Perform bubble sort on my_list.
"""
while not is_sorted(my_list):
for i in range(len(my_list) - 1):
if my_list[i] > my_list[i + 1]:
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
return my_list
my_list = random_list(50)
print(my_list)
print(is_sorted(my_list))
sorted_list = bubble_sort(my_list)
print(sorted_list)
print(is_sorted(sorted_list))
| true |
72c1e0aa39f4022e3483e98d4a586e3b00032d71 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/b104d935-486f-4ca1-b317-bf78949d3ae0__sort.py | 1,591 | 4.34375 | 4 | # Executes merge sort on an unsorted list
# Args:
# items: Unsorted list of numbers
#
# Returns:
# Sorted list of items
def merge_sort(unsorted_list):
# If unsorted_list is length = 1, then it's implicitly
# sorted. Just return it. Base case.
if len(unsorted_list) == 1:
return unsorted_list
# Create two new lists
unsorted_list_a = unsorted_list[0:(len(unsorted_list)/2)]
unsorted_list_b = unsorted_list[(len(unsorted_list)/2):len(unsorted_list)]
# Sort them
sorted_list_a = merge_sort(unsorted_list_a)
sorted_list_b = merge_sort(unsorted_list_b)
# Merge the two sorted lists and return
sorted_list = merge(sorted_list_a, sorted_list_b)
return sorted_list
# Merges two sorted lists
# Returns:
# Sorted list
def merge(list_a, list_b):
sorted_list = []
# Iterates over the two lists, removing elements and putting
# them in sorted_list until one of the lists is empty
while (len(list_a) > 0 and len(list_b) > 0):
if list_a[0] < list_b[0]:
sorted_list.append(list_a[0])
list_a.pop(0)
else:
sorted_list.append(list_b[0])
list_b.pop(0)
# One of the lists was empty so just add the rest
# of the non-empty one to sorted_list
if len(list_a) == 0:
sorted_list.extend(list_b)
if len(list_b) == 0:
sorted_list.extend(list_a)
return sorted_list
def merge_unit_test():
list_a = [1,2,8,9]
list_b = [3,4,6,10,11]
sorted_list = merge(list_a, list_b)
print(sorted_list)
# TODO: Add some assertions here
def merge_sort_test():
list_a = [3,6,1,3,7,8,0,10,22,323,1,5,4,2,85,39]
sorted_list = merge_sort(list_a)
print(sorted_list)
| true |
c5172eca5772e56a8ee0cd1f5dc7df51d72db5d1 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/67a0a05e-aeae-4325-9ac2-e56575c7747b__insertion.py | 671 | 4.125 | 4 | def sort(coll):
''' Given a collection, sort it using the insertion
sort method (sorted by reference).
O(n^2) performance
O(n) storage
:param coll: The collection to sort
:returns: The sorted collection
'''
for j in range(1, len(coll)):
k = coll[j]
i = j - 1
while i > 0 and coll[i] > k:
coll[i + 1] = coll[i]
i = i - 1
coll[i + 1] = k
return coll
def sort_clone(coll):
''' Given a collection, sort it using the insertion
sort method (sorted by copy).
:param coll: The collection to sort
:returns: The sorted collection
'''
return sort(list(coll))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.