blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
adfc200cf4be55de65e19c6dfc81c41f6cea7892 | texttest/storytext-selftest | /tkinter/widgets/menubutton/target_ui.py | 1,807 | 4.375 | 4 | #$Id: menubartk.py,v 1.1 2004/03/18 05:44:21 mandava Exp $
#this is program that creates a menubar using Tkinter widgets.
# a menubar is just a frame that holds menus.
#We will then pass menubar to all of the subsequent menus we'll define
#(File, Edit, Help, etc.) as the parent function.
#A menu in Tk is a combination of a Menubutton (the title of the menu) and
#the Menu (what drops down when the Menubutton is pressed)
try:
from tkinter import *
except:
from Tkinter import *
class mywidgets:
def __init__(self,root):
frame = Frame(root)
self.makeMenuBar(frame)
frame.pack()
def open(self):
print("Open!")
def makeMenuBar(self,frame):
menubar = Frame(frame,relief=RAISED,borderwidth=1)
menubar.pack()
#A menu in Tk is a combination of a Menubutton (the title of the
#menu) and the Menu (what drops down when the Menubutton is pressed)
mb_file = Menubutton(menubar,text='file')
mb_file.pack(side=LEFT)
mb_file.menu = Menu(mb_file)
#Once we've specified the menubutton and the menu, we can add
#different commands to the menu
mb_file.menu.add_command(label='open', command=self.open)
mb_file.menu.add_command(label='close')
mb_edit = Menubutton(menubar,text='edit')
mb_edit.pack(side=LEFT)
mb_edit.menu = Menu(mb_edit)
mb_edit.menu.add_command(label='copy')
mb_edit.menu.add_command(label='paste')
mb_help = Menubutton(menubar,text='help')
mb_help.pack(padx=25,side=RIGHT)
mb_file['menu'] = mb_file.menu
mb_edit['menu'] = mb_edit.menu
def main():
root = Tk()
k=mywidgets(root)
root.title('menu bar')
root.mainloop()
main()
| true |
9a42f4f082403c60ff224c7447e096ce03b3f3ce | JadeHayes/coding-challenges | /is_pal.py | 985 | 4.34375 | 4 | # Write an efficient method that checks whether any permutation ↴ of an input string is a palindrome. ↴
# You can assume the input string only contains lowercase letters.
# Examples:
# "civic" should return true
# "ivicc" should return true
# "civil" should return false
# "livci" should return false
def is_palindrome(word):
"""checks if any permutation of string is a palindrome."""
# each set of letters has a pair OR has 1 that it can rotate around
# set up a dictionary key (letter) : count
# loop through the values of the dictionary
word_dict = {}
odd = 0
for letter in word:
word_dict[letter] = word_dict.get(letter, 0) + 1
for count in word_dict.values():
if count % 2 != 0:
odd += 1
# if odd_count > 1 --> return false
if odd > 1:
return False
# else: return true
return True
is_palindrome("civic")
is_palindrome("ivicc")
is_palindrome("civil")
is_palindrome("livci") | true |
7bbaccc3164f4988c2e749630b552875e8211466 | JadeHayes/coding-challenges | /lazy-lemmings/lemmings.py | 832 | 4.21875 | 4 | """Lazy lemmings.
Find the farthest any single lemming needs to travel for food.
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
>>> furthest(7, [0, 6])
3
"""
def furthest(num_holes, cafes):
"""Find longest distance between a hole and a cafe."""
# START SOLUTION
worst = 0
for hole in range(num_holes):
# Looking at all cafes, find distance to this hole,
# and choose the smallest distance.
dist = min([abs(hole - cafe) for cafe in cafes])
# Keep track of the longest distance we've seen
worst = max(worst, dist)
return worst
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED; GREAT JOB!\n"
| true |
6a8d4210f42d8e66b0cc62770bbf33ce16a5de1e | JadeHayes/coding-challenges | /problem_solving_datastructures_algorithms/time_it.py | 1,804 | 4.1875 | 4 | # timeit.py
# check to see that list index is constant time O(1)
'''To use timeit you create a Timer object whose parameters
are two Python statements. The first parameter is a Python
statement that you want to time; the second parameter is a
statement that will run once to set up the test'''
import timeit
def test1():
"""testing time of list indexing"""
example = [1, 3, 2, 4, 5, 6, 8, 8, 8, 16, 28, 8]
return example[3]
def test2():
"""get item for dictionaries"""
my_dict = {1: None, 3: None, 2: None, 4: None}
return my_dict[1]
def test3():
"""set item for dictionaries"""
my_dict = {1: None, 3: None, 2: None, 4: None}
my_dict[8] = "yay"
def test4():
"""Delete item in a dictionary"""
my_dict = {1: None, 3: None, 2: None, 4: None}
del my_dict[3]
def test5():
"""Delete item in a list"""
example = [1, 3, 2, 4, 5, 6, 8, 8, 8, 16, 28, 8]
del(example[4])
def smallest(lst):
"""Given a list of numbers in random order, write an algorithm
that works in O(nlog(n)) to find the kth smallest number in the list."""
n = len(lst)
# loop through the list
while n > 0:
t1 = timeit.Timer("test1()", "from __main__ import test1")
print "List indexing", t1.timeit(number=1000), "milliseconds"
t2 = timeit.Timer("test2()", "from __main__ import test2")
print "Get item dictionary", t2.timeit(number=1000), "milliseconds"
t3 = timeit.Timer("test3()", "from __main__ import test3")
print "Set item dictionary", t3.timeit(number=1000), "milliseconds"
t4 = timeit.Timer("test4()", "from __main__ import test4")
print "Delete item in a dictionary", t4.timeit(number=1000), "milliseconds"
t5 = timeit.Timer("test5()", "from __main__ import test5")
print "Delete item in a list", t5.timeit(number=1000), "milliseconds"
| true |
741f97f3646be248079fccbf8f0a3bd4a53f1b8b | vipsh18/cs61a | /recursion/max_product_non_consecutive.py | 487 | 4.28125 | 4 | def max_product(s):
"""
Return the maximum product that can be formed using non-consecutive elements of s.
>>> max_product([10,3,1,9,2]) # 10 * 9
90
>>> max_product([5,10,5,10,5]) # 5 * 5 * 5
125
>>> max_product([])
1
"""
if len(s) <= 2:
return max(s) if len(s) >= 1 else 1
if len(s) == 3:
return max(s[0] * s[2], s[1])
return max(s[0] * max_product(s[2:]), s[1] * max_product(s[3:]))
print(max_product([10, 3, 9, 1, 5])) | true |
3dd0ab5d307c0d28f2c1811150b3dd437689fa87 | vipsh18/cs61a | /labs_hw/disc06.py | 642 | 4.25 | 4 | def merge(a, b):
"""
>>> def sequence(start, step):
... while True:
... yield start
... start += step
>>> a = sequence(2, 3) # 2, 5, 8, 11, 14, ...
>>> b = sequence(3, 2) # 3, 5, 7, 9, 11, 13, 15, ...
>>> result = merge(a, b) # 2, 3, 5, 7, 8, 9, 11, 13, 14, 15
>>> [next(result) for _ in range(10)]
[2, 3, 5, 7, 8, 9, 11, 13, 14, 15]
"""
x, y = next(a), next(b)
while True:
if x == y:
yield x
x, y = next(a), next(b)
elif x < y:
yield x
x = next(a)
else:
yield y
y = next(b) | false |
6e61a9a7fe86684d6f8fb97ea19b19b39151868e | vipsh18/cs61a | /iterators_generators/accumulate.py | 467 | 4.21875 | 4 | from operator import add, mul
def accumulate(iterable, f):
"""Takes in an iterable and a function f and yields each accumulated value from applying f to the running total and the next element.
>>> list(accumulate([1, 2, 3, 4, 5], add))
[1, 3, 6, 10, 15]
>>> list(accumulate([1, 2, 3, 4, 5], mul))
[1, 2, 6, 24, 120]
"""
it = iter(iterable)
curr = 1 if f == mul else 0
for num in it:
curr = f(num, curr)
yield curr | true |
13f8c02e9d192c60f1eedfbe7a7489ad3f6d17c5 | kevinfrancis/practice | /dp/robot_path.py | 1,723 | 4.1875 | 4 | #!/usr/bin/env python
import sys
# From Cracking the Coding interview
# Given
# maze r rows & c cols. maze[i][j] = { 0, if cell is traversable,
# 1, if it is an obstacle }
# robot standing at 0th row, 0th col.
# robot can only move right or down
# (i.e. next step from (i,j) can be (i+1, j) or (i, j+1) within the bounds of the maze
#
# Find a path from [0][0] to [r-1][c-1]
#
def find_path(maze):
path = []
r = len(maze) # num_rows
c = len(maze[0]) # num_cols
start_cell = (0, 0)
visited_set = set([])
# Core func (DFS)
def _find_path_from(end_cell):
(i, j) = end_cell
if i < 0 or j < 0 or maze[i][j] == 1 or (i,j) in visited_set: # not traversable
return False
print('visiting cell %s' % str(end_cell))
visited_set.add((i,j))
if start_cell == end_cell: # destination cell
return True
for prev_cell in [(i, j-1), (i-1, j)]: # find path from top & left adj cells
if _find_path_from(prev_cell):
path.append(prev_cell)
return True
return False
# Call inner func that finds path using DFS
if _find_path_from((r-1, c-1)) == True:
path.append((r-1, c-1))
return path
return path
def main():
maze = [[0, 0, 0, 0],
[1, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
path = find_path(maze)
if path is None:
print('No path found')
sys.exit(0)
print(path)
# Mark cells in path as 2 for easy viewing
for (i,j) in path:
maze[i][j] = 2
for row in maze:
print(row)
if __name__ == '__main__':
main()
| true |
6a792aee0b04ec52b8b18864ec84dea61a93e340 | kulkarnidk/datastructurePrograms | /Binary_Search_Tree.py | 651 | 4.25 | 4 | def factorial(num):
"""
@:param calculates the factorial of num
:param num:input for factorial method for calculation of factorial
:return:returns factorial number of num
"""
res = 1
for i in range(1, num + 1):
res = res * i
return res
tree_values=[]
tree_count=[]
num=int(input("enter number : "))
for i in range(1, num+1):
print("enter ",i,"value ")
tree_values.append(int(input()))
print("Trees :",tree_values)
for i in tree_values:
countBST1 = factorial(2 * i)
countBST2 = factorial(i + 1) * factorial(i)
tree_count.append(countBST1 // countBST2)
print("binary tree count: ",tree_count)
| true |
b72d5c8a330df8c72151a16fef910973d2715954 | indraputra147/pythonworkbook | /chapter1/ex23.py | 434 | 4.15625 | 4 | #Exercise 23: Area of a Regular Polygon
"""
Write a program that reads length of a side(s) and n number of sides from the user
then displays the area of a regular polygon constructed from these values.
"""
n = int(input("Enter the number of sides of polygon: "))
s = float(input("Enter the length of the side of polygon: "))
import math
a = (n * s * s) / (4 * math.tan(math.pi / n))
print("The area of the polygon is %.2f" % a)
| true |
3b9b1932f329ea632d86779847afa9aa6ef96a9e | indraputra147/pythonworkbook | /chapter2/ex48.py | 1,211 | 4.40625 | 4 | #Exercise 48: Birth Date to Astrological Sign
"""
The program will ask the user to enter his or her month and day of birth
Then report the user's zodiac sign
"""
MONTH, DAY = input("Enter your birthday: ").split()
DAY = int(DAY)
if MONTH == "December":
print("Capricorn") if DAY >= 22 else print("Sagittarius")
elif MONTH == "November":
print("Sagittarius") if DAY >= 22 else print("Scorpio")
elif MONTH == "October":
print("Scorpio") if DAY >= 23 else print("Libra")
elif MONTH == "September":
print("Libra") if DAY >= 23 else print("Virgo")
elif MONTH == "August":
print("Virgo") if DAY >= 23 else print("Leo")
elif MONTH == "July":
print("Leo") if DAY >= 23 else print("Cancer")
elif MONTH == "June":
print("Cancer") if DAY >= 21 else print("Gemini")
elif MONTH == "May":
print("Gemini") if DAY >= 21 else print("Taurus")
elif MONTH == "April":
print("Taurus") if DAY >= 20 else print("Aries")
elif MONTH == "March":
print("Aries") if DAY >= 21 else print("Pisces")
elif MONTH == "February":
print("Pisces") if DAY == 19 else print("Aquarius")
elif MONTH == "January":
print("Aquarius") if DAY >= 22 else print("Capricorn")
else:
print("Wrong Input!")
| false |
54ee4d44ee7e5851ad55dc04c85eaeb46bcb1c46 | indraputra147/pythonworkbook | /chapter2/ex52.py | 923 | 4.125 | 4 | #Exercise 51: Letter Grade to Grade Points
"""
The program begins by reading a letter from the user
then compute and display the equivalent number of grade points
"""
GRADE = input("Enter the letter of your grade (from A to F): ")
if GRADE == "A" or GRADE == "A+":
print("Your grade points is 4.0")
elif GRADE == "A-":
print("Your grade points is 3.7")
elif GRADE == "B+":
print("Your grade points is 3.3")
elif GRADE == "B":
print("Your grade pointas it 3.0")
elif GRADE == "B-":
print("Your grade points is 2.7")
elif GRADE == "C+":
print("Your grade points is 2.3")
elif GRADE == "C":
print("Your grade points is 2.0")
elif GRADE == "C-":
print("Your grade points is 1.7")
elif GRADE == "D+":
print("Your grade points is 1.3")
elif GRADE == "D":
print("Your grade points is 1.0")
elif GRADE == "F":
print("Your grade points is 0")
else:
print("Invalid letter grade!")
| true |
e7bbcbcd43636310ba8cc439390c7f378d8ece51 | indraputra147/pythonworkbook | /chapter1/ex15.py | 356 | 4.1875 | 4 | #Exercise 15: Distance Units
"""
Input of measurements in feet
output in inches yards, and miles
"""
#input in feet from the user
ft = float(input("Measurement in feet: "))
#compute the output
inch = ft * 12
yrd = ft / 3
mile = ft / 5280
print("output:")
print("%.2f" % inch + " inches")
print("%.2f" % yrd + " yards")
print("%.5f" % mile + " miles")
| true |
9f220aac7313af46cd9f016eb678f6285605c6b2 | indraputra147/pythonworkbook | /chapter1/ex27.py | 617 | 4.4375 | 4 | #Exercise 27: When is Easter?
"""
The program reads the year from the user
Then display the date of Easter in that year
using Anonymous Gregorian Computus Algorithm
"""
#import math
y = int(input("Input a year: "))
a = y % 19
b = y // 100
c = y % 100
d = b // 4
e = b % 4
f = (b + 8) // 25
g = (b - f + 1) // 3
h = (19*a + b - d - g + 15) % 30
i = c // 4
k = c % 4
l = (32 + 2*e + 2*i - h - k) % 7
m = (a + 11*h + 22*l) // 451
month = (h - l - 7*m + 114) // 31
day = 1 + ((h + l - 7*m + 114) % 31)
import month_name
msg = "The date of Easter for this year is {} {}"
print(msg.format(day, month_name.mn(month)))
| false |
bcd8616ee86c889b7db353718696c0f911aca56a | jeetmehta/Cracking-The-Coding-Interview | /Arrays and Strings/check_permutation.py | 1,168 | 4.125 | 4 | # CTCI - Chapter 1: Arrays and Strings #
# Question 1.2
# PROBLEM STATEMENT: Given two strings, write a method to decide if one is a permutation of the other.
# HINTS: #1, #84, #122, #131
# Checks if two strings are permutations of each other using hash maps
# O(n) time, O(n) space
def checkPermutations(firstString, secondString):
# Edge Case 1: No way two strings can be permutations of each other if they're different lengths
if (len(firstString) != len(secondString)):
return False
firstHashMap = {}
secondHashMap = {}
for char in firstString:
if char not in firstHashMap:
firstHashMap[char] = 1
else:
firstHashMap[char] += 1
for char in secondString:
if char not in secondHashMap:
secondHashMap[char] = 1
else:
secondHashMap[char] += 1
if firstHashMap == secondHashMap:
return True
else:
return False
# Main function - runs unit tests
def main():
firstString = "xyzabcd"
secondString = "bdaczx2"
if (checkPermutations(firstString, secondString)):
print "Strings are permutations of each other"
else:
print "Strings are not permutations"
# Prevents file from running as import
if __name__ == "__main__":
main() | true |
42b468d4eb709699c95eb5e9ce96418616f412d5 | poojasaini22/edx-Introduction-to-Python-Absolute-Beginner | /str_analysis.py | 723 | 4.21875 | 4 | #Create the str_analysis() function that takes a string argument. In the body of the function:
#Program: str_analysis() Function
def str_analysis(arg):
while True:
if arg=="":
str_analysis(input("enter"))
break
elif arg.isdigit()==True:
if int(arg)<=99:
print(arg,"smaller number than expected")
break
else:
print(arg,"is a pretty big number")
break
elif arg.isalpha()==True:
print(arg,"is all alphabetical character")
break
else:
print(arg,"is neither all digit characters nor all alpha")
break
str_analysis(input("enter"))
| true |
6b94a8fe1cab6d15504c19b40d8f8fcd79fb2094 | aa-glitch/aoc2019 | /day03/wire.py | 2,262 | 4.21875 | 4 | from typing import List, Tuple, Dict
def find_crossings(wire1: List[Tuple], wire2: List[Tuple]) -> List[Dict]:
"""Return all crossing points with distance and steps.
Find all coordinates where the given wires cross. For each point,
determine the manhattan distance to the origin ('dist') and the combined
running lengths of both wires to that point ('steps').
Args:
wire1 (List[Tuple]): First wire as a sequence of
(direction, distance) tuples indicating where the wire
runs and how far.
wire2 (List[Tuple]): Second wire.
Returns:
List[Dict]: All crossing points with information about
manhattan distance ('dist') and combined wire length ('steps').
Example:
>>> find_crossings([('U', 1), ('U', 1)])
[{
'crossing': (0, 1),
'dist': 1,
'steps': 2
}]
"""
crossings = []
# collect wire1 coordinates
wire1_coords = dict(get_wire_coordinates(wire1))
# compare wire2 coordinates to find crossing points
for coord, steps in get_wire_coordinates(wire2):
if coord in wire1_coords:
crossings.append({
'crossing': coord,
'dist': manhattan(coord),
'steps': steps + wire1_coords[coord]})
return crossings
def get_wire_coordinates(wire: List[Tuple]) -> Tuple[Tuple, int]:
"""Yield all positions on the grid covered by the wire."""
i = 0
pos = (0, 0)
for direction, distance in wire:
for _ in range(distance):
i += 1
pos = get_next_coord(pos, direction)
yield pos, i
def get_next_coord(position: Tuple, direction: str) -> Tuple:
"""Return the position after taking one step in 'direction'."""
steps = {
'U': (0, 1),
'D': (0, -1),
'L': (-1, 0),
'R': (1, 0)}
return tuple([i + j for i, j in zip(position, steps[direction])])
def manhattan(coord: Tuple) -> int:
"""Return manhattan distance of coordinate from the origin."""
return abs(coord[0]) + abs(coord[1])
def deserialize_wire(wire: str) -> List[Tuple]:
"""Parse the given string into a tuple representation."""
return [(s[0], int(s[1:])) for s in wire.split(',')]
| true |
8da0cf849cc0860ce41f08330f62e762cefc8721 | Darya1501/Python-course | /lesson-7/task-8.py | 503 | 4.21875 | 4 | # Минимальное и максимальное в последовательности
n = int(input())
if n < 2:
print('Последовательность должна состоять минимум из 2 цифр')
else:
min = max = int(input())
for i in range(n-1):
a = int(input())
if a < min:
min = a
if a > max:
max = a
print('Минимум равен', min)
print('Максимум равен', max) | false |
b2d4216d9398e55f905a5d96c816f35217a60a77 | apollovsilva/Python | /Aula 6/Exercícios em preparação/exrpreparacao5_aula6.py | 677 | 4.15625 | 4 | import turtle
import math
def polyline(t, length, n, angle):
for i in range(n):
t.fd(length)
t.lt(angle)
def polygon(t, length, n):
angle = 360/n # ângulos externos de um polígono regular de n lados
polilyne(t, length, n, angle)
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, step_length, n, step_angle)
def circle(t,r):
arc(t, r, 360) # coloquei 360 pois quero de desenhe sempre um círculo
jn = turtle.Screen()
bob = turtle.Turtle()
r = float(input('Digite o valor do raio: '))
circle(bob,r)
| false |
a794b59ccd1ced0828a677dfbbfe7c5ef25dd349 | adibsxion19/CS1114 | /Labs/lab9q2.py | 1,029 | 4.1875 | 4 | # Aadiba Haque
# CS - UY 1114
# 3 March 2020
#Lab 9 Q2
def digit1(string):
#sig: str
even_num = ''
odd_num = ''
for char in string:
if char== '0' or char == '2' or char =='4' or char == '6' or char =='8':
even_num += char
elif char == '1' or char == '3' or char == '5' or char == '7' or char == '9':
odd_num += char
return len(even_num), len(odd_num)
def digit2(string):
even_count = 0
odd_count = 0
num = int(string)
#temp_num = num
while num > 0:
digit = num % 10
num //= 10
if digit % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count
def main():
string = input("Please input a string: ")
even_count, odd_count = digit1(string)
print("Even digits:", even_count, "Odd digits:", odd_count)
even_count, odd_count = digit2(string)
print("Even digits:", even_count, "Odd digits:", odd_count)
main()
| false |
f8933fd2bd5739e868eb4f9b563538f849a18308 | adityakumar1990/iNueron | /list/sort_nested_list_one_level_nesting.py | 587 | 4.21875 | 4 | def sort_nested_list(input_list):
sorted_list=[]
for e in input_list:
if type(e) not in (str,int,float):
##print(e)
#sorted_list.append(e.sort(reverse=True))
##This will not work because e.sort(reverse=True) return none and none will be appended
e.sort(reverse=True)
sorted_list.append(e)
# this will work since sort in in-place-method
else:
sorted_list.append(e)
return sorted_list
#driver code
print( sort_nested_list([[4, 1, 6], [7, 8], [4, 10, 8]])) | true |
2ddc67b20fd96368558f5173c3964e666b027c7e | taoes/python | /007_函数式编程/练习_001.py | 459 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: 周涛
@contact: zhoutao825638@vip.qq.com
"""
# 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,
# 其他小写的规范名字。输入:['adam', 'LISA', 'barT']
# 输出:['Adam', 'Lisa', 'Bart']:
def normalize(name: str):
result = name[0].upper() + name[1:].lower()
return result
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
| false |
71044a5a1e03a9709daed327f969fa43e69eb644 | taoes/python | /006_高级特性/003_列表生成器.py | 882 | 4.125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: 周涛
@contact: zhoutao825638@vip.qq.com
"""
# 生成0-10的平方数
# 普通方式遍历生成
def normal_function():
result = []
for x in range(10):
result.append(x * x)
return result
# 使用列表生成器
def list_generator():
return [x * x for x in range(10)]
# 生成0-20之间的偶数的平方
def list_generator_even():
return [x * x for x in range(20) if x % 2 == 0]
# 双重生成器
def list_generator_double(str1, str2):
return [x + y for x in str1 for y in str2 if x != y]
if __name__ == '__main__':
print("normal_function() = ", normal_function())
print("list_generator() = ", list_generator())
print("0-20 of the even number of squares = ", list_generator_even())
# 两个数字123,789 的全排列
print("123 , 125 = ", list_generator_double("123", "125"))
| false |
3516fa49f214a7eb57d4592843ae3b498ca10853 | EmmanuelSHS/LeetCode | /lint_implement_trie.py | 1,397 | 4.25 | 4 | """
Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("lintcode")
trie.search("lint") will return false
trie.startsWith("lint") will return true
"""
class Trie:
def __init__(self):
self.root = {}
self.END = '/'
# @param {string} word
# @return {void}
# Inserts a word into the trie.
def insert(self, word):
node = self.root
for l in word:
# node assigned to node's children
# in this case left node = {}
node = node.setdefault(l, {})
# assign an ending mark to words
# must have an ending flag
node[self.END] = None
# @param {string} word
# @return {boolean}
# Returns if the word is in the trie.
def search(self, word):
node = self.root
for l in word:
if l not in node:
return False
node = node[l]
return self.END in node
# this returns T/F
# if ended, END in, out T; else F
# @param {string} prefix
# @return {boolean}
# Returns if there is any word in the trie
# that starts with the given prefix.
def startsWith(self, prefix):
node = self.root
for l in prefix:
if l not in node:
return False
node = node[l]
return True
trie = Trie()
trie.insert("xyz")
trie.insert("abc")
trie.insert("abn")
print trie.search("xyz")
print trie.startsWith("a")
| true |
d1a3694b40a21fe1d3f8b45555ff24e91ca9bc04 | meralegre/cs50 | /pset6/cash/cash.py | 968 | 4.1875 | 4 | from cs50 import get_float
def main():
change = get_positive_float("Change : ")
print('input change : ', change)
# Convert this input from float to int
cents = round(change*100)
print('input round : ', cents)
# Coins possible
quarter = round(0.25*100)
dime = round(0.10*100)
nickel = round(0.05*100)
penny = round(0.01*100)
# Count of coins
count = 0
while quarter <= cents :
count = count + 1
cents = cents - quarter
while dime <= cents :
count = count + 1
cents = cents - dime
while nickel <= cents :
count = count + 1
cents = cents - nickel
while penny <= cents :
count = count + 1
cents = cents - penny
print(count, end="\n")
def get_positive_float(prompt):
"""Prompt user for positive float"""
while True:
n = get_float(prompt)
if n > 0 :
break
return n
if __name__ == "__main__":
main()
| true |
b21f6d981ce96ee41c58779e81f33067d313b2de | hendalf332/tratata | /projShift.py | 2,932 | 4.125 | 4 | #!/usr/bin/env python
import os
import string
def clr():
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
alphabet=list(string.ascii_lowercase)
alphabet.append(' ')
alphabet_upper=list(string.ascii_uppercase)
punct=list(string.punctuation)
for x in range(0,9):
punct.append(str(x))
def menu():
clr()
msg="""1) Make a code
2) Decode a message
3) Quit
Enter your selection:
"""
try:
ans=int(input(msg))
except ValueError:
print('Please enter integer value from menu 1,2 or 3!!!')
return 0
return ans
def encode(str,num):
res=''
num=num%len(alphabet)
for symb in str:
if symb in alphabet:
pos=(alphabet.index(symb)-alphabet.index('a'))
if (pos+num)>=len(alphabet):
res=res+alphabet[(pos+num)%len(alphabet)]
else:
res=res+alphabet[pos+num]
elif symb in alphabet_upper:
pos=(alphabet_upper.index(symb)-alphabet_upper.index('A'))
if (pos+num)>=len(alphabet_upper):
res=res+alphabet_upper[(pos+num)%len(alphabet_upper)]
else:
res=res+alphabet_upper[pos+num]
elif symb in punct:
pos=(punct.index(symb)-punct.index('!'))
if (pos+num)>=len(punct):
res=res+punct[(pos+num)%len(punct)]
else:
res=res+punct[pos+num]
return res
def decode(str,num):
res=''
num=num%len(alphabet)
for symb in str:
if symb in alphabet:
pos=(alphabet.index(symb)-alphabet.index('a'))
if (pos-num)<0:
res=res+alphabet[len(alphabet)+(pos-num)]
else:
res=res+alphabet[pos-num]
elif symb in alphabet_upper:
pos=(alphabet_upper.index(symb)-alphabet_upper.index('A'))
if (pos-num)<0:
res=res+alphabet_upper[len(alphabet_upper)+(pos-num)]
else:
res=res+alphabet_upper[pos-num]
elif symb in punct:
pos=(punct.index(symb)-punct.index('!'))
if (pos-num)<0:
res=res+punct[len(punct)+(pos-num)]
else:
res=res+punct[pos-num]
return res
def main():
clr()
encstr=''
while True:
ans=menu()
if ans==1:
print('Make a code')
str=input('Enter string:')
key=int(input('Enter key:'))
encstr=encode(str,key)
print(encstr)
elif ans==2:
print('Decode message!!!')
dec_str=input('Enter encrypted string:')
dec_key=int(input('Enter decode key:'))
str=decode(dec_str,dec_key)
print(str)
elif ans==3:
print('Good bye!!')
exit()
else:
print('Enter correct code 1,2 or 3 !!!')
input()
main()
| true |
28604e80f9bd046f00dfff0b82b8cbf53f0edc4e | DanceSmile/python | /klass/klass_attribute.py | 382 | 4.15625 | 4 | '''
由于Python是动态语言
根据类创建的实例可以任意绑定属性。
'''
# 实例属性,
class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')
s.score = 90
# 类属性
# 定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到
class Student(object):
name = 'Student' | false |
25f67ce7883f88337f0be49e79b2611f2d74ba1a | shashank136/Personal_code | /algorithms/python_code/bubblesort.py | 625 | 4.40625 | 4 | class Bubblesort(object):
"""
It's an inplace sorting algorithm
time complexity of bubble sort is O(n^2)
space complexity of bubble sort is O(1)
"""
def __init__(self):
n = int(input("enter the number of elements: "))
a = []
for i in range(n):
a.append(int(input("enter the number: ")))
print("list to be sorted: ",a)
self.bubble_sort(a)
self.print_list(a)
def bubble_sort(self,a):
for j in range(len(a)-1,2,-1):
for i in range(0,j):
if a[i] > a[i+1]:
(a[i],a[i+1]) = (a[i+1],a[i])
def print_list(self,a):
print("list after sorting: ",a)
item = Bubblesort() | false |
8b980f1f09d963af977052476b8c42e785fbc6c4 | ashwinraghav08/calculator | /calculator_v2.py | 799 | 4.21875 | 4 | def add(num1, num2):
print (num1+num2)
def minus(num1, num2):
print (num1-num2)
def multiply(num1,num2):
print(num1*num2)
def divide(num1,num2):
print(num1/num2)
def get_input():
num1 = input("Enter num1: ")
#print(num1)
num2 = input("Enter num2: ")
#print(num2)
operation=input("Which method do you want to perform.\nThe options are 1 for add, 2 for minus, 3 for multiply, and 4 for divide: ")
if operation=="1":
add(int(num1),int(num2))
elif operation=="2":
minus(int(num1),int(num2))
elif operation=="3":
multiply(int(num1),int(num2))
elif operation=="4":
divide(int(num1), int(num2))
else:
print(f"{operation} is not a valid operation, the valid options are 1, 2, 3, 4")
get_input()
| true |
136a6666e7a3a6b73a440e1ac57f493076c4c0a7 | LukeJermaks/Programming | /Nested If Statement.py | 900 | 4.21875 | 4 | #Loop thing I guess.
#By Luke Jermaks
def NestedLoop():
score = int(input("Input Score\n >>>"))
if score > 89: #Needs to be > 89 due to the grade being only over 90 for a grade 9
print("Grade 9") #You could also use => or =< and then the lower bound of the grade
elif score > 79:
print("Grade 8")
elif score > 69:
print("Grade 7")
elif score > 59:
print("Grade 6")
elif score > 49:
print("Grade 5")
elif score > 39:
print("Grade 4")
elif score > 29:
print("Grade 3")
elif score > 19:
print("Grade 2")
elif score > 9:
print("Grade 1")
else:
print("Ungraded")
def Spacer():
print("")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("")
while True:
NestedLoop()
Spacer()
| true |
1c71af4bafdb4d4d3d18d82a89b64542efebf219 | mottola/dataquest_curriculum | /python_basics/python-methods.py | 1,566 | 4.46875 | 4 | # OBJECT METHODS IN PYTHON (METHODS CALL FUNCTIONS ON OBJECTS)
# OBJECT str
# _______________________
# capitalize(), replace()
# OBJECT float
# _________________________
# bit_length(), conjugate()
# OBJECT list
# ________________
# index(), count()
# LIST METHODS
# ______________
fam = ['liz', 1.73, 'emma', 1.68, 'mom', 1.71, 'dad', 1.89]
deposits = [174, 29, 314, 47, 162, 96, 287]
# INDEX METHOD
print(fam.index('mom')) # WHERE IS 'mom' IN THE LIST?
print(fam.index('dad')) # WHERE IS 'dad' IN THE LIST?
print(deposits.index(47)) # WHERE IS 47 IN THE LIST?
# COUNT METHOD
print(fam.count(1.73)) # HOW MANY TIMES DOES 1.73 OCCUR IN THE LIST?
print(fam.count('mom')) # HOW MANY TIMES DOES 'mom' OCCUR IN THE LIST?
print(deposits.count(29)) # HOW MANY 1'S ARE IN THE LIST
# APPEND METHOD
fam.append('me') # ADD 'me' TO THE END OF THE LIST
fam.append(1.71) # ADD 1.71 TO THE END OF THE LIST
deposits.append(65) # ADD 65 TO THE END OF THE LIST
print(deposits)
# SORT METHOD
deposits.sort() # SORT THE LIST FROM LEAST TO GREATEST
print(deposits)
# REVERSE METHOD
deposits.reverse() # REVERSE THE ORDER OF THE LIST
print(fam)
print(deposits)
# REVERSE METHOD
# STRING METHODS
# _______________
# USE help(str) TO VIEW STRING METHODS
sister = 'liz'
# CAPITALIZE METHOD
sister_cap = sister.capitalize() # RETURNS STRING WITH FIRST LETTER CAPITALIZED
print(sister_cap)
# REPLACE METHOD
sister_rep = sister.replace('z', 'sa').capitalize() # REPLACE 'z' WITH 'sa' AND CAPITALIZE
print(sister_rep)
# COUNT METHOD
print(sister.count('s'))
| true |
b98021728ffe1479acfa222d7f8489c85030ca22 | FOSS-UCSC/FOSSALGO | /algorithms/ar-expsq/python3/exponentiation_by_squaring.py | 378 | 4.375 | 4 | def exponentiation_by_squaring(base, power):
res = 1
while(power > 0):
if(power % 2 != 0):
res *= base #if power is ODD, multiply res with base
base *= base # square the base
power = power // 2 # halving power (integer)
return res
def main():
print(exponentiation_by_squaring(5, 6))
if __name__ == "__main__":
main() | true |
3c0138867df695fb0cb1a5892f8fcdca124d73cd | cheungh/python | /bubble_sort.py | 835 | 4.125 | 4 | """
Very inefficient sort method
do not use for sort for list larger than 200 items
use quick sort or merge sort instead
"""
def bubble_sort(A):
# for n element in list
n = len(A)
bound = n - 1
# let i be iterate counter of outer loop
# set swap to false to detect if swap occurred
swap = False
for i in xrange(n - 1):
new_bound = bound
for j in xrange(bound):
if A[j] > A[j+1]:
swap = True
A[j+1], A[j] = A[j], A[j + 1]
new_bound = j
bound = new_bound
print "bound is %s" % bound
print A
# a sorted list detected
if swap is False:
break
return A
X = [20, 45, 93, 67, 10, 97, 52, 88, 33, 92]
# test for a sorted list
# X = [1, 2, 3, 4, 5, 6]
Y = bubble_sort(X)
print Y
| true |
24ae4b94795980b14021e543dee79d894447c383 | lianhx/Python_Learning | /1.上课/第一次课/2.py | 410 | 4.1875 | 4 | import math # 导入math模块
side1 = int(input("请输入一个边长:")) # 得到一个边长
side2 = int(input("请输入另一个边长:")) # 得到第二个边长
angle = int(input("请输入夹角:")) # 得到夹角的值
a = 2*side1*side2*math.cos(angle*math.pi/180)
side3 = math.sqrt(side1**2 + side2**2 - a) # 利用余弦定理计算第三条边长
print(side3) # 打印第三条边长
| false |
2c0dc53acf5118aba7cf67124186a723ba97d633 | Eliasin/fun-things | /mark_catastrophe.py | 2,114 | 4.15625 | 4 | from functools import reduce
english_marks = [31, 20, 44, 49, 50, 33, 45, 21, 3, 17, 40]
math_marks = [26, 25, 30, 50, 41, 29, 19, 26, 38, 35, 42]
print("I have a set of english marks and a set of math marks, both are out of 50.")
def convert_marks_to_percentage(marks):
result = []
for mark in marks:
result.append(mark / 50 * 100)
return result
english_marks_percentage = convert_marks_to_percentage(english_marks)
print("The english marks are {}".format(english_marks_percentage))
print("That was pretty long winded, is there a standard way to apply some function to every member in a list?")
print("One google search later...")
math_marks_percentage = list(map((lambda x: x / 50 * 100), math_marks))
print("The math marks are {}".format(math_marks_percentage))
print("Now to get the class average.")
def average(marks):
total = 0
for mark in marks:
total += mark
return total / len(marks)
english_average = average(english_marks_percentage)
print("The average is... {:.1f}%, ouch. Let's see if the math marks are any better.".format(english_average))
math_average = reduce((lambda x, y: x + y), math_marks_percentage) / len(math_marks_percentage)
print("The math average is {:.1f}%, wait that's barely an improvement!".format(math_average))
def filter_marks(marks):
passing = []
for mark in marks:
if mark / 50 * 100 > 50:
passing.append(mark)
return passing
print("Well, time to find the averages of the passing scores.")
passing_english = filter_marks(english_marks)
passing_math = list(filter((lambda x: (x / 50 * 100) > 50), math_marks))
def average_mark(marks):
return reduce(
(lambda x, y: x + y),
map((lambda x: x / 50 * 100), marks)
)
print("So the passing grades are {} and {}".format(passing_english, passing_math))
passing_math_average = average_mark(passing_math) / len(passing_math)
passing_english_average = average_mark(passing_english) / len(passing_english)
print("And the passing averages are {:.2f}% and {:.2f}%.".format(passing_math_average, passing_english_average))
print("I guess thats a bit better.")
| true |
82ad2118b1979ffb7016418c9fe95cb3b682cc58 | zju-stu-lizheng/python_2021 | /面向对象/多态.py | 1,665 | 4.59375 | 5 | '''
多态:顾名思义就是多种状态、形态,就是同一种行为 对于不同的子类【对象】有
不同的行为表现
要想实现多态 必须得有两个前提需要遵守:
1.继承:多态必须发生在父类和子类之间
2.重写:子类需要重写父类的方法
多态的作用:
增加程序的灵活性
增加程序的扩展性
'''
# 案例演示
class Animal:
'''
父类[基类]
'''
def say_who(self):
print('我是一个动物....')
pass
pass
class Duck(Animal):
'''
鸭子类【子类】【派生类】
'''
def say_who(self):
print('我是一个鸭子')
pass
pass
class Dog(Animal):
def say_who(self):
print('我是一只小狗')
pass
pass
class Cat(Animal):
def say_who(self):
print('我是一只小猫')
pass
pass
class Bird(Animal):
'''
新增鸟类 无需修改原来的方法
'''
def say_who(self):
print('I am a bird.')
pass
pass
def commonInvoke(obj):
'''
统一调用方法
:param obj: 对象的实例
:return:
'''
obj.say_who()
pass
class People():
pass
class Student(People):
def say_who(self):
print('我是一年级的学生 李敏')
pass
pass
# duck1 = Duck()
# duck1.say_who()
#
# dog1 = Dog()
# dog1.say_who()
#
# cat1 = Cat()
# cat1.say_who()
listObj = [Duck(),Dog(),Cat(),Bird(),Student()]
for item in listObj:
'''
循环去调用函数
'''
commonInvoke(item)
pass
| false |
c1ae10792f7f8b259d278431bfbd1fba180b4776 | zju-stu-lizheng/python_2021 | /day03/parameter.py | 1,787 | 4.3125 | 4 | '''
参数的分类:
必选参数、默认参数【缺省参数】、可选参数、关键字参数
参数:其实就是函数为了实现某项特定的功能,进而为了得到实现功能所需要的数据
'''
# 1 必选参数
# def sum(a,b): # 形式参数:只是意义上的一种参数,再定义的时候是不占内存地址的
# sum = a+b
# print(sum)
# pass
#
#
# # 2 默认参数【缺省参数】
# def sum1(a=20,b=30): # 缺省参数始终放在参数列表的尾部
# print('默认参数使用=%d'%(a+b))
# pass
#
#
# # 可变参数(当参数的个数不确定时使用,比较灵活
# def getComputer(*args):
# '''
# 计算累加和
# :param args: 可变长的参数类型
# :return:
# '''
# # print(args)
# result = 0
# for item in args:
# result += item
# pass
# print('result=%d'%result)
# pass
#
#
# # 函数的调用
# sum(1,2) # 1 2 实际参数:实参
# sum1() # 在调用的时候,如果未赋值,就会用定义函数时给定的默认值
# getComputer(1)
# getComputer(1,2,3)
# 关键字可变参数
# **来定义
# 在函数体内 参数关键字是一个字典类型,key是一个字符串
def keyFunc(**kwargs):
print(kwargs)
pass
# 调用
dictA = {"name":'Leo', "age":35}
# keyFunc(**dictA)
# keyFunc(name='peter',age = 26)
# 组合的使用
def complexFunc(*args,**kwargs):
print(args)
print(kwargs)
pass
complexFunc(1,2,3,4,name='刘德华')
complexFunc(age=36)
# def TestMup(**kwargs,*args):
# '''
# 可选参数必须放到关键字可选参数之前
# :param kwargs:
# :param args:
# :return:
# '''
# pass
| false |
5b87ae1a4cfc1e7e44aed75a70fd5cbe37d32024 | zju-stu-lizheng/python_2021 | /day02/tuple.py | 885 | 4.40625 | 4 | '''
元组是一种不可变的序列,在创建之后不能做任何的修改
1.不可变
2.用()来创建,数据项用逗号分隔
3.可以实任何的类型
4.当元组中只有一个元素是,要加上逗号,否则会被当做整形来处理
5.可以支持切片
'''
# 元组的创建 ,不能进行修改
# tupleA = ()
tupleA = ('abcd', 89, 9.12, 'peter', [11, 22, 33])
# print(type(tupleA))
# print(tupleA)
# 元组的查询
# for item in tupleA:
# print(item,end=' ')
# print(tupleA[2])
print(tupleA[::-2]) # 表示反转字符串,每隔两个取一次
print(tupleA[-2:-1:]) # 倒着取下标 为 -2 到 -1区间的
print(tupleA[-4:-1:])
tupleA[4][0] = 285202 #可以对元组中的列表进行修改
print(tupleA)
tupleB = (1,)
print(type(tupleB))
tupleC = (1,2,3,4,3,4,4,1) #tuple(range(10))
print(tupleC.count(4))
| false |
b86b1c817be6bd24b9d05bb518b542cadb684483 | zju-stu-lizheng/python_2021 | /day03/函数01.py | 969 | 4.40625 | 4 | '''
什么是函数:一系列python语句的组合
一般是完成具体的独立的功能
为什么要使用函数:
代码的复用最大化以及最小化冗余代码
函数定义
def + 关键字 + 小括号 + 冒号 + 换行缩进 + 代码块
def 函数名 ():
代码块
函数调用
本质上就是去执行函数定义里面的代码块,再调用函数之前,必须先定义
'''
# 函数的定义
def printInfo(name,height,weight,hobby,profess):
'''
这个函数是用来打印个人信息的,是对小张信息的打印
:return:
'''
# 函数代码块
print('%s的身高是%f' % (name,height))
print('%s的体重是%f' % (name, weight))
print('%s的爱好是%s' % (name,hobby))
print('%s的专业是%s' % (name,profess))
pass
# 函数的调用
printInfo('小张',1.7, 160, '唱歌', '计算机信息管理')
# 处理其他的逻辑信息
# 多次去打印出小航的信息
| false |
6733cf341bc1480fb93b411cf9101ab699825d01 | stewartyoung/leetcodePy-easy-1-20 | /Algorithms/LongestCommonPrefix.py | 1,117 | 4.1875 | 4 | stringList1 = ["flower", "flow", "flight"]
stringList2 = ["dog", "racecar", "car"]
def longestCommonPrefix(stringList) -> str:
# If string list doesn't contain anything, return empty string
if not stringList:
return ''
# Take the last item in the stringList
lastItem = min(stringList)
# For character in (0,len of last item)
for char in range(len(lastItem)):
# For string in string list
for string in stringList:
# If strings character doesn't equal last items character at same index
if string[char] != lastItem[char]:
# return the string up to one before the character being examined, if its the first letter being compared return empty string
return lastItem[:char] if char > 0 else ''
# If we manage to get through the whole string return lastItem
return lastItem
print(longestCommonPrefix(stringList1))
print(longestCommonPrefix(stringList2))
| true |
b383deb55bf6598f2779a726503d383486f6419b | anupatboontor/workshop | /For/for_exercise.py | 448 | 4.15625 | 4 | # 2.จงเขียนตารางสูตรคูณให้ผลลัพท์ที่ออกมาเป็นแบบตัวอย่างด้านล่างโดยใช้คำสั่ง for
for number in range(2, 13):
for i in range(1, 13):
result = number * i
print("%d x %d = %d" % (number, i, result))
print(" ")
print("-------------------------------------------------------") | false |
82b13aae211e42ae1d23045f6da88847341863d1 | cs-fullstack-2019-fall/python-coding-concepts1-weekly-5-Kenn-CodeCrew | /question9.py | 355 | 4.21875 | 4 | # ### Problem 9:
# Ask the user for a positive number. Create an empty array and starting from zero, add each number by 1 into the array. Print EACH ELEMENT of the array.
userInput = int(input("Enter a positive number"))
emptyArray = []
for index in range(userInput+1):
emptyArray.append(index)
for eachElement in emptyArray:
print(eachElement) | true |
e42dab7c2dcc8a68da514bee6ac854292e137d6e | milkrong/Basic-Python-DS-Algs | /InsertionSort.py | 366 | 4.125 | 4 | def insertion_sort(arr_list):
for i in range(1, len(arr_list)):
cur = arr_list[i]
position = i
while position > 0 and arr_list[position - 1] > cur:
arr_list[position] = arr_list[position -1]
position -= 1
arr_list[position] = cur
return my_list
my_list = [8,2,1,3,5,4]
print(insertion_sort(my_list)) | false |
eabf756621d3a5f4598cc40eceb636f91a5a61e0 | milkrong/Basic-Python-DS-Algs | /BubbleSort.py | 497 | 4.28125 | 4 | def bubble_sort(input_list):
is_sorted = False
length = len(input_list) - 1
while not sorted:
is_sorted = True # assume it is sorted
for i in range(length):
if input_list[i] > input_list[i+1]:
is_sorted = False # find a position not sorted
input_list[i], input_list[i+1] = input_list[i+1], input_list[i]
return input_list
if __name__ == '__main__':
my_list = [12, 5, 13, 8, 9, 65]
print(bubble_sort(my_list)) | true |
9f5d85dd02c35ca6b6590b55823732ddf369fa45 | christopher-besch/arg_toolset | /substitution_cipher.py | 2,879 | 4.125 | 4 | """
substitute every letter with it's number from the alphabet and the other way around
"""
# assign each char a letter
def substitute(string, substitutes=None, joint=''):
# replace substitutes with default
if substitutes is None:
substitutes = {
"1": 'A',
"2": 'B',
"3": 'C',
"4": 'D',
"5": 'E',
"6": 'F',
"7": 'G',
"8": 'H',
"9": 'I',
"01": 'A',
"02": 'B',
"03": 'C',
"04": 'D',
"05": 'E',
"06": 'F',
"07": 'G',
"08": 'H',
"09": 'I',
"10": 'J',
"11": 'K',
"12": 'L',
"13": 'M',
"14": 'N',
"15": 'O',
"16": 'P',
"17": 'Q',
"18": 'R',
"19": 'S',
"20": 'T',
"21": 'U',
"22": 'V',
"23": 'W',
"24": 'X',
"25": 'Y',
"26": 'Z'
}
# create dictionary with substitutes in reversed order
inverse_substitutes = {v: k for k, v in substitutes.items()}
# update dict
substitutes = dict(**substitutes, **inverse_substitutes)
# cut at delimiters if existent
if joint != '':
string = string.split(joint)
# or just convert to list
else:
string = list(string)
# convert every char
text_list = []
current_idx = 0
while current_idx < len(string):
current_char = string[current_idx]
# add the current char with the next one (e.g. "02" -> "B")
# only when there is no delimiter and a next one exists
if joint == '' and current_idx + 1 < len(string):
double_char = current_char + string[current_idx + 1]
if double_char in substitutes.keys():
text_list.append(substitutes[double_char])
# jump 2 indices <- next char already used
current_idx += 2
continue
# or add only this char converted
if current_char in substitutes.keys():
text_list.append(substitutes[current_char])
current_idx += 1
# or itself if it can't be substituted
else:
text_list.append(current_char)
current_idx += 1
return joint.join(text_list)
if __name__ == "__main__":
# get cipher from file if unavailable
cipher = input("paste the text here: ").upper()
if cipher == '':
file_location = input("file location: ")
with open(file_location, encoding='utf-8') as file:
cipher = file.read().upper()
delimiter = input("delimiter: ")
print(substitute(cipher, joint=delimiter))
| false |
99fdab510f07e294362319bd0ff41e979b287693 | Clucas0311/PythonCourse | /pizza_toppings.py | 532 | 4.40625 | 4 | # Write a loop that prompts the user to enter a series of pizza toppings until
# they enter a "quit" value. As they enter each message, print a message saying
# You'll add that topping to their pizza
message = """\nWelcome to Pizza Shack!
What kind of toppings would you like to add to your pizza?:"""
message += "\n Enter 'quit' if you would like to leave the program: "
while True:
toppings = input(message)
if toppings == 'quit':
break
else:
print(f"We will add {toppings} to your pizza. Enjoy!")
| true |
ed71d577919662e06562094429f460f30ea0d0d3 | Clucas0311/PythonCourse | /2-10.py | 823 | 4.28125 | 4 | # Write a progran that produces 48 cookies with the ingredients listed
# 1.5 cups of sugar
# 1 cup of butter
# 2.75 cups of flour
regular_amt_cookies = 48
regular_amt_sugar = 1.5
regular_amt_butter = 1
regular_amt_flour = 2.75
# Prompt the user on how many cookies that they will like to make?
amount_of_cookies = float(input("How many cookies would you like to make?: "))
expected_cups_sugar = (amount_of_cookies / regular_amt_cookies) * \
regular_amt_flour
expected_cups_butter = (amount_of_cookies / regular_amt_cookies) * \
regular_amt_sugar
expected_cups_flour = (amount_of_cookies / regular_amt_cookies) * \
regular_amt_flour
print(f"""To make: {amount_of_cookies}, you need: {expected_cups_sugar:.2f} cups
of sugar, {expected_cups_butter:.2f} cups of butter and {expected_cups_flour:.2f}
cups of flour. """)
| true |
418c73d1e577cf0a3140e9f0cc85510248f6d6ce | Clucas0311/PythonCourse | /2-7.py | 321 | 4.25 | 4 | # A cars MPG can be calcuated:
# MPG = Miles driven / Gallons of gas used
miles_driven = float(input("How many miles did you drive: "))
gallons_of_gas = float(input("How many gallons of gas did you use?: "))
miles_per_gallon = miles_driven / gallons_of_gas
print(f"The number of miles driven: {miles_per_gallon} MPG")
| true |
890f88c45a3b66e02e75dc05d5bb7711e38e5d7a | Clucas0311/PythonCourse | /restaurant2.py | 1,009 | 4.125 | 4 | class Restaurant: # Make a class called restaurant
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f"{self.restaurant_name} is a beautiful restaurant, perfect for large parties")
print(f"{self.cuisine_type} is delicious, tastey and savory.")
def open_restaurant(self):
print(f"Yes, {self.restaurant_name} is open!")
the_restaurant = Restaurant("Uncle Julio's", "Mexican")
print(f"My favorite restaurant is {the_restaurant.restaurant_name}")
print(f"The {the_restaurant.cuisine_type} food is yummy")
# Make three different instances from the class and call describe_restaurant
fav_restaurant = Restaurant("Catch NYC","Seafood")
fav_restaurant.describe_restaurant()
restaurant3 = Restaurant("Founding Farmers", "American")
restaurant3.describe_restaurant()
restaurant4 = Restaurant("Medium Rare","Bistro")
restaurant4.describe_restaurant()
| true |
956916707ffe3eee148dbb01650936533e3fc656 | aruwentar/PythonSmallProjects | /Hangman/main.py | 2,038 | 4.125 | 4 | import re
def get_word_to_guess():
# STUB
return "barnacle"
def convert_word_to_char_list(word):
char_list = list()
for char in word:
char_list.append(char)
return char_list
def get_user_guess():
user_guess = str()
while True:
user_guess = input("Please guess your letter: ")
match = re.match("[a-zA-Z]", user_guess)
if len(user_guess) != 1 or not match:
print("Please enter a single character")
continue
else:
break
return user_guess
def calculate_number_of_attempts(word):
unique_chars = set()
for char in word:
unique_chars.add(char)
return len(unique_chars) - 3
def reveal_new_letters(listed_word, guess_indices, guess=[]):
guess_indices.extend([i for i, e in enumerate(listed_word) if e == guess])
word = str()
for i in range(len(listed_word)):
if i in guess_indices:
word += listed_word[i]
else:
word += '_'
return word
def main():
investigated_word = get_word_to_guess()
number_of_allowed_attempts = calculate_number_of_attempts(investigated_word)
listed_word = convert_word_to_char_list(investigated_word)
guess_indices = list()
attempts_made = 0
print("Number of letters in investigated word {:d}".format(len(investigated_word)))
while attempts_made < number_of_allowed_attempts:
guess = get_user_guess()
if guess in listed_word:
current_state = reveal_new_letters(listed_word, guess_indices, guess)
print(current_state)
if current_state == investigated_word:
print("Congratulations, you won!")
break
else:
current_state = reveal_new_letters(listed_word, guess_indices)
print(current_state)
attempts_made += 1
print("Number of attempts left {:d}".format(number_of_allowed_attempts - attempts_made))
if __name__ == "__main__":
main() | true |
e64ff752b5f33dbdef61008dc6b8692779658d1c | lucasgarciabertaina/python-exercises | /guides/guide05/g05e02.py | 1,663 | 4.6875 | 5 | """
Los siguientes ejercicios son en su mayoría
para reutilizar los enunciados de guías
anteriores, aplicando en la solución el uso de
funciones.
En los primeros 5 ejercicios trabajamos con el
texto: “Quiero comer manzanas, solamente
manzanas.”, considerar que una palabra es
toda secuencia de caracteres diferentes de los
separadores (los caracteres separadores son el
espacio, la coma y el punto).
2. Buscar una palabra y reemplazarla por otra
todas las veces que aparezca.
Ej.: ‘peras’ en lugar de ‘manzanas’ quedaría
'Quiero comer peras, solamente peras.'
"""
def stringToArray(string):
string = string.lower()
arrayWithoutDot = string.split('.')
arrayWithoutSpace = arrayWithoutDot[0].split(' ')
array = []
for i in range(len(arrayWithoutSpace)):
if i == 2:
array.append(arrayWithoutSpace[i][0:8])
else:
array.append(arrayWithoutSpace[i])
return array
def arrayToString(array):
string = ''
for i in range(len(array)):
if i == 2:
string += array[i]+', '
elif i == len(array)-1:
string += array[i]+'.'
else:
string += array[i]+' '
string = string.capitalize()
return(string)
def replaceWord(array, palabraARemplazar, palabra):
for i in range(len(array)):
if array[i] == palabraARemplazar:
array[i] = palabra
return array
text = 'Quiero comer manzanas, solamente manzanas.'
print(text)
wordToReplace = input('What word do you like to replace? ')
word = input('By what word? ')
array = replaceWord(stringToArray(text), wordToReplace, word)
print(arrayToString(array))
| false |
1e5343c11b7c4d3817a8f93ad982856115acf114 | lucasgarciabertaina/python-exercises | /guides/guide05/g05e10.py | 234 | 4.15625 | 4 | """
10. Cargar una lista con números. Invertir los
elementos (sin usar reverse). Mostrar.
"""
def reverse(numbers):
reverse = []
for i in range(len(numbers)-1, -1, -1):
reverse.append(numbers[i])
print(reverse)
| false |
9305e2365cfbc47cfc4f7572d05427dba0b12f98 | lucasgarciabertaina/python-exercises | /guides/guide05/g05e09.py | 640 | 4.3125 | 4 | """
9. Dada una lista cargada con números enteros,
obtener el promedio de ellos. Mostrar por
pantalla dicho promedio y los números ingresados
que sean mayores que él. Dos funciones:
promedio y mayorQue.
"""
def average(numbers):
total = 0
for number in numbers:
total += number
return total/len(numbers)
def greaterThan(average, numbers):
greater = []
for number in numbers:
if number > average:
greater.append(number)
return greater
print("The average is", average([6, 9, 6]), "and greater than", average(
[6, 9, 6]), "is/are:", greaterThan(average([6, 9, 6]), [6, 9, 6]))
| false |
70f9907e1b27b3421e4e4ae7a3babd81b62cff1d | lucasgarciabertaina/python-exercises | /guides/guide02/g02e03.py | 250 | 4.15625 | 4 | """
Mostrar por pantalla una lista de
20 números enteros consecutivos,
comenzando con un número
ingresado por teclado.
"""
number = int(input('Enter a number: '))
i = 1
while i != 20:
print('Number ', number)
i += 1
number = number+1
| false |
65359d84f0f12ff18a98c0f1acc21b288d6fe447 | ErickMwazonga/sifu | /strings/string_compression.py | 1,685 | 4.3125 | 4 | '''
443. String Compression
Link: https://leetcode.com/problems/string-compression/
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead,
be stored in the input character array chars.
Note that group lengths that are 10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Example 1:
Input: chars = ['a', 'a', 'b', 'b', 'c', 'c', 'c']
Output: Return 6, and the first 6 characters of the input array should be: ['a','2','b','2','c','3']
Explanation: The groups are 'aa', 'bb', and 'ccc'. This compresses to 'a2b2c3'.
Example 2:
Input: chars = ['a']
Output: Return 1, and the first character of the input array should be: ['a']
Explanation: The only group is 'a', which remains uncompressed since it's a single character.
'''
def compress(chars: list[str]) -> int:
n = len(chars)
if n == 1:
return 1
i, start, _count = 1, 0, 1
length = 0
while i < n:
if chars[i] != chars[i-1]:
chars[start+1] = str(_count)
start, _count = i, 1
length += 2
else:
_count += 1
i += 1
chars[start+1] = str(_count)
length += 2
chars = chars[:length]
return length
compress(['a', 'a', 'b', 'b', 'c', 'c', 'c'])
| true |
5215f67912c760305c6c22390711d8a11e4e546e | ErickMwazonga/sifu | /graphs/currency_conversion.py | 2,424 | 4.15625 | 4 | '''
Currency Conversion
Resource: https://www.youtube.com/watch?v=L9Me2tDDgY8
Paramenters:
1. array of currency conversion rates. E.g. ['USD', 'GBP', 0.77] which means 1 USD is equal to 0.77 GBP
2. an array containing a 'from' currency and a 'to' currency
Given the above parameters, find the conversion rate that maps to the 'from' currency to the 'to' currency.
Your return value should be a number.
Example:
You are given the following parameters:
1. Rates: ['USD', 'JPY', 110] ['USD', 'AUD', 1.45] ['JPY', 'GBP', 0.0070]
2. To/From currency ['GBP', 'AUD']
Find the rate for the 'To/From' curency. In this case, the correct result is 1.89.
# ADJACENCY LIST
{
'USD': [('JPY', 110), ('AUD', 1.45)],
'JPY': [('USD', 0.0091), ('GBP', 0.007)],
'AUD': [('USD', 0.69)],
'GBP': [('JPY', 142.86)]
}
'''
from collections import defaultdict
class CurrencyConverter:
def create_adjacency_list(self, rates):
adjacency_list = defaultdict(list)
for rate in rates:
to, _from, _rate = rate
adjacency_list[to].append((_from, _rate))
adjacency_list[_from].append((to, 1 / _rate))
return adjacency_list
def get_conversion(self, rates, queries):
'''BFS'''
output = []
adjacency_list = self.create_adjacency_list(rates)
for query in queries:
to, _from = query
queue = [(to, 1)]
visited = set([to])
found = False
if (to not in adjacency_list) and (_from not in adjacency_list):
output.append(-1)
continue
while queue:
curr_node, curr_multiplier = queue.pop(0)
if curr_node == _from:
output.append(round(curr_multiplier, 2))
found = True
break
for neighbour, multiplier in adjacency_list[curr_node]:
if neighbour not in visited:
visited.add(neighbour)
queue.append((neighbour, multiplier * curr_multiplier))
if not found:
output.append(-1)
return output
rates = [['USD', 'JPY', 110], ['USD', 'AUD', 1.45], ['JPY', 'GBP', 0.0070]]
queries = [['GBP', 'AUD']]
currency_converter = CurrencyConverter()
assert currency_converter.get_conversion(rates, queries) == [1.88]
| true |
0cb142038b9c99afb71841bd9f194a9fec21e695 | ErickMwazonga/sifu | /strings/reversed_words.py | 1,412 | 4.21875 | 4 | '''
Write a function reverse_words() that takes a message
as a list of characters and reverses the order of the words in place.
message = [
'c', 'a', 'k', 'e', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 's', 't', 'e', 'a', 'l'
]
reverse_words(message) -> 'steal pound cake'
'''
from typing import NoReturn
def reverse_words(message: list[str]) -> None:
'''O(n) time and O(1) space!'''
n = len(message)
# First we reverse all the characters in the entire message
reverse_characters(message, 0, n-1)
# This gives us the right word order but with each word backward
# Now we'll make the words forward again by reversing each word's characters
# We hold the index of the *start* of the current word
# as we look for the *end* of the current word
current_word_start_index = 0
for i in range(n + 1):
# Found the end of the current word!
if i == n or message[i] == ' ':
reverse_characters(message, current_word_start_index, i - 1)
# If we haven't exhausted the message our
# next word's start is one character ahead
current_word_start_index = i + 1
def reverse_characters(message: list[str], left: int, right: int) -> None:
while left < right:
# Swap the left char and right char
message[left], message[right] = message[right], message[left]
left, right = left + 1, right - 1
| true |
21b13df050bb393416e65d2671f6d7928fb34f6a | ErickMwazonga/sifu | /math/reverse_integer.py | 738 | 4.21875 | 4 | '''
7. Reverse Integer
Link: https://leetcode.com/problems/reverse-integer/
Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Examples:
1. 123 -> 321
2. -123 -> -321
3. 120 -> 21
4. 0 -> 0
'''
def reverse(x: int) -> int:
sign = -1 if x < 0 else 1
x = abs(x)
reversed_x = 0
while x > 0:
x, rem = divmod(x, 10)
reversed_x = (reversed_x * 10) + rem
return reversed_x * sign
assert reverse(123) == 321
assert reverse(-123) == -321
assert reverse(120) == 21
assert reverse(0) == 0
| true |
229e22715ff921f6dde25bdc8aa8b034832e3abb | ErickMwazonga/sifu | /hashmaps/jewels_and_stones.py | 849 | 4.125 | 4 | '''
771. Jewels and Stones
Link: https://leetcode.com/problems/jewels-and-stones/
You're given strings J representing the types of stones that are jewels,
and S representing the stones you have.
Each character in S is a type of stone you have.
You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters.
Letters are case sensitive, so 'a' is considered a different type of stone from 'A'.
Example 1:
Input: J = 'aA', S = 'aAAbbbb'
Output: 3
Example 2:
Input: J = 'z', S = 'ZZ'
Output: 0
'''
def numJewelsInStones(J: str, S: str) -> int:
jewels = set(J)
count = 0
for stone in S:
if stone in jewels:
count += 1
return count
assert numJewelsInStones('aA', 'aAAbbbb') == 3
assert numJewelsInStones('z', 'ZZ') == 0
| true |
a160d41841365f6bc5537b472fb9f94df459bbee | ErickMwazonga/sifu | /binary_search/sqrt/sqrt.py | 1,343 | 4.15625 | 4 | '''
69. Sqrt(x)
Link: https://leetcode.com/problems/sqrtx/
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated
and only the integer part of the result is returned.
Write a function that takes a non-negative integer and returns
the largest integer whose square is less than or equal to
the integer given.
Example:
Assume input is integer 300.
Then the expected output of the function should be
17, since 17^2 = 289 < 300. Note that 18^2 = 324 > 300,
so the number 17 is the correct response.
'''
def integer_square_root(x):
low, high = 0, x
while low <= high:
mid = low + (high - low) // 2
if mid * mid == x:
return mid
elif mid * mid < x:
low = mid + 1
else:
high = mid - 1
return low - 1
def integer_square_root_v2(x: int) -> int:
low, high = 0, x
while low <= high:
mid = low + (high - low) // 2
mid_squared = mid ** 2
if mid_squared <= x and (mid + 1) ** 2 > x:
return mid
elif mid_squared < x:
low = mid + 1
else:
high = mid - 1
return low
assert integer_square_root(300) == 17
assert integer_square_root(16) == 4
assert integer_square_root(17) == 4
| true |
22a28928de9b7cd4513c0aed9dddcbded63314b1 | ErickMwazonga/sifu | /recursion/learning/count_occurrences.py | 692 | 4.25 | 4 | '''
Given an array of integers arr and an integer num,
create a recursive function that returns the number of occurrences of num in arr
Example
input -> [4, 2, 7, 4, 4, 1, 2], num -> 4
output = 3
'''
def countOccurrences(arr: list[int], num: int, i: int = 0):
if i == len(arr):
return 0
if arr[i] == num:
return 1 + countOccurrences(arr, num, i+1)
else:
return countOccurrences(arr, num, i+1)
def countOccurrences_v2(arr: list[int], num: int, i: int = 0, acc: int = 0):
if i == len(arr):
return acc
if arr[i] == num:
return countOccurrences(arr, num, i+1, acc+1)
else:
return countOccurrences(arr, num, i+1, acc)
| true |
458be929b5f24b02589aa291010b2f4b7ba882de | ErickMwazonga/sifu | /graphs/shortest_path.py | 1,563 | 4.125 | 4 | '''
shortest path
https://structy.net/problems/shortest-path
Write a function, shortestPath, that takes in an array of edges for an undirected graph and two nodes (nodeA, nodeB).
The function should return the length of the shortest path between A and B.
Consider the length as the number of edges in the path, not the number of nodes.
If there is no path between A and B, then return -1.
Example 1
edges = [
['w', 'x'],
['x', 'y'],
['z', 'y'],
['z', 'v'],
['w', 'v']
]
shortestPath(edges, 'w', 'z') -> 2
Example 2
edges = [
['w', 'x'],
['x', 'y'],
['z', 'y'],
['z', 'v'],
['w', 'v']
]
shortestPath(edges, 'a', 'e') -> 3
'''
from collections import defaultdict
class Solution:
def shortestPath(self, edges, nodeA, nodeB):
graph = self.adjacency_list(edges) # graph
visited = set(nodeA)
queue = [[nodeA, 0]]
while queue:
node, distance = queue.pop(0)
if node == nodeB:
return distance
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.push([neighbor, distance + 1])
return -1
def adjacency_list(self, edges):
graph = defaultdict(list)
for edge in edges:
a, b = edge
graph[a].append(b)
graph[b].append(a)
return graph
edges = [
['w', 'x'],
['x', 'y'],
['z', 'y'],
['z', 'v'],
['w', 'v']
]
soln = Solution()
assert soln.shortestPath(edges, 'a', 'e') == 3
| true |
6e64d56410b082881f0a2316e8011f1691333f80 | davidhansonc/Python_ZTM | /random_game.py | 946 | 4.15625 | 4 |
'''
* File Name : random_game.py
* Language : Python
* Creation Date : 05-01-2021
* Last Modified : Wed Jan 6 22:46:12 2021
* Created By : David Hanson
'''
from random import randint
def run_guess(guess, answer):
try:
if 1 <= int(guess) <= 10:
if int(guess) == int(answer):
print('Way to go!')
return True
else:
print("Nope, you're dumb, please try again.")
return False
else:
print('No, within the range please.')
return False
except ValueError as err:
return err
if __name__ == '__main__':
random_number = randint(1, 10)
while True:
try:
from_input = int(input('Guess a number between 1 and 10: '))
if run_guess(from_input, random_number):
break
except ValueError:
print("Please enter a number.")
continue
| true |
16465477947bb81b1ea52473ed2e77fa7cb329c6 | ON1y01/web-code-editor | /files/2.py | 592 | 4.3125 | 4 | #2
print('Задание 2. Данo натуральное число. Найдите остатки от деления этого числа на 3 и на 5.')
a = float (input ('Введите натуральное число: '))
while (a<0 or a%1 !=0):
print ('Вы ввели ненатуральное число')
a = float (input ('Введите НАТУРАЛЬНОЕ число: '))
if (a>0 and a!=0 and a%1==0):
b = a%3
c = a%5
print ('Ответ: остатки от деления числа', a, 'на 3 и на 5 равны:')
print (b)
print (c)
input ('') | false |
6fa0434dd00c0c40d6c22d5c8dbb8732f0e208d0 | mohit266/Python-course-Edugrad | /Edugrad_1.py | 458 | 4.125 | 4 | """
QUESTION 1:
Swap the case of the string that comes as an input and return the string while making sure that the first letter of the string stays Uppercase.
Example -
Input - "PyThON"
Output - "PYtHon"
"""
def main(i):
result = ""
for ch in range(len(i)):
if ch == 0:
result += i[ch].upper()
elif i[ch].islower():
result += i[ch].upper()
else:
result += i[ch].lower()
return result | true |
0b877c9ef0b1af75f29325827b3249ef230c8844 | Mattia-Tomasoni/Esercizi-Python | /es31.py | 1,271 | 4.4375 | 4 | '''
TESTO:
Fornisci la rappresentazione in binario di un numero decimale. Dopo aver acquisito il valor del Numero
da trasformare, si esegue la divisione del numero per 2 e si calcola quoziente e resto.Il resto è la prima
cifra della rappresentazione binaria ì. Si ripete il rpocedimento assegnando il quoziente ottenuto a
Numero e ricalcolando la divisione per 2; la ripetizione prosegue mentre il quoziente ottenuto si mantiene
diverso da 0. La rappresentazione binaria del numero decimale è costituita dalle cifre binarie
ottenute come resti, lette in ordine inverso.
Confronta poi il risultato con il valore ottenuto dalla funzione predefinita del linguaggio per convertire
un numero decimale in binario.
'''
print("ESERCIZIO 31")
print("Programma conversione decimale-binario")
numero_binario = []
numero_iniziale = int(input("Qual è il numero? "))
numero = numero_iniziale
while True:
divisione = numero / 2
meno = divisione - 0.1
n = round(meno, 0)
a = int(numero % 2)
if n == 0:
numero_binario.append(a)
break
else:
numero_binario.append(a)
numero = round(meno, 0)
numero_binario.reverse()
print("Questo è il numero decimale:", numero_iniziale)
print("Questo è il numero binario:", numero_binario) | false |
c2f4904730f474b18290c7fc549086c1666d5cbc | chiragnarang3003/assignment6 | /assign6.py | 2,982 | 4.375 | 4 | '''
#Question1:->Create a function to calculate the area of a sphere by taking radius from user.
'''
def area_sphere(num):
'''Calculate the area of the sphere using Fuctions'''
pi=3.14
temp=4*pi*num*num
return temp
radius=int(input("Enter radius of the sphere : "))
output=area_sphere(radius)
print("The area of the sphere is :",output)
print()
'''
#Question2:->Write a function “perfect()” that determines if parameter number is a perfect number.
Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.
[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself),
sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
'''
def perfect(num):
'''Print all the perfect numbers lies in range (1,1000) '''
result=0
temp=num
for i in range(1,num):
if (num%i==0):
result=result+i
if (result==temp):
print(temp)
for i in range(1,1001):
perfect(i)
print()
'''
#Question3:->Print multiplication table of n using loops, where n is an
integer and is taken as input from the user.
'''
def table(num):
'''Multiplication table of nth table'''
for i in range (1,11):
temp=num*i
print(num,'*',i,"=",temp)
num1=int(input("Enter the table value you want to see the table : "))
table(num1)
print()
'''
#Question4:->Write a function to calculate power of a number
raised to other ( a^b ) using recursion.
'''
def power(a,b):
'''Power of a number....(the output comes in return is of float value)'''
num2=a
if b==0:
return a/a
else:
return(a*power(a,b-1))
value=int(input("Enter a number : "))
power1=int(input("Enter power of a number : "))
print(power(value,power1))
#or(Method 2)
def power(a,b):
'''Power of a number....(the output comes in return is of integer value)'''
num2=a
if b==1:
return a
else:
return(a*power(a,b-1))
value=int(input("Enter a number : "))
power1=int(input("Enter power of a number : "))
print(power(value,power1))
print()
#CLASSES AND OBJECTS:-->
'''
#Question1:->Get keys corresponding to a value in user defined dictionary.
'''
dict1=eval(input("Enter a dictionary : "))
val=(input("Enter a key whose value you want to print : "))
for key,value in dict1.items():
if (value==val):
break;
print(key)
print()
'''
#Question2:->Create a dictionary and store student names and create nested dictionary to store the subject wise marks of every student.Print the marks of a given student from that ductionary for every subject.
'''
student={'Chirag':{'maths':50,'physics':60,'chem':90},'Bandita':{'maths':90,'physics':95,'chem':99},'Sakshi':{'maths':100,'physics':99,'chem':100},'Hursh':{'maths':85,'physics':30,'chem':90}}
k1=input("enter the name of student whose marks you want to see:")
for key,value in student.items():
if k1 == key:
print(value)
print()
| true |
e34cde867262e8ae91ddb55f5d5d2898e7d7eec7 | SebastianN8/calculate_pi | /calculate_pi.py | 1,312 | 4.34375 | 4 | #
# calculate_pi.py
#
# Created by: Sebastian N
# Created on: April 19
#
# This program calculates pi according to iterations
#
# This is where math.floor comes from
import math
# Function that contains the loop in order to get the result of a gregory leibniz series
def calculate_pi(iterations_passed_in):
# Variables that will carry the count in the loop, the resul of the addition and the result for pi.
the_iterations = 0
addition = 0
pi = 0
# If statement that takes care of filtering inputs such as 0 and decimal numbers.
if (iterations_passed_in == math.floor(iterations_passed_in)) and iterations_passed_in > 0:
for the_iterations in range (0, iterations_passed_in):
the_iterations_float = float(the_iterations)
addition = addition + math_calculation(the_iterations_float)
pi = (math.floor((addition * 4)*1000))/1000
print str(pi)
else:
print 'Invalid iterations'
# Function that does the math involved in the gregory leibniz addition to be looped in calculate_pi()
def math_calculation(exponent):
numerator = ((-1)**exponent)
denominator = numerator / ((2*exponent) + 1)
return denominator
# Variable that saves the iteration that the user wants
iterations = input('What are the number of iterations that you need: ')
# Calling function
the_result = calculate_pi(iterations)
| true |
f525f2bc24bb8d015a687a475ae0e136f2b28983 | ritesh2905/StringPractice | /05FindingSubstring.py | 205 | 4.125 | 4 | # Substring in a string
str1 = 'the quick brown fox jumps over the lazy dog'
str2 = input('Enter a substring : ')
if str2 in str1:
print('Sunsting is present')
else:
print('Substring not found')
| true |
2683b4888e1654b57783905aacbf7d79f21d145c | Priyankasgowda/90dayschallenge | /p50.py | 1,834 | 4.375 | 4 | # Activity Selection Problem | Greedy Algo-1
# Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem.
# If a Greedy Algorithm can solve a problem, then it generally becomes the best method to solve that problem as the Greedy algorithms are in general more efficient than other techniques like Dynamic Programming. But Greedy algorithms cannot always be applied. For example, Fractional Knapsack problem (See this) can be solved using Greedy, but 0-1 Knapsack cannot be solved using Greedy.
"""The following implementation assumes that the activities
are already sorted according to their finish time"""
"""Prints a maximum set of activities that can be done by a
single person, one at a time"""
# n --> Total number of activities
# s[]--> An array that contains start time of all activities
# f[] --> An array that contains finish time of all activities
def printMaxActivities(s , f ):
n = len(f)
print "The following activities are selected"
# The first activity is always selected
i = 0
print i,
# Consider rest of the activities
for j in xrange(n):
# If this activity has start time greater than
# or equal to the finish time of previously
# selected activity, then select it
if s[j] >= f[i]:
print j,
i = j
# Driver program to test above function
s = [1 , 3 , 0 , 5 , 8 , 5]
f = [2 , 4 , 6 , 7 , 9 , 9]
printMaxActivities(s , f) | true |
4c7d779f8dfcabda3e19ec33136ef11687926ea0 | Priyankasgowda/90dayschallenge | /p38.py | 1,548 | 4.25 | 4 | # Maximum Length Chain of Pairs | DP-20
# You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs.
# Source: Amazon Interview | Set 2
# For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }, then the longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}}
class Pair(object):
def __init__(self, a, b):
self.a = a
self.b = b
# This function assumes that arr[] is sorted in increasing
# order according the first (or smaller) values in pairs.
def maxChainLength(arr, n):
max = 0
# Initialize MCL(max chain length) values for all indices
mcl = [1 for i in range(n)]
# Compute optimized chain length values in bottom up manner
for i in range(1, n):
for j in range(0, i):
if (arr[i].a > arr[j].b and mcl[i] < mcl[j] + 1):
mcl[i] = mcl[j] + 1
# mcl[i] now stores the maximum
# chain length ending with pair i
# Pick maximum of all MCL values
for i in range(n):
if (max < mcl[i]):
max = mcl[i]
return max
# Driver program to test above function
arr = [Pair(5, 24), Pair(15, 25), Pair(27, 40), Pair(50, 60)]
print('Length of maximum size chain is',
maxChainLength(arr, len(arr)))
| true |
ad9ad5ca321ec835fb046ea810b261ae4323c592 | AlexanderTankov/HackBulgaria-Haskell | /Intro/03-NameMatching/taskThree.py | 761 | 4.15625 | 4 | CHAR_FOR_NEXT_SYMBOL = '^n'
NUMBERS = '1234567890'
def get_language():
result = ''
input_for_language = input()
for char in range(0, len(input_for_language)):
if input_for_language[char] == '^':
result += input_for_language[char - 1]
return result
def check_for_word():
language = get_language()
input_for_word = input()
flag = True
for elem in language:
if elem not in input_for_word and elem not in NUMBERS:
flag = False
for elem in input_for_word and elem not in NUMBERS:
if elem not in language:
flag = False
if flag:
return 'yes'
else:
return 'no'
def main():
print(check_for_word())
if __name__ == '__main__':
main()
| false |
703522416cba310ae0f9b3b3bdf8647a6188d445 | phamva/phamvietanh---fundamentals---D4E12 | /Session 4/homework/dict2.py | 369 | 4.15625 | 4 | number = [1, 6 , 8 , 1 , 2 , 1 , 5 , 6]
# Write a program to count number occurrences in a list with count()
# a = input("enter your number")
# occurrences = number.count(1)
# print(a , "appear" , occurrences , "times in my list",)
# without count
a = input("enter your number")
number_occurrences = int(0)
for x in number :
if x == a :
print(x)
| false |
14846edd4e097696ae93306aa20b91ff2c407736 | phamva/phamvietanh---fundamentals---D4E12 | /Session 2/Homework/homeworkBMI.py | 324 | 4.15625 | 4 | H = int(input("height"))
W = int(input("weight"))
CM = H/100
BMI = W/CM**2
print("BMI")
if BMI < 16:
print("Severely underweight")
elif BMI >= 16 and BMI <=18.5:
print("Underweight")
elif BMI >= 18.5 and BMI <= 25:
print("Normal")
elif BMI >= 25 and BMI <= 30:
print("Overweight")
else :
print("sdfsd")
| false |
e2ebb7ff00d992d713817b9b062f9f2807945802 | carloxlima/curso_python | /exercicio033.py | 1,339 | 4.125 | 4 | n1 = int(input("Digite um número: "))
n2 = int(input("Digite um segundo número: "))
n3 = int(input("Digite um ultimo número: "))
if n1 > n2 :
if n1 > n3:
if n3 > n2:
print("O primeiro número é o maior. N: {}".format(n1))
print("O segundo é o menor. N {}".format(n2))
else:
print("O primeiro número é o maior. N: {}".format(n1))
print("O terceiro número é o menor. N: {}".format(n3))
else:
print("O terceiro número é o maior, N: {}".format(n3))
print("O segundo númer é o menor. N: {}".format(n2))
else:
if n2 > n3:
if n3 > n1:
print("O segundo número é o maior. N {}".format(n2))
print("O primeiro número é o menor. N: {}".format(n1))
else:
print("O segundo número é o maior. N {}".format(n2))
print("O terceiro número é o menor. N: {}".format(n3))
else:
print("O terceiro número é o maior: N {}".format(n3))
print("O primeiro número é o menor. N {}".format(n1))
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
maior = n1
if n2 > n1 and n2 > n3:
maior = n1
if n3 > n1 and n3 > n2:
maior = n3
print("O menor número é {}".format(menor))
print("O maior número é {}".format(maior)) | false |
081e9ab63f45f82814274dd037af5a9ca22599ee | JoachimIsaac/Interview-Preparation | /arrays_and_strings/reordering_words_in_a_sentence.py | 2,806 | 4.3125 | 4 | """
Problem 3:
Reverse the ordering of words in a sentence.
For example:
Input: "The weather is amazing today!"
Output: "today! amazing is weather The"
UMPIRE:
Understand:
--> can we get an empty string? yes
--> can we get a single letter ? yes
--> so we need to reverse the entire sentence but keep the words in the correct order ? yes
match:
--> Two pointer
Plan(with split):
--> we need to split the string into an array so that each word is in an index
--> we then need to reverse all the words
--> and return the joined array
time complexity :O(n) where n is the length of the input string
and space is O(n)
Plan(without split ):
1. we need to check if the string is empty
2. we need to check if the string is of length 1
3. if the string is not one of these two lengths we need to split it into an array not ignoring the white spaces, so we could just append all the characters into an array .
4. we need to then reverse the entire thing
6. then we need to traverse this array and get the start and end points of each word, when we get these we reverse them.
7. after reversing all the words and ignoring the white space we need to join the array to a string and return the answer.
time complexity :O(n) where n is the length of the input string
and space is O(n)
"""
class Solution:
def reordering_words_in_a_sentence1(self, sentence): # with split
if len(sentence) == 0:
return sentence
if len(sentence) == 1:
return sentence
sentence_array = sentence.split(' ')
self.reverse_array(0, len(sentence_array) - 1, sentence_array)
return " ".join(sentence_array)
def reordering_words_in_a_sentence2(self, sentence):
if len(sentence) == 0:
return sentence
if len(sentence) == 1:
return sentence
sentence_array = []
for letter in sentence:
sentence_array.append(letter)
self.reverse_array(0, len(sentence_array) - 1, sentence_array)
print(sentence_array)
start = 0
end = 0
while end < len(sentence_array):
if sentence_array[end] == " ":
self.reverse_array(start, end - 1, sentence_array)
start = end + 1
if end == len(sentence_array) - 1:
self.reverse_array(start, end, sentence_array)
end += 1
return ''.join(sentence_array)
def reverse_array(self, start, end, array):
while start < end:
array[start], array[end] = array[end], array[start]
start += 1
end -= 1
solution = Solution()
print(solution.reordering_words_in_a_sentence1("The weather is amazing today!"))
print(solution.reordering_words_in_a_sentence2("The weather is amazing today!"))
| true |
9ede3d57572351010d154f023ef131ca957316e8 | JoachimIsaac/Interview-Preparation | /LinkedLists/86.PartitionList.py | 1,986 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
UMPIRE:
--> we are getting a singlely linked list
--> the calue x is asusumed to always be there
--> what if we get an empty linked list (just return it ) same with one with only 1 value
--> keep the original order of the numbers
Input: head = 1------>4------>3----->2----->5----->2, x = 3
c
half less than and half greater than:
half less than: dummy---->1-->2-->2
half greater than or equal to: dummy--->4-->3--->5--->
Output: 1->2->2->4->3->5
attach the less than to the greater than
dummy.next = half greater than or equal to
result after fusion: dummy---->1-->2-->2--->4-->3--->5--->None
1-->2-->None n = 2
dummy--> 1
dummy-->2
head --> none :
return none
match:
--> dummy node
--> multi pass
--> out of place / inplace
--> use references
-->
"""
class Solution:
def partition(self, head, x): # Time O(n) and O(1) space
if head == None:
return None
if head.next == None:
return head
lessThan = dummy1 = ListNode(-1)
greaterOrEq = dummy2 = ListNode(-1)
"""
Input: head = 1------>4------>3----->2----->5----->2, x = 3
c
dummy1-->1-->2-->2--->None
dummy2-->4-->3-->5--->None
"""
curr = head
while curr:
if curr.val < x:
dummy1.next = curr
dummy1 = dummy1.next
curr = curr.next
else:
dummy2.next = curr
dummy2 = dummy2.next
curr = curr.next
# make sure the end of the greater than or equal to list ends with null.
dummy2.next = None
dummy1.next = greaterOrEq.next # connect each of them
return lessThan.next
| true |
58cb43bc2a31cdc0f4533666686ebff5e559d521 | TahirCanata/Class4-CS101Module-Week9 | /Stack2.py | 1,864 | 4.3125 | 4 |
class Stack: #2 Class kullaniyoruz, Stack Classinda, Class queue methodlarini kullaniyoruz
def __init__(self): #Esasen cikarma islemi disinda fark yok
self.q = Queue() #Stackte en son gireni ilk cikarmak icin dequeu ve enqueue islemlerini kullaniyoruz
def empty(self):
print(self.q.empty())
def push(self, data):
self.q.enqueue(data)
print(data, "is pushed")
def pop(self):
for element in range(self.q.get_size() - 1): # toplam eleman sayisinin bir eksigi kadar cikarma ve cikani tekrar ekliyoruz
dequeued = self.q.dequeue() # dequeuing
self.q.enqueue(dequeued) # cikani tekrar ekliyoruz, ta ki son giren eleman en one gelinceye kadar
print("{} is popped".format(self.q.dequeue())) # Simdi en yeni giren eleman en one gecti ve dequeue islemi ile cikariliyor
# ama eklenmiyor, for dongusu disinda
def size(self):
print("{} is the number of elements in stack".format(self.q.get_size()))
def top(self):
if not self.q.empty():
print("{} is head of stack".format(self.q.top()))
else:
print("No Elements in Stack!!!")
class Queue:
def __init__(self):
self.items = []
self.size = 0
def top(self):
return (self.items[-1])
def empty(self):
return (self.items == [])
def enqueue(self, data):
self.size += 1
self.items.append(data)
def dequeue(self):
self.size -= 1
return self.items.pop(0)
def get_size(self):
return self.size
s = Stack()
s.push(22)
s.push(33)
s.push(44)
s.push(55)
s.push(66)
s.size()
s.top()
s.pop()
s.pop()
s.pop()
s.empty()
s.size()
s.top() | false |
6db5b0a035b58bd2cf1e2ec243591726cf5beced | prajjwolmondal/Rock-Paper-Scissors | /rps.py | 2,148 | 4.46875 | 4 | # This is a rock paper scissors game in Python
#Goal
#Ask the player if they pick rock paper or scissors
#Have the computer chose its move
#Compare the choices and decide who wins
#Print the results
#Subgoals
#Let the player play again
#Keep a record of the score e.g. (Player: 3 / Computer: 6)
import random
def user_choice():
c = (raw_input("Please pick your move: ").lower());
if ((c != "rock") and (c != "paper") and (c !="scissors")):
print "Pick either rock, paper or scissors";
c = user_choice();
return c;
def comparing(user,comp):
u_score = 1;
c_score = 0;
if (user == comp):
print "It's a draw!"
return 2;
if ((user == "rock") and (comp == "paper")):
print "Computer wins this round."
return c_score;
elif ((user == "rock") and (comp == "scissors")):
print "You win this round."
return u_score;
if ((user == "paper") and (comp == "rock")):
print "You win this round."
return u_score;
elif ((user == "paper") and (comp == "scissors")):
print "Computer wins this round."
return c_score;
if ((user == "scissors") and (comp == "paper")):
print "You win this round."
return u_score;
elif ((user == "scissors") and (comp == "rock")):
print "Computer wins this round."
return c_score;
def main():
print "Welcome to my Rock Paper Scissors program.";
cont = "yes";
user_score = 0;
comp_score = 0;
while (cont == "yes"):
choice = user_choice();
comp_int = (int)(random.randint(1,3));
#For debugging: print "Choice of numb is "+str(comp_int);
choices = {'1': 'rock', '2': 'scissors', '3': 'paper'};
comp_choice = choices[str(comp_int)];
print "You played: "+choice;
print "Computer plays: "+comp_choice;
a = comparing(choice, comp_choice);
if (a==1):
user_score +=1;
elif (a==0):
comp_score +=1;
cont = raw_input("Another game?(yes/no) ").lower();
print "Player: "+str(user_score)+" / Computer: "+str(comp_score);
main()
| true |
70274cd39aa0d24b2209df12a3ef8b601bcc0e5a | suziW/myLeetCode | /155.py | 990 | 4.21875 | 4 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minRecord = [float('inf')]
def push(self, x: int) -> None:
self.stack.append(x)
if x <= self.minRecord[-1]:
self.minRecord.append(x)
print(self.stack, self.minRecord)
def pop(self) -> None:
x = self.stack.pop()
if x == self.minRecord[-1]:
self.minRecord.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.minRecord[-1]
if __name__ == "__main__":
# Your MinStack object will be instantiated and called as such:
minStack = MinStack() #
minStack.push(-2) #
minStack.push(0) #
minStack.push(-3) #
r1 = minStack.getMin() # --> 返回 -3.
minStack.pop() #
r2 = minStack.top() # --> 返回 0.
r3 = minStack.getMin() # --> 返回 -2.
print(r1, r2, r3)
| false |
4339bebc75fb603808739f5289ece703c2bbeaaf | ram4ibm/codeworks | /challenge3/dict_of_dict_value.py | 1,310 | 4.25 | 4 | #!/usr/bin/env python
# Incomplete : 40 min
# VARIABLES
#input_nested_var = dict(input("Enter the Nested input object: "))
#input_nested_key = input("Enter the Nested input key: ")
#input_nested_var = {"a": {"b": {"c": "d"}}}
input_nested_var = {"a": {"b": {"c": {"d": "e"}}}}
#input_nested_var = {"a": {"b": {"c": {"d": {"e": "f"}}}}}
# INITIALIZE FUNCTION VARS FOR COUNT AND ITEM
dictionary_values = 0
count_dict_items = input_nested_var
find_dict_item = input_nested_var
# MAIN
# Function to get value in a key a value pair
def get_dict_value(dictionary_input):
for (d_key, d_value) in dictionary_input.items():
return d_value
# Function to get the total no of values
def get_dict_value_count(dictionary_input):
if not isinstance(dictionary_input, str): # LAST VALUE wont be a dictionary
return get_dict_value(dictionary_input)
# CALL
# STEP 1: Count Dictionary Items
while count_dict_items:
count_dict_items = get_dict_value_count(count_dict_items)
dictionary_values = dictionary_values + 1
# STEP 2: Find the dict item
for key_value_to_display in range( dictionary_values - 1 ):
find_dict_item = get_dict_value(find_dict_item)
if key_value_to_display == ( dictionary_values - 2 ): # Display the key's value
print(find_dict_item)
| true |
2476666d622309d940c03489242121a701127610 | KolluriMounish/Python-problem-Solving | /problem_1.py | 893 | 4.4375 | 4 | #TODO: Given an array containing unsorted positive or negative integers with repeated
# values, you must arrange the array in such a way that all non-zeroes should be on the left-
# hand side of an array, and all zeroes should be on the right side of the array. Order of non-
# zero elements does not matter. You are not allowed to use any sorting approach.
def ordering_array(input_list):
final_list=[]
for value in input_list:
if value == 0: # if the given element is "ZERO" append it at the end of the list
final_list.append(value)
else: # if the given element is "non_zero" value then insert it in the front side of the list
final_list.insert(0,value)
return final_list
input_list = [1, 2, -4, 0, -1, 0, 3, 7, 0, 5, 0, 1, -1, 0]
resulted_list = ordering_array(input_list)
print(resulted_list) | true |
6b1dd83d8d95cc518483ec2ff963631702ca00aa | Malbshri/malbshri | /day 30.py | 741 | 4.15625 | 4 | Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # week 5
>>> # day 30
>>>
>>> for x in range (6) :
print(x)
0
1
2
3
4
5
>>>
>>> for x in range (2, 6) :
print(x)
2
3
4
5
>>>
>>> for x in range (2, 30, 3) :
print(x)
2
5
8
11
14
17
20
23
26
29
>>>
>>> for x in range (6) :
print(x)
else :
print("Finally finished!")
0
1
2
3
4
5
Finally finished!
>>>
>>> adj = ["red", "big", "tasty"]
>>> fruits = ["apple", "banana", "cherry"]
>>> for x in adj :
for y in fruits :
print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
>>>
>>>
| false |
bc25e8e24dccca506cbce23efa340fa6470f2b68 | Malbshri/malbshri | /lesson 59.py | 880 | 4.1875 | 4 | import re
#Replace all white-space charactor with the digit "9":
str = "The rsin in Spain"
x = re.sub("\s", "9", str)
print(x)
import re
#Replace the first two occurrence of white-space charactor with the digit 9"
str = "The rain in Spain"
x = re.sub("\s", "9", str, 2)
print(x)
import re
#The search() function returns a Mach object:
str = "The rain in Sapin"
x = re.search("ai", str)
print(x)
import re
#Search for an upper case "S" character in the beginning of a word, and print its position:
str = "The rain in Spain"
x = re.search(r"\bS\w+", str)
print(x.span())
import re
#The string property returns the search string:
str = "Thr rain in Spain"
x = re.search(r"\bS\w+", str)
print(x.string)
import re
#Search for an upper case "S" character in the beginning of a word, and print the word:
str = "Thr rain in Spain"
x = re.search(r"\bS\w+", str)
print(x.group())
| true |
9857a478ff0a80d9962a333bb2afe8f294694d0e | CleverOscar/python-udemy | /exercise/conditional.py | 893 | 4.25 | 4 | ## -*- coding: utf-8 -*-
#x = 5
#y = 6
#
#print('x =',x,'y =', y)
#print('X is less than Y:', x<y)
#print('X is greater than Y:',x>y)
#
#var_1 = 7
#var_2 = 7
#
#print('Var_1:', var_1, 'Var_2:', var_2)
#print(var_1 < var_2)
#print(var_1 > var_2)
#print(var_1 == var_2)
#print(var_1 <= var_2)
#print(var_1 >= var_2)
#print(var_1 != var_2)
#
#
##if statement practice
#
#some_condition = True
#
#if some_condition:
# print('The variable some_condition is TRUE')
#else:
# print('The variable some_condition is False')
#
#
#temp = int(input('Please enter the temperatue in Celsius. An integer between 0-40:>>>'))
#
#if temp > 30:
# print('It is warm outside!')
#elif temp <= 30 and temp > 20:
# print('It is warm but no time to wear shorts!')
#elif temp <= 20 and temp > 10:
# print('You will probably need a coat!')
#else: print('TOO COLD OUT!')
my_string = 'Python'
| true |
3bd04acf2d465c96e2914be6ade4d9283c7b72ec | cyndichin/DSANano | /Data Structures/Recursion/Deep Reverse.py | 1,749 | 4.71875 | 5 | #!/usr/bin/env python
# coding: utf-8
# ## Problem Statement
#
# Define a procedure, `deep_reverse`, that takes as input a list, and returns a new list that is the deep reverse of the input list.
# This means it reverses all the elements in the list, and if any of those elements are lists themselves, reverses all the elements in the inner list, all the way down.
#
# >Note: The procedure must not change the input list itself.
#
# **Example**<br>
# Input: `[1, 2, [3, 4, 5], 4, 5]`<br>
# Output: `[5, 4, [5, 4, 3], 2, 1]`<br>
#
# **Hint**<br>
# 1. Begin with a blank final list to be returned.
# 2. Traverse the given list in the reverse order.
# * If an item in the list is a list itself, call the same function.
# * Otheriwse, append the item to the final list.
#
# ### Exercise - Write the function definition here
# In[17]:
def deep_reverse(arr):
pass
# <span class="graffiti-highlight graffiti-id_25r0ar8-id_l0hi76f"><i></i><button>Show Solution</button></span>
# ### Test - Let's test your function
# In[16]:
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]
output = deep_reverse(arr)
if output == solution:
print("Pass")
else:
print("False")
# In[ ]:
arr = [1, 2, 3, 4, 5]
solution = [5, 4, 3, 2, 1]
test_case = [arr, solution]
test_function(test_case)
# In[ ]:
arr = [1, 2, [3, 4, 5], 4, 5]
solution = [5, 4, [5, 4, 3], 2, 1]
test_case = [arr, solution]
test_function(test_case)
# In[ ]:
arr = [1, [2, 3, [4, [5, 6]]]]
solution = [[[[6, 5], 4], 3, 2], 1]
test_case = [arr, solution]
test_function(test_case)
# In[ ]:
arr = [1, [2,3], 4, [5,6]]
solution = [ [6,5], 4, [3, 2], 1]
test_case = [arr, solution]
test_function(test_case)
| true |
01d65dd447d6bf558e67cc65829446c92eb62c8d | Ham5terzilla/python | /4th Lesson/Ex7.py | 672 | 4.125 | 4 | # Заполнить массив из 5 элементов случайными числами в интвервале -100 100. Найти сумму всех отрицательных элементов
# массива. Если отрицательных элементов массива нет, вывести собщение "отрицательных элементов нет".
from random import *
def randomm():
lst = [int(random() * 200 - 100) for i in range(5)]
s = sum([i for i in lst if i < 0])
if s == 0:
print("Отрицательных элементов нет")
else:
print(s)
for i in range(100):
randomm() | false |
abebd06788fd47dbab9773fc1f64e100de2476e2 | ATLS1300/pc04-generative-section12-kaily-fox | /PC04_GenArt.py | 2,262 | 4.125 | 4 | """
Created on Thu Sep 15 11:39:56 2020
PC04 start code
@author: Kaily Fox
********* HEY, READ THIS FIRST **********
My image is of a star and a moon in the night sky. I decided to do this
because the sky is one of my favorite parts of nature. Its' beauty is so
simplistic yet breath taking. The natural phenomenas that occur in the sky
never fail to amaze and calm me.
"""
import turtle
import math, random
turtle.colormode(255)
# turtle.tracer(0) # uncomment this line to turn off turtle's animation. You must update the image yourself using panel.update() (line 42)
# Create a panel to draw on.
panel = turtle.Screen()
w = 700 # width of panel
h = 700 # height of panel
panel.setup(width=w, height=h) #600 x 600 is a decent size to work on.
#You can experiment by making
# You must make 2 turtle variables
# You must use 2 for loops (a nested for loop counts as 2!)
# You must use at least 1 random element (something from the random library)
# Don't forget to comment your code! (what does each for loop do? What does the random function you'll use do?)
# =============== ADD YOUR CODE BELOW! =================
#set up star turtle
star = turtle.Turtle()
star.up()
star.speed(10)
star.goto(random.randint(-150,150),random.randint(-150,150))
star.color("yellow")
star.pensize(8)
star.begin_fill()
star.down()
#create loop for star
numInt=int(15)
for i in range(numInt):
star.forward(100)
star.right(144)
star.end_fill()
star.up()
#set up moon turtle
moon = turtle.Turtle()
moon.up()
moon.goto(random.randint(-150,150),random.randint(-150,150))
moon.color("grey")
moon.pensize(15)
moon.down()
moon.begin_fill()
moon.circle(20)
moon.end_fill()
moon.up()
#create craters for moon
moon.forward(20)
moon.down()
moon.color("white")
moon.pensize(2)
moon.begin_fill()
#create loop for craters
numInt=int(4)
for i in range(numInt):
moon.circle(3)
moon.up()
moon.forward(5)
moon.right(5)
moon.end_fill()
turtle.done()
# panel.update() # uncomment this if you've turned off animation (line 26). I recommend leaving this outside of loops, for now.
# =================== CLEAN UP =========================
# uncomment the line below when you are finished with your code (before you turn it in)
# turtle.done()
| true |
bd70add033e41749a61588e508b6bf8779cab5e2 | LuceroLuciano/bonitoDevoradorDePalabras | /funcionInput.py | 1,228 | 4.21875 | 4 | #print("Tell me something...")
#something = input()
#print("Mmm...", something, "...really?")
#the fuction input() whit an argument
"""
something = input("Tell me something...")
print("Mmm...", something, "...Really?")
"""
#Calculado la hipotenusa con vlores ingrsados
""""
cateto_a = float(input("Inserta la longitud del primer cateto: "))
cateto_b = float(input("Inserta la longitud del segundo cateto: "))
hipotenusa = ((cateto_a ** 2 + cateto_b ** 2) ** .5)
print("La longitud de la hipotenusa es: ", hipotenusa)
"""
# Encontrar el tiempo final de un periodo de
# tiempo dado, expresandolo en horas y minutos.
# Las horas van de 0 a 23 y los minutos de 0 a 59
hora = int(input("Hora de inicio (horas): "))
min = int(input("Minuto de inicio (minutos): "))
dura = int(input("Duración del evento (minutos): "))
#convesion de horas a minutos
# 1 hr = 60 min
tiempo_final_minutos = (min + dura)
conversion_minutos_a_horas = (tiempo_final_minutos % 60)
horas = ((tiempo_final_minutos // 60) + hora)
conversion_horas_a_minutos = (horas % 24)
tiempo_final = (conversion_horas_a_minutos, ":", conversion_minutos_a_horas)
print(tiempo_final)
print(str(conversion_horas_a_minutos) + ":" + str(conversion_minutos_a_horas))
| false |
1202fa13f40bb0f3d5138213af0ce12798beb6d0 | alexdemarsh/gocode | /blogmodel.py | 2,498 | 4.5 | 4 |
'''
Blog Model
Create a class to interface with sqlite3. This type of object is typically called a Model.
The table in sqlite3 will have two columns: post_name and post_text
Discuss with your neighbour on how to solve this challenge.
To connect Python to SQL, reference the following:
http://www.pythoncentral.io/introduction-to-sqlite-in-python/
Your model should be able to:
1) Open a sqlite3 db connection
2) Close the connection
3) Create a new table with the correct fields
4) Perform CRUD actions on the database table
C - Create
R - Read
U - Update
D - Destroy
'''
import sqlite3
class BlogModel():
def __init__(self,db_file):
self.db_file = db_file
self.post_name = None
self.post_text = None
def open(self):
"open sqlite3 db connection"
self.db = sqlite3.connect(self.db_file)
def close(self):
"close the connection to sqlite3"
self.db_file.close()
def create_table(self):
#create the table
cursor = self.db.cursor()
cursor.execute('''CREATE TABLE blogdb(id INTEGER PRIMARY KEY, post_name TEXT,
post_text TEXT)
''')
self.db.commit()
def create(self, post_name, post_text):
#create a new row with data that you pass in
cursor = self.db.cursor()
cursor.execute('''INSERT INTO blogdb(post_name, post_text)
VALUES(?,?)''', (post_name, post_text))
self.db.commit()
print 'Post created'
def read(self,id):
# "search for id, and return post_name and post_text as a string"
cursor = self.db.cursor()
cursor.execute('''SELECT post_name, post_text FROM blogdb WHERE id=?''', (id,))
post = cursor.fetchone()
for i in post:
print i
def update(self, id, post_name, post_text):
# "search for id, and set a new post_name and post_text"
cursor = self.db.cursor()
cursor.execute('''UPDATE blogdb SET post_name = ?, post_text = ? WHERE id = ? ''', (post_name, post_text, id))
self.db.commit()
def destroy(self,id):
#"search for id, and delete that row"
cursor = self.db.cursor()
cursor.execute('''DELETE FROM blogdb WHERE id = ? ''', (id,))
self.db.commit()
test_db = BlogModel("first_db.db")
test_db.open()
test_db.create("First Post!", "All the words!")
test_db.read("1")
test_db.update("1", "Better first post", "still more words!")
test_db.read("1")
| true |
3c07f4c0549d6d02ca7ca975b83af3943f3dd12b | STMcNamara/cs50-Problems | /pset6/vigenere/vigenere.py | 1,462 | 4.1875 | 4 | import sys
from cs50 import get_string
# Define a main function to allow returns
def main():
# Return 1 if incorrect number of arguments provided
if len(sys.argv) != 2:
print("Please provide one command line argument only")
sys.exit(1)
# Return 1 if the key is not letters ony
key = sys.argv[1]
if not key.isalpha():
print("Please provide only alphabetical characters")
sys.exit(1)
# Convert key to list of shifts
key = key.lower()
keylist = []
for i in key:
keylist.append(ord(i) - 97)
# Get string of plain text from the user
plaintext = get_string("plaintext: ")
ciphertext = ""
shiftpos = 0
shiftlen = len(keylist)
# For each i in plaintext:
for i in plaintext:
# If a letter:
if i.isalpha():
# Calculate the shift
shift = keylist[shiftpos]
# Check if shift needs to loop back
if ord(i.lower()) + shift > 122:
ciphertext += chr(ord(i) + shift - 26)
else:
ciphertext += chr(ord(i) + shift)
# Increment shift position
if shiftpos + 1 == shiftlen:
shiftpos = 0
else:
shiftpos += 1
# If not a letter append the symbol
else:
ciphertext += i
# Print the ciphertext
print(f"ciphertext: {ciphertext}")
if __name__ == "__main__":
main() | true |
2d499a16ab2c0af88d8fe1dc1bb1f755cc1fe0b3 | awsaavedra/coding-practice | /python/practice/2ndEditionLearningPythonTheHardWay/ex32.py | 492 | 4.125 | 4 | # creating non-empty arrays
the_count = [1, 2, 3, 4, 5]
fruits = ["Apples", "Oranges", "Tangerines", "Pears"]
change = [1, "two", 3, "four"]
for number in the_count:
print "This number %d " % number
for fruit in fruits:
print "This fruit: %s" % fruit
for i in change:
print "I got %r" %i
elements = []
for i in range(0,6):
print "Adding %d to the list." %i
elements.append(i) #append function:
#Now we can print them out too
for i in elements:
print "The element was %d" % i | true |
1f838acbcd6fc68280d7425dab45414467815a0e | awsaavedra/coding-practice | /python/practice/2ndEditionLearningPythonTheHardWay/ex15.py | 423 | 4.15625 | 4 | filename = raw_input("Please give me the filename you would like to open:")
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "I'll also ask you to type it again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt.close() #How do I use this .close() method goddamn it?
txt_again.close()
print "What is the close variable boolean value?" + closed | true |
cf27a6755dde266d83965d3bf01f2c9e8ef238cc | nalisharathod01/Python-Practice | /Python Programming/Integers.py | 833 | 4.28125 | 4 | #intergers
integerNumber = 1
intNum = 2
floatNumbers = 1.0
secondFloat = -229.0
print(integerNumber)
print(intNum)
print(floatNumbers)
#find types of the strings
string = "hello"
print(type(string))
print(type(secondFloat))
#only multiplication can be done with integers and string
#integers operations
#with division we get floating even if you give two integers
# ** to the power ^
print(1+1,1-1,1*8,25/3, 12**2 , 7%9)
print((2*3)**2)
#Boolean
trueBool = True
falseBool = False
print(trueBool)
print(falseBool)
print(floatNumbers == secondFloat)
print(floatNumbers != secondFloat)
print(trueBool == falseBool)
print(trueBool != falseBool)
print(integerNumber == floatNumbers)
print(type(integerNumber) == type(floatNumbers))
print (integerNumber > secondFloat)
print(floatNumbers < secondFloat)
age = 40
print(age > 25)
| true |
c0a2c9e9293a663314aca23381c1499ff53947ae | nalisharathod01/Python-Practice | /Python Programming/ifStatements.py | 1,007 | 4.21875 | 4 | #if condition:
#doApproritateThing
#elif differentCondition: #else of
#doMoreStuff
#elif condition3:
# morestuff
#else:
#doBaseCase/FallBack
number = 6
if number == 7:
print ("this number is 7")
elif type(number) == type(7):
print("same Type")
elif number ==6:
print("this is number 6")
else:
print("this is not a number nothing")
for num in range(10):
print(num)
if num%3 == 0:
print("Divisible by 3")
elif num%2 == 0:
print("Divisible by 2")
else:
print("Not divisible by 2 or 3")
#something in something
#something not in something
greeting = "Hello World"
checkWord = "Hello"
notCheck = "Good-Bye"
if checkWord in greeting:
print("This is a Greeting")
else:
print("this is not a Greeting")
if notCheck not in greeting:
print("This not a Greeting")
else:
print("this is a Greeting")
if True:
print("True")
else:
print("False")
| true |
14fdb7bfed2aaeb14425d81d9c5273d2e08ce3d3 | adriaanbd/data-structures-and-algorithms | /Python/data-structures/linked-lists/is_circular.py | 1,185 | 4.28125 | 4 | from singly_linked_list import LinkedList
def is_circular(linked_list: LinkedList) -> bool:
"""
Determine wether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
slow_runner = linked_list.head
fast_runner = linked_list.head
while fast_runner.next and fast_runner.next.next:
if slow_runner.next == slow_runner:
return True
fast_runner = fast_runner.next.next
slow_runner = slow_runner.next
if slow_runner == fast_runner:
return True
return False
list_with_loop = LinkedList([2, -1, 3, 0, 5])
# Creating a loop where the last node points back to the second node
loop_start = list_with_loop.head.next
node = list_with_loop.head
while node.next:
node = node.next
# last node points to head.next
node.next = loop_start
# Test Cases
print("Pass" if is_circular(list_with_loop) is True else "Fail")
print("Pass" if is_circular(LinkedList([-4, 7, 2, 5, -1])) is False else "Fail")
print("Pass" if is_circular(LinkedList([1])) is False else "Fail")
| true |
6e3b2f1686fd54223fe0474b6e250c6d2cd642b1 | brandonkwleong/coding-practice | /sorting/quick-sort.py | 2,701 | 4.3125 | 4 | #/opt/bin/python
"""
QUICK SORT
This script implements the quicksort algorithm.
Quicksort requires the 'partition' method, which is described below.
(Merge sort requires the 'merge' method).
Time Complexity:
O(n * log(n))
Worst case: O(n^2), depending on how the pivots are chosen
Note that in the general case, this algorithm works on average, better
than mergesort and does it in a space efficient manner (in-place).
Space Complexity:
O(n)
"""
def partition(array, left, right):
""" Partition the array
Inputs: (1) [LIST] List to sort
(2) [INTEGER] Left most index of the list
(3) [INTEGER] Rigth most index of the list
Outputs: [INTEGER] Index of the pivot
Description:
This method picks the right most value as the 'pivot'.
It then moves every value that is less than or equal to the
pivot the left of the pivot and everythin that is greater
to the right of the pivot.
It will return the correct place of where the pivot should be.
"""
pivot = array[right]
leftMark = 0
rightMark = right - 1
done = False
while done == False:
# Traverse right until a swap candidate is found
while leftMark <= rightMark and array[leftMark] <= pivot:
leftMark += 1
# Traverse left until a swap candidate is found
while rightMark >= leftMark and array[rightMark] >= pivot:
rightMark -= 1
if leftMark > rightMark:
done = True
else:
# Swap left & right marks
array[leftMark], array[rightMark] = array[rightMark], array[leftMark]
# Put the pivot in the rightful place
# Which is where the "Left Marker" is
array[leftMark], array[right] = array[right], array[leftMark]
return leftMark
def quicksort(array, left, right):
""" The Quicksort Algorithm
Inputs: (1) [LIST] List to be sorted
(2) [INTEGER] Left most index (typically: 0)
(3) [INTEGER] Right most index (typically: len(array)-1
Outputs: [LIST] Sorted list
Description:
The main algorithm after implementing partition.
(1) Base Case: When the 'left' is greater than 'right'
--> Return the array
(2) Partition
(3) Call quicksort on left half
(4) Call quicksort on right half
"""
if left > right:
return array
partitionIndex = partition(array, left, right)
quicksort(array, left, partitionIndex-1)
quicksort(array, partitionIndex+1, right)
return array
# ========== TESTING ==========
array = [1,7,3,5,9,2,4,8]
print(quicksort(array, 0, len(array)-1))
| true |
6308212919ba70665bb36456607cbaf77b90e49a | aah/project-euler | /python/e002.py | 1,410 | 4.125 | 4 | #!/usr/bin/env python3
"""Even Fibonacci Numbers
Project Euler, Problem 2
http://projecteuler.net/problem=2
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
"""
from e001 import bounded
def sum_even_fibs_with_values_below(n):
"""Sums all even-valued Fibonacci numbers with values below n.
>>> sum_even_fibs_with_values_below(55) == sum([2, 8, 34]) == 44
True
"""
return sum(bounded(even(fibs()), n))
def even(l):
"""Collects the even-valued elements of a list l.
>>> [i for i in even(range(10))]
[0, 2, 4, 6, 8]
"""
return filter(is_even, l)
def is_even(n):
"""Returns True if an integer is even.
>>> [is_even(i) for i in range(1, 6)]
[False, True, False, True, False]
"""
return not n & 1
def fibs(a=1, b=1):
"""Generates Fibonacci numbers.
>>> from itertools import islice
>>> [i for i in islice(fibs(), 11)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
"""
while True:
yield a
a, b = b, a + b
def main():
print(sum_even_fibs_with_values_below(4000000))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| true |
cd8c6c803c3d603ae3fd5363308bf6a85a8a9701 | isrt09/Python_Problem_Solving_Exercises | /Python with 70+ Problems/Dictionary.py | 1,394 | 4.125 | 4 | # Dictionary Part 1(Do this exercise in computer)
# Do the following
1.Create a dictionary which consist of Item(keys) and Quantity(values) of items in the shop.
Items Quantity
soap 10
bread 5
shampoo 8
2.Create another dictionary which consist of Item(Keys) and Price(values) of the items in the shop
Items Price
soap 20.50
bread 25.99
shampoo 80
3.Display the item with quantity and the cost of item in a single line like
The shop have 10 quantities of soap which cost 20.50 USD each.
# Dictionary Part 2 (Do this exercise in computer)
# do the following
1.Display only the subjects that are in dict1.
2.Display only the marks scored by student.
3.Delete the subject in which he got low marks and display the dictionary.
4.Change the mark scored in English to 24 and display the dictionary.
5.Now try to get the value of the history if not available print proper message.1
# Dictionary Part 3 (Do this exercise in computer)
# do the following
1. Add two dictionary and assign it to dict3 Display the dict3
2. Clear the dictionary dict2 Display the dict2
3. Delete the dictionary dict1.
4.Get input from the user and print the score in that subject if not available print proper message. (user input can be of any case.) | true |
b4d5f1f31f567a1b5b6fa573c9af39767425ab80 | willmartell/pyexercises | /100ex_28.py | 228 | 4.125 | 4 | """define a function that can accept two strings as input and concatenate them and then print it in the console"""
string1 = "hello"
string2 = "world"
def concat_str(s1,s2):
return s1+s2
print concat_str(string1,string2)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.