blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a4450612113faaf8813c6163c461fc483f05bb63 | HypeDis/DailyCodingProblem-Book | /Chapter-5-Hash-Table/5.2-Cut-Brick-Wall.py | 972 | 4.125 | 4 | """
A wall consists of several rows of bricks of various integer lengths and uniform height. Your goal is to find a vertical line going from the top to the bottom of the wall that cuts through the fewest number of bricks. If the line goes through the edge between two bricks, this does not count as a cut.
"""
from collections import defaultdict
wall = [
[3, 5, 1, 1],
[2, 3, 3, 2],
[5, 5],
[4, 4, 2],
[1, 3, 3, 3],
[1, 1, 6, 1, 1]
]
def fewest_cuts(wall):
cuts = defaultdict(int)
for row in wall:
length = 0
for brick in row[:-1]:
length += brick
cuts[length] += 1
maxLines = 0
maxPosition = None
for position in cuts:
if cuts[position] > maxLines:
maxLines = cuts[position]
maxPosition = position
totalRows = len(wall)
print(
f'the optimal position is {maxPosition}, with {totalRows - maxLines} cuts required')
fewest_cuts(wall)
| true |
a18a302670bdb1c93bcf41783c1f3763d261c716 | HypeDis/DailyCodingProblem-Book | /Chapter-3-Linked-Lists/3.1-Reverse-Linked-List.py | 987 | 4.125 | 4 | from classes import LinkedList
myLinkedList = LinkedList(10)
def reverse(self):
self.reverseNodes(None, self.head)
LinkedList.reverse = reverse
def reverseNodes(self, leftNode, midNode):
# basecase reach end of list
if not midNode.next:
self.head = midNode
else:
self.reverseNodes(midNode, midNode.next)
midNode.next = leftNode
LinkedList.reverseNodes = reverseNodes
def reverseNonRecursive(self):
prev, current = None, self.head
while current is not None:
temp = current.next
current.next = prev
prev = current
current = temp
self.head = prev
LinkedList.reverseNonRecursive = reverseNonRecursive
myLinkedList.insert(20)
myLinkedList.insert(15)
myLinkedList.insert(91)
print(myLinkedList.listNodes())
myLinkedList.reverse()
print(myLinkedList.listNodes())
myLinkedList.reverseNonRecursive()
print(myLinkedList.listNodes())
myLinkedList.reverseNonRecursive()
print(myLinkedList.listNodes())
| true |
a717b09b4d4d486e3a05b5a9046fe396a9d65959 | Jorza/pairs | /pairs.py | 1,367 | 4.28125 | 4 | def get_pair_list():
while True:
try:
# Get input as a string, turn into a list
pairs = input("Enter a list of integers, separated by spaces: ")
pairs = pairs.strip().split()
# Convert individual numbers from strings into integers
for i in range(len(pairs)):
pairs[i] = int(pairs[i])
return pairs
except ValueError:
# Go back to the start if the input wasn't entered correctly
print("Invalid input")
def find_pairs(the_list):
# Sum odd => one value even, one value odd
# Product even => one value even
# The condition for the odd sum guarantees an even product.
# Therefore, only need to check the sum.
# Split list into even and odd values
even_list = []
odd_list = []
for item in the_list:
new_list = even_list if item % 2 == 0 else odd_list
new_list.append(item)
# Find all pairs with one item from the even list and one item from the odd list
pairs = []
for odd_item in odd_list:
for even_item in even_list:
pairs.append([odd_item, even_item])
return pairs
def print_pairs(pairs):
for pair in pairs:
print(pair)
if __name__ == "__main__":
print_pairs(find_pairs(get_pair_list()))
| true |
3c0042882117531431b5d27506e5bf602c92e3d3 | henrikgruber/PythonSIQChallenge | /Skill2.3_Friederike.py | 936 | 4.53125 | 5 | # Create 3 variables: mystring, myfloat and myint.
# mystring should contain the word "hello.The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain the number 20.
# Finally, print all 3 variables by checking if mystring equals to "hello" then print it out. You then check if myfloat is really a float number and is equal to 10.0 - then you print it out (if both conditions are satisfied)
# And you do the same for int
mystring = "Hello"
myfloat= "string"
myint= 20
# mystring
if (type(mystring) is str) == True:
print(mystring)
elif (type(mystring) is str) != True:
print("No string")
# myfloat
if (type(myfloat)is float) == True:
print(myfloat)
elif (type(myfloat)) != True:
print("No float")
#myint
if (type(myint)is int) == True:
print(myint)
elif (type(myint)is int) != True:
print("No int") | true |
b44f4f5367ae2c8cb39de98e003dc9454d82970a | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill4.3_Vanessa.py | 1,028 | 4.78125 | 5 | #In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method.
# Create 3 lists: numbers, strings and names
numbers = []
strings = []
names = []
# Add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings variable
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("hello")
strings.append("world")
# Add names John, Eric and Jessica to strings list
names.append("John")
names.append("Eric")
names.append("Jessica")
#Create a new variable third_name with the third name taken from names list, using the brackets operator []. Note that the index is zero-based, so if you want to access the second item in the list, its index will be 1.
third_name = names[2]
# At the end print all lists and one variable created.
print("This is the list of numbers:", numbers)
print("This is the list of strings:", strings)
print("This is the list of names:", names)
print("This is the third name in the list of names:", third_name) | true |
b659d2d761ee8c0df61154e0497ddcf5a1fe2a80 | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill 2.3 Tamina.py | 777 | 4.40625 | 4 | # Create 3 variables: mystring, myfloat and myint.
# mystring should contain the word "hello.The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain the number 20.
# Finally, print all 3 variables by checking if mystring equals to "hello" then print it out. You then check if myfloat is really a float number and is equal to 10.0 - then you print it out (if both conditions are satisfied)
# And you do the same for int
mystring = input ("Please enter a string ")
myfloat = input ("please enter a float number ")
myint = input ("Please enter an integer ")
try:
val = str(mystring)
if mystring == "Hello":
print (mystring)
break;
else:
print ("Error")
| true |
1b65e04c12a9b0c1df4be645bb0b841c96a67277 | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill1.4_Vanessa.py | 512 | 4.25 | 4 | # This program finds the number of day of week for K-th day of year
print("Enter the day of the year:")
K = int(input())
a = (K % 7) + 3
if a == 0:
print("This day is a Sunday")
if a == 1:
print("This day is a Monday")
if a == 2:
print("This day is a Tuesday")
if a == 3:
print("This day is a Wednesday")
if a == 4:
print("This day is a Thursday")
if a == 5:
print("This day is a Friday")
if a == 6:
print("This day is a Saturday")
| true |
8b8a0b92e6e0697c486e0cdda96874934e4e48f0 | Sadashiv/interview_questions | /python/string_set_dictionary.py | 2,945 | 4.34375 | 4 | string = """
Strings are arrays of bytes representing Unicode characters.
Strings are immutable.
"""
print string
#String Operations details
str = "Hello Python"
str1 = "World"
print "String operations are started"
print str.capitalize()
print str.center(20)
print str.count('o')
print str.decode()
print str.encode()
print str.endswith('Python')
print str.expandtabs(12)
print str.find('P')
print str.format()
print str.index('y')
print str.isalnum()
print str.isalpha()
print str.isdigit()
print str.islower()
print str.isspace()
print str.istitle()
print str.isupper()
print str.lower()
print str.ljust(5)
print str.lstrip()
print str.partition('P')
print str.rfind('o')
print str.replace('o','r')
print str.rindex('o')
print str.rjust(20)
print str.rpartition('P')
print str.rsplit('P')
print str.rstrip('P')
print str.split('P')
print str.splitlines()
print str.startswith('Hello')
print str.strip()
print str.swapcase()
print str.title()
print str.upper()
print str.zfill(20)
print str.join(str1)
print str[0]
print str[6]
print str[-1]
print str[:]
print str[2:]
print str[:6]
print str[2:7]
print str[2:-2]
print "String operations are completed"
print ""
print "Sets details are started from here"
set_1 = """
A set is an unordered collection of items.
Every element is unique and must be immutable.
"""
print set_1
#set Operations details
print "Sets operations are started"
s = {1,2,3,4,3,2}
print s
set1 = {1,3}
set1.add(2)
print set1
set1.update([2,3,4])
print set1
set1.update([4,5], {1,6,8})
print set1
set1.discard(6)
print set1
set1.remove(8)
print set1
set2 = {"HelloWorld"}
print set2
set2.clear()
print set2
A = {1,2,3,4,5}
B = {4,5,6,7,8}
print(A|B)
print(A.union(B))
print(B.union(A))
print(A&B)
print(A.intersection(B))
print(B.intersection(A))
print(A-B)
print(B-A)
print(A.difference(B))
print(B.difference(A))
print(A^B)
print(B^A)
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
print "Sets operations are completed"
print ""
print "Dictionary details are started from here"
Dictionary = """
Python dictionary is an unordered collection of items.
a dictionary has a key:value pair.
"""
print Dictionary
#Dictionary Operations details
print "Dictionary operations are started"
dict = {'name':'Ramesh', 'age':28}
print dict.copy()
print dict.fromkeys('name')
print dict.fromkeys('age')
print dict.fromkeys('name','age')
print dict.get('name')
print dict.has_key('name')
print dict.has_key('Ramesh')
print dict.items()
for i in dict.iteritems():
print i
for i in dict.iterkeys():
print i
for i in dict.itervalues():
print i
print dict.keys()
print dict.values()
print dict.viewitems()
print dict.viewkeys()
print dict.viewvalues()
dict['name'] = 'Ram'
print dict
dict['age'] = 29
print dict
dict['address'] = 'Bijapur'
print dict
dict1 = {1:1, 2:4, 3:9, 4:16, 5:25}
print dict1.pop(4)
print dict1.popitem()
print dict1[5]
print dict1.clear()
print "Dictionary operations are completed" | true |
141f5d9eeb1020a83a79299fc7d3b93637058c83 | capncrockett/beedle_book | /Ch_03 - Computing with Numbers/sum_a_series.py | 461 | 4.25 | 4 | # sum_a_series
# A program to sum up a series of numbers provided from a user.
def main():
print("This program sums up a user submitted series of numbers.")
number_count = int(input("How many numbers will we be summing"
"up today? "))
summed = 0
for i in range(number_count):
x = float(input("Enter a number: "))
summed += x
print("The sum of the numbers is ", summed)
main()
| true |
80f931032dd8fbee7d859a1f04b9d2707d233227 | capncrockett/beedle_book | /Ch_03 - Computing with Numbers/triangle_area.py | 492 | 4.3125 | 4 | # triangle_area.py
# Calculates the area of a triangle.
import math
def main():
print("This program calculates the area of a triangle.")
print()
a = float(input("Please enter the length of side a: "))
b = float(input("Please enter the length of side b: "))
c = float(input("Please enter the length of side c: "))
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("The area of your triangle is ", area)
main()
| true |
b30b0e17c9c907d54c1d4e99b68c0580a00808c4 | capncrockett/beedle_book | /Ch_07 - Decision Structures/valid_date_func.py | 1,101 | 4.46875 | 4 | # valid_date_func.py
# A program to check if user input is a valid date. It doesn't take
# into account negative numbers for years.
from leap_year_func import leap_year
def valid_date(month: int, day: int, year: int) -> bool:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if 1 <= month <= 12:
# Month is OK. Move on.
# Determine last day in month.
if month == 2:
if leap_year(year):
last_day = 29
else:
last_day = 28
else:
last_day = days_in_month[month - 1]
# if day is also good, return True
if 1 <= day <= last_day:
return True
else:
return False
# def main():
# print("This program determines if a date input is valid.")
# month, day, year = input("Enter a date in format MM/DD/YYYY: ").split("/")
#
# if valid_date(int(month), int(day), int(year)):
# print("Date Valid.")
# else:
# print("Date is Invalid")
#
#
# for i in range(10):
# main()
| true |
b19f9c63a4c64753fc1c46a61177d05a0e08570b | capncrockett/beedle_book | /Ch_06 - Functions/sum_time.py | 545 | 4.25 | 4 | # sum_time.py
def sum_up_to(n):
summed = 0
for i in range(1, n + 1):
summed += i
print(f"The sum is {summed}.")
def sum_up_cubes(n):
summed = 0
for s in range(1, n + 1):
summed += s ** 3
print(f"The sum of the cubes is {summed}")
def main():
print("This program sums up the first n natural numbers and the \n"
"sum of the cubes of the first n natural numbers.\n")
n = int(input("Please enter a value for n: "))
sum_up_to(n)
sum_up_cubes(n)
main()
| true |
5c05feac6d95a6375275bc8ddb69d96fcd253f9b | capncrockett/beedle_book | /Ch_07 - Decision Structures/pay_rate_calc.py | 583 | 4.25 | 4 | # pay_rate_calc.py
# Program to calculate an employees pay rate, including overtime.
def main():
hours = eval(input("Enter employee total hours: "))
pay_rate = eval(input("Enter employee pay rate: "))
if hours <= 40:
pay = pay_rate * hours
print(f"Total pay = ${pay:0.2f}")
else:
base_pay = 40 * pay_rate
overtime = (hours - 40) * (pay_rate * 1.5)
print(f"Base pay = ${base_pay:0.02f}\n"
f"Overtime = ${overtime:0.02f}\n"
f"Total pay = ${base_pay + overtime:0.02f}")
main()
| true |
e9543a36d3cc89e88294035db335cf273c7b037a | capncrockett/beedle_book | /Ch_05 - Sequences/average_word_len.py | 998 | 4.3125 | 4 | # average_word_len
# Find the average word length of a sentence.
def main():
print("This program finds the average word length of a sentence.")
print()
sentence = input("Type a sentence: ")
word_count = sentence.count(' ') + 1
words = sentence.split()
letter_count = 0
for letters in words:
letter_count = letter_count + len(letters)
avg_word_length = letter_count // word_count
print(f"Letter count: {letter_count} ")
print(f"Word count: {word_count}")
print(f"Average word length: {avg_word_length}")
main()
# # c05ex10.py
# # Average word length
#
#
# def main():
# print("Average word length")
# print()
#
# phrase = input("Enter a phrase: ")
#
# # using accumulator loop
# count = 0
# total = 0
# for word in phrase.split():
# total = total + len(word)
# count = count + 1
#
# print("Average word length", total / count)
#
#
# main()
| true |
a7a921940f1cedee399c3d732f7a2cb4869979ef | DaanvanMil/INFDEV02-1_0892773 | /assignment6pt3/assignment6pt3/assignment6pt3.py | 367 | 4.25 | 4 | x = input ("how many rows? ")
printed = ("") #The printing string
n = x + 1 #Make sure it is x rows becasue of the range
for a in range(n): #Main for loop which prints n amount of lines
for b in range(a): #For loop which adds a amount of asterisks per line
printed += '*'
printed += '\n'
print printed | true |
4c687faa942587e54da9a4e4cdcc491865c93b82 | Billoncho/TurtelDrawsTriangle | /TurtleDrawsTriangle.py | 684 | 4.4375 | 4 | # TurtleDrawsTriangle.py
# Billy Ridgeway
# Creates a beautiful triangle.
import turtle # Imports turtle library.
t = turtle.Turtle() # Creates a new pen called t.
t.getscreen().bgcolor("black") # Sets the background to black.
t.pencolor("yellow") # Sets the pen's color to yellow.
t.width(2) # Sets the pen's width to 2.
t.shape("turtle") # Sets the shape of the pen to a turtle.
for x in range(100): # Sets the range of x to 100.
t.forward(3*x^2) # Moves the pen forward 3 times the value of x squared.
t.left(120) # Turns the pen left 120 degrees.
| true |
55eb79671bcc26fb01f38670730e7c71b5e0b6ff | vymao/SmallProjects | /Chess/ChessPiece.py | 956 | 4.125 | 4 | class ChessPiece(object):
"""
Chess pieces are what we will add to the squares on the board
Chess pieces can either moves straight, diagonally, or in an l-shape
Chess pieces have a name, a color, and the number of squares it traverses per move
"""
Color = None
Type = None
ListofPieces = [ "Rook", "Knight", "Pawn", "King", "Queen", "Bishop" , "Random"]
def __init__(self, dict_args):
""" Constructor for a new chess piece """
self.Type = dict_args["Type"]
self.Color = dict_args["Color"]
def __str__(self):
""" Returns the piece's string representation as the first letter in each word
example: bN - black knight, wR - white rook"""
if self.Type in ["Rook", "Knight", "Pawn", "King", "Queen", "Bishop"]:
color = self.Color[0]
if(self.Type != "Knight"):
pieceType = self.Type[0]
else:
pieceType = "N"
return color.lower() + pieceType.upper()
else:
return " "
| true |
01099d699d3e8b9919b117704f36d1c95ee75bcc | mitalijuneja/Python-1006 | /Homework 5/engi1006/advanced/pd.py | 1,392 | 4.1875 | 4 |
#########
# Mitali Juneja (mj2944)
# Homework 5 = statistics functionality with pandas
#
#########
import pandas as pd
def advancedStats(data, labels):
'''Advanced stats should leverage pandas to calculate
some relevant statistics on the data.
data: numpy array of data
labels: numpy array of labels
'''
# convert to dataframe
df = pd.DataFrame(data)
# print skew and kurtosis for every column
skew = df.skew(axis = 0)
kurt = df.kurtosis(axis = 0)
for col in range(df.shape[1]):
print("Column {} statistics".format(col))
print("\tSkewness = {}\tKurtosis = {}".format(skew[col], kurt[col]))
# assign in labels
df["labels"] = labels
print("\n\nDataframe statistics")
# groupby labels into "benign" and "malignant"
mean = df.groupby(["labels"]).mean().T
sd = df.groupby(["labels"]).std().T
# collect means and standard deviations for columns,
# grouped by label
b_mean = mean.iloc[:,0]
m_mean = mean.iloc[:,-1]
b_sd = sd.iloc[:,0]
m_sd = sd.iloc[:,-1]
# Print mean and stddev for Benign
print("Benign Stats:")
print("Mean")
print(b_mean)
print("SD")
print(b_sd)
print("\n")
# Print mean and stddev for Malignant
print("Malignant Stats:")
print("Mean")
print(m_mean)
print("SD")
print(m_sd)
| true |
bd367cea336727a2ccbd217e8e201aad6ab42391 | Eddie02582/Leetcode | /Python/069_Sqrt(x).py | 1,565 | 4.40625 | 4 | '''
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
'''
class Solution(object):
def mySqrt_build(self, x):
"""
:type x: int
:rtype: int
"""
return int(x**0.5)
'''
y**2=x
logy**2=logx
2logy=logx
y=10**(0.5*logx)
'''
def mySqrt_log(self, x):
import math
if x==0 :
return 0
return int( 10**(0.5 *math.log10(x)))
#Using Newton's method:
def mySqrt(self, x):
result = 1
if x == 0 :
return 0
while abs(result * result - x) >0.1:
result=(result + float(x) / result) /2
return int(result)
#Binary
def mySqrt(self, x: int) -> int:
l = 0
r = x
while l < r:
mid = (l + r + 1) // 2
if mid * mid == x:
return mid
elif mid * mid > x:
r = mid - 1
else:
l = mid
return r
sol =Solution()
assert sol.mySqrt(4)==2
assert sol.mySqrt(8)==2
assert sol.mySqrt(1)==1
assert sol.mySqrt(0)==0 | true |
ef5e3b08084b712e924f564ec05a235e157ce482 | Eddie02582/Leetcode | /Python/003_Longest Substring Without Repeating Characters.py | 2,886 | 4.125 | 4 | '''
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
'''
#!/usr/bin/python
# encoding=utf-8
class Solution:
'''
另用map 紀錄出現字母,right指針向右,如果沒出現就紀錄長度
,當出現過的字母,left 指針就跑到重複出現字母的位置
'''
def lengthOfLongestSubstring(self, s):
left,right,max_length=0,0,0
maps = set()
while right < len(s):
if s[right] not in maps:
maps.add(s[right])
right += 1
else:
maps.remove(s[left])
left += 1
max_length = max(right-left,max_length)
return max_length
def lengthOfLongestSubstring_array(self, s):
locations = [0]*256
l,r=0,-1
res = 0
while l < len(s):
if r + 1 < len(s) and not locations[ord(s[r +1])]:
r += 1
locations[ord(s[r])] += 1
else:
locations[ord(s[l])] -= 1
l += 1
res =max(res,r - l + 1)
return res
def lengthOfLongestSubstring(self, s):
if not s:
return 0
position = [-1] * 256
res = 0
l ,r = 0 ,0
while r < len(s) :
index = ord(s[r])
if position[index] >= l:
l = position[index] + 1
res = max(res ,r - l + 1)
position[index] = r
r += 1
return res
def lengthOfLongestSubstring_map(self, s):
if not s:
return 0
if len(s) <= 1:
return len(s)
locations = [-1 for i in range(256)]
index = -1
m = 0
for i, v in enumerate(s):
if locations[ord(v)] > index:
index = locations[ord(v)]
m = max(m, i - index)
locations[ord(v)] = i
return m
sol =Solution()
assert sol.lengthOfLongestSubstring('abcabcbb')==3
assert sol.lengthOfLongestSubstring('abcbcbb')==3
assert sol.lengthOfLongestSubstring('bbbbb')==1
assert sol.lengthOfLongestSubstring_map('pwwkew')==3
assert sol.lengthOfLongestSubstring(' ')==1
assert sol.lengthOfLongestSubstring('au')==2
| true |
b34977331a8f620c267ae294ddf3977cccf3f8f9 | ratansingh98/design-patterns-python | /factory-method/FactoryMethod.py | 1,328 | 4.34375 | 4 | #
# Python Design Patterns: Factory Method
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
# 2016
#
# Source code is licensed under MIT License
# (for more details see LICENSE)
#
import sys
#
# Product
# products implement the same interface so that the classes
# can refer to the interface not the concrete product
#
class Product:
def getName(self):
pass
#
# Concrete Products
# define product to be created
#
class ConcreteProductA(Product):
def getName(self):
return "type A"
class ConcreteProductB(Product):
def getName(self):
return "type B"
#
# Creator
# contains the implementation for all of the methods
# to manipulate products except for the factory method
#
class Creator:
def createProductA(self):
pass
def createProductB(self):
pass
#
# Concrete Creator
# implements factory method that is responsible for creating
# one or more concrete products ie. it is class that has
# the knowledge of how to create the products
#
class ConcreteCreator(Creator):
def createProductA(self):
return ConcreteProductA()
def createProductB(self):
return ConcreteProductB()
if __name__ == "__main__":
creator = ConcreteCreator()
p1 = creator.createProductA()
print("Product: " + p1.getName())
p2 = creator.createProductB()
print("Product: " + p2.getName())
| true |
5513562b84170f92d6581dc1da83414705338443 | ratansingh98/design-patterns-python | /abstract-factory/AbstractFactory.py | 1,921 | 4.28125 | 4 | #
# Python Design Patterns: Abstract Factory
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
# 2016
#
# Source code is licensed under MIT License
# (for more details see LICENSE)
#
import sys
#
# Product A
# products implement the same interface so that the classes can refer
# to the interface not the concrete product
#
class ProductA:
def getName(self):
pass
#
# ConcreteProductAX and ConcreteProductAY
# define objects to be created by concrete factory
#
class ConcreteProductAX(ProductA):
def getName(self):
return "A-X"
class ConcreteProductAY(ProductA):
def getName(self):
return "A-Y"
#
# Product B
# same as Product A, Product B declares interface for concrete products
# where each can produce an entire set of products
#
class ProductB:
def getName(self):
pass
#
# ConcreteProductBX and ConcreteProductBY
# same as previous concrete product classes
#
class ConcreteProductBX(ProductB):
def getName(self):
return "B-X"
class ConcreteProductBY(ProductB):
def getName(self):
return "B-Y"
#
# Abstract Factory
# provides an interface for creating a family of products
#
class AbstractFactory:
def createProductA(self):
pass
def createProductB(self):
pass
#
# Concrete Factories
# each concrete factory create a family of products and
# client uses one of these factories
#
class ConcreteFactoryX(AbstractFactory):
def createProductA(self):
return ConcreteProductAX()
def createProductB(self):
return ConcreteProductBX()
class ConcreteFactoryY(AbstractFactory):
def createProductA(self):
return ConcreteProductAY()
def createProductB(self):
return ConcreteProductBY()
if __name__ == "__main__":
factoryX = ConcreteFactoryX()
factoryY = ConcreteFactoryY()
p1 = factoryX.createProductA()
print("Product: " + p1.getName())
p2 = factoryY.createProductA()
print("Product: " + p2.getName())
| true |
7dc4a7cd2f0cea643673ee0ace3ccd2b8b5cf117 | bliiir/python_fundamentals | /16_variable_arguments/16_01_args.py | 345 | 4.1875 | 4 | '''
Write a script with a function that demonstrates the use of *args.
'''
def my_args(*args):
'''Print out the arguments received
'''
print('These are the arguments you gave me: \n')
for arg in args:
print(arg)
# Call the my_args function with a string, a number and a copy of itself
my_args('a string', 4, my_args)
| true |
609fc7970d1e8a9a1fc194c10d0ae73975e6c428 | jfeidelb/Projects | /PythonTextGame.py | 2,237 | 4.34375 | 4 | from random import randint
import operator
print("This is an educational game where you will answer simple math questions.")
print("How many questions would you like to answer?")
questionInput = input()
def MathQuestion(questionInput):
questionLoop = 0
score = 0
try:
#loop to control number of questions
while questionLoop < int(questionInput):
value1 = randint(1, 20)
value2 = randint(1, 20)
#variable to assign mathematical operation
operationVariable = randint(0, 3)
if operationVariable == 0:
correctMathAnswer = operator.add(value1, value2)
operation = "+"
elif operationVariable == 1:
correctMathAnswer = operator.sub(value1, value2)
operation = "-"
elif operationVariable == 2:
correctMathAnswer = operator.mul(value1, value2)
operation = "*"
elif operationVariable == 3:
while value1 % value2 != 0:
value1 = randint(1, 20)
value2 = randint(1, 20)
correctMathAnswer = operator.truediv(value1, value2)
operation = "/"
print()
#asking the math question to the user
print("What is " + str(value1) + operation + str(value2) + "?")
userInput = input()
try:
#checks the users answer with the correct answer
if float(userInput) == correctMathAnswer:
print("Yes! That is the correct answer!")
score += 1
print("Your score is: " + str(score))
else:
print("That is not the correct answer.")
print("Your score is: " + str(score))
#except statement to ensure a number is answered
except ValueError:
print("Please enter a numerical answer.")
questionLoop += 1
#except statement to ensure a number is entered
except ValueError:
print("Please enter a number!")
questionInput = input()
MathQuestion(questionInput)
MathQuestion(questionInput) | true |
383cf5c58b65554c25ba6c29ec5805c5e6abfbde | thekushkode/lists | /lists.2.py | 1,321 | 4.375 | 4 | # List Exercise 2
# convert infinite grocery item propt
# only accept 3 items
# groc list var defined
groc = []
#build list
while len(groc) < 3:
needs = input('Enter one grocery item you need: ')
groc.append(needs)
#groc2 list var defined
groc2 = []
#build list
while len(groc2) < 3:
needs2 = input('Enter one grocery item you need: ')
groc2.append(needs2)
#adds lists and puts them into a new list
groc_fin = groc + groc2
#or groc_fin = groc.extend(groc2)
print(groc_fin)
#ask for index to be replaced
index_to_replace = int(input('Enter the index of the iem you want to replace: '))
#ask for item to add
item_to_add = input('What item would you like to add: ')
#adds item to final list based on user inputs
groc_fin[index_to_replace] = item_to_add
#prints new list
print(groc_fin)
#code w/o comments
# groc = []
# while len(groc) < 3:
# needs = input('Enter one grocery item you need: ')
# groc.append(needs)
# groc2 = []
# while len(groc2) < 3:
# needs2 = input('Enter one grocery item you need: ')
# groc2.append(needs2)
# groc_fin = groc + groc2
# print(groc_fin)
# index_to_replace = int(input('Enter the index of the iem you want to replace: '))
# item_to_add = input('What item would you like to add: ')
# groc_fin[index_to_replace] = item_to_add
# print(groc_fin) | true |
b8d1d4a3facd658685105842d2ba4d25ce3bdd24 | abdulalbasith/python-programming | /unit-2/homework/hw-3.py | 368 | 4.25 | 4 | odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar',
'123451' , '0.0', 'papa', '-pq-']
number_of_strings = 0
for string in odd_strings:
string_length = len(string)
first_char= string [0]
last_char= string [-1]
if string_length > 3 and first_char == last_char:
number_of_strings += 1
print (number_of_strings)
| true |
89d79dc316e679596d8ffe70747316ed83b75442 | abdulalbasith/python-programming | /unit-3/sols-hw-pr5.py | 1,023 | 4.125 | 4 | #Homework optional problem #5
def letter_count (word):
count = {}
for l in word:
count[l] = count.get (l,0) +1
return count
def possible_word (word_list, char_list):
#which words in word list can be formed from the characters in the character list
#iterate over word_list
valid_words=[]
for word in word_list:
is_word_valid = True
#get a count of each character in word
char_count = letter_count(word)
#check each character in the word
for letter in word:
if letter not in char_list:
is_word_valid = False
else:
if char_list.count(letter) != char_count [letter]:
is_word_valid = False
#Add valid words to a list
if is_word_valid:
valid_words.append (word)
return valid_words
#testing
legal_words = ['go', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
letters = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
print (possible_word(legal_words,letters)) | true |
ecd28bb5b6fa31378207b40b9a6ea0c93db7e2b0 | Amaya1998/business_application | /test2.py | 565 | 4.21875 | 4 | import numpy as np
fruits= np.array (['Banana','Pine-apple','Strawberry','Avocado','Guava','Papaya'])
print(fruits)
def insertionSort(fruits):
for i in range(1, len(fruits)): # 1 to length-1
item = fruits[i]
# Move elements
# to right by one position
f = i
while f >0 and fruits[f-1] > item:
fruits[f] = fruits[f-1] # move value to right
f -= 1
fruits[f] = item # insert at correct place
insertionSort(fruits)
print(fruits)
| true |
a1a09bf2afeae4790b4c405446bdfd4d79c23eea | intkhabahmed/PythonProject | /Day1/Practice/Operators.py | 243 | 4.125 | 4 | num1 = input("Enter the first number") #Taking first number
num2 = input("Enter the second number") #Taking second number
print("Addtion: ",num1+num2)
print("Subtraction: ",num1-num2)
print("Multiply: ",num1*num2)
print("Division: ",num1/num2) | true |
5ada27d455d8bf9d51b6e71360ddd85175b0ac95 | wang264/JiuZhangLintcode | /AlgorithmAdvance/L2/require/442_implement-trie-prefix-tree.py | 1,802 | 4.3125 | 4 | # Implement a Trie with insert, search, and startsWith methods.
#
# Example
# Example 1:
#
# Input:
# insert("lintcode")
# search("lint")
# startsWith("lint")
# Output:
# false
# true
# Example 2:
#
# Input:
# insert("lintcode")
# search("code")
# startsWith("lint")
# startsWith("linterror")
# insert("linterror")
# search("lintcode“)
# startsWith("linterror")
# Output:
# false
# true
# false
# true
# true
# Notice
# You may assume that all inputs are consist of lowercase letters a-z.
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
"""
@param: word: a word
@return: nothing
"""
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
# return the node that has the last character of this word if exist.
def find(self, word):
node = self.root
for char in word:
node = node.children.get(char)
if node is None:
return None
return node
"""
@param: word: A string
@return: if the word is in the trie.
"""
def search(self, word):
node = self.find(word)
if node is None:
return False
return node.is_word
"""
@param: prefix: A string
@return: if there is any word in the trie that starts with the given prefix.
"""
def startsWith(self, prefix):
return self.find(prefix) is not None
trie = Trie()
trie.search('lintcode')
trie.startsWith("lint")
trie.insert("lint")
trie.startsWith("lint") | true |
c547b2db20d700bdc3b0bc06a7193e38e1d92440 | wang264/JiuZhangLintcode | /Algorithm/L4/require/480_binary-tree-paths.py | 2,826 | 4.21875 | 4 | # 480. Binary Tree Paths
# 中文English
# Given a binary tree, return all root-to-leaf paths.
#
# Example
# Example 1:
#
# Input:{1,2,3,#,5}
# Output:["1->2->5","1->3"]
# Explanation:
# 1
# / \
# 2 3
# \
# 5
# Example 2:
#
# Input:{1,2}
# Output:["1->2"]
# Explanation:
# 1
# /
# 2
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
rslt = []
this_path = []
self.helper(root, this_path, rslt)
return rslt
def helper(self, node, this_path, rslt):
# if this node is leave node
this_path.append(str(node.val))
if node.left is None and node.right is None:
temp_str = '->'.join(this_path)
rslt.append(temp_str)
else:
if node.left:
self.helper(node.left, this_path, rslt)
this_path.pop()
if node.right:
self.helper(node.right, this_path, rslt)
this_path.pop()
# divide and conquer
class Solution2:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
paths = self.tree_path_helper(root)
return ['->'.join(path) for path in paths]
def tree_path_helper(self, root):
# write your code here
if root is None:
return []
left_paths = self.tree_path_helper(root.left)
right_paths = self.tree_path_helper(root.right)
paths = left_paths + right_paths
if len(paths) == 0:
return [[str(root.val)]]
else:
for path in paths:
path.insert(0, str(root.val))
return paths
# DFS
class Solution3:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
paths = []
this_path = [str(root.val)]
self.dfs(root, this_path, paths)
return paths
def dfs(self, node, this_path, paths):
if node.left is None and node.right is None:
paths.append('->'.join(this_path))
if node.left:
this_path.append(str(node.left.val))
self.dfs(node.left, this_path, paths)
this_path.pop()
if node.right:
this_path.append(str(node.right.val))
self.dfs(node.right, this_path, paths)
this_path.pop()
from helperfunc import build_tree_breadth_first
sol = Solution3()
root = build_tree_breadth_first(sequence=[1, 2, 3, None, 5])
sol.binaryTreePaths(root=root)
| true |
48292de617f3eda89c003ac106a37d62e8f445d9 | wang264/JiuZhangLintcode | /Algorithm/L7/optional/601_flatten-2d-vector.py | 1,398 | 4.375 | 4 | # 601. Flatten 2D Vector
# 中文English
# Implement an iterator to flatten a 2d vector.
#
# 样例
# Example 1:
#
# Input:[[1,2],[3],[4,5,6]]
# Output:[1,2,3,4,5,6]
# Example 2:
#
# Input:[[7,9],[5]]
# Output:[7,9,5]
from collections import deque
class Vector2D(object):
# @param vec2d {List[List[int]]}
def __init__(self, vec2d):
self.deque = deque(vec2d)
self.next_element = None
# Initialize your data structure here
# @return {int} a next element
def next(self):
return self.next_element
# @return {boolean} true if it has next element
# or false
def hasNext(self):
if not self.deque:
return False
curr_element = self.deque.popleft()
while isinstance(curr_element, list):
for i in reversed(curr_element):
self.deque.appendleft(i)
if len(self.deque) != 0:
curr_element = self.deque.popleft()
else:
curr_element = None
if curr_element is None:
return False
else:
self.next_element = curr_element
return True
# Your Vector2D object will be instantiated and called as such:
vec2d = [[1, 2], [3], [4, 5, 6]]
i, v = Vector2D(vec2d), []
while i.hasNext(): v.append(i.next())
v
vec2d = [[], []]
i, v = Vector2D(vec2d), []
while i.hasNext(): v.append(i.next()) | true |
7fb4c1cab08e8ecb37dee89edf8a47093e54a1b5 | wang264/JiuZhangLintcode | /AlgorithmAdvance/L4/require/633_find-the-duplicate-number.py | 1,001 | 4.125 | 4 | # 633. Find the Duplicate Number
# 中文English
# Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
# guarantee that at least one duplicate number must exist.
# Assume that there is only one duplicate number, find the duplicate one.
#
# Example
# Example 1:
#
# Input:
# [5,5,4,3,2,1]
# Output:
# 5
# Example 2:
#
# Input:
# [5,4,4,3,2,1]
# Output:
# 4
# Notice
# You must not modify the array (assume the array is read only).
# You must use only constant, O(1) extra space.
# Your runtime complexity should be less than O(n^2).
# There is only one duplicate number in the array, but it could be repeated more than once.
class Solution:
"""
@param nums: an array containing n + 1 integers which is between 1 and n
@return: the duplicate one
"""
def findDuplicate(self, nums):
# write your code here
pass
sol = Solution()
sol.findDuplicate(nums=[5,4,4,3,2,1])
sol.findDuplicate(nums=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]) | true |
b20590161658824d6ec48d666ca7dafbb19bcbcd | wang264/JiuZhangLintcode | /Algorithm/L4/require/453_flatten-binary-tree-to-linked-list.py | 2,642 | 4.1875 | 4 | # 453. Flatten Binary Tree to Linked List
# 中文English
# Flatten a binary tree to a fake "linked list" in pre-order traversal.
#
# Here we use the right pointer in TreeNode as the next pointer in ListNode.
#
# Example
# Example 1:
#
# Input:{1,2,5,3,4,#,6}
# Output:{1,#,2,#,3,#,4,#,5,#,6}
# Explanation:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Example 2:
#
# Input:{1}
# Output:{1}
# Explanation:
# 1
# 1
# Challenge
# Do it in-place without any extra memory.
#
# Notice
# Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.
class Solution:
"""
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
if root is None:
return root
dummy_node = TreeNode(-1) # dummy node
prev_node = dummy_node
stack = [root]
while stack:
curr_node = stack.pop()
prev_node.left = None
prev_node.right = curr_node
prev_node = curr_node
if curr_node.right:
stack.append(curr_node.right)
if curr_node.left:
stack.append(curr_node.left)
return dummy_node.right
from helperfunc import TreeNode, build_tree_breadth_first
sol = Solution()
root = build_tree_breadth_first(sequence=[1, 2, 5, 3, 4, None, 6])
linked_list = sol.flatten(root)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import deque
class SolutionOutOfMemory:
"""
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
# write your code here
if root is None:
return None
q_traverse = deque([])
q_nodes = deque([])
q_traverse.append(root)
while q_traverse:
node = q_traverse.popleft()
q_nodes.append(node)
if node.right:
q_nodes.appendleft(node.right)
if node.left:
q_nodes.appendleft(node.left)
# fix the relationship.
root = q_nodes[0]
while len(q_nodes) > 1:
node = q_nodes.popleft()
node.left = None
node.right = q_nodes[0]
return root
sol = SolutionOutOfMemory()
root = build_tree_breadth_first(sequence=[1, 2, 5, 3, 4, None, 6])
linked_list = sol.flatten(root)
| true |
e9f8b128025f9273474c6c0af58541eb9fcf1ae8 | wang264/JiuZhangLintcode | /Intro/L5/require/376_binary_tree_path_sum.py | 1,969 | 4.21875 | 4 | # 376. Binary Tree Path Sum
# 中文English
# Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
#
# A valid path is from root node to any of the leaf nodes.
#
# Example
# Example 1:
#
# Input:
# {1,2,4,2,3}
# 5
# Output: [[1, 2, 2],[1, 4]]
# Explanation:
# The tree is look like this:
# 1
# / \
# 2 4
# / \
# 2 3
# For sum = 5 , it is obviously 1 + 2 + 2 = 1 + 4 = 5
# Example 2:
#
# Input:
# {1,2,4,2,3}
# 3
# Output: []
# Explanation:
# The tree is look like this:
# 1
# / \
# 2 4
# / \
# 2 3
# Notice we need to find all paths from root node to leaf nodes.
# 1 + 2 + 2 = 5, 1 + 2 + 3 = 6, 1 + 4 = 5
# There is no one satisfying it.
from helperfunc import TreeNode, build_tree_breadth_first
class Solution:
"""
@param: root: the root of binary tree
@param: target: An integer
@return: all valid paths
"""
def binaryTreePathSum(self, root, target):
rslt = self.binary_tree_path_sum_helper(root, target)
return [list(reversed(x)) for x in rslt]
def binary_tree_path_sum_helper(self, root, target):
# write your code here
if root is None:
return []
if root.left is None and root.right is None:
if root.val == target:
return [[target]]
else:
return []
left_rslt = self.binary_tree_path_sum_helper(root.left, target - root.val)
right_rslt = self.binary_tree_path_sum_helper(root.right, target - root.val)
rslt = left_rslt + right_rslt
for i in range(len(rslt)):
rslt[i].append(root.val)
return rslt
root = build_tree_breadth_first(sequence=[1, 2, 4, 2, 3])
sol = Solution()
rslt = sol.binaryTreePathSum(root=root, target=5)
print(rslt)
root = build_tree_breadth_first(sequence=[1, 2, -5, 4, None, 5, 6])
sol = Solution()
rslt = sol.binaryTreePathSum(root=root, target=2)
| true |
4924278da3dba92909c099754236d732d5ae6e09 | trinahaque/LeetCode | /Easy/String/reverseWordsInString.py | 942 | 4.15625 | 4 | # Given an input string, reverse the string word by word.
# Input: "the sky is blue"
# Output: "blue is sky the"
def reverseWordsInString(s):
if len(s) < 1:
return ""
elif len(s) < 2:
if s.isalnum() == True:
return s
result = ""
# splits the words into an array
strArr = s.split(" ")
# reverses the array
for i in range(int(len(strArr)/2)):
if strArr[i].isalnum() == False or strArr[len(strArr) - 1 - i].isalnum() == False:
break
strArr[i], strArr[len(strArr) - 1 - i] = strArr[len(strArr) - 1 - i], strArr[i]
# puts each word from the reversed array into result string except for the last one
for i in range(len(strArr) - 1):
if strArr[i].isalnum() == False:
break
result += strArr[i] + " "
result += strArr[len(strArr) - 1]
return result
input = "the sky blue"
print (reverseWordsInString("1 "))
| true |
b8c79c64b1f91888afb0fadaf80e9af7921f191d | haoccheng/pegasus | /leetcode/power_of_two.py | 416 | 4.375 | 4 | # Given an integer, determine if it is a power of two.
def power_of_two(n):
if n <= 0:
return False
else:
value = n
while (value > 0):
if value == 1:
return True
else:
r = value % 2
if r != 0:
return False
else:
value = value / 2
return True
print power_of_two(1)
print power_of_two(2)
print power_of_two(8)
print power_of_two(9)
| true |
2029924ab34ced3e322083702d175366ba02b12e | haoccheng/pegasus | /coding_interview/list_sort.py | 965 | 4.125 | 4 | # implement a function to sort a given list.
# O(n2): each iteration locate the element that should have been placed in the specific position, swap.
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def take(self):
buffer = [self.value]
if self.next is not None:
buffer += self.next.take()
return buffer
def create_linked_list():
w = Node(3)
x = Node(4)
y = Node(2)
z = Node(1)
w.next = x
x.next = y
y.next = z
return w
def sort_list(input):
root = input
curr = input
while (curr is not None):
min_v = curr.value
min_p = curr
pt = curr.next
while (pt is not None):
if (min_v > pt.value):
min_v = pt.value
min_p = pt
pt = pt.next
t = curr.value
curr.value = min_v
min_p.value = t
curr = curr.next
return root
input = create_linked_list()
print input.take()
sort = sort_list(input)
print sort.take()
| true |
9cb6bc62c648f66140ca8cc97a7eb264ce21a88c | ismaelconejeros/100_days_of_python | /Day 04/exercise_01.py | 521 | 4.4375 | 4 | #You are going to write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails".
#Important, the first letter should be capitalised and spelt exactly like in the example e.g. Heads, not heads.
#There are many ways of doing this. But to practice what we learnt in the last lesson, you should generate a
# random number, either 0 or 1. Then use that number to print out Heads or Tails.
import random
coin = random.randint(0,1)
if coin == 0:
print('Tails')
elif coin == 1:
print('Heads') | true |
1be3880c9dbce5695a23b3aa8fb6cd4fa043c8bc | ismaelconejeros/100_days_of_python | /Day 03/exercise_05.py | 2,192 | 4.21875 | 4 | #write a program that tests the compatibility between two people.
#To work out the love score between two people:
#Take both people's names and check for the number of times the letters in the word TRUE occurs.
# Then check for the number of times the letters in the word LOVE occurs.
# Then combine these numbers to make a 2 digit number.
#For Love Scores less than 10 or greater than 90, the message should be:
#"Your score is **x**, you go together like coke and mentos."
#For Love Scores between 40 and 50, the message should be:
#"Your score is **y**, you are alright together."
#Otherwise, the message will just be their score. e.g.:
#"Your score is **z**."
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
true = ['t','r','u','e','T','R','U','E']
love = ['l','o','v','e','L','O','V','E']
names = name1 + name2
true_num = 0
love_num = 0
for letter in names:
if letter in true:
true_num += 1
if letter in love:
love_num += 1
score = int(str(true_num) + str(love_num))
if score < 10 or score > 90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif score >= 40 and score <= 50:
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.")
#-------------Other way
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
names = name1.lower() + name2.lower()
t = names.count('t')
r = names.count('r')
u = names.count('u')
e = names.count('e')
l = names.count('l')
o = names.count('o')
v = names.count('v')
e = names.count('e')
true = str(t+r+u+e)
love = str(l+o+v+e)
score = int(true+love)
if score < 10 or score > 90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif score >= 40 and score <= 50:
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.") | true |
a5b39aec77a04693499049e27f6ee26ab3ff66e6 | Malcolm-Tompkins/ICS3U-Unit4-01-Python-While_Loops | /While_Loops.py | 695 | 4.125 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on May 12, 2021
# Determines sum of all numbers leading up to a number
def main():
# Input
user_input = (input("Enter your number: "))
try:
user_number = int(user_input)
loop_counter = 0
while (loop_counter < user_number):
total = (user_number / 2) * (1 + user_number)
loop_counter = loop_counter + 1
print("{0:,.0f} is the total sum of the previous numbers before {1}"
.format(total, user_number))
except Exception:
print("{} is not an integer".format(user_input))
finally:
print("Done.")
if __name__ == "__main__":
main()
| true |
e37cb75f5da75f5c0e24a79fde1551f7debf8799 | exeptor/TenApps | /App_2_Guess_The_Number/program_app_2.py | 873 | 4.25 | 4 | import random
print('-------------------------------------')
print(' GUESS THE NUMBER')
print('-------------------------------------')
print()
random_number = random.randint(0, 100)
your_name = input('What is your name? ')
guess = -1
first_guess = '' # used this way in its first appearance only; on the second it will be changed
while guess != random_number:
raw_guess = input('What is your{} guess {}? '.format(first_guess, your_name))
guess = int(raw_guess)
first_guess = ' next' # change on the second appearance in the loop to enrich user experience
if guess < random_number:
print('Sorry {}, {} is LOWER!'.format(your_name, guess))
elif guess > random_number:
print('Sorry {}, {} is HIGHER!'.format(your_name, guess))
else:
print('Congratulation {}, {} is the correct number!'.format(your_name, guess))
| true |
9ac51bc45b2f5dfb09bb397ce0aa9c1e5ae06034 | engineerpassion/Data-Structures-and-Algorithms | /DataStructures/LinkedList.py | 2,417 | 4.1875 | 4 | class LinkedListElement():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def is_empty(self):
empty = False
if self.head is None:
empty = True
return empty
def add(self, value):
element = LinkedListElement(value)
if self.is_empty():
self.head = element
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = element
return
def delete(self, value):
deleted = False
if not self.is_empty():
if self.head.value == value:
temp = self.head
self.head = self.head.next
del temp
deleted = True
if not deleted and self.head.next is not None:
prev = self.head
current = self.head.next
while current is not None:
if current.value == value:
prev.next = current.next
del current
deleted = True
break
prev = current
current = current.next
return deleted
def traverse(self):
s = ""
temp = self.head
while temp is not None:
s += str(temp.value)
temp = temp.next
if temp is not None:
s += "->"
print(s)
return
def main():
ll = LinkedList()
print("Created an empty Linked List!")
print("Adding 1.")
ll.add(1)
print("Linked list looks as follows:")
ll.traverse()
print("Adding 2.")
ll.add(2)
print("Linked list looks as follows:")
ll.traverse()
print("Adding 3.")
ll.add(3)
print("Adding 4.")
ll.add(4)
print("Adding 5.")
ll.add(5)
print("Linked list looks as follows:")
ll.traverse()
print("Removing 3.")
ll.delete(3)
print("Linked list looks as follows:")
ll.traverse()
print("Removing 4.")
ll.delete(4)
print("Linked list looks as follows:")
ll.traverse()
print("Removing 1.")
ll.delete(1)
print("Linked list looks as follows:")
ll.traverse()
"""
Uncomment the following line to run the file.
"""
#main() | true |
531470e218f42e9f88b95968c05469ffd5e81554 | Morgenrode/Euler | /prob4.py | 725 | 4.1875 | 4 | '''prob4.py: find the largest palidrome made from the product of two 3-digit numbers'''
def isPalindrome(num):
'''Test a string version of a number for palindromicity'''
number = str(num)
return number[::-1] == number
def search():
'''Search through all combinations of products of 3 digit numbers'''
palindrome = 0
for x in range(100,1000):
for y in range(100,1000):
z = x * y
if isPalindrome(z) and z > palindrome:
palindrome = z
else:
pass
return palindrome
print(search())
| true |
166ed8b161017285f5fe6c52e76d8a985b6ba903 | acheimann/PythonProgramming | /Book_Programs/Ch1/chaos.py | 553 | 4.46875 | 4 | # File: chaos.py
# A simple program illustrating chaotic behavior.
#Currently incomplete: advanced exercise 1.6
#Exericse 1.6 is to return values for two numbers displayed in side-by-side columns
def main():
print "This program illustrates a chaotic function"
x = input("Enter a number between 0 and 1: ")
y = input ("Enter a second number between 0 and 1:")
n = input("How many numbers should I print?")
for i in range(n):
x = 2.0 * x * (1 - x)
print x
y = 2.0 * y * (1-y)
print y
main() | true |
1262c1d720d1a6d51261e0eb5ca739abe7545254 | acheimann/PythonProgramming | /Book_Programs/Ch3/sum_series.py | 461 | 4.25 | 4 | #sum_series.py
#A program to sum a series of natural numbers entered by the user
def main():
print "This program sums a series of natural numbers entered by the user."
print
total = 0
n = input("Please enter how many numbers you wish to sum: ")
for i in range(n):
number = input("Please enter the next number in your sequence: ")
total = total + number
print "Your total adds up to", total
main()
| true |
431a0f0002427aa49f2cb3c4df8fb0fd3a6fa2ba | acheimann/PythonProgramming | /Book_Programs/Ch2/convert_km2mi.py | 391 | 4.5 | 4 | #convert_km2mi.py
#A program to convert measurements in kilometers to miles
#author: Alex Heimann
def main():
print "This program converts measurements in kilometers to miles."
km_distance = input("Enter the distance in kilometers that you wish to convert: ")
mile_equivalent = km_distance * 0.62
print km_distance, "kilometers is equal to ", mile_equivalent, "miles."
main() | true |
3d40a99ce2dd3e7965cf4284455091e715ca1227 | Ray0907/intro2algorithms | /15/bellman_ford.py | 1,630 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# single source shortest path algorithm.
from sys import maxsize
# The main function that finds shortest
# distances from src to all other vertices
# using Bellman-Ford algorithm. The function
# also detects negative weight cycle
# The row graph[i] represents i-th edge with
# three values u, v and w.
def BellmanFord(graph, V, E, src):
# Initialize distance of all vertices as infinite.
dis = [maxsize] * V
# Initialize distance of source as 0
dis[src] = 0
'''
Relax all edges |V| - 1 times. A simple shortest path from src to any other vertex can have at-most |V| -1 edges.
'''
for i in range(V -1):
for j in range(E):
if dis[graph[j][0]] + \
graph[j][2] < dis[graph[j][1]]:
dis[graph[j][1]] = dis[graph[j][0]] + graph[j][2]
'''
Check for negative-weight cycles.The above step gurantees shortest distances if graph doesn't contain negative weight cycle. If we get a shorter path, then there is a cycle.
'''
for i in range(E):
x = graph[i][0]
y = graph[i][1]
weight = graph[i][2]
if dis[x] != maxsize and dis[x] + weight < dis[y]:
print('Graph contains negative weight cycle')
print('Vertex Distance from source')
for i in range(V):
print('%d\t\t%d' % (i, dis[i]))
if __name__ == '__main__':
V = 5 # Number of vertices in graph
E = 8 # NUmber of edges in graph
'''
Every edge has three values (u, v, w) where the edge is from vertex u to v.And weight of the edge is w.
'''
graph = [[0, 1, -1], [0, 2, 4], [1, 2, 3],
[1, 3, 2], [1, 4, 2], [3, 2, 5],
[3, 1, 1], [4, 3, -3]]
BellmanFord(graph, V, E, 0)
| true |
e9c98d8d13b3b55e9fd02d19d6ab17df4f1eb0d7 | MohamedAamil/Simple-Programs | /BinarySearchWords.py | 1,805 | 4.21875 | 4 | """
BinarySearchWords.py
To check whether a word is in the word list, you could use the in operator, but
it would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a
bisection search (also known as binary search), which is similar to what you
do when you look a word up in the dictionary (the book, not the data
structure). You start in the middle and check to see whether the word you are
looking for comes before the word in the middle of the list. If so, you search
the first half of the list the same way. Otherwise you search the second half.
Either way, you cut the remaining search space in half. If the word list has
113,809 words, it will take about 17 steps to find the word or conclude that it’s
not there.
Write a function called in_bisect that takes a sorted list and a target value and
returns True if the word is in the list and False if it’s not
"""
def in_bisect(Target, Strings):
"""
Searches for the Element using Binary Search
:param Target: String , Word
:param Strings: List , Words
:return: Boolean
"""
First = 0
Last = len(Strings) - 1
while First <= Last:
Mid = (First + Last) // 2
if Target == Strings[Mid]:
return Mid+1
elif Target < Strings[Mid]:
Last = Mid - 1
else:
First = Mid + 1
else:
return False
Length = eval(input("Enter Range: "))
Arr = []
for i in range(Length):
Words = eval(input("Enter Sorted String : "))
Arr.append(Words)
Elem = input("\n Enter Element to search: ")
Pos = in_bisect(Elem,Arr)
if not Pos:
print("Element not Found!!")
else:
print("\n Element found in Position : ", Pos) | true |
92f328387b9d1754ad0f5fc71d2626acd3c82666 | MohamedAamil/Simple-Programs | /SumOfDigits.py | 397 | 4.21875 | 4 | """
SumOfDigits.py : Displays the Sum of Digits of the given Number
"""
def get_sumofDigits(Num):
"""
Calculates the Sum of Digits
:param Num: integer , Number
"""
Sum = 0
while Num != 0:
a = Num % 10
Sum = Sum + a
Num = Num // 10
print("Sum of Digits : ",Sum)
Num = eval(input("Enter a Number: "))
get_sumofDigits(Num)
| true |
ffaab16f7ee68be9b9599cca7e2906279430d19d | trangthnguyen/PythonStudy | /integercuberootwhile.py | 388 | 4.34375 | 4 | #!/usr/bin/env python3
#prints the integer cube root, if it exists, of an
#integer. If the input is not a perfect cube, it prints a message to that
#effect.
x = int(input('Enter integer number:'))
guess = 0
while guess ** 3 < abs(x):
guess = guess + 1
if guess ** 3 == abs(x):
if x < 0:
guess = - guess
print('Cube root of', x, 'is:', guess)
else:
print(x, 'is not a perfect cube')
| true |
c58cd3ffc8bc84c8b21d8821daf55fca3f197eb3 | trangthnguyen/PythonStudy | /numberstringsum.py | 418 | 4.1875 | 4 | #!/usr/bin/env python3
#Let s be a string that contains a sequence of decimal numbers
#separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints
#the sum of the numbers in s.
x = input('Enter a string:')
count = 0
sum = 0
for i in x:
if i in '0123456789':
count = count + 1
sum = sum + int(i)
if count > 0:
print('Sum of the numbers in', x, 'is', sum)
else:
print('There is no number in', x)
| true |
f22285f06df5b6c8d79febe605d7471919356199 | kshruti1410/python-assignment | /src/q2.py | 822 | 4.15625 | 4 | """ abc is a by default abrstract class present """
from abc import ABC, abstractmethod
class Person(ABC):
""" inherit ABC class """
@abstractmethod
def get_gender(self):
""" skipping the function """
pass
class Female(Person):
""" this class return gender of a person """
def get_gender(self):
""" self is by default argument """
print("Person is Female")
class Male(Person):
""" this class return gender of a person """
def get_gender(self):
""" self is by default argument """
print("Person is Male")
try:
PARENT = Person()
except TypeError:
print(TypeError)
finally:
print("Female class method")
FEMALE = Female()
FEMALE.get_gender()
print("Male class method")
MALE = Male()
MALE.get_gender() | true |
bcb068344d4db4f5ae984ad6f6d63a378587ad83 | Abed01-lab/python | /notebooks/Handins/Modules/functions.py | 1,289 | 4.28125 | 4 | import csv
import argparse
def print_file_content(file):
with open(file) as f:
reader = csv.reader(f)
for row in reader:
print(row)
def write_list_to_file(output_file, lst):
with open(output_file, 'w') as f:
writer = csv.writer(f)
for element in lst:
f.write(element + "\n")
def write_strings_to_file(file, *strings):
with open(file, 'w') as f:
for string in strings:
f.write(string + "\n")
print(string)
def read_csv(input_file):
with open(input_file) as f:
new_list = []
reader = csv.reader(f)
for row in reader:
new_list.append(row)
return new_list
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A program that reads from csv and write to txt. the path is the location of the csv and file_name is the location of the file to write to.')
parser.add_argument('path', help='The path to the csv file')
parser.add_argument('-file', '--file_name', help='The file to write to')
args = parser.parse_args()
print('csv path:', args.path)
print('file_name:', args.file_name)
if args.file_name is not None:
write_list_to_file(args.file_name, read_csv(args.path)) | true |
ad7819e0dde2bf2b8583f992ec18f7ef5261cd0b | Intro-to-python/homework1-MaeveFoley | /problem2.py | 534 | 4.34375 | 4 | #homework1
#Due 10/10/18
# Problem 2
#Write a Python program to guess a number between 1 to 9.
# User is prompted to enter a guess. If the user guesses wrong then
#the prompt appears again until the guess is correct, on successful guess,
#user will get a "Well guessed!" message, and the program will exit.
#(Hint use a while loop)
#Don't forget to import random
import random
targetNum = random.randint(1,9)
guessNum = input("Enter a number")
while guessNum = targetNum:
print("Well guessed!")
else:
print(input("Try again!"))
| true |
edac7d307b6001b92023f46bddd49fd29af13715 | williamwbush/codewars | /unfinished/algorithm_night.py | 2,116 | 4.15625 | 4 | # Problem 1:
# https://www.hackerrank.com/challenges/counting-valleys/problem
# Problem 2:
# You found directions to hidden treasure only written in words. The possible directions are "NORTH", "SOUTH","WEST","EAST".
# "NORTH" and "SOUTH" are opposite directions, as are "EAST" and "WEST". Going one direction and coming back in the opposite direction leads to going nowhere. Someone else also has these directions to the treasure and you need to get there first. Since the directions are long, you decide to write a program top figure out the fastest and most direct route to the treasure.
# Write a function that will take a list of strings and will return a list of strings with the unneeded directions removed (NORTH<->SOUTH or EAST<->WEST side by side).
# Example 1:
# input: ['NORTH','EAST','WEST','SOUTH','WEST','SOUTH','NORTH','WEST']
# output:['WEST','WEST']
# In ['NORTH','EAST','WEST','SOUTH','WEST','SOUTH','NORTH','WEST'] 'NORTH' and 'SOUTH' are not directly opposite but they become directly opposite after reduction of 'EAST' and 'WEST'. The whole path can be reduced to ['WEST','WEST'].
# Example 2:
# input: ['EAST','NORTH','WEST','SOUTH']
# output:['EAST','NORTH','WEST','SOUTH']
# Not all paths are reducible. The path ['EAST','NORTH','WEST','SOUTH'] is not reducible. 'EAST' and 'NORTH', 'NORTH' and 'WEST', 'WEST' and 'SOUTH' are not directly opposite of each other and thus can't be reduced. The resulting path has
inp = ['EAST','NORTH','WEST','SOUTH']
position = [0,0]
for d in inp:
if d == 'NORTH':
position[1] += 1
elif d == 'SOUTH':
position[1] -= 1
elif d == 'EAST':
position[0] += 1
elif d == 'WEST':
position[0] -= 1
print(position)
directions = []
if position[0] > 0:
for i in range(position[0]):
directions.append('EAST')
if position[0] < 0:
for i in range(abs(position[0])):
directions.append('WEST')
if position[1] > 0:
for i in range(position[1]):
directions.append('NORTH')
if position[1] < 0:
for i in range(abs(position[1])):
directions.append('SOUTH')
print(directions)
| true |
615b00ffe0a15294d2b65af008f6889ef622e005 | igauravshukla/Python-Programs | /Hackerrank/TextWrapper.py | 647 | 4.25 | 4 | '''
You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.
Input Format :
The first line contains a string, S.
The second line contains the width, w.
Constraints :
0 < len(S) < 1000
0 < w < len(S)
Output Format :
Print the text wrapped paragraph.
Sample Input 0
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output 0
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
'''
import textwrap
def wrap(string, max_width):
l = textwrap.wrap(string,max_width)
return "\n".join(l)
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
| true |
83c33d7ffe87715f233c63902d36bcfdab77460a | panditprogrammer/python3 | /python72.py | 354 | 4.40625 | 4 | # creating 2D array using zeros ()Function
from numpy import *
a=zeros((2,3) ,dtype=int)
print(a)
print("This is lenth of a is ",len(a))
n=len(a)
for b in range(n):
# range for index like 0,1,in case of range 2.
m=len(a[b])
print("This is a lenth of a[b]",m)
for c in range(m):
#print("This is inner for loop")
print( b,c,"index =",a[b][c])
| true |
9fdcf03a227850f99153d4948c26c3415ccb34f2 | panditprogrammer/python3 | /Tkinter GUI/tk_python01.py | 774 | 4.28125 | 4 | from tkinter import *
#creating a windows
root=Tk()
# geometry is used to create windows size
root.geometry("600x400")
# To creating a label or text you must use Label class
labelg=Label(root,text="This is windows",fg= "red", font=("Arial",20))
# fg for forground color and bg for background color to change font color
lab1=Label(root,fg="blue",text="this is another\n label",font=("Arial",20)).pack()
# .pack is used for packing on windows and displaying
labelg.pack()
lab2=Label(root,bg="gray",width="20",height="3",text="label 2" ,
fg="green",font=("Arial",18)).pack()
#minsize is used for windows size
root.minsize(480,300)
text=Label(text="This is simple windows.",font=("Arial 16")).pack()
root.mainloop()
print(" after mainloop run successfully")
| true |
26230d0e8b712a5ea37bb008e578768ed322b5c7 | jktheking/MLAI | /PythonForDataScience/ArrayBasics.py | 1,027 | 4.28125 | 4 | import numpy as np
array_1d = np.array([1, 2, 3, 4, 589, 76])
print(type(array_1d))
print(array_1d)
print("printing 1d array\n", array_1d)
array_2d = np.array([[1, 2, 3], [6, 7, 9], [11, 12, 13]])
print(type(array_2d))
print(array_2d)
print("printing 2d array\n", array_2d)
array_3d = np.array([[[1, 2, 3], [6, 7, 9]], [[11, 12, 13], [12, 19, 12]]])
print(type(array_3d))
print("printing 3d array\n")
print(array_3d)
# array multiplication, let's first see the multiplication of 2 lists
mul_list1 = [1, 2, 3, 4]
mul_list2 = [4, 3, 2, 1]
mul_list_result = list(map(lambda x, y: x*y, mul_list1, mul_list2))
print("\nmultiplication of list using lambda:", mul_list_result)
# let's see how multiplication for arrays, binary operators in numpy works element-wise.
# Note : To use binary operators on array, size of operand arrays must be dimension-wise same.
mul_array1 = np.array(mul_list1)
mul_array2 = np.array(mul_list2)
mul_array_result = mul_array1 * mul_array2;
print("\n multiplication of array:", mul_array_result)
| true |
bd48356cbcf6e50f44dd26a88b8b8e2178311ef0 | AtulRajput01/Data-Structures-And-Algorithms-1 | /sorting/python/heap-sort.py | 1,331 | 4.15625 | 4 | """
Heap Sort
Algorithm:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1.
Finally, heapify the root of the tree.
3. Repeat step 2 while the size of the heap is greater than 1.
Example Testcase - I/P - [12, 11, 13, 5, 6, 7]
O/P - 5 6 7 11 12 13
Time Complexity - O(n*Logn)
"""
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
# check if left child of root exists and is greater than root
if l < n and arr[largest] < arr[l]:
largest = l
# check if right child of root exists and is greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# swap values in needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
# heapify the root
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
# building a max heap
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
# extract elements one by one
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
# Driver code
arr = list(map(int, input().split()))
heapSort(arr)
n = len(arr)
print("Sorted array is")
print(*arr)
| true |
7deb2d43fbf45c07b5e2186c320e77bdad927c18 | iAmAdamReid/Algorithms | /recipe_batches/recipe_batches.py | 1,487 | 4.125 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients, count=0):
# we need to globally track how many batches we've made, and pass recursively
# TODO: find how to do this w/o global variables
global batches
batches = count
can_cook = []
# if we do not have any necessary ingredient, return 0
if len(recipe) > len(ingredients):
return 0
# we need to see if we are able to make a batch
for item in ingredients:
if ingredients[item] >= recipe[item]:
can_cook.append(True)
else:
can_cook.append(False)
# if we have all necessary ingredients, add a batch to count and subtract from ingredients
if all(can_cook):
batches += 1
remainder = {key: ingredients[key] - recipe.get(key, 0) for key in ingredients.keys()}
# recursion call with the remaining ingredients
recipe_batches(recipe, remainder, batches)
return batches
### NOTES
# this subtracts the recipe from the ingredients and gives the remainder
# remainder = {key: ingredients[key] - recipe.get(key, 0) for key in ingredients.keys()}
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients)) | true |
1f0d340225be278ee074362f280207a60be9ed63 | Ardra/Python-Practice-Solutions | /chapter3/pbm11.py | 332 | 4.125 | 4 | '''Problem 11: Write a python program zip.py to create a zip file. The program should take name of zip file as first argument and files to add as rest of the arguments.'''
import sys
import zipfile
directory = sys.argv[1]
z = zipfile.zipfile(directory,'w')
length = len(sys.argv)
for i in range(2,length):
z.write(sys.argv[i])
| true |
09c3839dbbe5c8cfc50eff2e5bd07fa5851695c0 | Ardra/Python-Practice-Solutions | /chapter6/pbm1.py | 203 | 4.21875 | 4 | '''Problem 1: Implement a function product to multiply 2 numbers recursively using + and - operators only.'''
def mul(x,y):
if y==0:
return 0
elif y>0:
return x+mul(x,y-1)
| true |
c19f67d6f4a5d2448fb4af73f1e3f12d3786bd1c | Ardra/Python-Practice-Solutions | /chapter3/pbm2.py | 742 | 4.21875 | 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.'''
def listfiles(dir_name):
import os
list = os.listdir(dir_name)
return list
def word_frequency(words):
frequency = {}
for w in words:
frequency[w] = frequency.get(w, 0) + 1
return frequency
def ext_count(dir_name):
list1 = listfiles(dir_name)
#print list1
list2 = []
for x in list1:
list2.append(x.split('.'))
#print list2
list3 = []
for x in list2:
if(len(x)>1):
list3.append(x[1])
return word_frequency(list3)
| true |
29d5d901fc4ea681b9c2caa9f2dddf954174da4d | Ardra/Python-Practice-Solutions | /chapter2/pbm38.py | 399 | 4.15625 | 4 | '''Problem 38: Write a function invertdict to interchange keys and values in a dictionary. For simplicity, assume that all values are unique.
>>> invertdict({'x': 1, 'y': 2, 'z': 3})
{1: 'x', 2: 'y', 3: 'z'}'''
def invertdict(dictionary):
new_dict = {}
for key, value in a.items():
#print key, value
new_dict[value]=key
#print new_dict
return new_dict
| true |
874438d788e903d45edc24cc029f3265091130b1 | IDCE-MSGIS/sample-lab | /mycode_2.py | 572 | 4.25 | 4 | """
Name: Banana McClane
Date created: 24-Jan-2020
Version of Python: 3.4
This script is for randomly selecting restaurants! It takes a list as an input and randomly selects one item from the list, which is output in human readable form on-screen.
"""
import random # importing 'random' allows us to pick a random element from a list
restaurant_list = ['Dominos Pizza', 'Mysore', 'Restaurant Thailande', 'Lemeac', 'Chez Leveque', 'Sushi', 'Italian', 'Poutineville']
restaurant_item = random.choice(restaurant_list)
print ("Randomly selected item from list is " + restaurant_item)
| true |
c5a84486c9e216b5507fb076f1c9c64257804232 | DaveG-P/Python | /BookCodes/DICTIONARIES.py | 2,745 | 4.59375 | 5 | # Chapter 6
# A simple dictionary
person = {'name': 'david', 'eyes': 'brown', 'age': 28}
print(person['name'])
print(person['eyes'])
# Accessing values in a dictionary
print(person['name'])
# If there is a number in value use str()
print(person['age'])
# Adding new key-valu pairs
person['dominate side'] = 'left'
person['city'] = 'bogota'
# Starting with an empty list
countries = {}
countries['country'] = 'france'
countries['capital'] = 'paris'
# Modifying values in dictionary
countries['capital'] = 'nice'
print("The new capital of France is " + countries['capital'])
# another example
France = {
'capital': 'paris',
'idioma': 'frances',
'presidente': 'emmanuel macron',
'moneda': 'euro',
}
# Removing key value pairs
del France['moneda']
# A dictionary of similar objects
languages = {
'jen': 'python',
'david': 'python',
'andre': 'C ++',
'felipe': 'javascript',
}
print("David's favorite language is " + languages['david'].title() + ".")
# Looping through a dictionary
# Looping through all key values
for k, v in France.items():
print("\nKey: " + k)
print("\nValue: " + v)
# Looping though all the keys
for key in France.keys():
print(key.title())
friends = ['jen', 'andre']
for name in languages.keys():
print(name.title())
if name in firends:
print("HI " + name.title()
# Looping though keys in order
for key in sorted(France.keys()):
print(name.title() + ".")
# Looping through all values
print("Here are the following facts about France")
for value in France.values():
print(value.title())
# Using set pulls out uniquge values
for language in set(languages.values()):
print(language.title())
# Nesting
# List of dictioaries
France = {'capital': 'paris', 'idioma': 'frances'}
Spain = {'capital': 'madrid', 'idioma': 'catellano'}
UK = {'capital': 'londres', 'idioma':'ingles'}
countries = [France, Spain, UK]
for country in countries:
print(country)
# A list in a dictionary
UK = {'capital': 'londres', 'idioma':['ingles', 'gales', 'escoses']}
France = {'capital': 'paris', 'idioma': ['frances', 'breton', 'gascon']}
Spain = {'capital': 'madrid', 'idioma': ['catellano', 'catalan', 'aragones']}
# dictionary inside a dictionary
countries = {
UK = {
'capital': 'londres',
'idioms':['ingles','gales', 'escoses'],
'monarcha': 'isabel II',
},
France = {
'capital': 'paris',
'idioma': ['frances', 'breton', 'gascon'],
'monarcha': 'depuso'
},
Spain = {
'capital': 'madrid',
'idioma': ['catellano', 'catalan', 'aragones'],
'monarcha': 'felipe vi'
},
}
for country, facts in countries.items():
print("\nCountry: " + country.title)
| true |
9773d6abe3781c5c2bc7c083a267a3b84bc30983 | proTao/leetcode | /21. Queue/622.py | 1,931 | 4.1875 | 4 | class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
self.data = [None] * k
self.head = 0
self.tail = 0
self.capacity = k
self.size = 0
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue.
Return true if the operation is successful.
"""
if self.size == self.capacity:
return False
self.data[self.tail] = value
self.tail = (self.tail + 1) % self.capacity
self.size += 1
return True
def deQueue(self) -> bool:
"""
Delete an element from the circular queue.
Return true if the operation is successful.
"""
if self.size == 0:
return False
self.data[self.head]
self.head = (self.head + 1) % self.capacity
self.size -= 1
return True
def Front(self) -> int:
"""
Get the front item from the queue.
"""
return self.data[self.head] if self.size else -1
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
if self.size:
return self.data[(self.tail + self.capacity - 1)%self.capacity]
else:
return -1
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
return self.size == 0
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
return self.size == self.capacity
if __name__ == "__main__":
obj = MyCircularQueue(2)
print(obj.enQueue(1))
print(obj.enQueue(2))
print(obj.enQueue(3))
print(obj.deQueue())
print(obj.Front())
print(obj.Rear())
print(obj.isEmpty())
print(obj.isFull()) | true |
be7f5249e86caa685f932b2cbd962d11fb9596a5 | purusottam234/Python-Class | /Day 17/exercise.py | 722 | 4.125 | 4 | # Create a list called numbers containing 1 through 15, then perform
# the following tasks:
# a. Use the built in function filter with lambda to select only numbers even elements function.
# Create a new list containing the result
# b.Use the built in function map with a lambda to square the values of numbers' elements. Create
# a new list containing the result function
# c. Filter numbers even elements , then map them to their squares .Create
# a new list containing the result
numbers = list(range(1, 16))
print(numbers)
a = list(filter(lambda x: x % 2 == 0, numbers))
print(a)
b = list(map(lambda x: x ** 2, numbers))
print(b)
c = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(c)
| true |
03b3e29c726f1422f5fa7f6ec200af74bad7b678 | purusottam234/Python-Class | /Day 17/generatorexperessions.py | 530 | 4.1875 | 4 | from typing import Iterable
# Generator Expression is similar to list comprehension but creates an Iterable
# generator object that produce on demand,also known as lazy evaluation
# importance : reduce memory consumption and improve performance
# use parenthesis inplace of square bracket
# This method doesnot create a list
numbers = [10, 2, 3, 4, 5, 6, 7, 9, 10]
for value in (x**2 for x in numbers if x % 2 != 0):
print(value, end=' ')
squares_of_odds = (x ** 2 for x in numbers if x % 2 != 0)
print(squares_of_odds)
| true |
c212f377fd1f1bf1b8644a068bbf0a4d48a86fb0 | purusottam234/Python-Class | /Day 5/ifelif.py | 524 | 4.28125 | 4 | # pseudo code
# if student'grade is greater than or equal to 90
# display "A"
# else if student'grade is greater than or equal to 80
# display "B"
# else if student'grade is greater than or equal to 70
# display "C"
# else if student'grade is greater than or equal to 60
# display "D"
# else
# display "E"
# Python implementation
grade = int(input("Enter your marks:"))
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
elif grade >= 60:
print("D")
else:
print("E")
| true |
dd012da4f847a1ac2d8ee942adcad572104fa345 | pianowow/projecteuler | /173/173.py | 967 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: CHRISTOPHER_IRWIN
#
# Created: 05/09/2012
##We shall define a square lamina to be a square outline with a square "hole" so
##that the shape possesses vertical and horizontal symmetry. For example, using
##exactly thirty-two square tiles we can form two different square laminae.
##
##With one-hundred tiles, and not necessarily using all of the tiles at one time,
##it is possible to form forty-one different square laminae.
##
##Using up to one million tiles how many different square laminae can be formed?
from time import clock
max = 1000000
count = 0
clock()
for holeSide in range(1,int(max/4)):
#1block all the way around
t = 1
numBlocks = (holeSide+t)*4
while numBlocks <= max:
count += 1
t+=2
numBlocks += (holeSide+t)*4
print (count, clock(), 'seconds') | true |
d28564c2c36afa5fe4e96ce763d90bd07b6f2bcd | alok162/Geek_Mission-Python | /count-pair-sum-in-array.py | 901 | 4.125 | 4 | #A algorithm to count pairs with given sum
from collections import defaultdict
#function to calculate number of paris in an array
def countPairSum(d, arr, sum):
count = 0
#storing every array element in dictionary and
#parallely checking every element of array is previously
#seen in dictionary or not
for i in arr:
if sum-i in d:
count+=d[sum-i]
d[i]+=1
else:
d[i]+=1
return count
#main function or driven program
if __name__=='__main__':
#taking input number of test cases
t=int(input())
for test in range(t):
#taking input n number of element in an array
#and sum is to find pair through array element
n, sum = map(int,input().split())
arr = list(map(int,input().split()))
#defining dictionary
d = defaultdict(int)
print(countPairSum(d, arr, sum))
| true |
0700f44ab1b11b60d28cd635aeaf20df5b90959d | jaolivero/MIT-Introduction-to-Python | /Ps1/ProblemSet1.py | 779 | 4.125 | 4 |
r = 0.04
portion_down_payment = 0.25
current_savings = 0.0
annual_salary = float(input( "What is your annual salary: "))
portion_saved = float(input("what percentage of your salary would you like to save? write as a decimal: "))
total_cost = float(input("what is the cost of your deam home: "))
monthly_savings = (annual_salary / 12) * portion_saved
down_payment = total_cost * portion_down_payment
months = 0
while current_savings < down_payment:
current_savings += monthly_savings + (current_savings * r / 12)
months += 1
print ("It would take you " + str(months) + " months to save for the down payment of your dreams home")
print(months)
| true |
04acb5cf7f7f70354415001e67ba64b6062e97aa | isiddey/GoogleStockPrediction | /main.py | 2,377 | 4.25 | 4 | #Basic Linear Regression Tutorial for Machine Learning Beginner
#Created By Siddhant Mishra
#We will try to create a model to predict stock price of
#Google in next 3 days
import numpy as np
import pandas as pd
import quandl as qd
import math
from sklearn import preprocessing, cross_validation
from sklearn.linear_model import LinearRegression
# Getting the Stock data from Quandl
print("Getting stock from Quandl .........")
googleStock = qd.get('WIKI/GOOGL')
# Printing un altered dataset
pd.set_option('display.max_columns',None)
print("\nGoogle Stock from Quandl: \n\n {}".format(googleStock.head()))
# Indexing to filter relevant data
features = ['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']
dataset = googleStock[features]
print("--------------------------------------------------------------------\n"*2)
print("Filtered Dataset: \n {}".format(dataset.head()))
# Modifying/Defining features for modelset (data cleaning + manipulation)
# We remove outliers here and also NAN and other bad data
modelset = dataset[['Adj. Close', 'Adj. Volume']]
modelset.loc[:,'Stock Variance'] = (dataset['Adj. High']-dataset['Adj. Close']) / dataset['Adj. Close']*100
modelset.loc[:,'Percentage Change'] = (dataset['Adj. Close']-dataset['Adj. Open']) / dataset['Adj. Open']*100
modelset = modelset.fillna(-999999)
#modelset.fillna(-999999, inplace=True)
print("--------------------------------------------------------------------\n"*2)
print("Model Set W/O Label :\n {}".format(modelset.head()))
# Define Label
predictionCol = 'Adj. Close'
print(len(modelset))
forecastShift = int(math.ceil(0.005*len(modelset)))
modelset['Label'] = modelset[predictionCol].shift(-forecastShift)
modelset.dropna(inplace=True)
#Define X and Y for Linear Equation
# X is going to be our features and Y is going to be Label
# so we find Y = Omega(X)
X = np.array(modelset.drop(['Label'],1))
Y = np.array(modelset['Label'])
# Feature Scale and do it over entire dataset
# We do this before dividing data to have uniform normalization equation
X = preprocessing.scale(X)
Y = np.array(modelset['Label'])
# Create Training and Testing Set
XTrain, XTest, YTrain, YTest = cross_validation.train_test_split(X, Y, test_size=0.15)
# Create and Train model
clf = LinearRegression()
clf.fit(XTrain, YTrain)
accuracy = clf.score(XTest, YTest)
print("\n\nModel Accuracy = {}".format(accuracy))
| true |
6545045e6e520f70af769078d008a3e72492c4fe | saifazmi/learn | /languages/python/sentdex/basics/48-53_matplotlib/51_legendsAndGrids.py | 728 | 4.15625 | 4 | # Matplotlib labels and grid lines
from matplotlib import pyplot as plt
x = [5,6,7,8]
y = [7,3,8,3]
x2 = [5,6,7,8]
y2 = [6,7,2,6]
plt.plot(x,y, 'g', linewidth=5, label = "Line One") # assigning labels
plt.plot(x2,y2, 'c', linewidth=10, label = "Line Two")
plt.title("Epic Chart")
plt.ylabel("Y axis")
plt.xlabel("X axis")
plt.legend() # display legends, call AFTER plotting what needs to be in legend
plt.grid(True, color='k') # display grid, black in color
'''
' things are displayed in the order they are called, for example line 2 draws
' over line 1 as we are ploting them in that order.
' But a grid line will always be drawn behind everything else, no matter when
' and where the function is called.
'''
plt.show()
| true |
b6a0bc120206cbb24f780c8b35065925c9ae038a | saifazmi/learn | /languages/python/sentdex/intermediate/6_timeitModule.py | 1,765 | 4.1875 | 4 | # Timeit module
'''
' Measures the amount of time it takes for a snippet of code to run
' Why do we use timeit over something like start = time.time()
' total = time.time() - start
'
' The above is not very precise as a background process can disrupt the snippet
' of code to make it look like it ran for longer than it actually did.
'''
import timeit
# print(timeit.timeit("1+3", number=500000000))
##input_list = range(100)
##
##def div_by_five(num):
## if num % 5 == 0:
## return True
## else:
## return False
##
##xyz = (i for i in input_list if div_by_five(i))
##
##xyz = [i for i in input_list if div_by_five(i)]
## Timing creation of a generator expression
print("Gen Exp:", timeit.timeit("""
input_list = range(100)
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
xyz = (i for i in input_list if div_by_five(i))
""", number=5000))
## Timing creation of a list comprehension
print("List Comp:", timeit.timeit("""
input_list = range(100)
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
xyz = [i for i in input_list if div_by_five(i)]
""", number=5000))
## Timing iterating over a genexp
print("Iter GenExp:", timeit.timeit("""
input_list = range(100)
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
xyz = (i for i in input_list if div_by_five(i))
for i in xyz:
x = i
""", number=500000))
## Timing iterating over a list comp
print("Iter ListComp:", timeit.timeit("""
input_list = range(100)
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
xyz = [i for i in input_list if div_by_five(i)]
for i in xyz:
x = i
""", number=500000))
| true |
dcc08fb3c7b4ef7eeee50d79bd1751b537083339 | saifazmi/learn | /languages/python/sentdex/basics/8_ifStatement.py | 302 | 4.46875 | 4 | # IF statement and assignment operators
x = 5
y = 8
z = 5
a = 3
# Simple
if x < y:
print("x is less than y")
# This is getting noisy and clutered
if z < y > x > a:
print("y is greater than z and greather than x which is greater than a")
if z <= x:
print("z is less than or equal to x")
| true |
f9d01749e966f4402c3591173a145b65380d2102 | saifazmi/learn | /languages/python/sentdex/basics/62_eval.py | 900 | 4.6875 | 5 | # Using Eval()
'''
' eval is short for evaluate and is a built-in function
' It evaluates any expression passed through it in form of a string and will
' return the value.
' Keep in mind, just like the pickle module we talked about, eval has
' no security against malicious attacks. Don't use eval if you cannot
' trust the source. For example, some people have considered using eval
' to evaluate strings in the browser from users on their website, as a
' way to create a sort of "online editor." While you can do this, you have
' to be incredibly careful!
'''
# a list as a string
list_str = "[5,6,2,1,2]"
print("BEFORE eval()")
print("list_str", list_str)
print("list_str[2]:", list_str[2])
list_str = eval(list_str)
print("\nAFTER eval()")
print("list_str", list_str)
print("list_str[2]:", list_str[2])
x = input("code:")
print(x)
check_this_out = eval(input("code>"))
print(check_this_out)
| true |
27634a1801bd0a5cbe1ca00e31052065a8e4ce9b | saifazmi/learn | /languages/python/sentdex/basics/64-68_sqlite/66_readDB.py | 852 | 4.40625 | 4 | # SQLite reading from DB
import sqlite3
conn = sqlite3.connect("tutorial.db")
c = conn.cursor()
def read_from_db():
c.execute("SELECT * FROM stuffToPlot") # this is just a selection
data = c.fetchall() # gets the data
print(data)
# Generally we iterate through the data
for row in data:
print(row) # each row is basically a tuple
c.execute("SELECT * FROM stuffToPlot WHERE value = 3")
data = c.fetchall()
print(data)
for row in data:
print(row)
c.execute("SELECT * FROM stuffToPlot WHERE unix > 1520423573")
data = c.fetchall()
print(data)
for row in data:
print(row)
c.execute("SELECT value, datestamp FROM stuffToPlot WHERE unix > 1520423573")
data = c.fetchall()
print(data)
for row in data:
print(row)
read_from_db()
c.close()
conn.close()
| true |
95443c1973cf14c5467b2fb8c4e24fda942bdfa9 | saifazmi/learn | /languages/python/sentdex/intermediate/7_enumerate.py | 830 | 4.40625 | 4 | # Enumerate
'''
' Enumerate takes an iterable as parameter and returns a tuple containing
' the count of item and the item itself
' by default the count starts from index 0 but we can define start=num as param
' to change the starting point of count
'''
example = ["left", "right", "up", "down"]
# NOT the right way of doing this
for i in range(len(example)):
print(i, example[i])
print(5*'#')
# Right way of writing the above code
for i, j in enumerate(example):
print(i, j)
print(5*'#')
# Creating a dictionary using enumerate, where key is the index value
new_dict = dict(enumerate(example))
print(new_dict)
[print(i, j) for i, j in enumerate(new_dict)]
print(5*'#')
# Creating a list using enumerate
new_list = list(enumerate(example))
print(new_list)
[print(i, j) for i, j in enumerate(new_list, start=1)]
| true |
8bbb0737979d0709d1edca705a4966f369a110de | saifazmi/learn | /languages/python/sentdex/intermediate/2_strConcatAndFormat.py | 1,161 | 4.21875 | 4 | # String concatenation and formatting
## Concatenation
names = ["Jeff", "Gary", "Jill", "Samantha"]
for name in names:
print("Hello there,", name) # auto space
print("Hello there, " + name) # much more readable, but makes another copy
print(' '.join(["Hello there,", name])) # better for performance, no copies
print(', '.join(names)) # preferable when joining more than 2 or more strings
import os
location_of_files = "/home/saif/learn/notes/python/sentdex_tuts/intermediate"
file_name = "1_intro.txt"
print(location_of_files + '/' + file_name) # not the correct way but works
# proper method of joining for file paths/location
with open(os.path.join(location_of_files, file_name)) as f:
print(f.read())
## Formatting
who = "Gary"
how_many = 12
# Gary bought 12 apple today!
# this is not the most optimal way of doing this.
# in python2 we could have used something like %s etc.
print(who, "bought", how_many, "apples today!")
# In python 3 we use {} combined with format()
print("{} bought {} apples today!".format(who, how_many))
# you can also give order sqeuence
print("{1} bought {0} apples today!".format(who, how_many))
| true |
04652bd04e648972fd819c39d288b8f52577eb14 | saifazmi/learn | /languages/python/sentdex/basics/43_tkMenuBar.py | 1,464 | 4.25 | 4 | # Tkinter Menu Bar
'''
' Menus are defined with a bottom-up approach
' the menu items are appended to the menu, appended to menu bar,
' appended to main window, appended to root frame
'''
from tkinter import *
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
#quitButton = Button(self, text="Quit", command=self.client_exit)
#quitButton.place(x=0, y=0)
# define a menu bar instance
menu = Menu(self.master) # this is the menu of the main window
self.master.config(menu=menu)
# Create a menu item for the menu bar
file = Menu(menu)
# Add a command "Exit" to the menu item
file.add_command(label="Save") # example
file.add_command(label="Exit", command=self.client_exit)
# Add the menu item "File" to the menu bar as a cascading menu
menu.add_cascade(label="File", menu=file)
# Add another menu item to the menu bar
edit = Menu(menu)
edit.add_command(label="Undo") # not adding a command for now
menu.add_cascade(label="Edit", menu=edit)
def client_exit(self):
exit()
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
| true |
2f6bb6a1d83586fe2504c1ceb787392891bd011d | lucky1506/PyProject | /Item8_is_all_digit_Lucky.py | 311 | 4.15625 | 4 | # Item 8
def is_all_digit(user_input):
"""
This function validates user entry.
It checks entry is only digits from
0 to 9, and no other characters.
"""
numbers = "0123456789"
for character in user_input:
if character not in numbers:
return False
return True
| true |
086101d275de833242f8fcfd2acddbfd6af62919 | gelfandbein/lessons | /fibonacci.py | 1,176 | 4.625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 4 18:50:32 2020
@author: boris
"""
"""Write a program that asks the user how many Fibonnaci numbers to
generate and then generates them. Take this opportunity to think
about how you can use functions. Make sure to ask the user to enter
the number of numbers in the sequence to generate.
(Hint: The Fibonnaci seqence is a sequence of numbers where the
next number in the sequence is the sum of the previous two numbers
in the sequence.
The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
"""
import pprint
num = int(input("Введите до какого числа считать последовательность Фибоначчи: "))
def fibonacci(num):
fib1, fib2 = 0, 1
for _ in range(num):
fib1, fib2 = fib2, fib1 + fib2
yield fib1
for fib in fibonacci(num):
print(fib, end=' ')
print()
pp = pprint.PrettyPrinter()
pp.pprint(sum(fibonacci(num)))
print("next...\n")
def fib(f):
if f == 0:
return 0
if f == 1:
return 1
return fib(f - 1) + fib(f - 2)
a = int(input("enter num: "))
print(fib(a))
| true |
7d7d6e70123576f89a5c8d318fc7339ec7c1a771 | shreyan-naskar/Python-DSA-Course | /Strings/Max frequency/prog.py | 532 | 4.3125 | 4 | '''
Given a string s of latin characters, your task is to output the character which has
maximum frequency.
Approach:-
Maintain frequency of elements in a separate array and iterate over the array and
find the maximum frequency character.
'''
s = input("Enter the string : ")
D = {}
Freq_char = ''
Freq = 0
for i in s :
if i not in D.keys() :
D[i] = 1
else :
D[i] += 1
for i in D.keys() :
if D[i] > Freq :
Freq = D[i]
Freq_char = i
print("Most frequent character : ", Freq_char)
print("Frequency : ", Freq)
| true |
591e06efb766c4fd99986c756192b68d91ea2fd3 | shreyan-naskar/Python-DSA-Course | /Functions in Python/find primes in range/primes.py | 429 | 4.15625 | 4 | #Finding all primes in a given range.
def isPrime( n ) :
count = 0
for i in range(2,n) :
if n%i == 0 :
count = 0
break
else :
count = 1
if count == 1 :
return True
else :
return False
n = int(input('Enter the upper limit of Range : '))
List_of_Primes = []
for i in range(1,n+1) :
if isPrime(i) :
List_of_Primes.append(i)
print('\nList of prime numbers in the range 1 to', n, 'is : ', List_of_Primes)
| true |
2dbeef63ca251b9d9ab446b8776ea376ac3b0451 | akshajbhandari28/guess-the-number-game | /main.py | 1,584 | 4.1875 | 4 | import random
print("welcome to guess the number game! ")
name = input("pls lets us know ur name: ")
print("hello, ", name, "there are some things you need tp know before we begin..")
print("1) you have to guess a number so the number u think type only that number and nothing else")
print("2) you will get three chances to guess the number")
print("3) you have to guess the number between 1 and 10")
print("3) if you guess the number you win!!!")
play = input("if you agree to the rules and wanna play type 'yes' ")
if play == "yes":
print("great lets begin!!")
else: print("ok, then bye till next time :)"); exit()
rn = random.randint(0, 10)
guess1 = int(input("pls guess a number: "))
if guess1 == rn:
print("correct! great job!! :)")
exit()
if guess1 > rn:
print("the number is smaller than this")
if guess1 < rn:
print("the number is bigger than this")
guess2 = int(input("try again!!: "))
if guess2 == rn:
print("correct! great job!! :)")
exit()
if guess2 > rn:
print("the number is smaller than this")
if guess2 < rn:
print("the number is bigger than this")
guess3 = int(input("try again!!: "))
if guess3 == rn:
print("correct! great job!! :)")
exit()
if guess3 > rn:
print("the number is smaller than this")
if guess3 < rn:
print("the number is greater than this")
guess4 = int(input("try again!!: "))
if guess4 == rn:
print("correct! great job!! :)")
exit()
if guess4 > rn:
print("sorry but you lost, better luck next time :)")
if guess4 < rn:
print("sorry but you lost, better luck next time :)")
| true |
3829020674ee0e08dd307a6e89606752f27f810b | Meowsers25/py4e | /chapt7/tests.py | 2,099 | 4.125 | 4 | # handle allows you to get to the file;
# it is not the file itself, and it it not the data in file
# fhand = open('mbox.txt')
# print(fhand)
# stuff = 'hello\nWorld'
# print(stuff)
# stuff = 'X\nY'
# print(stuff)
# # \n is a character
# print(len(stuff)) # 3 character string
# a file is a sequence of lines with \n at the end of each line
# use the for loop to iterate through the sequence
# xfile = open('mbox.txt') # use quotations!!!!!
# # cheese is the iteration variable, it goes through each line
# for cheese in xfile:
# print(cheese) # for each line inn xfile, print line
# counting lines in a file
# fhand = open('mbox.txt')
# count = 0
# for line in fhand:
# count = count + 1
# print('Line Count: ', count)
# # reading the 'whole' file
# fhand = open('mbox.txt')
# inp = fhand.read() # reads whole file into a single string
# print(len(inp))
# print(inp[:20]) # prints first 20 characters
# searching through a file
# fhand = open('mbox.txt')
# count = 0
# for line in fhand:
# if line.startswith('From:'):
# line = line.rstrip() # .rstrip takes away the whitespace
# count = count + 1
# print(line)
# print(count)
# skipping with continue
# this does the same as above code
# fhand = open('mbox.txt')
# for line in fhand:
# line = line.rstrip()
# if not line.startswith('From:'):
# continue
# print(line)
# using 'in' to select lines
# fhand = open('mbox.txt')
# for line in fhand:
# line = line.rstrip()
# if not '@uct.ac.za' in line:
# continue
# print(line)
# prompt for filename
# fname = input('Enter the file name: ')
# fhand = open(fname)
# count = 0
# for line in fhand:
# if line.startswith('Subject:'):
# count += 1
# print('There were', count, 'subject lines in', fname)
# dealing with bad file names
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
quit()
count = 0
for line in fhand:
if line.startswith('Subject:'):
count += 1
print('There were', count, 'subject lines in', fname)
| true |
fe5e4243e64ebedaa1b31718b2be256e24cd52a3 | bipulhstu/Data-Structures-and-Algorithms-Through-Python-in-Depth | /1. Single Linked List/8. Linked List Calculating Length.py | 1,401 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self, data):
#create memory
new_node = Node(data)
#insertion in an empty linked list
if self.head is None:
self.head = new_node
return
#insertion at the end of the linked list
last_node = self.head
while last_node.next is not None:
last_node = last_node.next
last_node.next = new_node
def count_nodes_iterative(self):
temp = self.head
count = 1
while temp.next:
count+=1
temp = temp.next
return count
def count_nodes_recursive(self, node):
if node is None:
return 0
return 1+ self.count_nodes_recursive(node.next)
if __name__ == "__main__":
llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
print(llist.count_nodes_iterative())
print(llist.count_nodes_recursive(llist.head))
llist.print_list() | true |
05caa2fd68e08437ee71919e6bc044168d4b69fc | emsipop/PythonPractice | /pig_latin.py | 680 | 4.28125 | 4 | def pig_latin():
string = input("Please enter a string you would like translating: ").lower() #Changes case of all characters to lower
words = string.split(" ") # Splitting the user's input into an array, each item corresponding to each word in the sentence
translation = [] # An empty array which each translated word will be appended to
for word in words: # The following will occur for each item in the array
translation.append(word[1:] + word[0] + "ay") # Each word is translated and added to the new array
return " ".join(translation) # The new array is then turned back into a string and is returned to give the full translated string
| true |
4a1333b1c3da67ad28f85a9094066b52c6ad51b6 | gaurav9112in/FST-M1 | /Python/Activities/Activity8.py | 238 | 4.125 | 4 | numList = list(input("Enter the sequence of comma seperated values : ").split(","))
print("Given list is ", numList)
# Check if first and last element are equal
if (numList[0] == numList[-1]):
print("True")
else:
print("False")
| true |
0e8240844666542eeb745b0e53c5471e9a7d55a9 | sergiuvidican86/MyRepo | /exerc4 - conditions 2.py | 327 | 4.1875 | 4 | name = "John"
age = 24
if name == "John" and age == 24:
print("Your name is John, and you are also 23 years old.")
if name == "test"
pass
if name == "John"or name == "Rick":
print("Your name is either John or Rick.")
if name in ["John", "Rick"]:
print("Your name is either John or Rick.") | true |
63c29133e42fb808aa8e42954534eef33508e22b | oscarwu100/Basic-Python | /HW4/test_avg_grade_wu1563.py | 1,145 | 4.125 | 4 | ################################################################################
# Author: BO-YANG WU
# Date: 02/20/2020
# This program predicts the approximate size of a population of organisms.
################################################################################
def get_valid_score():#re print the question
n= int(input('Enter a score: '))
while n< 0 or n> 100:
print('Invalid Input. Please try again.', end='')
n= int(input('Enter a score: '))
return n
def calc_average(l):#cal avg
return sum(l)/ len(l)
def determine_grade(g):# A B C D
if g>= 90:
return 'A'
elif g>= 80:
return 'B'
elif g>= 70:
return 'C'
elif g>= 60:
return 'D'
else:
return 'F'
number=[0]* 5
for i in range(0,5):
number[i]=get_valid_score()
print('The letter grade for', format(number[i], '.1f'), 'is', determine_grade(number[i]), end='')
print('.', end='')
print('')
print('The average test score is', format(calc_average(number), '.2f')) # print out the average result
| true |
6dd26ecb710eec1d072c7971044b29362b244b10 | AMRobert/Simple-Calculator | /Simple_Calculator.py | 1,846 | 4.15625 | 4 | #SIMPLE CALCULATOR
#Function for addition
def addition(num1,num2):
return num1 + num2
#Function for subtraction
def subtraction(num1,num2):
return num1 - num2
#Function for multiplication
def multiplication(num1,num2):
return num1 * num2
#Function for division
def division(num1,num2):
return num1 / num2
#Function for Calculation
def calc():
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
choice = int(input("Enter your choice: "))
if choice == 1:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Addition of",int(num1),"and",int(num2),"=",addition(num1,num2))
elif choice == 2:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Subtraction of",num1,"and",num2,"=",subtraction(num1,num2))
elif choice == 3:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Multiplication of",num1,"and",num2,"=",multiplication(num1,num2))
elif choice == 4:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Division of",num1,"and",num2,"=",division(num1,num2))
else:
print("Invalid Input")
print("Please choose the correct options")
calc()
print("SIMPLE CALCULATOR")
print("Choose which operation you want to do!..")
calc()
for i in range(100):
print("<------------------------>")
print("Do you want to continue!..")
print("1.yes")
print("2.No")
second_choice = int(input("Enter your choice: "))
if second_choice==1:
calc()
else:
print("Thank You")
exit()
| true |
e8af57b1a0b5d1d6ec8e8c7fa2899c2ddc8f2135 | lnogueir/interview-prep | /problems/stringRotation.py | 1,174 | 4.40625 | 4 | '''
Prompt:
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1.
(e.g., "waterbottle" is a rotation of "erbottlewat").
Follow up:
What if you could use one call of a helper method isSubstring?
'''
# Time: O(n), Space: O(n)
def isStringRotation(s1, s2):
if len(s1) != len(s2):
return False
strLength = len(s1) or len(s2)
s1Prefix = []
s1Suffix = [c for c in s1]
s2Prefix = [c for c in s2]
s2Suffix = []
for idx in range(strLength):
if s1Suffix == s2Prefix and s1Prefix == s2Suffix:
return True
s1Prefix.append(s1Suffix.pop(0))
s2Suffix.insert(0, s2Prefix.pop())
return False
'''
Follow up:
Notice that if isStringRotation(s1, s2) == True
Let `p` be the prefix of the string and `s` the suffix.
Then s1 can be broken down into s1=`ps` and s2=`sp`
Therefore, notice that s1s1 = `psps`, so s2 must be a substring.
So: return isSubstring(s1+s1, s2)
'''
print(isStringRotation("waterbottle", "erbottlewat"))
print(isStringRotation("waterbottle", "erbottlewqt"))
print(isStringRotation("waterbottle", "eniottlewdt"))
print(isStringRotation("lucas", "sluca"))
print(isStringRotation("lucas", "wluca"))
| true |
334d1b51189b1492bb754f0db69a2357cc8e0f15 | abideen305/devCamp-task | /Bonus_Task_2.py | 1,845 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
# program to replace a consonant with its next concosnant
#Starting by definig what is vowel and what is not. Vowel are just: a,e,i,o,u
#defining a function with the name vowel and its argument v
def vowel(v):
#if statement to taste if the word containing any of the letters of vowel
if (v != 'a' and v != 'e' and
v != 'i' and v != 'o' and
v != 'u'):
#the program should return false is it doesn't
return False
#returning true if the word containings vowel letter(s)
return True
#Now to have a function to replace a consonant
#Here, I am defining my function with the name replaceConsonants and argument c
def replaceConsonants(c):
#looping through range of the length of c
for i in range(len(c)):
if (vowel(c[i])==False):
#replacing z with b and not a
if (c[i] == 'z'):
c[i] = 'b'
#an else statement to defining another condition if the argument is not z
else:
#here I am replacing the consonant with the next one with the method ord
c[i] = chr(ord(c[i]) + 1)
# checking and relacing the word if the next word above is a vowel. No two consecutive word is a vowel in alphabet
if (vowel(c[i])==True):
c[i] = chr(ord(c[i]) + 1)
return ''.join(c)
# taking input from the user for word to replace its consonants
# and converting it to lowercase using .lower method
c = input("Enter a sentence to replace its consonants: ")
#storing my function in a variable called string and converting it to list
string = replaceConsonants(list(c))
#replacing ! with nothing because by default the program will replace any space with exclamation
string = string.replace("!", " ")
#printing final result
print(string)
| true |
97433547ac2da4227d9c64499727b46c5b05c3f7 | Mayank2134/100daysofDSA | /Stacks/stacksUsingCollection.py | 490 | 4.21875 | 4 | #implementing stack using
#collections.deque
from collections import deque
stack = deque()
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack:')
print(stack)
# pop() function to pop element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
| true |
3f81995adbbbc6c32e77ca7aaa05c91f5dd25d99 | Lexielist/immersive---test | /Prime.py | 204 | 4.15625 | 4 | A = input("Please input a number: ")
print ("1 is not a prime number")
for number in range (2,A):
if num%A == 0:
print (num," is a prime number)
else: print (num,"is not a prime number) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.