blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
377c78d18db40dd93bd16b65a9a1a4547c508216 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/16 Databases/databases.py | 896 | 4.3125 | 4 | #!/usr/bin/python3
# Databases in python
# Database used here is SQLite 3
# row factory in sqlite3
import sqlite3
def main():
# Connects to database and creates the actual db file if not exits already
db = sqlite3.connect('test.db')
# Interact with the database
db.execute('drop table if exists test')
db.execute('create table test(t1 text, i1 int)')
db.execute('insert into test (t1, i1) values(?, ?)', ('one', 1))
db.execute('insert into test (t1, i1) values(?, ?)', ('two', 2))
db.execute('insert into test (t1, i1) values(?, ?)', ('three', 3))
db.execute('insert into test (t1, i1) values(?, ?)', ('four', 4))
# commit the changes in database
db.commit()
cursor = db.execute('select i1, t1 from test order by i1')
# Data comes in tuple
for row in cursor:
print (row)
if __name__ == "__main__": main()
| true |
33d9a7cc53d070f8575fa5b3b044edd4eb5e9fe4 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/12 Classes/generator.py | 1,218 | 4.46875 | 4 | #!/usr/bin/python3
# A generator object is an object that can be used in the context of an iterable
# like in for loop
# Create own range object with inclusive range
class inclusive_range:
def __init__(self, *args):
numargs = len(args)
if numargs < 1 :
raise TypeError('Requries at least one argument')
elif numargs == 1:
self.start = 0
self.stop = args[0]
self.step = 1
elif numargs == 2:
self.start = args[0]
self.stop = args[1]
self.step = 1
elif numargs == 3:
(self.start, self.stop, self.step) = args
else:
raise TypeError('Number of arguments should be 3, but they are {}'.format(numargs))
# Generator
def __iter__(self):
i = self.start
while i <= self.stop:
yield i
i += self.step
def main():
# generator object
o = range(0, 25, 1) # start, stop
for i in o: print(i, end = ' ')
print()
mygen = inclusive_range(1,18)
for i in mygen: print(i, end = ' ')
print()
for i in inclusive_range(10): print (i , end = ' ')
if __name__ == "__main__": main() | true |
d2d7d34fa745243c91ab891f0fdd3e28ba8b16d0 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/14 Containers/dictionary.py | 1,397 | 4.28125 | 4 | #!/usr/bin/python3
# Organizing data with dictionaries
def main():
d1 = {'one' : 1, 'two' : 2, 'three' : 3}
print(d1, type(d1))
# dictionary using dict constructor
d2 = dict(one = 1, two = 2, three = 3)
print(d2, type(d2))
d3 = dict(four = 4, five = 5, six = 6)
print(d3, type(d3))
# Using keyword arguments
# ** this denots the kwargs
d4 = dict(one = 1, two = 2, three = 3, **d3)
print(d4, type(d4))
# check if a value is in dictionary
print('four' in d3)
print('three' in d3)
# Iterate over dict elements
# to print all the keys
for key in d4:
print(key, end = ' ')
print()
# Iterate over dict elements to print all the keys and values
for key,value in d4.items():
print(key, "=", value)
print()
# Get a particular item from a dictionary
print("d4['three'] =", d4['three'])
# get method to get a value for a key from a dict object
print(d3.get('three'))
print(d4.get('three'))
# Set a default return value in case key is not present
print(d3.get('three', 'Not Found'))
# delete an item from a dict
del d3['four']
print(d3, type(d3))
# pop an item from a dict
# In dictionary it requires atleast one argument
d3.pop('five')
print(d3, type(d3))
if __name__ == "__main__": main()
| true |
f33362d646b39360d8bdc20d346a369fdf7d6a19 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/05 Variables/Finding_type_identity.py | 1,300 | 4.3125 | 4 | #!/bin/python3
# Finding the type and identity of a variable
# Everything is object and each object has an ID which is unique
def main():
print("Main Starts !")
x = 42
print("x:",x)
print("id of x:",id(x))
print("id of 42:",id(42))
print("type of x:", type(x))
print("type of 42:", type(42))
# ID of x and 42 is same as the object x references to
# integer 42 and thus have the same ID
# So, Number 42 is an object
y = 42
print("y:",y)
print("id of y:",id(y))
print("id of 42:",id(42))
print("type of y:", type(y))
print("type of 42:", type(42))
# == operator compares the value
print("x == y:", x == y)
# They are exactly the same objects
# As they have the same id
# 'is' compares the id rather than the value
print("x is y:", x is y)
z = dict(x = 42)
print(type(z))
print(z)
print(id(z))
z2 = dict(x = 42)
print(type(z2))
print(z2)
print(id(z2))
print("z == z2:", z == z2) # True
print("z is z2:", z is z2) # False as they are differnt objects
# All muttable objects gets unique ID
# Whereas the immutable objects get different ID
# Variables in python are references to objects
if __name__ == "__main__": main() | true |
a9a1e6045d4a0ba4ff26f662bfc670c4ae007693 | alvintangz/pi-python-curriculum | /adventuregame.py | 745 | 4.34375 | 4 | # Simple adventure game for day 3.
hero = input("Name your hero. ")
print("\n" + hero + " has to save their friend from the shark infested waters.")
print("What do they do?")
print("A. Throw a bag of salt and pepper in the water?")
print("B. Drink up the whole ocean?")
print("C. Do nothing.\n")
option = input("What do they do? Type in an option. ");
if(option == "A"):
print("Great! Theyjust seasoned their friend so the sharks will have a " +
"delicious lunch!")
elif(option == "B"):
print("Their body can't handle that? Where does their pee go?")
elif(option == "C"):
print("Correct. Sharks are actually not that dangerous! " +
"Just tell their friend to relax.")
else:
print("That option is not valid.") | true |
8ca0ed2176a8dac59fd50ae330c278b1cf649ac1 | jzaunegger/PSU-Courses | /Spring-2021/CSE-597/MarkovChains.py | 1,804 | 4.3125 | 4 | '''
This application is about using Markov Chains to generate text using
N grams. A markov chain is essentially, a series of states, where each state
relates to one another in a logical fashion. In the case of text generation,
a noun phrase is always followed by a verb phrase.
Lets say we have two states: A and B
A -> B with a 25% chance of occuring
A -> B with a 25% chance of occuring
B -> A with a 25% chance of occuring
B -> B with a 25% chance of occuring
This idea can be applied in a ton of different ways, from text generation to
weather predictions or financial analysis.
'''
import os, random
# Set parameters
input_path = os.path.join(os.getcwd(), 'Corpus', 'Lovecraft', 'Azathoth.txt')
ngram_size = 5
markov_count = 1000
n_grams = {}
input_text = ''
# Read the file
with open(input_path, 'r') as txt_file:
input_text = txt_file.read()
# Determine the N-Grams
for i in range(len(input_text)-ngram_size):
gram = input_text[i:i+ngram_size]
# Check that we have enough characters to get a next char
if i == len(input_text) - ngram_size:
break
else:
next_char = input_text[i+ngram_size]
# Check if ngram is already in the dictionary
if gram in n_grams.keys():
pass
else:
n_grams[gram] = []
# Append next character
n_grams[gram].append(next_char)
# Generate new text from the ngram analysis
current_gram = input_text[0:ngram_size]
result = current_gram
for k in range(markov_count):
possibilities = n_grams[current_gram]
if len(possibilities) == 0:
break
next_char = random.choice(possibilities)
result += next_char
current_gram = result[len(result)-ngram_size:len(result)]
print(result) | true |
28bf44989f72a0a9c14d5a34bb1068437800c72a | mustail/Election_analysis | /practice/python_practice2.py | 1,711 | 4.46875 | 4 | # python practice continued
print("Hello world.")
print("Arapahoe and Denver are not in the list of counties.")
# printing with f string
my_votes = int(input("How many votes did you get in the election?"))
total_votes = int(input("What is the total number of votes in the election?"))
percentage_votes = (my_votes/total_votes) * 100
#print("I received " + str(percentage_votes)+ "% of total votes.")
message_to_candidate = (
f"You received {my_votes:,} number of votes. "
f"The total number of votes cast was {total_votes:,}. "
f"You received {my_votes/total_votes*100:.2f}% of the total votes."
)
print(message_to_candidate)
print(f"I received {my_votes/total_votes*100}% of the total votes.")
print(f"I received {percentage_votes}% of the total election.")
counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222}
for county, voters in counties_dict.items():
#print(county + " county has " + str(voters) + " registered voters.")
print(f"{county} county has {voters:,} number of registered voters.")
# skill drill
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"county":"Jefferson", "registered_voters": 432438}
]
for county_dict in voting_data:
print(f"{county_dict['county']} county has {county_dict['registered_voters']:,} number of registered voters.")
# very important here: If you use double quotation marks for the f-strings containing the keys,
# then be sure to use single quotation marks for the keys and values of the dictionary.
# I tried the above (for ex. county, registered_voters) with double quotes, but it did not work.
| true |
6873b522169569c7e04a6e39c065fdab343f6405 | Sabdix/Python-Tutorials | /Dictionaries.py | 465 | 4.25 | 4 | # A dictionary is a collection which is unordered, changeable and indexed.
thisDict = {
"apple": "green",
"bannana": "yellow",
"cherry": "red"
}
print(thisDict)
#Changing elements
thisDict["apple"] = "red"
print(thisDict)
#Create dictionary with method
thisdict = dict(apple="green", bannana="yellow", cherry="red")
print(thisdict)
#adding items
thisdict["damson"] = "purple"
print(thisdict)
#deleting items
del(thisdict["bannana"])
print(thisdict) | true |
abbc2b40c22b26f2c2305a5b69b91cb8ccb63b9a | Sabdix/Python-Tutorials | /Json.py | 1,302 | 4.4375 | 4 | # importing JSON
import json
# If you have a JSON string, you can parse it to convert it in to a dictionary
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
#If you have a Python object, you can convert it into a JSON string
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
#Convert Python objects into JSON strings, and print the values:
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
#Another example
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
#Formating the Result
print(json.dumps(x, indent=4))
#Change the separator
print(json.dumps(x, indent=4, separators=(". ", " = ")))
#Order the Result
print(json.dumps(x, indent=4, sort_keys=True)) | true |
bbfa000ad67f734df09ed03e70d85119123cfef0 | sangeetjena/datascience-python | /Dtastructure&Algo/algo/water_supply.py | 826 | 4.1875 | 4 | """Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.
The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which means that water cannot pass through that particular city. Determine the maximum number of cities to which water can be supplied.
"""
path={1:[2,3],2:[4,6],3:[],4:[5],5:[],6:[7],7:[]}
supply=[]
block=[2]
cnt=0
def line_draw(source):
global cnt
for v in path[source]:
if(v in block):
continue
else:
line_draw(v)
if v not in supply:
cnt=cnt+1
supply.append(v)
return
line_draw(1)
print(supply)
line_draw(1)
| true |
00503cb30615d01facc609ef894f0ee570717a96 | kajaltingare/Python | /Basics/verbing_op.py | 328 | 4.4375 | 4 | # Write a program to accept a string from user & perform verbing operation.
inp_stmt=input("Enter the statement: ")
if(len(inp_stmt)>=3):
if(inp_stmt.endswith("ing")):
print(inp_stmt[:-3]+'ly')
else:print(inp_stmt+'ing')
else:
print('Please enter verb atleast 3 or more number of characters in it.')
| true |
58b6f4caa8b080662653399a75cff2afc9ff6691 | kajaltingare/Python | /Basics/Patterns/pattern6_LL.py | 334 | 4.125 | 4 | # Write a program to print LowerLeft side pattern of stars.
def Pattern6(n):
for i in range(1,n+1):
for _ in range(0,n-i+1):
print('*',end='')
print()
def main():
n = eval(input('Enter the no of rows want to print pattern: '))
Pattern6(n)
if __name__ == '__main__':
main()
| true |
c0af2569858fa4b0d2e8d8c2246d7948a8d97841 | kajaltingare/Python | /Basics/UsingFunc/fibboSeriesWithUpperLimit.py | 433 | 4.21875 | 4 | # Write a program to print fibonacci series with given upper limit, starting from 1.
def fiboSeries(upperLmt):
a,b=1,1
print(a,b,end='')
#for i in range(1,upperLmt):
while((a+b)<=upperLmt):
c=a+b
print(' %d'%c,end='')
a=b
b=c
def main():
upperLmt = eval(input('Enter upper limit of fibo to print: '))
fiboSeries(upperLmt)
if __name__=='__main__':
main()
| true |
9b4de2ccf3539b1f714c3855bff8989f19f433fa | kajaltingare/Python | /Basics/min_of_3.py | 260 | 4.21875 | 4 | # Write a program to accept three numbers from user & find minimum of them.
n1,n2,n3=eval(input("Enter the 3 no.s: "))
if(n1<n2 and n1<n3):print("{0} is minimum".format(n1))
elif(n2<n1 and n2<n3):print('%d is minimum.'%n2)
else:print('%d is minimum.'%n3)
| true |
831023701ff1b841124a34e1eebb20f05489cc6a | kajaltingare/Python | /Basics/UsingFunc/isDivisibleByEight.py | 481 | 4.34375 | 4 | # Write a program to accept a no from user & check if it is divisible by 8 without using arithmatic operators.
def isDivisibleByEight(num):
if(num&7==0):
return True
else:
return False
def main():
num = eval(input('Enter the number: '))
result = isDivisibleByEight(num)
if(result):
print('%d is divisible by 8.'%num)
else:
print('%d is not divisible by 8.'%num)
if __name__ == '__main__':
main()
| true |
a8c06bb0934f021d06a854bba1861b83d31bd4e1 | kajaltingare/Python | /Basics/basic_str_indexing.py | 676 | 4.65625 | 5 | #String-Immutable container=>some basics about string.
name="kajal tingre"
print("you entered name as: ",name)
#'kajal tingre'
print("Accessing 3rd char in the string(name[2]): ",name[2])
print("2nd including to 5th excluding sub-string(name[2:5]): ",name[2:5])
print("Printing alternate char from 1st position(name[::2]): ",name[::2])
print("Printing string from 2nd char to end(name[2::]): ",name[2::])
print("Print last char of string(name[-1::]): ",name[-1::])
print("Printing in between string(name[1:-5]): ",name[1:-5])
print("When starting index>end index, prints nothing(name[5:2]): ",name[5:2])
print("if we give step value in above as(name[5:2:-1]): ",name[5:2:-1])
| true |
094559f9145b0d98920ed6960f275c0de68f0d48 | Ahed-bahri/Python | /squares.py | 250 | 4.25 | 4 | #print out the squares of the numbers 1-10.
numbers=[1,2,3,4,5,6,7,8,9,10]
for i in numbers:
print("the square of each number is : ", i**2)
#mattan strategy
for i in range(1,11):
print("the square of each number is : ", i**2)
| true |
da3e46522a54ff4971dda36cb3a0ad19de85e874 | donchanee/python_trick | /Chaining_Comparison.py | 502 | 4.25 | 4 | # Chaining comparison operators:
>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True
'''
In case you're thinking it's doing 1 < x, which comes out as True, and then comparing True < 10,
which is also True, then no, that's really not what happens (see the last example.)
It's really translating into 1 < x and x < 10, and x < 10 and 10 < x * 10 and x*10 < 100,
but with less typing and each term is only evaluated once.
'''
| true |
ed37d9243eda6d10b8f2cb0e8c3c55791ed99e38 | KlimDos/exercism_traning | /python/yacht/yacht.py | 2,457 | 4.1875 | 4 | """
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a common practice to export both constants and functions that work with
those constants (ex. the constants in the os, subprocess and re modules).
You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type
"""
# Score categories.
# Change the values as you see fit.
YACHT = "YACHT"
ONES = "ONES"
TWOS = "TWOS"
THREES = "THREES"
FOURS = "FOURS"
FIVES = "FIVES"
SIXES = "SIXES"
FULL_HOUSE = "FULL_HOUSE"
FOUR_OF_A_KIND = "FOUR_OF_A_KIND"
LITTLE_STRAIGHT = "LITTLE_STRAIGHT"
BIG_STRAIGHT = "BIG_STRAIGHT"
CHOICE = "CHOICE"
def findSame(dice: list):
s = sorted(dice.copy())
count_left = s.count(s[0])
count_right = s.count(s[-1])
return s, count_left, count_right
def score(dice, category):
result = 0
sorted_dice, r1, r2 = findSame(dice)
for i in dice:
if category == "ONES":
if i == 1:
result += 1
elif category == "TWOS":
if i == 2:
result += 2
elif category == "THREES":
if i == 3:
result += 3
elif category == "FOURS":
if i == 4:
result += 4
elif category == "FIVES":
if i == 5:
result += 5
elif category == "SIXES":
if i == 6:
result += 6
if category == "FULL_HOUSE":
if r1 == 3 and r2 == 2 or r1 == 2 and r2 == 3:
result = sum(dice)
else:
result = 0
elif category == "FOUR_OF_A_KIND":
if r1 >= 4:
result = 4 * sorted_dice[0]
elif r2 >= 4:
result = 4 * sorted_dice[-1]
else:
result = 0
elif category == "LITTLE_STRAIGHT":
if sorted_dice == [1, 2, 3, 4, 5]:
result = 30
else:
result = 0
elif category == "BIG_STRAIGHT":
if sorted_dice == [2, 3, 4, 5, 6]:
result = 30
else:
result = 0
elif category == "CHOICE":
result = sum(dice)
elif category == "YACHT":
if r1 == 5:
result = 50
else:
result = 0
return result
| true |
c2bccd3dc5edb3734482d4540c954292ae6bc85f | shun-lin/Shun-LeetCode-OJ-solutions | /Algorithm/ImplmentingQueueUsingStacks.py | 1,718 | 4.40625 | 4 | class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
# stack is first in last out so in python we can use append to add and
# pop front
# we want to implement a queue which is first in first out
self.stacks = [[], []]
self.activeStackIndex = 0
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
otherStateIndex = 1 - self.activeStackIndex
while len(self.stacks[self.activeStackIndex]) > 0:
lastElement = self.stacks[self.activeStackIndex].pop()
self.stacks[otherStateIndex].append(lastElement)
self.stacks[otherStateIndex].append(x)
while len(self.stacks[otherStateIndex]) > 0:
lastElement = self.stacks[otherStateIndex].pop()
self.stacks[self.activeStackIndex].append(lastElement)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
return self.stacks[self.activeStackIndex].pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
lastElementInex = len(self.stacks[self.activeStackIndex]) - 1
return self.stacks[self.activeStackIndex][lastElementInex]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return len(self.stacks[self.activeStackIndex]) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
| true |
e064c21b78829ef1a99ce2e205c7298cca798afc | gmaher/flask-react-be | /src/crypto/password.py | 938 | 4.3125 | 4 | import bcrypt
def hash_password(pw, rounds=10):
"""
Uses the bcrypt algorithm to generate a salt and hash a password
NOTE: ONLY PASSWORDS < 72 CHARACTERS LONG!!!!
:param pw: (required) password to hash
:param rounds: number of rounds the bcrypt algorithm will run for
"""
if not type(pw) == str:
raise RuntimeError('password {} is not a string!'.format(pw))
if len(pw) >= 72:
raise RuntimeError('password {} has length {} > 72!'.format(pw,len(pw)))
return bcrypt.hashpw(pw,bcrypt.gensalt(rounds))
def pw_is_valid(pw,hashed_pw):
"""
compare the entered password to the hashed one and see if they match up
:param pw: (required) password entered by user
:param hashed_pw: (required) the hashed password we stored in the database
"""
if not type(pw) == str: return False
if len(hashed_pw) != 60: return False
return bcrypt.checkpw(pw,hashed_pw)
| true |
3207b1deeb5506e7d1346291901a759cc2549fca | TianfangLan/LetsGoProgram | /Python/week_notes/week2_QueueADT_v1.py | 1,718 | 4.34375 | 4 | class EmptyQueueException(Exception):
pass
class Queue():
''' this class defines a Queueu ADT and raises an exception in case the queue is empty and dequeue() or front() is requested'''
def __init__(self):
'''(Queue) -> Nonetype
creates an empty queue'''
# representation invariant
#_queue is a list
#if _queue is not empty then
# _queue[0] referes to the front/head of the queue
# _queue[-1] referes to the back/tail of the queue
# _queue[:] referes to the elements of the queue in the order of insertion
self._queue = []
def enqueue(self, element):
''' (Queue, obj) -> NoneType
add element to the back of the queue'''
# The element goes to the back of queue
self._queue.append(element)
def dequeue(self):
'''(Queue) -> obj
remove and returns the element at the front of the queue
raise an exception if _queue is empty'''
if self.is_empty():
raise EmptyQueueException ("This queue is empty")
#remove and return the item at the front
return self._queue.pop(0)
def is_empty(self):
''' (Queue) -> bool
returns true if _queue is empty'''
return (len(self._queue) == 0)
def size(self):
'''(Queue) -> int
returns the number of elements, which are in _queue'''
return len(self._queue)
def front(self):
'''(Queue) -> obj
returns the first element, which is in _queue
It raises an exception if this queue is empty'''
if (self.is_empty()):
raise EmptyQueueException("This Queue is Empty")
return self._queue[0] | true |
54492efbf4c23f590bef414dcfc611dc28dde4a0 | mrklyndndcst/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2022 | /Beginner/D004_Randomisation_and_Python_Lists/ProjectD4_Rock_Paper_Scissors.py | 1,551 | 4.15625 | 4 | import random
rock = "👊"
paper = "✋"
scissors = "✌️"
choices = [rock, paper, scissors]
player = int(input(f"What do you choose? type 1 for {rock}, 2 for {paper} or 3 for {scissors}\n"))
print("You choose")
if player < 1 or player > 3:
print("Invalid")
ai = random.randint(1 , 3)
print("Artificial Intelligence choose")
print(choices[ai - 1])
print("You loose!, please follow simple instructions..")
elif player >= 1 or player <= 3:
print(choices[player - 1])
ai = random.randint(1 , 3)
print("Artificial Intelligence choose")
print(choices[ai - 1])
if player == ai:
print("Draw!, Try again..")
elif player == 1 and ai == 2 or player == 2 and ai == 3 or player == 3 and ai == 1:
print("You loose!, Pay your debt..")
else:
print("You Win!, get your rewards..")
# user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
# if user_choice >= 3 or user_choice < 0:
# print("You typed an invalid number, you lose! ")
# else:
# print(game_images[user_choice])
# computer_choice = random.randint(0, 2)
# print("Computer chose:")
# print(game_images[computer_choice])
# if user_choice == 0 and computer_choice == 2:
# print("You win!")
# elif computer_choice == 0 and user_choice == 2:
# print("You lose")
# elif computer_choice > user_choice:
# print("You lose")
# elif user_choice > computer_choice:
# print("You win!")
# elif computer_choice == user_choice:
# print("It's a draw") | true |
e999d005eff83eca21ec9e1f4acb28cc96ba4d0b | zhanglulu15/python-learning | /python学习基础及简单实列/basic learing 6.py | 246 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 10:41:55 2018
@author: lulu
"""
count = 3
while count <= 5:
print("the count less than 5",count)
count = count + 1
else:
print("the count greater than 5",count) | true |
52c689ac08f7020700ec0ede437162eb1c0e7f81 | Valuoch/pythonClass | /pythonoperators.py | 1,375 | 4.53125 | 5 | #OPERATORS
#special symbols in python to carry out arithmetic and logical computations
#They include;
#1.arithmetic- simple math operations eg addition, sustraction, multiplication(*), division(/), modulas(%), floor(//),exponent(**)etc
#x=10
#y=23
#print(x+y)
#print(x-y)
#print(x/y)
#print(x*y)
#print(x%y)
#print(x//y)
#print(x**y)
# x = input("Enter a number:")
# print(type(x))
# x = input("Enter a number:"),
# y = input("Enter a number:")
# sum= int(x) + int(y)
# print(sum)
# 2.Comparison Operators eg greater than(>),less than(<), ==,|=,
# >=, <=
# a) greater than >
# a=12
# b=13
# a= int(input("Enter a value:"))
# b= int(input("Enter a value:"))
# print("a > is", a>b)
# print("a < is", a<b)
# print("a == is", a==b)
# print("a ! b is", a!=b)
# print("is a >=b is", a>=b)
# print("is a <=b is", a<=b)
# 3.Logical Operators
# eg and, or , not
# 1. and- returns true ONLY if both operands are true
#2.or- returns true if any of the operands is true
#3.not-inverts the true value
# m = True
# n = False
# print("m and n is", m and n)
# print("m or n", m or n)
# print("not n is", not n)
# 4. Assignment Operators - used to assign values to a variable eg =, +=, -=
# c = 10
# print(c)
# c += 10
# print(c)
# (c = c +1 0)
# c -= 5
# print(c)
# (c = c -5)
# c *= 4
# print(c)
# (c = c * 4)
#5. Membership Operators
#6. Identity Operators
#7. Bitwise Operators | true |
ccb56373dde67a27e4c4bfabd234b6d0a310cf86 | alexthomas2020/Banking | /test_Account.py | 2,028 | 4.3125 | 4 | # Banking Application
# Author: Alex Thomas
# Updated: 11/10/2020
import unittest
from Account import get_account, get_accounts, Account
"""
Banking Application - Unit tests for Account class.
Run this program to view results of the tests.
"""
class TestAccount(unittest.TestCase):
def test_get_account(self):
# check if the function returns account details.
ac_num = 'A1469'
ac_dict = get_account(ac_num)
self.assertGreater(len(ac_dict), 0)
def test_get_accounts(self):
# check if the function returns 1 or more account records.
accounts = get_accounts()
self.assertGreater(len(accounts.shape), 0)
def test_add_account_record(self):
# check if the function inserts account record into database.
ac_num = 'A_TEST1'
ac_type = 'C'
open_date = '12/12/2020'
close_date = ""
balance = int(10.00)
status = 'A'
customer_id = "C_TEST123"
account = Account(ac_num, ac_type, open_date, close_date, balance, status)
account.add_account_record(customer_id)
ac_dict = get_account(ac_num)
self.assertGreater(len(ac_dict), 0)
def test_deposit(self):
# check if the function deposit adds money to the account.
ac_num = 'A1469'
acc_dict = get_account(ac_num)
balance = acc_dict['balance']
account = Account(ac_num, "", "", "", balance, "")
deposit_amount = 99.00
new_balance = account.deposit(deposit_amount)
self.assertGreater(new_balance, deposit_amount)
def test_withdrawal(self):
# check if the function withdraws amount from the account.
ac_num = 'A1469'
acc_dict = get_account(ac_num)
balance = acc_dict['balance']
account = Account(ac_num, "", "", "", balance, "")
withdraw_amount = 99.00
new_balance = account.withdraw(withdraw_amount)
self.assertGreater(new_balance, withdraw_amount)
if __name__ == '__main__':
unittest.main()
| true |
6966ec8f669922fa1a78661630eb6732ba5b549a | matthew02/project-euler | /p005.py | 820 | 4.1875 | 4 | #!/usr/bin/env python3
"""Project Euler Problem 5: Smallest multiple
Find the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20.
https://projecteuler.net/problem=5
Usage:
python3 p0005.py [number]
"""
import sys
from math import gcd
from typing import List
def smallest_multiple(numbers: List[int]) -> int:
"""Finds the smallest integer multiple of a list of numbers.
Calculates the smallest number that is evenly divisible by all numbers in
given list, also known as the least common multiple.
"""
result = 1
for num in numbers:
result *= num // gcd(num, result)
return result
def main(stop: int):
"""Prints the result."""
print(smallest_multiple(range(1, int(stop) + 1)))
if __name__ == '__main__':
main(int(sys.argv[1]))
| true |
3d8813c43d8f57d133fb2f487cd15f65b9a59106 | gabrielbessler/ProgrammingCompetition | /AI18/AI18_1.py | 1,422 | 4.65625 | 5 | #!/bin/python3
import sys
'''
Problem Statement
You have been given an integer which represents
the length of one of cathetus of a right-angle triangle.
You need to find the lengths of the remaining sides.
There may be multiple possible answers; any one will be accepted.
'''
def pythagorean_triple(side_length):
'''
Given one cathetus of a right-angle triangle, this
function computes and returns a 3-tuple containing
3 sides of integer values for the triangle.
'''
if side_length % 2 == 1: #a is odd
k = (side_length - 1) // 2
b = 2*(k+1)*k
c = (k+1)**2 + k**2
return int(side_length), int(b), int(c)
else: #a is even
num_div = 0
while side_length % 2 != 1:
side_length //= 2
num_div += 1
if side_length == 1: # this means a was a power of 2
side_length *= (2 ** num_div)
multiple = side_length // 4
return int(side_length), int(3 * multiple), int(5 * multiple)
else:
k = (side_length - 1) // 2
b = 2*(k+1)*k
c = (k+1)**2 + k**2
mul = 2 ** num_div
return int(side_length * mul), int(b*mul), int(c*mul)
# Integer division is required (floating point math is annoying)
a = int(input().strip())
triple = pythagorean_triple(a)
print(" ".join(map(str, triple)))
| true |
85f848d0e6e073ec282e96cb98481eda112c43e4 | dstamp1/FF-BoA-2020 | /day01/day01c-ForLoops.py | 2,787 | 4.6875 | 5 | ### For Loops ###
# Computers are really good at repeating the same task over and over again without making any mistakes/typos
# Let's imagine we were having a competition to see who could type out "print('hello')" as many times as we could without using copy and paste.
# We might type out
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
# and quickly get bored or maybe a typo!
## What kind of tasks do you often have to repeat or maybe a company might need to repeat? Let's chatstorm. annticipated responses: marketing emails, order emails, happy birthday emails, etc.
## the most basic way to complete a task multiple times is too use a for loop like so:
for i in range(10):
print("Hello")
## Let's do a chat waterfall, so type but don't send yet, how many times "Hello" will print on the screen?
## let's examine what that i is doing by modifying our code
for i in range(10):
print(f"i is currently {i}")
print("Hello")
## The letter i is used as this placeholder (this placeholder frustratingly doesn't have a name, but is most commonly called the "iterator", "loop counter", "iteration variable" or "constant of iteration"), but the term i isn't special or reserved, it's just the most common. You might have seen it before in a math class during summations
## since it's a variable, we can call it anything we want so we can referennce it later.
### There are soooo many things you can do with loops. Let's talk about finding sums and you can think about other uses of the superpower.
## Lets say we want to find the sum of the numbers 5,6,7 and 8
## We could use this code:
sum = 0
for i in range(5,9):
sum += i
print(f"The sum is currently {sum}.")
print(f"The loop is over, and the total is {sum}!")
# What is the value of sum before the loop starts?
# What is the value of sum after the loop has gone one round?
# What is the value of sum after the loop has gone two rounds?
#### Let's skip over 'looping with a condition' in the teacherhub for time purposes ######
## I will mention it's something we can do
## Looping over strings ###
## So we've looked at looping over a range(), but we can loop over any 'iterable' like a string.
your_word = input("Give me a word and I'll spell it.")
print(f"Okay! I'll try to spell {your_word}.")
for letter in your_word:
print(letter)
## Lab Time: we'll be working on the loopy math lab
# git clone https://github.com/upperlinecode/loopy-math-python-iteration.git
## You might want to explore the documentation for the range() function https://www.w3schools.com/python/ref_func_range.asp
## and if you might want to know more about the modulo function to find even numbers https://www.pythoncentral.io/using-python-to-check-for-odd-or-even-numbers/ | true |
8c997e49168c94f312993b43f08b26c857579ba6 | vijaysharma1996/Python-LIst-Basic-Programmes | /list find the sum of element in list.py | 232 | 4.25 | 4 | # Python program to find sum of elements in list
# creating a list
list1 = [11, 5, 17, 18, 23]
# using sum() function
total = sum(list1)
# printing total value
print("Sum of all elements in given list: ", total)
| true |
b489616b270128b30f5f06ad34c2e4f613cdf575 | imnikkiz/Conditionals-and-Variables | /guessinggame.py | 2,344 | 4.15625 | 4 | import random
def check_guess(guess, correct):
""" Compare guess to correct answer.
Return False once guess is correct.
"""
if guess == correct:
return False
elif guess < 1 or guess > 100:
print "Your guess is out of the range 1-100, try again."
elif guess > correct:
print "Your guess is too high, try again."
else:
print "Your guess is too low, try again."
return True
def generate_guess():
""" Check raw_input for valid guess format.
Return guess and number of guesses as a tuple.
"""
count = 0
while True:
try:
guess = float(raw_input("What is your guess? > "))
count += 1
break
except ValueError:
print "Oops! That wasn't a number! Try again."
count +=1
return guess, count # Return a tuple
def play_game(player):
""" Choose number randomly. Track guess and number of guesses
until player guesses the correct number. Return number of guesses.
"""
print ("%s, I'm thinking of a number between 1 and 100. "
"Try to guess my number.") % player
number = random.randrange(1,101)
total_number_of_tries = 0
guessing = True
while guessing:
guess, guess_count = generate_guess() # Unpack the returned tuple
total_number_of_tries += guess_count
guessing = check_guess(guess, number) # False = guess is correct
print ("Well done, %s! You found my number "
"in %d tries!") % (player, total_number_of_tries)
return total_number_of_tries
def main():
""" Greet player and track high score.
Each round is instigated by play_game, and the round score is assigned to
game_score. The highest score is tracked in main. Player may choose
to continue playing.
"""
your_name = raw_input("Welcome to the guessing game! What is your name? > ")
high_score = 1000
playing = True
while playing:
game_score = play_game(your_name)
high_score = min(high_score, game_score)
print "Your score is: ", game_score
print "Best score is: ", high_score
answer = raw_input("Would you like to play again? > ")
if answer[0].upper() == "N":
playing = False
if __name__ == "__main__":
main()
| true |
6166a4a86a3a486745dee02399b400820ba446d9 | raresrosca/CtCI | /Chapter 1 Arrays and Strings/9_stringRotation.py | 847 | 4.125 | 4 | import unittest
def is_rotation(s1, s2):
"""Return True if s2 is a rotation of s1, False otherwise"""
for i, c in enumerate(s2):
if c == s1[0]:
if s2[i:]+s2[:i] == s1:
return True
return False
def is_rotation_2(s1, s2):
"""Return True if s2 is a rotation of s1, False otherwise. Uses the 'in' operator."""
if len(s1) == len(s2) != 0 and s2 in s1+s1:
return True
return False
class Test(unittest.TestCase):
'''Test Cases'''
data = [
('waterbottle', 'erbottlewat', True),
('foo', 'bar', False),
('foo', 'foofoo', False)
]
def test_string_rotation(self):
for [s1, s2, expected] in self.data:
actual = is_rotation_2(s1, s2)
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main()
| true |
55885f48b318943495a44ff4454b5c21ca1f3f45 | sirajmuneer123/anand_python_problems | /3_chapter/extcount.py | 533 | 4.125 | 4 | #Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.
import os
import sys
cwd=os.getcwd()
def count(cwd):
list1=os.listdir(cwd)
newlist=[]
frequency ={}
for i in list1:
if os.path.isfile(i):
newlist.append(i.split(".")[1])
for j in newlist:
frequency[j]=frequency.get(j,0)+1
for key,value in frequency.items():
print key ,value
count(cwd)
| true |
9fdf38d1a2c8bf2460625ff16b4ebc6692936cfc | sirajmuneer123/anand_python_problems | /2_chapter/factorial.py | 412 | 4.1875 | 4 | #Problem 5: Write a function factorial to compute factorial of a number. Can you use the product function defined in the previous example to compute factorial?
array=[]
def factorial(number):
while number!=0:
array.append(number)
number=number-1
return array
def product(num):
mul=1
a=len(num)
while a!=0:
mul=mul*num[a-1]
a=a-1
return mul
s=product(factorial(4))
print "factorial is =%s" % s
| true |
38171858be0fc89461f6e38bb85d7585c18525c1 | LTTTDH/dataScienceHelpers | /NaNer.py | 477 | 4.125 | 4 | # This function was created to deal with numerical columns that contain some unexpected string values.
# NaNer converts all string values into np.nans
def NaNer(x):
"""Takes a value and converts it into a float.
If ValueError: returns np.nan
Originally designed to use with pandas DataFrames.
Example: your_df['YourColumn'].transform(NaNer)
"""
try:
x = float(x)
except ValueError:
x = np.nan
return x
| true |
ee9d018f5a7fd7e23e66f972c0ab3aa8f8d19e27 | PingryPython-2017/black_team_palindrome | /palindrome.py | 823 | 4.28125 | 4 | def is_palindrome(word):
''' Takes in an str, checks to see if palindrome, returns bool '''
# Makes sure that the word/phrase is only lowercase
word = word.lower()
# Terminating cases are if there is no characters or one character in the word
if len(word) == 0:
return True
if len(word) == 1:
return True
# Checks if the first character in the word is different than the last character is the world. If not, then that means the word is not a palindrome.
if word[0] != word[len(word) - 1]:
return False
# This means that the first character is equal to the last character.
else:
# Slices the word so that the first character and the last character is cut off.
word2 = word[1:-1]
# Recurses with this new word.
if is_palindrome(word2) == True:
return True
else:
return False
| true |
be832202e22425289126c594a6c5649cff49d533 | dan76296/stopwatch | /stopwatch.py | 1,495 | 4.25 | 4 | import time
class StopWatch:
def __init__(self):
''' Initialises a StopWatch object'''
self.start_time = None
self.end_time = None
def __repr__(self):
'''Represents the object in a readable format'''
return 'Time Elapsed: %r' % ':'.join((self.convertSeconds(self.result)))
def start(self):
''' Start the StopWatch '''
self.start_time = time.time()
def stop(self):
''' Stop the StopWatch'''
self.end_time = time.time()
pass
def split(self):
'''Starts a split timer'''
self.split_start_time = time.time()
pass
def unsplit(self):
'''Stops the split timer, returns time elapsed since split'''
self.result = time.time() - self.split_start_time
return self.__repr__()
def time_elapsed(self):
'''Time elapsed since last start'''
self.result = time.time() - self.start_time
return self.__repr__()
def total_runtime(self):
'''Time elapsed between Start and Stop'''
self.result = self.end_time - self.start_time
return self.__repr__()
def convertSeconds(self, seconds):
'''Converts seconds into hours and minutes'''
h = int(seconds//(60*60))
m = int((seconds-h*60*60)//60)
s = round(seconds-(h*60*60)-(m*60), 2)
h = str(h) + 'h'
m = str(m) + 'm'
s = str(s) + 's'
return h.strip('.'), m.strip('.'), s
| true |
aa08a6475f125520389646b0551301a54dafcf89 | GitFiras/CodingNomads-Python | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 992 | 4.4375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
# sort numbers
numbers_ = [ 1, 5, 4, 67, 88, 99, 3, 2, 12]
numbers_.sort()
print(numbers_)
# check for odd numbers use % to check: 0 = even, 1 is odd
x = len(numbers_)
if x % 2 == 1:
numbers_.append(0) # add '0' to the list, because list is odd
# sort numbers in tuples of two in a list
list_numbers = []
# print(numbers_[::2]) steps of 2, starting at the start of the list
for i in range(0,len(numbers_),2): # range start at start of list, till end of list, by steps of 2
j = tuple(numbers_[i:i+2]) # turn the 2 numbers into tuples
list_numbers.append(j) # append new numbers to new list
print(list_numbers)
| true |
be616a73c1e05410a1461277824f37d45e8a3d24 | GitFiras/CodingNomads-Python | /13_aggregate_functions/13_03_my_enumerate.py | 693 | 4.3125 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate():
index = 0
value_list = ['apple', 'banana', 'pineapple', 'orange', 'grape'] # list
for value in value_list: # loop for values in list
index += 1 # increase index by 1 with each value
yield index -1, value # yield output: index, value
print(list(my_enumerate())) # call function and print in list | true |
64c9d551092b05a7d1fc1b4919403731cb2aa07d | GitFiras/CodingNomads-Python | /04_conditionals_loops/04_01_divisible.py | 473 | 4.40625 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
num = int(input('Please provide a number between 1 and 1,000,000,000: '))
if num % 3 == 0: # if output is 0, the number can be divided by 3 without residual value.
print(int(num/3))
else:
print("Your number cannot be divided by 3, please insert another number")
| true |
48550e1cb00bf023ec1394a0d0c8116fa0c8c456 | GitFiras/CodingNomads-Python | /06_functions/06_01_tasks.py | 2,146 | 4.25 | 4 | '''
Write a script that completes the following tasks.
'''
# define a function that determines whether the number is divisible by 4 or 7 and returns a boolean
print("Assignment 1 - Method 1:")
def div_by_4_or_7(x):
if x % 4 == 0:
print(f"{x} is divisible by 4: ",True) # boolean True if function returns True
return True
elif x % 7 == 0:
print(f"{x} is divisible by 7: ",True) # boolean True if function returns True
return True
else:
print(f"{x} is divisible by 4 or 7: ",False) # boolean False if function returns False
return False
var = div_by_4_or_7(7) # calling the function with variable input = 7
print(var)
# define a function that determines whether a number is divisible by both 4 and 7 and returns a boolean
print("Assignment 2")
def div_by_4_and_7(z):
if z % 4 == 0 and z % 7 == 0:
print(f'{z} is divisible by 4 and 7: {True}')
return True
else:
print(f"{z} is not divisible by 4 and 7: ",False)
return False
var2 = div_by_4_and_7(28) # calling the function with variable input = 28
print("divisible by 4 and 7: ",var2)
# take in a number from the user between 1 and 1,000,000,000
# call your functions, passing in the user input as the arguments, and set their output equal to new variables
num = 0
# while num != 100: # optional while loop
num = int(input("Please insert a number between 1 and 1,000,000,000: ")) # user input INT
div_by_4_or_7(num) # calling function with input = num
div_by_4_and_7(num) # calling function with input = num
# print your new variables to display the results
xx = div_by_4_or_7(num) # new variable based on function
yy = div_by_4_and_7(num) # new variable based on function
print("div_by_4_or_7",xx)
print("div_by_4_and_7",yy)
| true |
3ad789eadbc061a3dafa8af235e28282e659ad63 | GitFiras/CodingNomads-Python | /09_exceptions/09_05_check_for_ints.py | 669 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
while True:
try:
user_input = input("Please provide a number value: ")
int_input = (int(user_input))
if user_input == int:
print(f'Your input {user_input} was correct.')
break # break if correct
except ValueError as val_err:
print(f'Your input {user_input} was not a number value. Please try again.') | true |
c43746c218b0df727e187614f7859b0146575356 | GitFiras/CodingNomads-Python | /03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 506 | 4.3125 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list_ = []
# Iteration from dict to list with tuples
for i in input_dict:
j = (i, input_dict[i])
list_.append(j)
print(list_)
print(sorted(list_, key = lambda sorted_number : sorted_number[1])) # sort by the number of index 1 [1]. | true |
20acb5c9c5b63cfb04b70a82a815027e856fb517 | GitFiras/CodingNomads-Python | /Inheritance - Course Example Code.py | 1,361 | 4.46875 | 4 | class Ingredient:
"""Models an Ingredient."""
def __init__(self, name, amount):
self.name = name
self.amount = amount
def expire(self):
"""Expires the ingredient item."""
print(f"whoops, these {self.name} went bad...")
self.name = "expired " + self.name
def __str__(self):
return f"You have {self.amount} {self.name}."
# we can define new classes that take over all their superclasses' variables and methods:
class Spice(Ingredient): # means it inherits from the Ingredient class
# test of Class
# p = Ingredient('peas', 12)
# print(p)
# s = Spice('salt', 200)
# print(s) # no need to define __str__() again - it works!
# let's give Spice a method that its superclass doesn't have!
def grind(self):
print(f"You have now {self.amount} of ground {self.name}.")
c = Ingredient('carrots', 3)
p = Spice('pepper', 20)
print(c, p)
p.grind()
# c.grind() # produces an error
class Spice(Ingredient):
# we override this inherited method
def expire(self):
if self.name == 'salt':
print(f"{self.name} never expires! ask the sea!")
else:
print(f"eh... sorry but that {self.name} actually got bad!")
self.name = "expired " + self.name
c = Ingredient('carrots', 3)
p = Spice('pepper', 20)
s = Spice('salt', 200)
print(c, p, s)
p.expire()
print(p)
# try calling expire() with the c and s objects!
| true |
f39fadba2f9d57dd9c9f59c827619f891d579fa4 | SnehaMercyS/python-30-days-internship-tasks | /Day 7 task.py | 1,734 | 4.125 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #1) create a python module with list and import the module in anoother .py file and change the value in list
>>> list=[1,2,3,4,5,6]
>>> import mymodule
>>> mymodule.list.append(7)
>>> print(mymodule.list)
[1, 2, 3, 4, 5, 6, 7]
>>> #2) install pandas package (try to import the package in a python file
>>> import pandas as pd
>>> import numpy as np
>>> import sys
>>> sys._stdout_=sys.stdout
>>> fruit = np.array(['apple','orange','mango','pear'])
>>> series = pd.Series(fruits)
>>> print(series)
0 apple
1 orange
2 mango
3 pear
dtype: object
>>> #3) import a module that picks random number and write a program to fetch a random number from 1 to 100 on every run
>>> import random
>>> print("random integer is :",random.randint(1,100))
random integer is : 93
>>> #4) import sys package and find the python path
>>> import sys
>>> sys.path
['C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\pandas', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\ELCOT\\Downloads\\python-3.9.0-amd64.exe', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
>>> #5)try to install a package and uninstall a package using pip
>>>
| true |
81af9ef448d9228b34e6c8017b034ccd6405d9ea | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Arrays/2dArrays.py | 1,025 | 4.125 | 4 | import os
# Create a 2D array and print some of their elements.
studentGrades = [[72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60]]
print(studentGrades[1])
print(studentGrades[0])
print(studentGrades[2])
print(studentGrades[3][4])
# Traverse the array.
for student in studentGrades:
for grade in student:
print(grade, end=" ")
print()
# Insert an element into the 2D array.
os.system("cls")
studentGrades.insert(1, [84, 93, 72, 60, 75])
for student in studentGrades:
for grade in student:
print(grade, end=" ")
print()
# Update elements of the array.
studentGrades[0] = [77, 90, 92, 95, 74]
studentGrades[1][2] = 77
os.system("cls")
for student in studentGrades:
for grade in student:
print(grade, end=" ")
print()
# Delete elements of the array.
del(studentGrades[0][2])
del(studentGrades[1])
os.system("cls")
for student in studentGrades:
for grade in student:
print(grade, end=" ")
print()
| true |
ba5b7564b61ea7d0bacdfcb2ac19024a39f163ae | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Stacks and Queues/sortingQueues.py | 730 | 4.15625 | 4 | import queue
# Create the object and add some elements to it.
myQueue = queue.Queue()
myQueue.put(14)
myQueue.put(27)
myQueue.put(11)
myQueue.put(4)
myQueue.put(1)
# Sort with Bubble Sort algorithm.
size = myQueue.qsize()
for i in range(size):
# Remove the element.
item = myQueue.get()
#Remove the next element.
for j in range(size-1):
nextItem = myQueue.get()
# Check which item is greater and put the smaller one at the beginning of the Queue.
if item > nextItem:
myQueue.put(nextItem)
else:
myQueue.put(item)
item = nextItem
myQueue.put(item)
while(myQueue.empty() == False):
print(myQueue.queue[0], end=" ")
myQueue.get()
| true |
ec94e882ff4f039bad9c0785c6d615c445cb706b | shyboynccu/checkio | /old_library/prime_palindrome.py | 1,877 | 4.28125 | 4 | #!/usr/local/bin/python3
# An integer is said to be a palindrome if it is equal to its reverse in a string form. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N. You must find the smallest integer M >= N such that M is a prime number and M is a palindrome.
# Input: An integer.
# Output: A prime palindrome. An integer.
from math import sqrt, floor
def is_prime(number):
for n in range(2, floor(sqrt(number)) + 1):
if number % n == 0:
return False
return True
def find_smallest_prime_palindrome(lower_bound, palindrome_list):
for m in palindrome_list:
if m >= lower_bound and is_prime(m):
return m
return None
def checkio(data):
palindrome = [[],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[11, 22, 33, 44, 55, 66, 77, 88, 99]]
digit = 1
while True:
if digit < 3:
m = find_smallest_prime_palindrome(data, palindrome[digit])
if m:
return m
else:
mid_palindrome_list = palindrome[digit-2]
this_palindrome_list = []
for n in range(1, 10):
if mid_palindrome_list:
temp_list = [n*10**(digit-1) + x*10 + n for x in mid_palindrome_list]
if data < pow(10, digit):
m = find_smallest_prime_palindrome(data, temp_list)
if m:
return m
this_palindrome_list += temp_list
palindrome.append(this_palindrome_list)
digit += 1
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(31) == 101, 'First example'
assert checkio(130) == 131, 'Second example'
assert checkio(131) == 131, 'Third example' | true |
48798e1b51baefc7c23b92cf86b34eef35313cee | emilnorman/euler | /problem007.py | 493 | 4.15625 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
#
# What is the 10 001st prime number?
def next_prime(p):
temp = p + 2
for i in xrange(3, temp, 2):
if ((temp % i) == 0):
return next_prime(temp)
return temp
n = 2
prime = 3
while(n < 10001):
prime = next_prime(prime)
n += 1
print(n, prime)
print("n:"),
print(n)
print("prime:"),
print(prime)
| true |
05bd5cba24b50221d83ae84bee8958dff9b2c7ae | rsoemardja/Python | /PythonAndPygameArcade/Chapter 3 Quiz Games and If Statements/3.2/PythonOrder/PythonOrder/test.py | 996 | 4.3125 | 4 | # we are going to be taking a look at logic with if Statements
# Their is actually a hidden error
# The error is that computer looks at each statement
# and is 120 > 90. It is indeed and the else would execute but the else DID not excute hence the logic error
temperature=input("What is the temperature in Fahrenheit? ")
temperature=int(temperature)
if temperature > 90:
print("It is hot outside.")
elif temperature > 110:
print ["Oh man, you could fry egg on the pavement"]
elif temperature < 30:
print ("It is cold outside.")
else:
print("It is not hot outside")
print ("Done")
# This is now correct and now the statement should be okay
temperature=input("What is the temperature in Fahrenheit? ")
temperature=int(temperature)
if temperature > 110:
print("It is hot outside.")
elif temperature > 90:
print ["Oh man, you could fry egg on the pavement"]
elif temperature < 30:
print ("It is cold outside.")
else:
print("It is not hot outside")
print ("Done")
| true |
313c45fa97a1c12eee440966216c3904f549cd07 | KDRGibby/learning | /nthprime.py | 781 | 4.46875 | 4 | def optimusPrime():
my_list = [1,2]
my_primes = []
prime_count = 0
# this is supposed to add numbers to my_list until the prime count reaches x numbers.
while prime_count < 10:
last_num = my_list[-1]
my_list.append(last_num + 1)
#here we check to see if a number in my_list is a prime
for i in my_list:
#divisibles counts how many numbers can be evenly divided into x. Primes are only divisible by 2 numbers, itself and 1.
divisibles = 0
if last_num % i == 0:
divisibles += 1
if divisibles < 3:
#at this point we should have found a prime and thus we are adding to the prime count and appending the number to my_primes list.
prime_count = prime_count + 1
my_primes.append(last_num)
print my_list
print my_primes
optimusPrime()
| true |
e170befde825656d17d5b17b81cd51d3c0f09c55 | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/P/P-1.36.py | 294 | 4.125 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python program that inputs a list of words, separated by whitespace,
and outputs how many times each word appears in the list. You
need not worry about efficiency at this point, however, as this topic is
something that will be addressed later in this book
""" | true |
fbef3fb244b0ecb1c97a293c1f9e029fe3273f6f | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 2/R/R-2.4.py | 426 | 4.3125 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number
of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your class should
include methods for setting the value of each type, and retrieving the value
of each type.
""" | true |
3d1efee5bd503d5503ecafc36e40b60ef833fb7c | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/R/R-1.1.py | 590 | 4.40625 | 4 | #-*-coding: utf-8 -*-
"""
Write a short Python function, is_multiple(n, m), that takes two integer
values and returns True if n is a multiple of m, that is, n = mi for some
integer i, and False otherwise
"""
def is_multiple(n, m):
n = int(n)
m = int(m)
if n % m == 0 and n != 0:
return True
else:
return False
if __name__ == '__main__':
e = is_multiple(4, 2)
print e
# e1 = is_multiple(4, 4)
# print e1
# e2 = is_multiple(0, 4)
# print e2
# e3 = is_multiple(4, 0)
# print e3
# e4 = is_multiple(4, 5)
# print e4
| true |
092eca02e6e2d164b20444d05b2c328e0b548cb6 | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/P/P-1.32.py | 395 | 4.21875 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python program that can simulate a simple calculator, using the
console as the exclusive input and output device. That is, each input to the
calculator, be it a number, like 12.34 or 1034, or an operator, like + or =,
can be done on a separate line. After each such input, you should output
to the Python console what would be displayed on your calculator.
""" | true |
88f2f7683025b2fcbcc0006b279bce698743d10b | himanshu2801/leetcode_codes | /sort colors.py | 912 | 4.15625 | 4 | """
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Follow up:
Could you solve this problem without using the library's sort function?
Could you come up with a one-pass algorithm using only O(1) constant space?
"""
class Solution:
def sortColors(self, nums: List[int]) -> None:
p0 = 0
p2 = len(nums)-1
p1 = 0
while p1<=p2:
if nums[p1] == 2:
nums[p2],nums[p1] = nums[p1],nums[p2]
p2 -= 1
elif nums[p1] == 0:
nums[p0],nums[p1] = nums[p1],nums[p0]
p0 += 1
p1 += 1
else:
p1 += 1
return nums
| true |
96ffd6f2d96e810840f4e8aab3bd3d5968f600ba | bitomann/classes | /pizza_joint.py | 1,322 | 4.625 | 5 | # 1. Create a Pizza type for representing pizzas in Python. Think about some basic
# properties that would define a pizza's values; things like size, crust type, and
# toppings would help. Define those in the __init__ method so each instance can
# have its own specific values for those properties.
class Pizza:
def __init__(self):
self.size = ""
self.crust_type = ""
self.toppings = []
# 2. Add a method for interacting with a pizza's toppings, called add_topping.
def add_topping(self, topping):
self.toppings.append(topping)
# 3. Add a method for outputting a description of the pizza (sample output below).
def print_order(self):
print(f"The pizza is {self.size} inches with a {self.crust_type} crust with "
+ " and ".join(self.toppings) + ".")
# 4. Make two different instances of a pizza. If you have properly defined the class,
# you should be able to do something like the following code with your Pizza type.
meat_lovers = Pizza()
meat_lovers.size = 16
meat_lovers.crust_type = "deep dish"
meat_lovers.add_topping("Pepperoni")
meat_lovers.add_topping("Olives")
meat_lovers.print_order()
# You should produce output in the terminal similar to the following string:
# "I would like a 16-inch, deep-dish pizza with Pepperoni and Olives."
| true |
c05f369e874662f1f383cd25148e99c980f37d49 | Vohsty/password-locker | /user.py | 1,472 | 4.21875 | 4 | class User:
"""
Class to generate new instances of users
"""
user_list= [] # Empty user list
def __init__(self, f_name, l_name, username, password):
'''
To take user input to create a new user
'''
self.f_name = f_name
self.l_name = l_name
self.username = username
self.password = password
def save_user(self):
'''
save_user method saves user objects into user_list
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_user method deletes a saved user from the user_list
'''
User.user_list.remove(self)
@classmethod
def find_by_username(cls, username):
'''
Method that takes in a username and returns a user that matches that username.
Args:
username: username to search for
Returns :
User of person that matches the username.
'''
for user in cls.user_list:
if user.username == username:
return user
@classmethod
def user_exist(cls, username):
'''
Method that checks if a user exists from the user array.
Args:
username: username to search if it exists
Returns :
Boolean: True or false depending if the user exists
'''
for user in cls.user_list:
if user.username == username:
return True | true |
3f6e66a5e45651ee7fe6dd0454f771b6343edc29 | davidjbrossard/python | /hello.py | 669 | 4.3125 | 4 | import math as m
"""
This method takes in a string and returns another string. It encrypts the content of the string by using the Caesar cipher.
"""
def encrypt(message, offset):
encryptedString = "";
for a in message:
encryptedString+=chr(ord(a)+offset);
return encryptedString;
"""
This method takes in a string and returns another string. It decrypts the content of the string by using the inverse of the Caesar cipher
"""
def decrypt(message,offset):
decryptedString = "";
for a in message:
decryptedString+=chr(ord(a)-offset);
return decryptedString;
print(encrypt("Zebulon", 1));
print(decrypt(encrypt("Zebulon", 1),1)); | true |
9473f6456519749d1b687bc83cf290e9d31316cf | KoushikRaghav/commandLineArguments | /stringop.py | 1,399 | 4.125 | 4 | import argparse
def fileData(fileName,stringListReplace):
with open(fileName,'w') as f:
f.write(str(stringListReplace))
print stringListReplace
def replaceString(replace,stringList,fileName,word):
rep = replace.upper()
stringListReplace = ' '
for w in stringList:
stringListReplace = w.replace(word, rep)
fileData(fileName,stringListReplace)
def findString(word, stringList):
for s in stringList:
if word in s:
print ('{} is found\n'.format(word.upper()))
#print stringList
else:
print 'String is not found\n'
exit()
def fileOpen(fileName):
with open(fileName,'r') as f:
stringList = f.read().split(',')
return stringList
def argParser():
parser = argparse.ArgumentParser(description = 'String Operation')
parser.add_argument('filename', help = 'name of the file')
parser.add_argument('s',help = 'word for searching strings in the file')
parser.add_argument('-r', help = 'word for replacing strings in the file')
args = parser.parse_args()
return args
def main():
args = argParser()
fileName = args.filename
word = args.s
replace = args.r
if args.s is not None:
stringList = fileOpen(fileName)
findString(word, stringList)
else:
exit()
#print args.word
if replace is None:
print stringList
exit()
else:
replaceString(replace,stringList,fileName,word)
if __name__ == '__main__':
main()
| true |
5ce58dda0c9928a43e3463e7447ce63f404c5e51 | brickfaced/data-structures-and-algorithms | /challenges/multi-bracket-validation/multi_bracket_validation.py | 2,197 | 4.34375 | 4 | class Node:
"""
Create a Node to be inserted into our linked list
"""
def __init__(self, val, next=None):
"""
Initializes our node
"""
self.val = val
self.next = next
def __repr__(self, val):
"""
Displays the value of the node
"""
return '{val}'.format(val=self.val)
class Stack:
def __init__(self, iter=[]):
self.top = None
self._height = 0
for item in iter:
self.push(item)
def __repr__(self):
"""
Returns a string that contains the value of the top of the stack
"""
if self._height == 0:
return 'Stack is empty'
return 'Top of stack is {}'.format(self.top.val)
def __str__(self):
"""
Returns the value of the top of the stack
"""
if self._height == 0:
return 'Stack is empty'
return self.top.val
def __len__(self):
return self._height
def peek(self):
"""
Returns the value of the top of the stack
"""
return self.top.val
def push(self, val):
"""
Pushes a new value at the top of the stack
"""
self.top = Node(val, self.top)
self._height += 1
def pop(self):
"""
Removes the value at the top of the stack and sets the next value
as the new top
"""
if len(self) == 0:
raise IndexError('Stack is empty')
temp = self.top
self.top = temp.next
self._height -= 1
return temp.val
def multi_bracket_validation(string):
"""
Validates if each bracket has a pair
"""
if isinstance(string, str) is False:
raise TypeError('Input is not a string')
brackets = {'(': ')', '{': '}', '[': ']'}
balance = Stack()
for i in string:
if i in brackets.keys():
balance.push(i)
if i in brackets.values():
if balance.top is None:
return False
elif brackets[balance.top.val] == i:
balance.pop()
if len(balance) == 0:
return True
return False
| true |
d1f9324a011cbbe33a65a2005115e06ab86f74d1 | brickfaced/data-structures-and-algorithms | /data-structures/binary_search_tree/fizzbuzztree.py | 602 | 4.5625 | 5 | def fizzbuzztree(node):
"""
Goes through each node in a binary search tree and sets node values to
either Fizz, Buzz, FizzBuzz or skips through them depending if they're
divisible by 3, 5 or both. The best way to use this function is to
apply it to a traversal method. For example: BST.in_order(fizzbuzztree)
"""
if node.val % 3 == 0 and node.val % 5 == 0:
node.val = 'FizzBuzz'
return
if node.val % 5 == 0:
node.val = 'Buzz'
return
if node.val % 3 == 0:
node.val = 'Fizz'
return
else:
pass
return
| true |
0a748373a51802c7500f8b6bd72cbd44d3f467d9 | brickfaced/data-structures-and-algorithms | /data-structures/hash_table/repeated_word.py | 857 | 4.125 | 4 | """Whiteboard Challenge 31: Repeated Word"""
from hash_table import HashTable
def repeated_word(text):
"""
Function returns the first repeated word.
First thing it does is splits the inputted string
into a list and for each word in that list it checks
if that word is already in the hash table, if it isn't it adds
word to the hash table. If it is it'll return that word and
complete the problem domain. If it goes through the entire word list
and there is no repeat words it'll return a informative output
"""
if type(text) is not str:
raise TypeError('Please Enter A String')
words = text.split(' ')
word_hasher = HashTable()
for word in words:
if word_hasher.get(word) == [word]:
return word
word_hasher.set(word, word)
return 'There are no repeated words'
| true |
b26893e0db5a57db2eed7de038eedc67337aecbf | abhaysingh00/PYTHON | /even odd sum of 3 digit num.py | 307 | 4.21875 | 4 | n= int(input("enter a three digit number: "))
i=n
sm=0
count=0
while(i>0):
count=count+1
sm=i%10+sm
i=i//10
if(count==3):
print(sm)
if(sm%2==0):
print("the sum is even")
else:
print("the sum is odd")
else:
print("the number entered is not of 3 digits")
| true |
7bd2f2e61e7a2728c265e2606e06fc8e95e6d7e3 | aman1698/Semester-5 | /SEE/1/1a.py | 728 | 4.125 | 4 | def insert():
l=[]
while(True):
print("1-insert an element\n2-exit")
n=int(input())
if(n==1):
print("Enter the element")
n1=int(input())
l.append(n1)
else:
return l
l1=insert()
#l1=input().split()
print("Original List: ",l1)
l1.sort()
l2=len(l1)
print("Maximum Element ",l1[l2-1])
print("Minimum Element ",l1[0])
l3=int(input("Enter the number to be inserted\n"))
l1.append(l3)
print("List after insertion : ",l1)
l4=int(input("Enter the element to be deleted\n"))
if l4 in l1:
l1.remove(l4)
print("List after Deletion : ",l1)
else:
print("Element not present to be Deleted")
l5=int(input("Enter the element to be searched\n"))
if l5 in l1:
print("Element Found")
else:
print("Element not found")
| true |
8b83fbcfd31ba3cc1676ee16906a6bbd2935af98 | sanketsoni/6.00.1x | /longest_substring.py | 796 | 4.375 | 4 | """
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
"""
s = 'abcabc'
maxlength = 0
string1 = s[0]
string2 = s[0]
for i in range(len(s)-1):
if s[i+1] >= s[i]:
string1 += s[i+1]
if len(string1) > maxlength:
string2 = string1
maxlength = len(string1)
else:
string1 = s[i+1]
i += 1
print("Longest substring in alphabetical order is:{}".format(string2))
| true |
72f2fa7a7980edb279f23269173545890ebd360b | mohor23/code_everyday | /binary_search(recursive).py | 701 | 4.125 | 4 | //binary search using recursion in python
def binary_search(arr,l,h,number):
if l<=h:
mid=(l+h)//2
if(arr[mid]==number):
return mid
elif(number<arr[mid]):
binary_search(arr,l,mid-1,number)
else:
binary_search(arr,mid+1,h,number)
else:
return -1
arr=[]
n=int(input("enter the number of elements of array"))
for i in range(0,n):
ele=int(input("enter the elements of the array in sorted order"))
arr.append(ele)
print(arr)
number=int(input("enter the element to be searched"))
result=binary_search(arr,0,n-1,number)
if(result==-1):
print("element not found")
else:
print("element found at index",result)
| true |
8b6df693a8931d87148817973e68ef401f524d73 | xuefengCrown/Learning-Python | /Beginning Python/database.py | 2,953 | 4.15625 | 4 | # Listing 10-8. A Simple Database Application
# database.py
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
pid = raw_input('Enter unique ID number: ')
person = {}
person['name'] = raw_input('Enter name: ')
person['age'] = raw_input('Enter age: ')
person['phone'] = raw_input('Enter phone number: ')
db[pid] = person
def lookup_person(db):
"""
Query user for ID and desired field, and fetch the corresponding data from
the shelf object
"""
pid = raw_input('Enter ID number: ')
field = raw_input('What would you like to know? (name, age, phone) ')
field = field.strip().lower()
print field.capitalize() + ':', \
db[pid][field]
def print_help():
print 'The available commands are:'
print 'store : Stores information about a person'
print 'lookup : Looks up a person from ID number'
print 'quit : Save changes and exit'
print '? : Prints this message'
def enter_command():
cmd = raw_input('Enter command (? for help): ')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('C:\\database.dat') # You may want to change this name
try:
while True:
cmd = enter_command()
if cmd == 'store':
store_person(database)
elif cmd == 'lookup':
lookup_person(database)
elif cmd == '?':
print_help()
elif cmd == 'quit':
return
finally:
database.close()
if __name__ == '__main__': main()
The program shown in Listing 10-8 has several interesting features:
• Everything is wrapped in functions to make the program more structured. (A possible
improvement is to group those functions as the methods of a class.)
• The main program is in the main function, which is called only if __name__ == '__main__'.
That means you can import this as a module and then call the main function from another
program.
• I open a database (shelf) in the main function, and then pass it as a parameter to the other
functions that need it. I could have used a global variable, too, because this program is
so small, but it’s better to avoid global variables in most cases, unless you have a reason
to use them.
• After reading in some values, I make a modified version by calling strip and lower on
them because if a supplied key is to match one stored in the database, the two must be
exactly alike. If you always use strip and lower on what the users enter, you can allow
them to be sloppy about using uppercase or lowercase letters and additional white-
space. Also, note that I’ve used capitalize when printing the field name.
• I have used try and finally to ensure that the database is closed properly. You never
know when something might go wrong (and you get an exception), and if the program
terminates without closing the database properly, you may end up with a corrupt data-
base file that is essentially useless. By using try and finally, you avoid that.
| true |
fafaffc7c97297e40be44fb5b0bd2b77b6bfb4e2 | InfinityTeq/Introduction-to-Python3 | /module05/m5-practice/data-comparison.py | 902 | 4.15625 | 4 | # for this module's practice:
# we will use sets to compare data
# created by : C0SM0
# sets of animals that can live on land and sea [respectively]
can_live_on_land = {"Wolves", "Alligator", "Deer"}
can_live_in_sea = {"Fish", "Dolphin", "Alligator"}
# create terrestial specific sets for the creature types
land_creatures = can_live_on_land - can_live_in_sea
sea_creatures = can_live_in_sea - can_live_on_land
amphibious_creatures = can_live_on_land & can_live_in_sea
# output, creatures that can live on land
print(f"Creatures that live on land:\n{land_creatures}\n")
print(f"Creatures that live in water:\n{sea_creatures}\n")
print(f"Creatures that live in both:\n{amphibious_creatures}\n")
# feel free to keep practicing, here are some more ideas
"""
- compare food at home to food on your grocery list
- prevent duplicate entries when creating an account or submitting quiz/survey answers
""" | true |
534f12658f7dffa0efca11c00226adb79df46c76 | InfinityTeq/Introduction-to-Python3 | /module03/m3-practice/multiplication-tables.py | 682 | 4.4375 | 4 | # for this module's practice:
# we will make a program that will generate multiplication tables
# created by : C0SM0
# variables
range_limit = range(1, 13)
# iterate through each table
for table_number in range_limit:
# banner
print(f"\nMultiplication Table for {table_number}:")
# iterate through each multiple
for multiple in range_limit:
answer = table_number * multiple
print(f"{table_number} x {multiple} = {answer}")
# feel free to keep practicing, here are some more ideas
"""
- multiplication table with user input
- users can ask for certain tables or to list the first 12
- a quiz that can end if a question is answered wrong
"""
| true |
8219a19e2e78f610f4acdff4d3139c5b65d36642 | mhamzawey/DataStructuresAlgorithms | /InsertionSort.py | 665 | 4.28125 | 4 | from BinarySearch import binarySearch
def insertionSort(arr):
"""
Insertion sort is a simple sorting algorithm
that works the way we sort playing cards in our hands.
:param arr:
:return: arr
Complexity O(n^2
"""
for i in range(len(arr)):
current = arr[i]
j = i - 1
while j >= 0 and arr[j] > current:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = current
return arr
x_array = [54, 26, 93, 17, 77, 31, 44, 55, 20, 89, 0]
print("Insertion Sort Algorithm: " + str(insertionSort(x_array)))
y = binarySearch(55, x_array, 0, len(x_array) - 1)
print(y)
| true |
af531dfc2e22c0b2ef6500bb74b484331f2c6ac7 | chokkalingamk/python | /Bitwise_operators.py | 588 | 4.28125 | 4 | #This is the Bitwise program to check
print ("Welcome to Addition Calculator")
print ("Enter the value A")
a = int(input())
print ("Enter the value B")
b = int(input())
and_val = (a & b)
or_val = (a | b)
xor_val = (a ^ b)
#not_val = (a ~ b)
left_val = (a << b)
right_val = (a >> b)
print ("The value of A is ", a )
print ("The value of B is ", b )
print ("The value of AND is", and_val)
print ("The value of OR is", or_val)
print ("The value of XOR is", xor_val)
#print ("The value of not is", not_val)
print ("The value of left is", left_val)
print ("The value of right is", right_val)
| true |
955ba7fa1d1b396827c775318180d15ccf0b0ffe | ambateman/TechAcademy | /Python/PyDrill_Datetime_27_idle.py | 732 | 4.125 | 4 | #Python 2.7
#Branches open test
#Drill for Item 62 of Python Course
#
#The only quantity that should matter here is the hour. If the hour is between 9 and 21
#for that office, then that office is open.
import datetime
portlandTime = datetime.datetime.now().hour
nyTime = (portlandTime + 3)%24 #NYC is three hours ahead of portland
londonTime = (portlandTime + 8)%24 #London is 8 hours ahead of portland
#Which of the non-Portland branch offices are open?
if nyTime>=9 and nyTime<21:
print "NYC Branch Office is Open"
else:
print "NYC Branch Office is Closed"
if londonTime>=9 and londonTime<21:
print "London Branch Office is Open"
else:
print "London Branch Office is Closed"
| true |
dc46be41cfc4becb94a1eeaec36fc098942b9fd7 | devyanshi-t/Contibution | /Codes/case.py | 493 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 10:25:35 2020
@author: devyanshitiwari
You are given a string and your task is to swap cases.
In other words, convert all lowercase letters to uppercase letters and vice versa.
"""
def swap_case(s):
x=""
for i in s:
if i.islower():
x=x+i.upper()
else:
x=x+i.lower()
return x
if __name__ == '__main__':
s = raw_input()
result = swap_case(s)
print (result)
| true |
71e368e81fee53211cfecaed497d06a3b385f703 | eventuallyrises/CS61A | /hw1_q4.py | 624 | 4.125 | 4 | """Hailstone Sequence problem"""
def hailstone(n):
"""Print the hailstone sequence starting at n and return its length.
>>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1
10
5
16
8
4
2
1
>>> a
7
"""
assert n > 0, 'Seed number %d is not greater than 0' % n
assert type(n) == int, 'Seed number is not an Integer'
count = 1
while n != 1:
print(n)
if(n % 2 == 0): # N is even
n = n // 2
else: # N is odd
n = (n * 3) + 1
count += 1
print(n)
return count
| true |
b457618da678f79c59ceb9b6e191e5c6a18df933 | Vivekyadv/InterviewBit | /Tree Data Structure/2 trees/1. merge two binary tree.py | 2,064 | 4.15625 | 4 | # Given two binary tree A and B. merge them in single binary tree
# The merge rule is that if two nodes overlap, then sum of node values is the new value
# of the merged node. Otherwise, the non-null node will be used as the node of new tree.
# Tree 1 Tree 2 Merged Tree
# 2 3 5
# / \ / \ / \
# 1 4 + 6 1 --> 7 5
# / \ \ / \ \
# 5 2 7 5 2 7
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# Method 1: merge tree b in tree a and return a
def merge(self, a, b):
a.val = a.val + b.val
if a.left and b.left:
self.merge(a.left, b.left)
if a.right and b.right:
self.merge(a.right, b.right)
if not a.left and b.left:
a.left = b.left
if not a.right and b.right:
a.right = b.right
def mergeTree1(self, a, b):
if not a:
return b
elif b:
self.merge(a, b)
return a
# Method 2: create new tree and merge a and b
def mergeTree2(self, a, b):
if not a and not b:
return None
if a and not b:
return a
if b and not a:
return b
root = TreeNode(a.val + b.val)
root.left = self.mergeTree2(a.left, b.left)
root.right = self.mergeTree2(a.right, b.right)
return root
def inorder(self, node):
if not node:
return
self.inorder(node.left)
print(node.val, end=' ')
self.inorder(node.right)
node1 = TreeNode(2)
l = TreeNode(1)
ll = TreeNode(5)
r = TreeNode(4)
node1.left = l
node1.right = r
l.left = ll
# Tree 2
node2 = TreeNode(3)
l_ = TreeNode(6)
lr_ = TreeNode(2)
r_ = TreeNode(1)
rr_ = TreeNode(7)
node2.left = l_
node2.right = r_
l_.right = lr_
r_.right = rr_
sol = Solution()
newTree = sol.mergeTree2(node1, node2)
sol.inorder(newTree) | true |
edcd7c026b3fd1a6122be4e78f13a77516a9c9e2 | Vivekyadv/InterviewBit | /String/String math/4. power of 2.py | 1,531 | 4.25 | 4 | # Find if Given number is power of 2 or not.
# More specifically, find if given num can be expressed as 2^k where k >= 1.
# Method 1: using log func
# 2 ^ k = num
# k*log(2) = log(num)
# k = log(num,2)
# if ceil value of k is equal to k then it can be expressed
num1 = "1024"
num2 = "1023"
from math import log, ceil
def power(num):
num = int(num)
if num < 2:
return 0
k = log(num,2)
return 1 if ceil(k) == k else 0
print(power(num1), end= ' ')
print(power(num2))
# Method 2: divide num in loop and check if its completely divisible by 2
def power(num):
num = int(num)
if num < 2:
return 0
while num != 1:
if num % 2 == 0:
num = num//2
else:
return 0
return 1
print(power(num1), end= ' ')
print(power(num2))
# Method 3: using bitwise & operator
# Logic: If we subtract a power of 2 numbers by 1 then all unset bits
# after the only set bit become set; and the set bit becomes unset.
# Example: 16 (10000) and 15 (01111) --> bitwise and of 16 and 15
# is 00000 i.e 0
# Time Complexity: O(1)
def power(num):
num = int(num)
if num == 1 :
return 0
if num & (num-1) == 0:
return 1
else:
return 0
print(power(num1), end= ' ')
print(power(num2))
# Method 4: if num is power of 2, then no_of bit 1 is equal = 1
def power(num):
num = int(num)
bin_num = bin(num)
if bin_num.count('1') == 1:
return 1
else:
return 0
print(power(num1), end= ' ')
print(power(num2)) | true |
cb1225395f4f4787d998a299bfa40e077da4421c | hualili/opencv | /deep-learning-2020S/20-2021S-0-2slicing-2021-2-24.py | 2,631 | 4.21875 | 4 | """
Program: 2slicing.py
Coded by: HL
Date: Feb. 2019
Status: Debug
Version: 1.0
Note: NP slicing
Slicing arrays, e.g., taking elements from one given index to another given index.
(1) pass slice instead of index as: [start:end].
(2) define the step like: [start:end:step].
(3) if we don't pass start its considered 0, and
If we don't pass end its considered length of array in that dimension, and
If we don't pass step its considered 1
ref: https://www.w3schools.com/python/numpy_array_slicing.asp
"""
import sys
import numpy as np
#================
# Slicing 1D tensor, float 32 or float 64 for np
x = np.array([5,6,13,-2.1,100])
print ('x')
print (x)
print ('slicing: [start:end] = [1:3]')
print (x[1:3])
print ('Negative slicing: [-start:-end] start counting from the end = [-3:-1]')
print (x[-3:-1])
print ('step: [start:end:step] = [1:5:2]')
print (x[1:5:2])
print ('step: [start:end:step] = [::2]')
print (x[::2])
y = x.ndim
print ('vector x dimension')
print (y)
print ('---------------------\n')
#================
# Slicing 2D tensor, float 32 or float 64 for np
x = np.array([[5,6,13,-2.1],
[0,1,-1.1,0.1],
[2,1,-1, 0.15]])
print ('2D tensor x')
print (x)
print ('slicing: [row, start:end] = [0, 1:3]')
print (x[0,1:3])
print ('step: [row, start:end:step] = [0, ::2]')
print (x[0,::2])
y = x.ndim
print ('vector x dimension')
print (y)
print ('---------------------\n')
#================
# 3D tensor, float 32 or float 64 for np
x = np.array([[[0,1,2,3],
[4,5,6,7],
[8,9,10,11]],
[[12,13,14,15],
[16,17,18,19],
[20,21,22,23]],
[[24,25,26,27],
[28,29,30,31],
[32,33,34,35]]])
print ('3D tensor x')
print (x)
print ('slicing: [index2D, index1D(row), start:end] = [0,1, 1:3]')
print (x[0,1,1:3])
'''
now, [::1] to select all matrices, and all rows, and col 1
'''
print ('slicing: [index2D, index1D(row), start:end] = [::2]')
print (x[::2])
print ('slicing: [index2D, index1D(row), start:end] = [::,2]')
print (x[::,2])
'''
now, [::1] to select all matrices, and all rows, and col
'''
#print ('step: [index2D, index1D(row), start:end:step] = [0,1, ::2]')
#print (x[0,::2])
y = x.ndim
print ('vector x dimension')
print (y)
'''
Note: NumPy arrays iterate over the left-most axis first.
https://stackoverflow.com/questions/28010860/slicing-3d-numpy-arrays/28010900
'''
#if src is None:
# print ('Error opening image!')
# print ('Usage: pdisplay.py image_name\n')
#while True:
# c = cv2.waitKey(500)
# if c == 27:
# break
| true |
894e677b208321a842d980a623f9a00bdee2ecea | gan3i/CTCI-Python | /Revision/LinkedList/remove_duplicates_2.1_.py | 2,738 | 4.15625 | 4 |
#ask questions
# 1. is it a doubly linked list or singly linked list
# 2. what type of data are we storing, integer? float? string? can there be negatives,
class Node():
def __init__(self,data):
self.data = data
self.next = None
# in interview do not write the linked list class assume that it's given
class LinkedList():
def __init__(self):
self.head = None
# linear space and time complexity
def remove_duplicates(self):
if self.head == None:
return
# hash set the keeps track of values that we have already seen
hash_set =set()
current = self.head
prev = None
while current:
if current.data in hash_set: # found the duplicate node
temp = current
current = current.next
self.remove_node(temp, prev)
else:
hash_set.add(current.data)
prev = current
current = current.next
# quadratic time and constant space
def remove_duplicates1(self):
current = self.head
while current:
prev_node = current
next_node = current.next
while next_node:
if prev_node.data == next_node.data:
temp = next_node
next_node = next_node.next
self.remove_node(temp,prev_node)
else:
prev_node = next_node
next_node = next_node.next
current = current.next
def remove_node(self,node, prev):
prev.next = node.next
node = None
# algorithm ends here rest is just are just helper methods for linked list
@staticmethod
# to add a new Node to the sigly linked list
def add_node(head,data):
# if the head is None return new node
if head == None:
return Node(data)
# else travel to the end of the Node recursively and insert the new node at the end
head.next = LinkedList.add_node(head.next,data)
return head
def add(self,data):
# self.head = LinkedList.add_node(self.head, data)
if self.head == None:
self.head = Node(data)
end = self.head
while end.next:
end = end.next
end.next = Node(data)
def print(self):
current = self.head
while current:
print(current.data)
current = current.next
linked_list = LinkedList()
linked_list.add(1)
# linked_list.add(1)
# linked_list.add(3)
# linked_list.add(3)
# linked_list.add(4)
linked_list.remove_duplicates1()
linked_list.print()
| true |
6169a5437d4ea11923d0857763dbc8c26ab8fc10 | lonely7yk/LeetCode_py | /LeetCode484FindPermutation.py | 2,821 | 4.21875 | 4 | """
By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a
decreasing relationship between two numbers, 'I' represents an increasing relationship between
two numbers. And our secret signature was constructed by a special integer array, which contains
uniquely all the different number from 1 to n (n is the length of the secret signature plus 1).
For example, the secret signature "DI" can be constructed by array [2,1,3] or [3,1,2], but won't
be constructed by array [3,2,4] or [2,1,3,4], which are both illegal constructing special string
that can't represent the "DI" secret signature.
On the other hand, now your job is to find the lexicographically smallest permutation of [1, 2, ... n]
could refer to the given secret signature in the input.
Example 1:
Input: "I"
Output: [1,2]
Explanation: [1,2] is the only legal initial spectial string can construct secret signature "I", where
the number 1 and 2 construct an increasing relationship.
Example 2:
Input: "DI"
Output: [2,1,3]
Explanation: Both [2,1,3] and [3,1,2] can construct the secret signature "DI",
but since we want to find the one with the smallest lexicographical permutation, you need to output [2,1,3]
Note:
The input string will only contain the character 'D' and 'I'.
The length of input string is a positive integer and will not exceed 10,000
"""
from typing import List
# # reverse: O(n) - O(1)
# class Solution:
# def findPermutation(self, s: str) -> List[int]:
# # 将 nums 从 left 到 right 中的进行反转
# def reverse(nums, left, right):
# while left < right:
# nums[left], nums[right] = nums[right], nums[left]
# left += 1
# right -= 1
# n = len(s)
# nums = list(range(1, n + 2))
# i = 0
# while i < n:
# # I 表示上升,不需要改动
# if s[i] == 'I':
# i += 1
# else:
# j = i
# # 找到递减的范围
# while j < n and s[j] == 'D':
# j += 1
# reverse(nums, i, j)
# i = j
# return nums
# Stack: O(n) - O(n)
class Solution:
def findPermutation(self, s: str) -> List[int]:
stack = [1]
res = []
n = len(s)
for i in range(n):
# 每当遇到 I,表明升序,把 stack 全部排出放到 res 中
if s[i] == 'I':
while stack:
res.append(stack.pop())
# 每个数当要放到 stack 中
stack.append(i + 2)
while stack:
res.append(stack.pop())
return res
| true |
1ffd9e7ad58b95c2cc0ea50932209de8ce1218c2 | lonely7yk/LeetCode_py | /LeetCode425WordSquares.py | 2,901 | 4.15625 | 4 | """
Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.
b a l l
a r e a
l e a d
l a d y
Note:
There are at least 1 and at most 1000 words.
All words will have the exact same length.
Word length is at least 1 and at most 5.
Each word contains only lowercase English alphabet a-z.
Example 1:
Input:
["area","lead","wall","lady","ball"]
Output:
[
[ "wall",
"area",
"lead",
"lady"
],
[ "ball",
"area",
"lead",
"lady"
]
]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
Example 2:
Input:
["abat","baba","atan","atal"]
Output:
[
[ "baba",
"abat",
"baba",
"atan"
],
[ "baba",
"abat",
"baba",
"atal"
]
]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
"""
from typing import List
import collections
class TrieNode:
def __init__(self):
self.words = []
self.children = collections.defaultdict(TrieNode)
class Trie:
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
p = self.root
for c in word:
p = p.children[c]
p.words.append(word)
def getWordsWithPrefix(self, prefix):
p = self.root
for c in prefix:
p = p.children[c]
return p.words
# Trie + BackTracking
# 用 trie 记录每个前缀对应的 words。对于每一次 backtrack,找到下一层的前缀,根据前缀找到所有单词候选,然后依次回溯
# https://leetcode.com/problems/word-squares/discuss/91333/Explained.-My-Java-solution-using-Trie-126ms-1616
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
trie = Trie()
for word in words:
trie.addWord(word)
def dfs(curr, res, step, n):
# step == n 说明已生成 word square
if step == n:
res.append(curr)
return
prefix = ""
for i in range(step):
prefix += curr[i][step]
# 找到所有前缀为 prefix 的单词
wordsWithPrefix = trie.getWordsWithPrefix(prefix)
for word in wordsWithPrefix:
dfs(curr + [word], res, step + 1, n)
res = []
for word in words:
dfs([word], res, 1, len(word))
return res
words = ["area","lead","wall","lady","ball"]
res = Solution().wordSquares(words)
print(res)
| true |
b336e49c34dff2b02b7fd80f3f1ef8ab12513ec5 | lonely7yk/LeetCode_py | /LeetCode401BinaryWatch.py | 2,155 | 4.1875 | 4 | """
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom
represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all
possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:
- The order of output does not matter.
- The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
- The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid,
it should be "10:02".
"""
from typing import List
class Solution:
# DFS: 24ms 90%
# 注意精度问题
# def readBinaryWatch(self, num: int) -> List[str]:
# def dfs(res, time, num, start, timeList):
# # round 很关键
# if round((time - int(time)) * 100) > 59 or int(time) > 11: return
# if num == 0:
# hour = int(time)
# minute = round(100 * (time - hour)) # round 很关键
# hourStr = str(hour)
# minuteStr = str(minute) if minute >= 10 else '0' + str(minute)
# res.append(hourStr + ':' + minuteStr)
# return
# for i in range(start, len(timeList)):
# dfs(res, time + timeList[i], num - 1, i + 1, timeList)
# timeList = [8, 4, 2, 1, 0.32, 0.16, 0.08, 0.04, 0.02, 0.01];
# res = []
# dfs(res, 0, num, 0, timeList)
# return res
# Bit operation: 32ms 57%
def readBinaryWatch(self, num: int) -> List[str]:
res = []
for h in range(12):
for m in range(60):
if (bin(h) + bin(m)).count('1') == num:
res.append('%d:%02d' % (h, m))
return res
if __name__ == '__main__':
res = Solution().readBinaryWatch(2)
print(res)
| true |
8c36c1856f7a002736f85d36d5b6af586b613faf | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1363LargestMultipleofThree.py | 2,572 | 4.25 | 4 | """
Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
Since the answer may not fit in an integer data type, return the answer as a string.
If there is no answer return an empty string.
Example 1:
Input: digits = [8,1,9]
Output: "981"
Example 2:
Input: digits = [8,6,7,1,0]
Output: "8760"
Example 3:
Input: digits = [1]
Output: ""
Example 4:
Input: digits = [0,0,0,0,0,0]
Output: "0"
Constraints:
1 <= digits.length <= 10^4
0 <= digits[i] <= 9
The returning answer must not contain unnecessary leading zeros.
"""
from typing import List
class Solution:
# O(n): 88ms 100%
# 3的倍数的数必须满足所有位数加起来是3的倍数
# 如果加起来是 %3=1 说明要减去一个 %3=1 或者两个 %3=2
# 如果加起来是 %3=2 说明要减去一个 %3=2 或者两个 %3=1
def largestMultipleOfThree(self, digits: List[int]) -> str:
# 使用map_生成字符串
def generateStr(map_):
res = ""
for i in range(9, 0, -1):
res += str(i) * map_[i]
# res 为空,说明1-9都没值
if res == "":
return "0" if map_[0] else ""
res += "0" * map_[0]
return res
# 删除num个 map_ 中余数为 remainder 的数
def delMap(map_, num, remainder):
tmp = {1: [1, 4, 7], 2: [2, 5, 8]}
l = tmp[remainder]
cnt = 0
for i in l:
while map_[i]:
map_[i] -= 1
cnt += 1
if cnt == num: break
if cnt == num: break
map_ = [0 for i in range(10)]
s = 0
for digit in digits:
map_[digit] += 1
s += digit
r1 = map_[1] + map_[4] + map_[7]
r2 = map_[2] + map_[5] + map_[8]
if s % 3 == 0:
return generateStr(map_)
elif s % 3 == 1:
if r1 >= 1:
delMap(map_, 1, 1)
return generateStr(map_)
elif r2 >= 2:
delMap(map_, 2, 2)
return generateStr(map_)
elif s % 3 == 2:
if r2 >= 1:
delMap(map_, 1, 2)
return generateStr(map_)
elif r1 >= 2:
delMap(map_, 2, 1)
return generateStr(map_)
return ""
if __name__ == '__main__':
digits = [0,0,0]
res = Solution().largestMultipleOfThree(digits)
print(res)
| true |
07f16a7a3c94ffb901cfa58800c1ea6d43c01ba2 | lonely7yk/LeetCode_py | /LeetCode080RemoveDuplicatesfromSortedArrayII.py | 2,097 | 4.125 | 4 | """
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most
twice and return the new length.
Do not allocate extra space for another array; you must do this by modifying the input array
in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer, but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input
array will be known to the caller.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3]
Explanation: Your function should return length = 5, with the first five elements of nums
being 1, 1, 2, 2 and 3 respectively. It doesn't matter what you leave beyond the returned length.
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3]
Explanation: Your function should return length = 7, with the first seven elements of nums being
modified to 0, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond
the returned length.
Constraints:
0 <= nums.length <= 3 * 10^4
-10^4 <= nums[i] <= 10^4
nums is sorted in ascending order.
"""
from typing import List
# O(n)
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: return 0
idx1 = 1
idx2 = 1
lastVal = nums[0]
cnt = 1
while idx2 < len(nums):
if nums[idx2] == nums[idx2 - 1]:
cnt += 1
else:
lastVal = nums[idx2]
cnt = 1
if cnt <= 2:
nums[idx1] = nums[idx2]
idx1 += 1
idx2 += 1
return idx1
| true |
2ad306d0b108ae285a558caf7a29d762f3a2caee | devendrapansare21/Python-with-Lets-Upgrage | /Assignment_Day-4.py | 693 | 4.1875 | 4 | '''Program to find number of 'we' in given string and their positions in string '''
str1="what we think we become ; we are Python pragrammers"
print("Total number of 'we' in given string are ", str1.count("we"))
print("position of first 'we'--> ",str1.find("we"))
print("position of last 'we'--> ",str1.rfind("we"))
'''Program to check whether the given string is in lower case or upper case'''
str1 = input("Enter the string --->")
while str1.isalpha()!=True:
str1=input("Given string is not proper. Please enter again--->")
if str1.islower()==True:
print("Given string is in Lower Case")
elif str1.isupper()==True:
print("Given string is in Upper Case") | true |
48021044a11b7c223777765d4586f343212bc0ac | dasszer/sudoki | /sudoki.py | 2,445 | 4.15625 | 4 | import pprint
# sudoki.py : solves a sudoku board by a backtracking method
def solve(board):
"""
Solves a sudoku board using backtracking
:param board: 2d list of ints
:return: solution
"""
find = find_empty(board)
if find:
row, col = find
else:
return True
for i in range(1, 10):
if valid(board, (row, col), i):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
def find_empty(board):
"""
finds an empty space in the board
:param board: partially complete board
:return: (int, int) row col
"""
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
def valid(board, pos, num):
"""
Returns true if the attempted move is valid
:param board: 2d list of ints
:param pos: (row, col)
:param num: int
:return: bool
"""
# Check in row
for i in range(0, len(board)):
if board[pos[0]][i] == num and pos[1] != i:
return False
# Check in col
for i in range(0, len(board)):
if board[i][pos[1]] == num and pos[1] != i:
return False
# Check in box
box_x = pos[1]//3
box_y = pos[0]//3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == num and (i, j) != pos:
return False
return True
def print_board(board):
"""
prints the board
:param board: 2d List of ints
:return: None
"""
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - - - -")
for j in range(len(board[0])):
if j % 3 == 0:
print(" | ", end = "")
if j == 8:
print(board[i][j], end="\n")
else:
print(str(board[i][j]) + " ", end="")
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7],
]
pp = pprint.PrettyPrinter(width=41, compact=True)
solve(board)
pp.pprint(board) | true |
a1f9631072c3e8da6a46de97db2cb0a3b9bcdb99 | priyatharshini23/2 | /power.py | 217 | 4.4375 | 4 | # 2
num=int(input("Enter the positive integer:"))
exponent=int(input("Enter exponent value:"))
power=1
i=1
while(i<=exponent):
power=power*num
i=i+1
print("The Result of{0}power{1}={2}".format(num,exponent,power)
| true |
6730b03c1a640ce24dcca9a2a335906295209339 | rajasekaran36/GE8151-PSPP-2020-Examples | /unit2/practice-newton-squareroot.py | 362 | 4.3125 | 4 | print("Newton Method to find sq_root")
num = int(input("Enter number: "))
guess = 1
while(True):
x = guess
f_x = (x**2) - num
f_d_x = 2*x
actual = x - (f_x/f_d_x)
actual = round(actual,6)
if(guess == actual):
break
else:
print("guess=",guess,"actual=",actual)
guess = actual
print("sq_root of",num,"is",guess) | true |
70d0f8c4cc2fc8bb64513fa5b4350501a0812ad7 | Aamir-Meman/BoringStuffWithPython | /sequences/reduce-transforming-list.py | 646 | 4.15625 | 4 | """
The reduce function is the one iterative function which can be use
to implement all of the other iterative functions.
The basic idea of reduce is that it reduces the list to a single value.
The single value could be sum as shown below, or any kind of object including a new list
"""
from _functools import reduce
nums = [1, 2, 3, 4, 5]
def sum_number(total, next_val):
print("total: {}, next_val: {}".format(total, next_val))
return (total + next_val)/2
# total_sum = reduce(sum_number, nums)
total_sum = reduce(lambda acc, current: acc + current, nums)
# total_sum = reduce(lambda x, y: (x + y)/2, nums)
print(total_sum)
| true |
067c7fea36ae0de1ac94277db2f3215270a1040d | Tiger-a11y/PythonProjects | /dict Exercise.py | 479 | 4.21875 | 4 | # Apni Dictionary
dict = { "Set" : "Sets are used to store multiple items in a single variable.",
"Tuples" : "Tuples are used to store multiple items in a single variable.",
"List" : "Lists are used to store multiple items in a single variable.",
"String" : "Strings in python are surrounded by either single quotation marks, or double quotation marks."}
print("enter the Word:")
Search=input()
print(dict[Search])
print("Thanks for using Dictionary")
| true |
0d19edda62a7a9a5d74f0cd59405eb82cbaa924f | sankalpg10/GAN_Even_Num_Generator | /dataset.py | 1,240 | 4.125 | 4 | import math
import numpy as np
def int_to_bin(number: int) -> int:
# if number is negative or not an integer raise an error
if number < 0 or type(number) is not int:
raise ValueError("only positive integers are allowed")
# converts binary number into a list and returns it
return [int(x) for x in list(bin(number))[2:]]
from typing import Tuple, List
def data_generator(max_int: int, batch_size: int=16) -> Tuple[List[int], List[List[int]]]:
# calculate number of digits required to represent the largest number provided by user
# i.e. max length = log2(max_int)
max_length = int(math.log(max_int, 2))
# generate data, i.e. total batch_size numeer of even integers between 0 and max_int/2
sampled_integers = np.random.randint(0, int(max_int)/2, batch_size)
# generate labels for that, all would be 1 as all of them are even numbers
labels = [1] * batch_size
# generate binary numbers for training
data = [int_to_bin(int(x*2)) for x in sampled_integers]
# 0 padding to make the length of all binary numbers of same length i.e. equal to max_length
data = [([0]*(max_length - len(x))) + x for x in data]
return labels, data | true |
75764f96681592643f63082b017aa4c1a64d5e56 | justawho/Python | /TablePrinter.py | 620 | 4.25 | 4 | ## A function named printTable() that rakes a list of lists of strings and
## displays it in a well-organized table
def printTable(someTable):
colWidths = [0] * len(someTable)
for j in range (len(someTable[0])):
for i in range(len(someTable)):
colWidths[i] = len(max(someTable[i], key=len))
item = someTable[i][j]
print (item.rjust(colWidths[i]), end='' + ' ')
print('')
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
| true |
92f7400e1ffa24879e1626c42e1e5c21c2e4eda8 | eshthakkar/coding_challenges | /bit_manipulation.py | 1,108 | 4.125 | 4 | # O(n^2 + T) runtime where n is the total number of words and T is the total number of letters.
def max_product(words):
"""Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.
You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
>>> print max_product(["ac","abb"])
0
>>> print max_product(["wtfn","abcde","abf"])
20
"""
max_product = 0
bytes = [0] * len(words)
for i in xrange(len(words)):
val = 0
for char in words[i]:
val |= 1<<(ord(char) - ord('a'))
bytes[i] = val
for i in xrange(len(words)):
for j in xrange(i+1,len(words)):
if bytes[i] & bytes[j] == 0:
max_product = max(max_product,len(words[i]) * len(words[j]))
return max_product
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "ALL TESTS PASSED. GOOD WORK!"
print
| true |
3e6f61f56ba8f3973be04896b5827c9bf99f664b | eshthakkar/coding_challenges | /rectangle_overlap.py | 1,895 | 4.1875 | 4 | # Overlapping rectangle problem, O(1) space and time complexity
def find_rectangular_overlap(rect1, rect2):
""" Find and return the overlapping rectangle between given 2 rectangles"""
x_overlap_start_pt , overlap_width = find_range_overlap(rect1["x_left"], rect1["width"], rect2["x_left"], rect2["width"])
y_overlap_start_pt , overlap_height = find_range_overlap(rect1["y_bottom"], rect1["height"], rect2["y_bottom"], rect2["height"])
# return null rectangle if there is no overlap
if not overlap_width or not overlap_height:
return {
"x_left" : None,
"y_bottom" : None,
"width" : None,
"height" : None
}
return {
"x_left" : x_overlap_start_pt,
"y_bottom" : y_overlap_start_pt,
"width" : overlap_width,
"height" : overlap_height
}
def find_range_overlap(point1, length1, point2, length2):
""" find and return the overlapping start point and length"""
highest_start_point = max(point1, point2)
lowest_end_point = min(point1 + length1, point2 + length2)
if highest_start_point >= lowest_end_point:
return (None, None)
overlap_length = lowest_end_point - highest_start_point
return (highest_start_point, overlap_length)
rect1 = {
"x_left" : 1,
"y_bottom" : 5,
"width" : 10,
"height" : 4
}
rect2 = {
"x_left" : 5,
"y_bottom" : 7,
"width" : 8,
"height" : 6
}
rect3 = {
"x_left" : 11,
"y_bottom" : 5,
"width" : 2,
"height" : 4
}
print find_rectangular_overlap(rect1, rect2)
# Expected answer
# {'width': 6, 'y_bottom': 7, 'x_left': 5, 'height': 2}
print find_rectangular_overlap(rect1, rect3)
# Expected answer
# {'width': None, 'y_bottom': None, 'x_left': None, 'height': None}
| true |
49421b3c6d6cd17108c8a9ef1c58130c2c531d3e | eshthakkar/coding_challenges | /kth_largest_from_sorted_subarrays.py | 676 | 4.125 | 4 | # O(k) time complexity and O(1) space complexity
def kth_largest(list1,list2,k):
""" Find the kth largest element from 2 sorted subarrays
>>> print kth_largest([2, 5, 7, 8], [3, 5, 5, 6], 3)
6
"""
i = len(list1) - 1
j = len(list2) - 1
count = 0
while count < k:
if list1[i] > list2[j]:
result = list1[i]
i -= 1
else:
result = list2[j]
j -= 1
count += 1
return result
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "All tests passed. Good work!"
print
| true |
2dfff17f70a01dcaf4d742352055b160fbc06669 | jimibarra/cn_python_programming | /miniprojects/trip_cost_calculator.py | 396 | 4.375 | 4 | print("This script will calculate the cost of a trip")
distance = int(input("Please type the distance to drive in kilometers: "))
usage = float(input("Please type the fuel usage of your car in liters/kilometer: "))
cost_per_liter = float(input("Please type the cost of a liter of fuel: "))
total_cost = cost_per_liter * usage * distance
print(f'The total cost of your trip is {total_cost}.')
| true |
a9cfee9934cc75445451574cfc4878cb11d39f4d | jimibarra/cn_python_programming | /07_classes_objects_methods/07_02_shapes.py | 1,539 | 4.625 | 5 | '''
Create two classes that model a rectangle and a circle. The rectangle class should
be constructed by length and width while the circle class should be constructed by
radius.
Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle),
perimeter (of the rectangle) and circumference of the circle.
'''
import math
class Rectangle:
'''Class to model a rectangle '''
def __init__(self, length, width):
self.length = length
self.width = width
def __str__(self):
return f'Rectangle has length {self.length} and width {self.width}.'
def area_rect(self):
area_r = self.length * self.width
return area_r
def perim_rect(self):
perim_r = (2 * self.length) + (2 * self.width)
return perim_r
class Circle:
'''Class to model a circle'''
def __init__(self, radius):
self.radius = radius
def __str__(self):
return f'Circle has radius {self.radius}.'
def area_circle(self):
area_c = math.pi * (self.radius ** 2)
return area_c
def circum_circle(self):
circum_c = 2 * math.pi * self.radius
return circum_c
my_rect = Rectangle(3, 4)
my_circ = Circle(5)
print(my_rect)
print(my_circ)
print (f'The area of the rectangle is {my_rect.area_rect()}.')
print (f'The perimeter of the rectangle is {my_rect.perim_rect()}.')
print (f'The area of the circle is {my_circ.area_circle()}.')
print (f'The circumference of the circle is {my_circ.circum_circle()}.')
| true |
b1b191321e4f71bf57f4052aaa91cb01c8d60501 | jimibarra/cn_python_programming | /07_classes_objects_methods/07_01_car.py | 1,075 | 4.53125 | 5 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and demonstrate
changing the objects attributes.
'''
class Car:
'''Class to model cars'''
def __init__(self, model, year, max_speed=60):
self.model = model
self.year = year
self.max_speed = max_speed
def __str__(self):
return f'The car is a {self.year} {self.model} with a max speed of {self.max_speed}.'
def increment_max_speed(self):
self.max_speed += 5
j_car = Car('BMW Z3', 1998)
d_car1 = Car('BMW Z3', 2001)
d_car2 = Car('Jaguar VP', 2005, 70)
print(j_car)
print(d_car1)
print(d_car2)
j_car.increment_max_speed()
j_car.increment_max_speed()
print(j_car)
d_car2.increment_max_speed()
d_car2.increment_max_speed()
d_car2.increment_max_speed()
print(d_car2)
d_car2.year = 2008
print(d_car2)
| true |
8c1053a3d6092c244c89f36e11d60cc63b1d9090 | jimibarra/cn_python_programming | /03_more_datatypes/2_lists/03_11_split.py | 540 | 4.40625 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
user_string = input("Please enter a string: ")
my_list = user_string.split(" ")
print(my_list)
my_dict = {}
my_set = set(my_list)
for item in my_set:
count = 0
count = my_list.count(item)
my_dict[item] = count
max_count = max(my_dict, key=lambda x: my_dict.get(x))
print(f'The word {max_count} appears the most at {my_dict[max_count]} times')
| true |
900c1185f0af45dd797ce33c0e0ce11fb759a449 | jimibarra/cn_python_programming | /02_basic_datatypes/2_strings/02_09_vowel.py | 991 | 4.4375 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
#Total Vowel Count
vowel = ['a', 'e', 'i', 'o', 'u']
string = input('Please enter a string of characters: ')
count = 0
for i in string:
if i in vowel:
count = count + 1
print(f'The number of vowels in the string is {count}.')
#Count of Each Vowel
count_a = 0
count_e = 0
count_i = 0
count_o = 0
count_u = 0
for i in string:
if i in vowel:
if i == 'a':
count_a = count_a + 1
elif i == 'e':
count_e = count_e + 1
elif i == 'i':
count_i = count_i + 1
elif i == 'o':
count_o = count_o + 1
else:
count_u = count_u + 1
print(f'Counts By Vowel - a:{count_a}, e:{count_e}, i:{count_i}, o:{count_o}, u:{count_u}')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.