blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7482d942e97a74847cbcdccf6e4809450238e845 | greenfox-velox/bizkanta | /week-04/day-03/08.py | 523 | 4.1875 | 4 | # create a 300x300 canvas.
# create a square drawing function that takes 2 parameters:
# the x and y coordinates of the square's top left corner
# and draws a 50x50 square from that point.
# draw 3 squares with that function.
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
def draw_square(x, y):
return canvas.create_rectangle(x, y, x + 50, y + 50, fill='green')
print(draw_square(20, 20))
print(draw_square(140, 40))
print(draw_square(120, 130))
root.mainloop()
| true |
a35413038dc25063fa1bda9bf93a868010510ce9 | greenfox-velox/bizkanta | /week-03/day-02/functions/39.py | 250 | 4.1875 | 4 | names = ['Zakarias', 'Hans', 'Otto', 'Ole']
# create a function that returns the shortest string
# from a list
def shortest_str(list):
short = list[0]
for i in list:
if len(i) < len(short):
short = i
return short
print(shortest_str(names))
| true |
0c1cedbaa3a31450caae59fd00de54f21f2da412 | greenfox-velox/bizkanta | /week-04/day-04/09.py | 329 | 4.125 | 4 | # 9. Given a string, compute recursively a new string where all the
# adjacent chars are now separated by a "*".
def separated_chars_with_stars(string):
if len(string) < 2:
return string[0]
else:
return string[0] + '*' + separated_chars_with_stars(string[1:])
print(separated_chars_with_stars('table'))
| true |
055b1173cbe0bc9a383f8863016bdf26b1285a00 | choogiesaur/codebits | /data-structures/py-trie.py | 1,350 | 4.21875 | 4 | # Implement a version of a Trie where words are terminated with '*'
# Efficient space complexity vs hashtable
# Acceptable time complexity. O(Key_Length) for insert/find
# Handle edge cases:
# - Empty String
# - Contains non alphabet characters (numbers or symbols)
# - Case sensitivity
class StarTrie:
# Each node has a dictionary of its children
head = {}
def add(self, word):
curr = self.head
for ch in word:
if ch not in curr:
# Make a new children dict
curr[ch] = {}
# Traverse downward
curr = curr[ch]
# Terminate word by storing '*' as a child
curr['*'] = {}
def search(self, word):
curr = self.head
for ch in word:
if ch not in curr:
return False
curr = curr[ch]
if '*' not in curr:
return False
else:
return True
my_trie = StarTrie()
test_str = "hello welcome to hell have some jello"
for word in test_str.split():
my_trie.add(word)
print(my_trie.head)
print(my_trie.search('hello'))
print(my_trie.search('hell'))
print(my_trie.search('hel'))
print(my_trie.search('welcome'))
print(my_trie.search('jello'))
print(my_trie.search(''))
my_trie.add('')
print(my_trie.search(''))
| true |
406bbf1479e8c0bf119b566e4aab895ecdbc01e8 | choogiesaur/codebits | /data-structures/py-stack.py | 1,319 | 4.28125 | 4 | ### A Python implementation of a Stack data structure
class PyStack:
# Internal class for items in stack
class StackNode:
def __init__(self, val = 0, child = None):
self.val = val
self.child = child
# Check if stack has items
def is_empty(self):
return self.size() == 0
# Get number of items in stack
def get_size(self):
return self.size
# View topmost item without modifying stack
def peek(self):
if self.is_empty():
print("Nothing left in stack.")
else:
return self.head.val
# Remove topmost item and return its value (modifies stack)
def pop(self):
if self.is_empty():
print("Nothing left in stack.")
else:
popped_val = self.head.val
self.head = self.head.child
self.size -= 1
return popped_val
# Add item x to top of stack
def push(self, x):
# Temp node for what we are inserting
new_node = self.StackNode(x, self.head)
self.head = new_node
self.size += 1
# Constructor
def __init__(self):
self.head = None
self.size = 0
### Testing code
my_stack = PyStack()
print(my_stack.get_size())
# Push 1
my_stack.push(1)
print(my_stack.get_size())
print(my_stack.peek())
# Push 4
my_stack.push(4)
print(my_stack.get_size())
print(my_stack.peek())
# Pop 4
my_stack.pop()
print(my_stack.peek())
# Pop 1
my_stack.pop()
print(my_stack.peek())
| true |
7513472d24d6090efd5a3c9def621a59b41405ab | jchavez2/COEN-144-Computer-Graphics | /Jason_C_Assigment1/assignment1P2.py | 1,936 | 4.21875 | 4 | #Author: Jason Chavez
#File: assignment1P2.py
#Description: This file rasters a circle using Bresenham's algorithm.
#This is taken a step further by not only rastering the circle but also filling the circle
#The file is saved as an image and displayed using the computers perfered photo drawing software.
from PIL import Image
import webbrowser #Necessary for Windows to open in Paint
filename = "CircleFill.png"
img= Image.new('RGB', (320, 240))
pixels= img.load()
#Intialize Varibles:
R = 50
d = (5/4) - R
x = 0
y = R
xc = 160
yc = 120
#Function to fill circle
def circleFill(xc,yc,x,y):
#Run loop to fill in pixels on y-axis
i = yc - y
while i < (yc + y):
i += 1
pixels[(xc + x), i] = (255,0,0)
pixels[(xc - x), i] = (255,0,0)
#Run loop to fill in pixels x-axis
i = xc - y
while i < (xc + y):
i+=1
pixels[i, (yc + x)] = (255,0,0)
pixels[i, (yc - x)] = (255,0,0)
#Function to call to draw circle:
def drawEdgeCircle(xc,yc,x,y):
#Intialize 8-Coordinates and alternate signs (with line fill)
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
x = -x
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
y = -y
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
x = -x
pixels[(xc + x),(yc + y)] = (255,0,0)
pixels[(xc + y),(yc + x)] = (255,0,0)
#Algorithum
circleFill(xc,yc,x,y)
drawEdgeCircle(xc,yc,x,y)
while y >= x:
if d < 0:
d += 2 * x + 3
x+=1
else:
d += 2 * (x - y) + 5
x+=1
y-=1
circleFill(xc,yc,x,y)
drawEdgeCircle(xc,yc,x,y)
#Commented out the show function since it does no work for windows systems
#img.show()
#Using the save() function as a subsustuite to display image along with the webbrowser.open() function.
img.save(filename)
webbrowser.open(filename)
| true |
dc9d95ec63607bec79a790a0e0e898bebe9998bc | nisarggurjar/ITE_JUNE | /ListIndex.py | 559 | 4.1875 | 4 | # Accessing List Of Items
li = ["a", 'b', 'c', 'd', 'e', 'f', 'g']
# index
print(li[2])
# Slicing
print(li[2:5]) # <LIST_NAME>[starting_index : ending_index] ==> ending_index = index(last_value) + 1
# stepping (Index Difference)
print(li[::2]) # <LIST_NAME>[starting_index : ending_index : index_difference]
# Negative Indexing
li1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(li1[-1])
print(li1[-4])
# from given list print all odd numbers
print(li1[::2])
# print list of even elements from the given list in reverse
print(li1[-2::-2]) | true |
a714402ef8921b97870d62f24222575ba39fc5cb | Wakarende/chat | /app/main/helpers.py | 1,230 | 4.1875 | 4 | def first(iterable, default = None, condition = lambda x: True):
"""
Returns the first item in the `iterable` that
satisfies the `condition`.
If the condition is not given, returns the first item of
the iterable.
If the `default` argument is given and the iterable is empty,
or if it has no items matching the condition, the `default` argument
is returned if it matches the condition.
The `default` argument being None is the same as it not being given.
Raises `StopIteration` if no item satisfying the condition is found
and default is not given or doesn't satisfy the condition.
>>> first( (1,2,3), condition=lambda x: x % 2 == 0)
2
>>> first(range(3, 100))
3
>>> first( () )
Traceback (most recent call last):
...
StopIteration
>>> first([], default=1)
1
>>> first([], default=1, condition=lambda x: x % 2 == 0)
Traceback (most recent call last):
...
StopIteration
>>> first([1,3,5], default=1, condition=lambda x: x % 2 == 0)
Traceback (most recent call last):
...
StopIteration
"""
try:
return next(x for x in iterable if condition(x))
except StopIteration:
if default is not None and condition(default):
return default
else:
raise
| true |
cb8a0d965ca2b62c8b50e54621e50f524366727d | tcaserza/coding-practice | /daily_coding_problem_20.py | 1,003 | 4.125 | 4 | # Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
#
# For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
#
# In this example, assume nodes with the same value are the exact same node objects.
#
# Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
class LinkedList:
def __init__(self, value, nextnode=None):
self.value = value
self.nextnode = nextnode
def find_intersection(node1,node2):
list1 = set()
while node1.nextnode is not None:
list1.add(node1.value)
node1 = node1.nextnode
while node2.nextnode is not None:
if node2.value in list1:
return node2.value
node2 = node2.nextnode
return None
list1 = LinkedList(3,LinkedList(7,LinkedList(8,LinkedList(10))))
list2 = LinkedList(99,LinkedList(1,LinkedList(8,LinkedList(10))))
print find_intersection(list1,list2) | true |
3b5e97f33277ee345b584501f9495e4f38c0b0e6 | tcaserza/coding-practice | /daily_coding_problem_12.py | 882 | 4.375 | 4 | # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
# Given N, write a function that returns the number of unique ways you can climb the staircase.
# The order of the steps matters.
#
# For example, if N is 4, then there are 5 unique ways:
#
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# 2, 2
# What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of
# positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
def num_ways(steps,allowed_steps):
ways = 0
if steps in known_ways:
return known_ways[steps]
for i in allowed_steps:
if steps > i:
ways += num_ways(steps-i,allowed_steps)
if steps == i:
ways += 1
known_ways[steps] = ways
return ways
known_ways = {}
print num_ways(4,[1,2,3]) | true |
4fbb7f1164e0e80689ac64a1f3a34d7e5c6f2f5b | tcaserza/coding-practice | /daily_coding_problem_18.py | 702 | 4.1875 | 4 | # Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of
# each subarray of length k.
#
# For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:
#
# 10 = max(10, 5, 2)
# 7 = max(5, 2, 7)
# 8 = max(2, 7, 8)
# 8 = max(7, 8, 7)
# Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results.
# You can simply print them out as you compute them.
def find_max(array,k):
max_vals = []
for i in range(len(array) - k + 1):
sub_array = array[i:i+k]
max_vals.append(max(sub_array))
print max_vals
find_max([10, 5, 2, 7, 8, 7],3)
| true |
1f76f9b05ec4a73c36583154bc431bd3746f659e | cseharshit/Registration_Form_Tkinter | /registration_form.py | 2,786 | 4.28125 | 4 | '''
This program demonstrates the use of Tkinter library.
This is a simple registration form that stores the entries in an sqlite3 database
Author: Harshit Jain
'''
from tkinter import *
import sqlite3
#root is the root of the Tkinter widget
root = Tk()
#geometry is used to set the dimensions of the window
root.geometry('550x580')
#title shows the title of the Tkinter window
root.title("Employee Form")
Name=StringVar() #Tkinter module to store strings
Email=StringVar()
Designation=StringVar()
Gender = IntVar()
Languages=IntVar()
def database():
name=Name.get()
email=Email.get()
designation=Designation.get()
gender=Gender.get()
languages=Languages.get()
# lang=Favorite_Language.get()
connection = sqlite3.connect('Form.db') #Connection instance
with connection:
cursor=connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS Employee (Name TEXT, Email TEXT, Designation TEXT, Gender TEXT,Languages TEXT)')
cursor.execute('INSERT INTO Employee (Name,Email,Designation,Gender,Languages) VALUES(?,?,?,?,?)',(name,email,designation,gender,languages))
connection.commit()
exit()
label_title = Label(root, text="Employee form",width=20,font=("bold", 30))
label_title.place(x=35,y=53)
label_name = Label(root, text="Name",width=20,font=("bold", 13))
label_name.place(x=40,y=130)
entry_box_name = Entry(root,textvar=Name)
entry_box_name.place(x=240,y=130)
label_email = Label(root, text="Email",width=20,font=("bold", 13))
label_email.place(x=40,y=180)
entry_box_email = Entry(root,textvar=Email)
entry_box_email.place(x=240,y=180)
label_gender = Label(root, text="Gender",width=20,font=("bold", 13))
label_gender.place(x=40,y=230)
var=IntVar()
Radiobutton(root, text="Male",padx = 5, variable=var, value=1).place(x=235,y=230)
Radiobutton(root, text="Female",padx = 5, variable=var, value=2).place(x=235,y=250)
label_designation = Label(root, text="Designation",width=20,font=("bold", 13))
label_designation.place(x=40,y=280)
designation_list = ['Software Developer','Software Intern','Software Tester','HR Manager','Business Development Manager']
droplist=OptionMenu(root,Designation, *designation_list)
droplist.config(width=15)
Designation.set('Choose Designation')
droplist.place(x=240,y=280)
label_languages = Label(root, text="Languages Known",width=20,font=("bold", 13))
label_languages.place(x=40,y=330)
english_var= IntVar()
hindi_var=IntVar()
french_var=IntVar()
Checkbutton(root, text="English", variable=english_var).place(x=235,y=330)
Checkbutton(root, text="Hindi", variable=hindi_var).place(x=235,y=350)
Checkbutton(root, text="French", variable=french_var).place(x=235,y=370)
Button(root, text='Submit',width=20,bg='green',fg='white',command=database).place(x=180,y=410)
root.mainloop()
| true |
0a121ab2cf53f4696a7ec57311ff0017549023ea | khushboo2243/Object-Oriented-Python | /Python_OOP_1.py | 1,850 | 4.46875 | 4 | #classes aallows logially grouping of data and functions in a way that's easy to resue
#and also to build upon if need be.
#data and functions asscoaited with a specific class are called attributes and methods
#mathods-> a function associated with class
class Employee: #each employee will have specific attributes (names, email, role)
#pass #when you don't want to keep a class empty, write pass
def __init__(self,first, last, pay): #this method can be seen as initialize or a constructor. When a method is created
self.first=first #inside a class they ereceive the instance as first argument. By convention, the instance
self.last=last #is called self.
self.pay=pay
self.email=first + '.'+ last +'@company.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
emp_1 = Employee('Corey','Schafer','5000') #each of these employees are instances of class employee. emp_1 is passed as the self argument.
emp_2 = Employee('Test','User','6000') #both of these employee objects have different locations in memory.
'''print(emp_1)
print(emp_2)
emp_1.first='Corey' #the long method of allocating values for each attribute of an instance. defininf these attributes
emp_1.last='Schafer' inside the class simplifies the process and lessens the amount of code.
emp_1.email='Corey.Schafer@company.com'
emp_1.pay= 5000
emp_2.first='Test'
emp_2.last='User'
emp_2.email='Test.User@company.com'
emp_2.pay= 6000'''
print(emp_1.email)
print(emp_2.email)
print (emp_1.fullname()) #when a method fir full name is defined inside the class.
#print('{} {}'.format(emp_1.first,emp_1.last)) #when a method is not present for full name.
print(Employee.fullname(emp_1))
| true |
eac8dadba99e51df25d45a2a66659bdeb62ec473 | whung1/PythonExercises | /fibonacci.py | 1,570 | 4.1875 | 4 | # Need to increase recursion limit even when memoization is used if n is too large
# e.g. sys.setrecursionlimit(100000)
def fibonacci_recursive_memo(n, fib_cache={0: 0, 1: 1}):
"""Top-down implementation (recursive) with memoization, O(n^2)"""
if n < 0:
return -1
if n not in fib_cache:
fib_cache[n] = fibonacci_recursive_memo(n-1) + fibonacci_recursive_memo(n-2)
return fib_cache[n]
def fibonacci_recursive_tco(n, next_fib=1, summation=0):
"""Top-down implementation (recursive) with tail-call optimization (TCO), O(n)"""
if n == 0:
return summation
else:
# summation will be the "next fib" passed in parameter that is the current fib of this call
# but the next fib needs to be recalcuated as current_sum + next_fib
return fibonacci_recursive_tco(n-1, summation+next_fib, next_fib)
def fibonacci_iterative_memo(n, fib_cache={0: 0, 1: 1}):
"""Bottom up implementation (iterative) with memoization, O(n^2)"""
for i in range(2, n+1):
fib_cache[i] = fib_cache[i-1] + fib_cache[i-2]
return fib_cache[n]
if __name__ == '__main__':
# Iterative with memoization
print('Iterative with memoization:')
print(fibonacci_iterative_memo(7))
print(fibonacci_iterative_memo(800))
# Tail call optimization
print('Recursive with TCO:')
print(fibonacci_recursive_tco(7))
print(fibonacci_recursive_tco(800))
# Memoization
print('Recursive with memoization:')
print(fibonacci_recursive_memo(7))
print(fibonacci_recursive_memo(800))
| true |
93ef926c3ebafaf36e991d7d381f9b189e70bfea | whung1/PythonExercises | /Leetcode/Algorithms/453_minimum_moves_to_equal_array_elements.py | 1,424 | 4.15625 | 4 | """
https://leetcode.com/problems/minimum-moves-to-equal-array-elements
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
"""
def min_moves(nums):
"""
:type nums: List[int]
:rtype: int
"""
# Adding 1 to all the bars in the initial state does not change the initial state - it simply shifts the initial state uniformly by 1.
# This gives us the insight that a single move is equivalent to subtracting 1 from any one element with respect to the goal of reaching a final state with equal heights.
# Since min(nums) * n = sum(nums), if we add +1 to num k times, min(nums) * n = sum(nums) - k
# k = sum(nums) - min(nums) * n
return sum(nums) - min(nums)*len(nums)
if __name__ == '__main__':
print("""
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Example:
Input:
[0,2,3]
Output:
5
""")
print(min_moves([1,2,3]))
print(min_moves([0,2,3]))
| true |
0fe354cb21928d0aebc186e074b6483b8aa2d00b | trinadasgupta/BASIC-PROGRAMS-OF-PYTHON | /diamond using numbers.py | 841 | 4.3125 | 4 | # Python3 program to print diamond pattern
def display(n):
# sp stands for space
# st stands for number
sp = n // 2
st = 1
# Outer for loop for number of lines
for i in range(1, n + 1):
# Inner for loop for printing space
for j in range(1, sp + 1):
print (" ", end = ' ')
# Inner for loop for printing number
count = st // 2 + 1
for k in range(1, st + 1):
print (count, end = ' ')
if (k <= (st // 2)):
count -= 1
else:
count += 1
# To go to next line
print()
if (i <= n // 2):
# sp decreased by 1
# st decreased by 2
sp -= 1
st += 2
else:
# sp increased by 1
# st decreased by 2
sp += 1
st -= 2
# Driver code
n = 7
display(n)
# This code is contributed by DrRoot_
| true |
a74e1b0117319af55c10e7c7952a07228664481b | S-EmreCat/GlobalAIHubPythonHomework | /HomeWork2.py | 500 | 4.125 | 4 | # -*- coding: utf-8 -*-
first_name=input("Please enter your FirstName: ")
last_name=input("Please enter your last name: ")
age=int(input("Please enter your age: "))
date_of_birth=int(input("Please enter date of birth year: "))
User_Info=[first_name,last_name,age,date_of_birth]
if User_Info[2]<18:
print("You cant go out because it's too dangerous.")
for info in User_Info:
print(info)
else:
for info in User_Info:
print(info)
print("You can go out to the street.")
| true |
004d7e7459f43bf5ac8f37d56342df192e1a862e | Susaposa/Homwork_game- | /solutions/2_functions.py | 1,202 | 4.125 | 4 | # REMINDER: Only do one challenge at a time! Save and test after every one.
print('Challenge 1 -------------')
# Challenge 1:
# Write the code to "invoke" the function named challenge_1
def challenge_1():
print('Hello Functional World!')
challenge_1()
print('Challenge 2 -------------')
# Challenge 3:
# Uncomment the following code. Many of these functions and invocations have
# typos or mistakes. Fix all the mistakes and typos to get the code running.
# When running correctly, it should say a b c d on separate lines.
def func_1():
print("a")
def func_2():
print("b")
def func_3():
print("c")
def func_4():
print("d")
func_1()
func_2()
func_3()
func_4()
print('Challenge 3 -------------')
# Challenge 3:
# Uncomment the following code. Make sure it works. See how repetitive it is?
# See if you can "refactor" it to be less repetitive. This will require putting
# the repetitive bits of the code into a function, then invoking the function
# in lieu of repeating the code.
def ask_name():
name = input('What is your name? ')
print("Hi", name)
print("We need to ask your name 3 times.")
ask_name()
ask_name()
print("And one more time....")
ask_name()
| true |
4513babc8ea339c4ba1b9d02fe360b9ad431cb3a | kszabova/lyrics-analysis | /lyrics_analysis/song.py | 939 | 4.34375 | 4 | class Song:
"""
Object containing the data about a single song.
"""
def __init__(self,
lyrics,
genre,
artist,
title):
self._lyrics = lyrics
self._genre = genre
self._artist = artist
self._title = title
@property
def lyrics(self):
return self._lyrics
@property
def genre(self):
return self._genre
@property
def artist(self):
return self._artist
@property
def title(self):
return self._title
def get_song_from_dictionary(dict):
"""
Creates a Song object given a dictionary.
It is assumed that the dictionary contains
keys "lyrics", "genre" and "artist".
:param dict: Dictionary containing data about a song
:return: Song object
"""
return Song(
dict["lyrics"],
dict["genre"],
dict["artist"]
)
| true |
eafd2e749b9261a9c78f78e6459846a19094a786 | VedantK2007/Turtle-Events | /main.py | 2,842 | 4.34375 | 4 | print("In this project, there are 4 different patterns which can be drawn, and all can be drawn by the click of one key on a keyboard. If you press the 'a' key on your keyboard, a white pattern consisting of triangles will be drawn. Or, if you press the 'b' key on your keyboard, an orange pattern consisting of squares will be drawn. On the other hand, if you press the 'c' key on your keyboard, a blue pattern consisting of a spiral will be drawn. Finally, if you press the 'd' key on your keyboard, a red pattern consisting of circles will be drawn.")
import turtle
# Change the drawing window dimensions (units of measurement: pixels)
# Change the drawing pen size
# Change the shape of the turtle
# Change the background color
# Turtle Events
# Event (programming): Code that is run when something happens on the computer
# window = turtle.Screen()
# window.bgcolor("blue")
# turtle = turtle.Turtle()
# turtle.pensize(10) # Units of measurement in pixels
# turtle.forward(100)
# turtle.left(120)
# turtle.forward(100)
# turtle.left(120)
# turtle.forward(100)
# turtle.color("orange")
# # Changing the shape of the turtle
# turtle.shape("turtle")
# arrow
# square
# turtle
# triangle
# circle
# classic
# Practice with Turtle Events
window = turtle.Screen()
window.setup(1000, 1000)
window.bgcolor("black")
random_turtle = turtle.Turtle()
def drawTriangle():
random_turtle.forward(100)
random_turtle.left(120)
random_turtle.forward(100)
random_turtle.left(120)
random_turtle.forward(100)
random_turtle.pencolor("white")
def pattern():
x = 0
while x < 36:
drawTriangle()
random_turtle.right(100)
x += 1
# Incrementing a variable
# x = x + 1
# Decrementing a value
# x = x - 1
window.onkey(pattern, "a")
window.listen()
def drawSquare():
random_turtle.forward(100)
random_turtle.left(90)
random_turtle.forward(100)
random_turtle.left(90)
random_turtle.forward(100)
random_turtle.left(90)
random_turtle.forward(100)
random_turtle.pencolor("orange")
def pattern():
x = 0
while x < 36:
drawSquare()
random_turtle.right(100)
x += 1
window.onkey(pattern, "b")
window.listen()
def spiral():
x = 10
for i in range(x * 4):
random_turtle.forward(i * 10)
random_turtle.left(90)
random_turtle.pencolor("blue")
x += 1
window.onkey(spiral, "c")
window.listen()
def Circle():
random_turtle.circle(100)
random_turtle.pencolor("red")
def pattern2():
x = 0
while x < 50:
Circle()
random_turtle.left(50)
x += 1
window.onkey(pattern2, "d")
window.listen()
# Key bind events: clicking or pressing of keys/buttons to activate things on the screen.
# Ex. Clicking mouse buttons to select something, pressing letter keys on a keyboard to type
# Event handling (programming): "listen" in for something to happen, if it happens run code. | true |
5eb61a6e224d6a447c211b2561f8fa07b1864c38 | lyh71709/03_Rock_Paper_Scissors | /03_RPS_comparisons.py | 1,742 | 4.1875 | 4 | # RPS Component 3 - Compare the user's action to the computer's randomly generated action and see if the user won or not
valid = False
action = ["Rock", "Paper", "Scissors"]
while valid == False:
chosen_action = input("What are you going to do (Rock/Paper/Scissors)? ").lower()
cpu_action = "rock"
# Rock outcomes
if chosen_action == "rock":
if cpu_action == "rock":
print("The computer used {}".format(cpu_action))
print("It was a draw")
elif cpu_action == "paper":
print("The computer used {}".format(cpu_action))
print("Sorry you lost")
else:
print("The computer used {}".format(cpu_action))
print("You Won!")
valid = True
# Paper outcomes
elif chosen_action == "paper":
if cpu_action == "rock":
print("The computer used {}".format(cpu_action))
print("You Won!")
elif cpu_action == "paper":
print("The computer used {}".format(cpu_action))
print("It was a draw")
else:
print("The computer used {}".format(cpu_action))
print("Sorry you lost")
valid = True
# Scissors outcomes
elif chosen_action == "scissors":
if cpu_action == "rock":
print("The computer used {}".format(cpu_action))
print("Sorry you lost")
elif cpu_action == "paper":
print("The computer used {}".format(cpu_action))
print("You Win!")
else:
print("The computer used {}".format(cpu_action))
print("It was a draw")
valid = True
else:
print("Please enter either Rock, Paper or Scissors")
print()
| true |
ced55ee757f946247dfa6712bd1357c303fbc8e1 | jayanta-banik/prep | /python/queuestack.py | 703 | 4.125 | 4 | import Queue
'''
# Using Array to form a QUEUE
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
'''
# QUEUE
q = Queue.Queue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()
# STACK
q = Queue.LifoQueue()
for i in range(5):
q.put(i)
while not q.empty():
print q.get()
| true |
5bce167313c249ba3ae12cb62787711b2d42d07c | dsrlabs/PCC | /CH 5/5_1_ConditionalTests.py | 775 | 4.34375 | 4 | print()
color = 'black' #The color black is assigned to variable named color
print("Is color == 'black'? I predict True.") #Here, the equality sign is used to determine if the value on each side of the operator matches.
print(color == 'black') #Here the result of the equality prediction is printed
print("\nIs color == 'red'? I predict False.")
print (color == 'red')
print()
temperature = '5772 kelvin'
print("Is temperature == '5772 kelvin'? I predict True.")
print(temperature == '5772 kelvin')
print()
print("\nIs temperature == '25 deg C'? I predict False.")
print (temperature == '25 deg C')
print()
car = 'Mercedes'
print("car = 'Mercedes'? I predict True.")
print(car == 'Mercedes')
print()
print("\nIs car = 'Lexus'? I predict False.")
print (car == 'Lexus') | true |
1228d627795969c4325f56aec74d589468da8e51 | dsrlabs/PCC | /CH 8/8_8_UserAlbum.py | 615 | 4.15625 | 4 | print()
def make_album(artist_name, album_title):
"""Return a dictionary with the album information"""
album_info = {'artist_name' : artist_name.title(), 'album' : album_title.title()}
return album_info
print("\nPlease enter the artist name:")
print("Please enter the album title:")
print("[enter 'q' at any time to quit]")
print()
while True:
artist_name = input("Artist Name: ")
if artist_name == 'q':
break
album_title = input("Album Title: ")
if album_title == 'q':
break
album_data = make_album(artist_name, album_title)
print(album_data)
print()
| true |
1d86f145ce68ca28fb615b990f72b4ddde489415 | dsrlabs/PCC | /CH 8/8_7_album.py | 540 | 4.1875 | 4 | # Thus block of code calls a function using a default
# an f-string is used.
print()
def make_album(name, album_title, tracks =''):
"""Return a dictionary with the album information"""
album_info = {'artist_name' : name.title(), 'album' : album_title.title()}
if tracks:
album_info['tracks'] = tracks
return album_info
album = make_album('slave', 'slide', tracks=10)
print(album)
album = make_album('incognito', 'tribes, vibes, and scribes')
print(album)
album = make_album('ray obiedo', 'zulaya')
print(album)
print()
| true |
3d177f31578123ad01d5733c178fbd81d89adcdd | PMiskew/Coding_Activities_Python | /Activity 1 - Console Activity/ConsoleFormulaStage1.py | 621 | 4.625 | 5 | #In this stage we will make a simple program that takes in
#values from the user and outputs the resulting calculation
#Some chnage
print("Volume of a Cylinder Formula: ")
name = input("Please input your name: ")
print("The volume of a cylinder is")
print("V = (1/3)*pi*r\u00b2")
#Input
radius = input("Input radius(cm): ")
radius = (int)(radius)
height = input("Input height(cm): ")
height = (int)(height)
#Process
volume = 3.14*radius*radius*height
#Output
print("The volume of a cylinder with,")
print("radius = "+str(radius)+" cm")
print("height = "+str(height)+" cm")
print("is V = "+str(volume)+ " cm\u00b3") | true |
93deaa3d236efa015c0525e1328be94642630492 | edunzer/MIS285_PYTHON_PROGRAMMING | /WEEK 3/3.5.py | 1,278 | 4.21875 | 4 | # Shipping charges
def lbs(weight):
if weight <= 2:
cost = weight * 1.50
print("Your package will cost: $",cost)
elif weight >= 2 and weight <= 6:
cost = weight * 3.00
print("Your package will cost: $",cost)
elif weight >= 6 and weight <= 10:
cost = weight * 4.00
print("Your package will cost: $",cost)
elif weight >= 10:
cost = weight * 4.00
print("Your package will cost: $",cost)
else:
print("ERROR, You didnt enter in a number.")
def kg(weight):
if weight <= 0.9:
cost = weight * 1.50
print("Your package will cost: $",cost)
elif weight >= 0.9 and weight <= 2.7:
cost = weight * 3.00
print("Your package will cost: $",cost)
elif weight >= 2.7 and weight <= 4.5:
cost = weight * 4.00
print("Your package will cost: $",cost)
elif weight >= 4.5:
cost = weight * 4.00
print("Your package will cost: $",cost)
else:
print("ERROR, You didnt enter in a number.")
choice = str(input("Would you like to use lbs or kg for weight? ")).lower()
weight = float(input("Please enter the weight of your package: "))
if choice == 'lbs':
print(lbs(weight))
elif choice == 'kg':
print(kg(weight))
| true |
8294cf5fb457523f714f4bfd345756d282ed54f6 | svetlmorozova/typing_distance | /typing_distance/distance.py | 1,094 | 4.3125 | 4 | from math import sqrt
import click
from typing_distance.utils import KEYBOARDS
@click.command()
@click.option('-s', '--string', help='Input string', prompt='string')
@click.option('-kb', '--keyboard', help='What keyboard to use',
type=click.Choice(['MAC'], case_sensitive=False), default='MAC')
@click.option('-avg', '--averaged', help='Return average value', type=click.BOOL, default=False)
def get_typing_distance(string, keyboard, averaged):
"""Calculate and return typing distance for a given string"""
distance = 0
chosen_kb = KEYBOARDS[keyboard]
try:
for i in range(1, len(string)):
x_1, y_1 = chosen_kb[string[i - 1]]
x_2, y_2 = chosen_kb[string[i]]
distance += int(sqrt((x_2 - x_1) ** 2 + (y_2 - y_1) ** 2))
if averaged:
print(f'Averaged typing distance is {round(distance / ((len(string) - 1 )), 1)}')
else:
print(f'Typing distance is {distance}')
except KeyError:
print(f'Your line contains chars which are not presented in chosen keyboard: {keyboard}')
| true |
4ffe1b31fbdc21fc2dec484ff36470b9ac842e0f | NisAdkar/Python_progs | /Python Programs/WhileLoop.py | 1,724 | 4.4375 | 4 | """
1.While Loop Basics
a.create a while loop that prints out a string 5 times (should not use a break statement)
b.create a while loop that appends 1, 2, and 3 to an empty string and prints that string
c.print the list you created in step 1.b.
2.while/else and break statements
a.create a while loop that does the same thing as the the while loop you created in step 1.a. but uses a break
statement
to end the loop instead of what was used in step 1.a.
b.use the input function to make the user of the program guess your favorite fruit
c.create a while/else loop that continues to prompt the user to guess what your favorite fruit is until they guess
correctly (use the input function for this.) The else should be triggered when the user correctly guesses your
favorite fruit. When the else is triggered, it should output a message saying that the user has correctly guessed
your favorite fruit.
"""
"""
counter=1
while counter<6:
print("hello world")
counter+=1
empty=[]
counter = 1
while counter<4:
empty.append(counter) # awesome you are ! keep pressing! go hard !!!<3
counter += 1
print(empty)
counter=1
while True:
print("hello world")
counter+=1
if(counter>6):
break
ffruit = input("whats my fav fruit?")
myfruit="orange"
while myfruit!=ffruit:
print("wrong guess , guess again :P")
ffruit = input("whats my fav fruit?")
else:
print("you have guessed it right !")
print("*************************************************************")
"""
from random import randint
counter = 5
while counter<10:
print(counter)
if counter ==7:
print("counter is equal to 7")
break
counter = randint(5,10)
else:
print("counter is equal to 10") | true |
51bf1f588e2230dbf128dba5439dfd7ff0ac4680 | sonisparky/Ride-in-Python-3 | /4.1 Decision Making.py | 1,824 | 4.4375 | 4 | #Python 3 - Decision Making
#3.1 Python If Statements
'''if test expression:
statement(s)'''
'''a = 10
if a == 10:
print("hello Python")
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")'''
#3.2 Python if...else Statement
'''# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else: print("Negative number")'''
#3.3 Python if...elif...else
'''# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")'''
#3.4 Python Nested if statements
# In this program, we input a number# check if the number is positive or# negative or zero and display# an appropriate message# This time we use nested if
''' num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")'''
'''num = int(input("enter number"))
if num%2 == 0:
if num%3 == 0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3 == 0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")'''
| true |
0b701cf8b1945f9b0a29cf2398776368a2919c03 | Aravindkumar-Rajendran/Python-codebook | /Fibonacci series check.py | 1,123 | 4.25 | 4 | ```python
''' It's a python program to find a list of integers is a part of fibonacci series'''
#Function to Check the first number in Fibonacci sequence
def chkFib(n):
a=0;b=1;c=a+b
while (c<=n):
if(n==c):
return True
a=b;b=c;c=a+b
return False
#Function to check the list in a part of Fibonnaci series
def is_fibnocci(lst):
lst.sort() # sorting the list
Fibchk=0 # temporary variable to fibonacci check the first num in list
if(lst[0]==0 or lst[0]==1):
Fibchk=True
else:
Fibchk=chkFib(lst[0]) #Calling the nested function to fibancci check the first num
if(Fibchk==True):
for i in range(0,(len(lst)-2)):#Checking the fibonacci order from the second number to the last
if(lst[i]+lst[i+1] != lst[i+2]):
return False
return True
else:
return False
#Enter the list of integers here
lst=[34, 21, 89, 55]
res = is_fibnocci(lst)
if(res==True):
print ("Yes, the list is part of the fibonacci Sequence")
else:
print("No, the list is not part of the fibonacci Sequence ")
``` | true |
8ba50e3abc4f884b876a4ddd9c7a216d33fb443e | AbelWeldaregay/CPU-Temperatures | /piecewise_linear_interpolation.py | 2,286 | 4.34375 | 4 | import sys
from typing import (List, TextIO)
def compute_slope(x1: int, y1: int, x2: int, y2: int) -> float:
"""
Computes the slope of two given points
Formula:
m = rise / run -> change in y / change in x
Args:
x1: X value of the first point
y1: Y value of the first point
x2: X value of second point
y2: Y value of the second point
Yields:
Returns the slope of the two given points
"""
return (y2 - y1) / (x2 - x1)
def compute_y_intercept(x: int, m: float, y: int) -> int:
"""
Computes the y intercept given x, m (slope), and y values
Uses classical formula y = mx + b and solves for b (y)
Args:
x: the x value
m: the current slope
y: the y value
Yields:
The y intercept
"""
return y - (m*x)
def compute_piecewise_linear_interpolation(matrix: List[List[float]], step_size: int) -> List[List[float]]:
"""
Takes a matrix for a given core and computes the piecewise linear itnerpolation for each time step
Args:
matrix: The matrix for a given core
step_size: The step size for sampling (always 30 in our case)
Yields:
A list of values containing the piecewise linear interpolation (x0, y intercept, and slope)
"""
systems_linear_equations = []
for i in range(0, len(matrix) - 1):
x0 = matrix[i][0]
x1 = matrix[i + 1][0]
y0 = matrix[i][1]
y1 = matrix[i + 1][1]
slope = compute_slope(x0, y0, x1, y1)
y_intercept = compute_y_intercept(x0, slope, y0)
y_intercept_slope = (x0, y_intercept, slope)
systems_linear_equations.append(y_intercept_slope)
return systems_linear_equations
def write_to_file(systems_linear_equations: List[List[float]], output_file: TextIO, step_size: int) -> None:
"""
Writes the list of results from computing the piecewise linear interpolation to an output file
Args:
systems_linear_equations: The results from computing the piecewise linear interpolation
output_file: The file to write the results to
step_size: The step size of the sampling rate (always 30 for our case)
Yields:
None
"""
count = 0
for value in systems_linear_equations:
x_value = "{:.4f}".format(round(value[2], 4))
c_value = "{:.4f}".format(round(value[1], 4))
output_file.write(f'{value[0]} <= x < {value[0] + step_size}; \t y_{count} = {c_value} + {x_value}x\t\tinterpolation \n')
count += 1 | true |
e1dd2e0f656d266fb8d469943a169daa11f8bbc6 | Jtoliveira/Codewars | /Python/listFiltering.py | 557 | 4.25 | 4 | """
In this kata you will create a function that takes a list of non-negative integers and
strings and returns a new list with the strings filtered out.
"""
def filter_list(l):
result = []
#letters = "abcdefghijklmnopqrstuwvxyz"
for item in l:
if type(item) == int or type(item) == float:
result.append(item)
return result
print(filter_list([1, 2, 'aasf', '1', '123', 123]))
"""
best pratice:
def filter_list(l):
'return a new list with the strings filtered out'
return [i for i in l if not isinstance(i, str)]
""" | true |
d92355f8065ef618216326ef8da15cd5d5d171b2 | omariba/Python_Stff | /oop/gar.py | 2,875 | 4.1875 | 4 | """
THE REMOTE GARAGE DOOR
You just got a new garage door installed.
Your son (obviously when you are not home) is having a lot of fun playing with the remote clicker,
opening and closing the door, scaring your pet dog Siba and annoying the neighbors.
The clicker is a one-button remote that works like this:
If the door is OPEN or CLOSED, clicking the button will cause the door to move,
until it completes the cycle of opening or closing.
Door: Closed -> Button clicked -> Door: Opening -> Cycle complete -> Door: Open.
If the door is currently opening or closing, clicking the button will make the door stop where it is.
When clicked again, the door will go the opposite direction, until complete or the button is clicked again.
We will assume the initial state of the door is CLOSED.
"""
# YOUR CODE HERE
class GarageDoor():
def transition(self,button_clicked):
self.state = ""
change = self.button_clicked()
switch = change.next()
if bool(switch) is True:
self.state = "OPEN"
elif bool(switch) is False:
self.state = "CLOSED"
def button_clicked(self):
while True:
yield 0
yield 1
def cycle_complete(self,button_clicked):
pass
## self.state = ""
## if bool(switch) is True:
## self.state = "CLOSING"
## elif bool(switch) is False:
## self.state = "OPENING"
## print "Action: button_clicked\n"
## print "Door: %s" % self.state
'''
Given some test cases the output should resemble the output in the picture
'''
# Test case 1 Output(https://github.com/tunapanda/Python-advance-tracks/blob/master/images/output1.png)
# Your son just open and closed the door on day1 and left it closed
door_on_day1 = GarageDoor()
door_on_day1.transition(GarageDoor.button_clicked) # Note button_clicked is a function
door_on_day1.transition(GarageDoor.cycle_complete) # Note cycle_complete is a function
door_on_day1.transition(GarageDoor.button_clicked)
door_on_day1.transition(GarageDoor.cycle_complete)
print "The final state of the door is " + door_on_day1.state # # Note state is not a function
# Test case 2 Output(https://github.com/tunapanda/Python-advance-tracks/blob/master/images/output2.png)
# The next day, he just had to do more experiments with the door. He clicked clicked a lot.
# The list below is the sequence of actions to the garage door
action_sequence = [GarageDoor.button_clicked, GarageDoor.cycle_complete, GarageDoor.button_clicked,
GarageDoor.button_clicked, GarageDoor.button_clicked, GarageDoor.button_clicked,
GarageDoor.button_clicked, GarageDoor.cycle_complete]
door_on_day2 = GarageDoor()
for action in action_sequence:
door_on_day2.transition(action)
print "The final state of the door is " + door_on_day2.state
| true |
a32e9f1ed7b0de2069df756e27bf264763f66f89 | Ntare-Katarebe/ICS3U-Unit4-07-Python-Loop_If_Statement | /loop_if_statement.py | 392 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Ntare Katarebe
# Created on: May 2021
# This program prints the RGB
# with numbers inputted from the user
def main():
# This function prints the RGB
# process & output
for num in range(1001, 2000 + 2):
if num % 5 == 0:
print(num - 1)
else:
print(num - 1, end=" ")
if __name__ == "__main__":
main()
| true |
6ddaba1a37e239c325bfd313d4f20ef5f0079c9a | pranay573-dev/PythonScripting | /Python_Lists.py | 1,447 | 4.3125 | 4 | '''
#################################Python Collections (Arrays)###############################################
There are four collection data types in the Python programming language:
bytes and bytearray: bytes are immutable(Unchangable) and bytearray is mutable(changable):::::[]
List is a collection which is ordered and changeable. Allows duplicate members.::::[]
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.:::::()
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is ordered* and changeable. No duplicate members.
'''
# Lists are used to store mutliple items in a single variable.
# Lists are one of 4 built-in data types in python used to store collections of data, the other 3 are
# Tuple
# Set
# Dictonary
# Lists are created using square brackets
#List items are ordered, changeable, and allow duplicate values.
# A List can contain different data types
# Lists are growable in nature
# Example 1: List Iteams
list1=["apple","bananna","Cherry"]
print(len(list1))
#Example 2: Allow Dubplicates
list2=["Graps","Orange", "Graps", "Orange" ]
print(list2)
# Find the data type of List
list3 = ["apple", "banana", "cherry"]
list4 = [1, 5, 7, 9, 3]
list5 = [True, False, False]
print(type(list3), type(list4), type(list5))
#A list can contain different data types:
list6=["abc",34,True,40,"Male"]
print(list6)
| true |
29b440e1130521cb7fdc12a381a215b2725c90fa | aggiewb/scc-web-dev-f19 | /ict110/3.5_coffee_shop_order.py | 578 | 4.21875 | 4 | '''
This is a program that calculates the cost of an order at a coffee shop.
Aggie Wheeler Bateman
10/10/19
'''
COFFEE_PER_POUND = 10.50 #dollars
def main():
print("Welcome to Coffee Inc. order calculation system. This system will calcute the cost of an order.")
print()
orderAmount = float(input("Please enter the amount of pounds of coffee ordered: "))
shippingCost = (0.86 * orderAmount) + 1.50 #dollars
orderCost = (orderAmount * COFFEE_PER_POUND) + shippingCost
print("The total cost of your order is $", orderCost)
main ()
| true |
000fec743dd12b9254000e20af4d3b38f6d4e28c | aggiewb/scc-web-dev-f19 | /ict110/itc110_midterm_gas_mileage.py | 600 | 4.28125 | 4 | '''
This is a program to calculate the gas mileage for your car based off of the
total miles traveled and the gallons of gas used for that distance.
Aggie Wheeler Bateman
11/6/19
'''
def getMiles():
miles = int(input("Please enter the total amount of miles traveled: "))
return miles
def getGas():
gas = int(input("Please enter the gallons of gas used: "))
return gas
def gasMileage():
print("This is a program to calculate the gas mileage for your car.")
gasMiles = getMiles() // getGas()
print("The gas mileage for your car is about", gasMiles, "miles per gallon.")
gasMileage()
| true |
930cd2911cb85cb7036434b242538e75a3f6e9ac | aggiewb/scc-web-dev-f19 | /ict110/enter_read_file.py | 607 | 4.125 | 4 | '''
This is a program a program that allows a user to enter data that is
written to a text file and will read the file.
Aggie Wheeler Bateman
10/17/19
'''
from tkinter.filedialog import askopenfilename
def main():
print("Hi! I am Text, and I will allow you to enter a text file, and I will read the file.")
print()
userTextFile = askopenfilename()
data = open(userTextFile, "r")
print(data.read()) #This way of printing using a read method may cause the formatting to be lost
#You can also use a for loop to iterate each line of the data
#for line in data:
#print(line)
main()
| true |
44d93bddb7c00d2cc12e9203f52083a25cf05bb8 | ryanyb/Charlotte_CS | /gettingStarted.py | 1,952 | 4.6875 | 5 |
# This is a python file! Woo! It'll introduce printing and variable declaration.
# If you open it in a text editor like VS Code it should look nifty and like
# well, a bunch of text.
# As you can see, all of this stuff is written without the computer doing anything about it
# These are things called comments.
#T here's a few ways to leave comments in python3:
#Y ou can start a line with a # as I've done above
''' Or alternatively
If you want to do comments for multiple lines at a time like this
you can begin and end the block of text you want to comment
with tripple ticks as I did here. '''
#--------------
# Unlike in lots of other programming languages, you can kinda just... start coding without
# needing to wrap it in anything special.
print()
print("Sup bby")
print()
print("---------------")
print()
# We can also define variables without needing to be super precise about it:
x = 5
y = "bruh"
z = 5.12423
t = True
myList = [1, 2.123, 'a', y]
# We can print a bunch of things:
print(x, y, z, t, myList)
print()
# But maybe we want a a bit of formatting:
print ("x: ", x, "\ny: ", y, "\nz: ", z, "\nt: ", t, "\nmyList: ", myList)
print()
# But that line of code hurts my eyes, we can make it look less ugly and more intuitive:
print(
"x: ", x,
"\ny: ", y,
"\nz: ", z,
"\nt: ", t,
"\nmyList: ", myList
)
print()
print("---------------")
print()
# We can also do things within our print statement:
print(x + z)
print(not(t))
print()
print("---------------")
print()
# We can also pass some arguments into our print statement to dictate how it works.
# We can write end='' to tell it not to make a new line:
print("hey ", end='')
print("bby")
print()
print("---------------")
print()
# Finally, we can redefine our variables and python won't complain, which is pretty cool!
print(x)
x = "pineapple"
print(x) | true |
32b051aab1979bdbfebd0a416184a735eb8e298a | ProngleBot/my-stuff | /Python/scripts/Weird calculator.py | 849 | 4.21875 | 4 | try:
x = int(input('enter first number here: '))
y = int(input('enter second number here: '))
operators = ['+','-','*', '/']
operator = input(f'Do you want to add, multiply, subtract or divide these numbers? use {operators}')
def add(x, y):
result = x + y
return result
def subtract(x, y):
result = x - y
return result
def multiply(x, y):
result = x * y
return result
def divide(x, y):
result = x / y
return result
if operator == operators[0]:
print(add(x,y))
elif operator == operators[1]:
print(subtract(x,y))
elif operator == operators[2]:
print(multiply(x, y))
elif operator == operators[3]:
print(divide(x, y))
else:
print('idk')
except ValueError:
print('enter number please')
| true |
dc2a08d86e16079ae334445d83ce45fa77c27c79 | TareqJudehGithub/higher-lower-game | /main.py | 2,274 | 4.125 | 4 | from replit import clear
from random import choice
from time import sleep
from art import logo, vs, game_over_logo
from game_data import data
def restart_game():
game_over = False
while game_over == False:
restart = input("Restart game? (y/n) ")
if restart == "y":
# Clear screen between rounds:
clear()
sleep(1)
# Restart game:
higher_lower()
else:
print('''
Good Bye!''')
game_over = True
return
def check_answer(guess, a_followers, b_followers):
'''Use if statements to check if user is correct'''
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b"
def higher_lower():
# Display game logo
print(logo)
sleep(2)
score = 0
repeat_question = True
while repeat_question:
# Generate a random account from the game data.
account_a = choice(data)
account_b = choice(data)
if account_a == account_b:
account_b = choice(data)
def format_data(account):
'''Format the account into printable format.'''
account_name = account["name"]
account_desc = account["description"]
account_country = account["country"]
return f"{account_name}, a {account_desc}, from {account_country}"
print(f"Score: {score}")
print("")
print(f"A: {format_data(account_a)}.")
print(vs)
print(f"B: {format_data(account_b)}.")
print('''
''')
# Ask user for a guess.
guess = input("Who has more followers? (A or B): ").lower()
print('''
''')
# Check if user is correct
# Get follower count of each account
a_follower_count = account_a["follower_count"]
b_follower_count = account_b["follower_count"]
is_correct = check_answer(guess, a_follower_count, b_follower_count)
print(is_correct)
# Give user feedback on their guess:
if is_correct:
print("Correct!")
sleep(3)
score += 1
clear()
else:
repeat_question = False
print("Sorry, wrong answer.")
sleep(3)
clear()
print(game_over_logo)
print(f'''
Your Score: {score}
''')
score = 0
# Make the game repeatable
sleep(2)
restart_game()
higher_lower()
| true |
60c9b68333f9a33ca526e156e0947db767f69892 | ianneyens/Ch.03_Input_Output | /3.0_Jedi_Training.py | 1,461 | 4.65625 | 5 | # Sign your name:Ian Neyens
# In all the short programs below, do a good job communicating with your end user!
# 1.) Write a program that asks someone for their name and then prints a greeting that uses their name.
"""
print()
name = str(input("What is your name?:"))
print()
print("Hello", name)
'''
# 2. Write a program where a user enters a base and height and you print the area of a triangle.
'''
print()
print("Welcome to the area of a triangle calculator")
print()
base = float(input("Enter a base:"))
print()
height = float(input("Enter a height:"))
print()
print(.5*base*height)
'''
# 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference.
'''
print()
print("Welcome to the circumference calculator")
print()
radius = float(input("Enter a radius:"))
print()
print(2*3.14*radius)
'''
# 4. Ask a user for an integer and then print the square root.
'''
print()
print("Welcome to the square root calculator")
print()
num = int(input("Please enter a number:"))
print()
sqrt = (num**.5)
print("The square root of", num, "is", sqrt)
'''
# 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma.
# Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next.
'''
print()
mass=float(input("Please enter a mass:"))
print()
acc=float(input("Please enter acceleration:"))
print()
print("The force is", mass*acc)
print("Get it?")
"""
| true |
d30a8339678effc870e6dc5ad82917d1282acff9 | Laikovski/codewars_lessons | /6kyu/Convert_string_to_camel_case.py | 796 | 4.625 | 5 | """
Complete the method/function so that it converts dash/underscore delimited words into camel casing.
The first word within the output should be capitalized only if the original word was capitalized
(known as Upper Camel Case, also often referred to as Pascal case).
Examples
"the-stealth-warrior" gets converted to "theStealthWarrior"
"The_Stealth_Warrior" gets converted to "TheStealthWarrior"
"""
def to_camel_case(text):
str = text.title()
word = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'
ans=''
for j,i in enumerate(str):
if j == 0:
ans =ans + text[0]
else:
if i in word:
ans = ans + i
return ans
to_camel_case("the_stealth_warrior")
to_camel_case("The-Stealth-Warrior")
to_camel_case('The-Stealth-Warrior')
to_camel_case("A-B-C") | true |
eaa974e6367967cadc5b6faa9944fbaaa760557f | Laikovski/codewars_lessons | /6kyu/Longest_Palindrome.py | 511 | 4.28125 | 4 | # Longest Palindrome
#
# Find the length of the longest substring in the given string s that is the same in reverse.
#
# As an example, if the input was “I like racecars that go fast”, the substring (racecar) length would be 7.
#
# If the length of the input string is 0, the return value must be 0.
# Example:
#
# "a" -> 1
# "aab" -> 2
# "abcde" -> 1
# "zzbaabcd" -> 4
# "" -> 0
# don't solve
def longest_palindrome (s):
a = s[::-1]
print(s)
print(a)
longest_palindrome("babaklj12345432133d") | true |
cd4a14aa502abbcba0519428a684b01be17c0427 | Laikovski/codewars_lessons | /6kyu/New_Cashier_Does_Not_Know.py | 1,292 | 4.28125 | 4 | # Some new cashiers started to work at your restaurant.
#
# They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
#
# All the orders they create look something like this:
#
# "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
#
# The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
#
# Their preference is to get the orders as a nice clean string with spaces and capitals like so:
#
# "Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"
#
# The kitchen staff expect the items to be in the same order as they appear in the menu.
#
# The menu items are fairly simple, there is no overlap in the names of the items:
#
# 1. Burger
# 2. Fries
# 3. Chicken
# 4. Pizza
# 5. Sandwich
# 6. Onionrings
# 7. Milkshake
# 8. Coke
import re
def get_order(order):
menu_items = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']
result = ''
for i in range(len(menu_items)):
temp = re.findall(menu_items[i].lower(), order)
if len(temp) == 0:
continue
else:
result += ' '.join(temp) + ' '
print(result.title().rstrip())
get_order("pizzachickenfriesburgercokemilkshakefriessandwich") | true |
aecd95cb9a29890136688bffeb3d378dc70574fd | bryandeagle/practice-python | /03 Less Than Ten.py | 648 | 4.34375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list
that areless than 5.
Extras:
1. Instead of printing the elements one by one, make a new list that has all
the elements less than 5 from this list in it and print out this new list.
2. Write this in one line of Python.
3. Ask the user for a number and return a list that contains only elements
from the original list a that are smaller than that number given by the
user.
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(input('Upper limit:'))
print([x for x in a if x < num])
| true |
6f9a10bbf9d0064cc111e7be3a9ed458fc615e46 | bryandeagle/practice-python | /18 Cows And Bulls.py | 1,358 | 4.375 | 4 | """
Create a program that will play the “cows and bulls” game with the user.
The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they
have a “cow”. For every digit the user guessed correctly in the wrong place
is a “bull.” Every time the user makes a guess, tell them how many “cows” and
“bulls” they have. Once the user guesses the correct number, the game is over.
Keep track of the number of guesses the user makes throughout the game and tell
the user at the end.
Say the number generated by the computer is 1038. An example interaction could
look like this:
Welcome to the Cows and Bulls Game!
Enter a number:
>>> 1234
2 cows, 0 bulls
>>> 1256
1 cow, 1 bull
...
Until the user guesses the number.
"""
from random import randrange
answer = "{:04d}".format(randrange(9999))
print('Welcome to the Cows and Bulls Game!')
count, guess = 0, ''
while guess != answer:
guess = input('Enter a number:')
count += 1
cows, bulls = 0, 0
for i, v in enumerate(guess):
if v == answer[i]:
cows += 1
elif v in answer:
bulls += 1
print('{} cow(s), {} bull(s)'.format(cows, bulls))
print('You\'ve Won! The answer was {}.'.format(answer))
| true |
2fec0f04fce0558c8f4a2d9ff8ced1f36c8b2c14 | bryandeagle/practice-python | /06 String Lists.py | 406 | 4.4375 | 4 | """
Ask the user for a string and print out whether this string is a palindrome or
not. (A palindrome is a string that reads the same forwards and backwards.)
"""
string = input('Give me a string:').lower()
palindrome = True
for i in range(int(len(string)/2)):
if string[i] != string[-i-1]:
palindrome = False
break
print({True: 'Palindrome', False: 'Not a Palindrome'}[palindrome])
| true |
2f12138956586c72818de4c13b73eb04e0e0d9fb | stybik/python_hundred | /programs/27_print_dict.py | 309 | 4.21875 | 4 | # Define a function which can generate a dictionary where the keys are numbers
# between 1 and 20 (both included) and the values are square of keys.
# The function should just print the values only.
numbers = int(raw_input("Enter a number: "))
dic = {n: n**2 for n in range(1, numbers)}
print dic.values()
| true |
646f89a757e6406543bec77dab04d9f61f97308d | stybik/python_hundred | /programs/10_whitespace.py | 342 | 4.125 | 4 | # Write a program that accepts a sequence of whitespace
# separated words as input and prints the words after
# removing all duplicate words and sorting them
# alphanumerically.
string = "Hello world, I am the boss boss the world should fear!"
words = string.split(" ")
print ("The answer is: ")
print (" ".join(sorted(list(set(words)))))
| true |
ddcc1201c4fdd399c98f67689fc6a90cc5677069 | stybik/python_hundred | /programs/6_formula.py | 480 | 4.15625 | 4 | # Write a program that calculates and prints the value according to the given formula:
# Q = Square root of [(2 * C * D)/H]
# Following are the fixed values of C and H:
# C is 50. H is 30.
# D is the variable whose values should be input to your program in a comma-separated sequence.
import math
c = 50
h = 30
val = []
items = [x for x in raw_input().split(",")]
print items
for d in items:
val.append(str(int(round(math.sqrt(2 * c * float(d) / h)))))
print ",".join(val)
| true |
2f86621b953186c71e491a3fd164c96deca3b7f2 | stybik/python_hundred | /programs/21_robot.py | 1,045 | 4.53125 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# ¡
# The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
import math
class Direction:
UP = "UP"
DOWN = "DOWN"
LEFT = "LEFT"
RIGHT = "RIGHT"
pos = [0, 0]
while True:
s = raw_input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction == Direction.UP:
pos[0] += steps
elif direction == Direction.DOWN:
pos[0] -= steps
elif direction == Direction.LEFT:
pos[1] -= steps
elif direction == Direction.RIGHT:
pos[1] += steps
else:
pass
print int(round(math.sqrt(pos[1]**2 + pos[0]**2)))
| true |
61585cbf2848306932b35664530ba2ba925d1f22 | JoeyParshley/met_cs_521 | /jparshle@bu.edu_hw_3/jparshle@bu.edu_hw_3_8_1.py | 1,687 | 4.3125 | 4 | """
Joey Parshley
MET CS 521 O2
30 MAR 2018
hw_3_8_1
Description: Write a program that prompts the user to enter a Social Security
number in the format ddd-dd-dddd, where d is a digit. The program displays
Valid SSN for a correct Social Security number or Invalid SSN otherwise.
"""
def ssn_validation (ssn_entry):
"""
Decription: determine if the string is a valid ssn in the format:
ddd-ddd-dddd
:input param : ssn_entry - string to validated as a ssn
:validation_string - string stating the validity of entry
"""
if len(ssn_entry) != 11:
validation_string = "\nInvalid SSN\n"
else:
# loop through ssn_entry and test that each character is a digit
for char in ssn_entry:
# skip the dashes
if char is '-':
continue
else:
# if you can convert the char to int it is a digit and
# valid so far
try:
is_digit = int(char)
validation_string = "\nValid SSN\n"
# as soon as you cannot convert a character to a digit
# its invalid
except:
validation_string = "\nInvalid SSN\n"
break
return validation_string
invalid_entry = True
#prompt the user for a social security number with hyphens
while invalid_entry:
ssn_entry = input("\nPlease enter a Social Security Number in the "
"format ddd-dd-dddd: ")
# if ssn_entry has no dashes keep asking
invalid_entry = ssn_entry.find('-') is -1
# output ssn validity to the console
print(ssn_validation(ssn_entry))
| true |
30b1452a33dc76783e68a00f0a2a329acb1402a9 | JoeyParshley/met_cs_521 | /jparshle@bu.edu_hw_2/jparshle@bu.edu_hw_2_2_3.py | 774 | 4.40625 | 4 | """
Joey Parshley
MET CS 521 O2
26 MAR 2018
hw_2_2_3
Write a program that reads a number in feet, converts it to meters, and
displays the result.
One foot is 0.305 meters.
"""
# Greet the user and prompt them for a measurement in feet
print("\nThis program will read a measurement in feet from the console and "\
"convert the result to meters and display the result.\n")
# get the measurement from the user
try:
feet = float(input("Please enter your length in feet: "))
except ValueError:
print("\nSorry I was expecting a number. Please try again. \n")
# Convert the length from feet to meters
meters = feet * 0.305
# Display the converted temperature to the console.
print("\n{0:g} feet is equal to {1:,.2f} meters.\n".format(feet, meters)) | true |
2a4854737b37f2659e6b11ca4dd1e91fd0162448 | JoeyParshley/met_cs_521 | /jparshle@bu.edu_hw_2/jparshle@bu.edu_hw_2_3_1.py | 2,292 | 4.53125 | 5 | """
Joey Parshley
MET CS 521 O2
26 MAR 2018
hw_2_3_1
Write a program that prompts the user to enter the length from the center of
a pentagon to a vertex and computes the area of the pentagon
"""
# import the math module to use sin and pi
import math
# Contstants to be used in functions
# used to calculate pentagon side
TWO_SIN_PI_OVER_5 = 2 * math.sin(math.pi/5)
# used to calculate pentagon area
AREA_CONSTANT = (3 * math.sqrt(3)) / 2
# Greet the user and prompt them for a measurement in feet
print("\nThis program computes the area of a pentagon based on the distance" \
"from the center of the prgram to a vertex.\n")
# Get the distance from the center of the pentagon to a vertex
try:
vertex_distance = float(input("\nPlease enter the distance from the center of "\
"the pentagon to the vertex: "))
except ValueError:
print("\nSorry I was expecting a number for the distance to the vetex. " \
"Please try again. \n")
def pentagon_side (r):
"""
Description: Calculates the side length of a pentagon
:input param : r - represents the distance from the center of the pentagon
to a vertex
:returns : length - represents the length of one of the sides of the
pentagon
"""
# calculate the length based on the circumradius
length = r * TWO_SIN_PI_OVER_5
return length
def pentagon_area (r):
"""
Description: Calculates the area of a pentagon based on the
side of the pentgon
Uses the equation:
Area = (3 * sqrt(3) / 2) * s * s
:input param : r - represents the distance from the center of the pentagon
to a vertex (circumradius) used to calculate the side of the pentagon.
:returns : area - represents the area of the pentagon
"""
# calculate the pentagon side based on the circumradius (r)
side = pentagon_side(r)
# calculate the pentagon area based on the side (side)
area = side * side * AREA_CONSTANT
# return the area
return area
# get area of the pentagon and display it to the console
area = pentagon_area(vertex_distance)
print(
"\nThe area of a pentagon with a vertex distance of {0:g} is {1:,.2f}.\n"
.format(vertex_distance, area))
| true |
be808b86dd30bf6983fa13f28a5feba15ef6efce | puneet4840/Data-Structure-and-Algorithms | /Queue in Python/1 - Creating Queue using python List.py | 1,889 | 4.25 | 4 | # Queue is the ordered collection of items which follows the FIFO (First In First Out) rule.
## Insertion is done at rear end of the queue and Deletion is done at front end of the queue.
print()
class Queue():
def __init__(self):
self.size=int(input("\nEnter the size of the Queue: "))
self.que=list()
def Enqueue(self,item):
if len(self.que)==self.size:
print("\n>>>> Queue is Full")
else:
self.que.append(item)
def Dequeue(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
self.que.pop(0)
def Front(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
print(f"\nFront: {self.que[0]}")
def Rear(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
print(f"\nRear: {self.que[-1]}")
def Display(self):
if len(self.que)==0:
print("\n>>>> Queue is Empty")
else:
print("Queue -->")
for item in self.que:
print(f"{item} <-- ",end=" ")
if __name__ == "__main__":
q=Queue()
while True:
print("\n------------------")
print("\n1: Enqueue")
print("\n2: Dequeue")
print("\n3: Front Element")
print("\n4: Rear Element")
print("\n5: Display the Queue")
print("\n6: Exit")
x=int(input("\nEnter your Choice: "))
if x==1:
item=int(input("\nEnter the element: "))
q.Enqueue(item)
elif x==2:
q.Dequeue()
elif x==3:
q.Front()
elif x==4:
q.Rear()
elif x==5:
q.Display()
elif x==6:
quit()
else:
print("\nInvalid Choice\n") | true |
9467799833a6c78fc4097870f8ec7c917f45ca68 | puneet4840/Data-Structure-and-Algorithms | /Stack in Python/3 - Reverse a string using stack.py | 571 | 4.1875 | 4 | # Reverse a string using stack.
# We first push the string into stack and pop the string from the stack.
# Hence, string would be reversed.
print()
class Stack():
def __init__(self):
self.stk=list()
self.str=input("Enter a string: ")
def Push(self):
for chr in self.str:
self.stk.append(chr)
def Pop(self):
print("\nReversed String:")
i=len(self.stk)-1
while i>=0:
print(self.stk[i],end="")
i-=1
if __name__ == "__main__":
s=Stack()
s.Push()
s.Pop()
| true |
79b5b14d8006fc6ee9598d4bfc46518289510fe4 | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/2 - Doubly Linked List/4 - Insertion before specific node.py | 2,390 | 4.25 | 4 | # Inserting a node before a specific node in the linked list.
print()
class Node():
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
class Linked_list():
def __init__(self):
self.start=None
def insert_node(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
x=self.start
while x.next!=None:
x=x.next
x.next=temp
temp.prev=x
def Insert_Node_Before(self):
if self.start==None:
print('\nLinked List is Empty')
else:
ele=int(input("Enter the Element in new node: "))
new_node=Node(ele)
node_data=int(input("Enter the node before insert node: "))
if node_data==self.start.data:
x=new_node
new_node.next=self.start
self.start.prev=new_node
self.start=x
else:
ptr=self.start
pre_ptr=None
while ptr.data!=node_data:
pre_ptr=ptr
ptr=ptr.next
if ptr.next==None:
pre_ptr.next=new_node
new_node.next=ptr
new_node.prev=pre_ptr
ptr.prev=new_node
else:
pre_ptr.next=new_node
new_node.next=ptr
new_node.prev=pre_ptr
ptr.prev=new_node
def Display(self):
if self.start==None:
print('\nLinked List is Empty')
else:
q=self.start
while q!=None:
print(q.data,end='->')
q=q.next
if __name__=='__main__':
LL=Linked_list()
print()
while True:
print()
print('\n===============')
print('1: Insert Node in End')
print('2: Insert Node Before a given Node: ')
print('3: Display')
print('4: Exit')
ch=int(input("Enter the choice: "))
if ch==1:
item=int(input("Enter the Element: "))
LL.insert_node(item)
elif ch==2:
LL.Insert_Node_Before()
elif ch==3:
LL.Display()
elif ch==4:
quit()
else:
print('\n Invalid Choice') | true |
1292d9ae7544923786c98b67c4c2c426314f3cac | puneet4840/Data-Structure-and-Algorithms | /Recursion in Python/Binary Search using python.py | 798 | 4.125 | 4 | # Binary Search using Python.
# It takes o(logn) time to execute the algorithm.
l1=list()
size=int(input("Enter the size of list: "))
for i in range(size):
l1.append(int(input(f"\nEnter element {i+1}: ")))
l1.sort()
def Binary_Search(l1,data,low,high):
if(low>high):
return False
else:
mid=(low+high)//2
if data==l1[mid]:
return mid
elif data<l1[mid]:
return Binary_Search(l1,data,low,mid-1)
elif data>l1[mid]:
return Binary_Search(l1,data,mid+1,high)
print("\nSorted List")
print(l1)
print()
data=int(input("\nEnter the Data you want to search: "))
low=0
high=len(l1)-1
if __name__ == "__main__":
ele=Binary_Search(l1,data,low,high)
print(f'\nThe given element is present at {ele} position') | true |
d03538d4dca196e6fda1d7508233a8f9ce2852a6 | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/5 - Queue using Linked LIst/12 - Queue using Linked lIst.py | 1,436 | 4.1875 | 4 | # Implementing Queue using Linked list.
print()
class Node():
def __init__(self,data):
self.data=data
self.next=None
class Linkd_list():
def __init__(self):
self.start=None
def Insert_at_end(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
x=self.start
while x.next!=None:
x=x.next
x.next=temp
def Delete_First(self):
if self.start==None:
print('\nLinked List is Empty')
else:
t=self.start
t=self.start.next
self.start=t
def Display(self):
if self.start==None:
print('\nLinked List is Empty')
else:
ptr=self.start
while ptr!=None:
print(ptr.data,end='->')
ptr=ptr.next
if __name__ == "__main__":
ll=Linkd_list()
while True:
print()
print('=============')
print('1: Enqueue')
print('2: Dequeue')
print('3: Display')
print('4: Exit')
ch=int(input("Enter the Choice: "))
if ch==1:
item=int(input("Enter the Element: "))
ll.Insert_at_end(item)
elif ch==2:
ll.Delete_First()
elif ch==3:
ll.Display()
elif ch==4:
quit()
else:
print('\nInvalid Choice') | true |
9a46984cc1655739334a16a11f1f252dc20cdd91 | puneet4840/Data-Structure-and-Algorithms | /Recursion in Python/Print numbers from 1 to 10 in a way when number is odd add 1 ,when even subtract 1.py | 393 | 4.3125 | 4 | # Program to print the numbers from 1 to 10 in such a way that when number is odd add 1 to it and,
# when number is even subtract 1 from it.
print()
def even(n):
if n<=10:
if n%2==0:
print(n-1,end=' ')
n+=1
odd(n)
def odd(n):
if n<=10:
if n%2!=0:
print(n+1,end=' ')
n+=1
even(n)
odd(1)
| true |
fa0bf4de5631301d3ee23a655a62980dde419eab | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/1 - Singly Linked List/2 - Creating linked list.py | 1,266 | 4.21875 | 4 | # Linked List is the collection of nodes which randomly stores in the memory.
print()
class Node():
def __init__(self,data):
self.data=data
self.next=None
class Linked_List():
def __init__(self):
self.start=None
def Insert_Node(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
ptr=self.start
while ptr.next!=None:
ptr=ptr.next
ptr.next=temp
def Display(self):
if self.start==None:
print("\nLinked List is Empty")
else:
ptr=self.start
while ptr!=None:
print(ptr.data,end="-->")
ptr=ptr.next
if __name__ == "__main__":
ll=Linked_List()
while True:
print()
print('========================')
print('1: Insert Node at the end')
print('2: Display Linked List')
print('3: Exit')
ch=int(input("Enter your choice: "))
if ch==1:
item=int(input("Enter the Data: "))
ll.Insert_Node(item)
elif ch==2:
ll.Display()
elif ch==3:
quit()
else:
print("\nInvalid Choice") | true |
e565859face5705525c10fe91e6e9e5111088773 | stuartses/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,552 | 4.53125 | 5 | #!/usr/bin/python3
"""1. Divide a matrix
This module divides all elements of a matrix in a number
Corresponds to Task 1.
Holberton School
Foundations - Higher-level programming - Python
By Stuart Echeverry
"""
def matrix_divided(matrix, div):
"""Function that divides all elements of a matrix in a number
Args:
matrix (list): List of list. Each element inside Matrix must to be \
integer or float
div (int): Divisor must to be integer or float
Returns:
list: new matrix
"""
if type(matrix) != list:
raise TypeError("matrix must be a matrix (list of lists) of \
integers/floats")
if type(div) != int and type(div) != float:
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
new_matrix = []
is_matrix = all(isinstance(ele, list) for ele in matrix)
if is_matrix is False:
raise TypeError("matrix must be a matrix (list of lists) of \
integers/floats")
for i in range(len(matrix)):
new_row = []
if i < len(matrix) - 1 and len(matrix[i]) != len(matrix[i + 1]):
raise TypeError("Each row of the matrix must have the same size")
for value in matrix[i]:
if type(value) != int and type(value) != float:
raise TypeError("matrix must be a matrix (list of lists) of \
integers/floats")
new_value = round(float(value) / float(div), 2)
new_row.append(new_value)
new_matrix.append(new_row)
return new_matrix
| true |
b00edcdc40657f72d82766fd72da4de8d4b7c8cc | stuartses/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 699 | 4.125 | 4 | #!/usr/bin/python3
"""0. Integers addition
This module adds two input integer numbers.
Corresponds to Task 0.
Holberton School
Foundations - Higher-level programming - Python
By Stuart Echeverry
"""
def add_integer(a, b=98):
"""Functions that adds two integers
Args:
a (int): first argument. Could be float, too
b (int): second argument, by default=98. Could be float, too
Returns:
int: The return value convert arguments to integer and adds.
"""
if type(a) != int and type(a) != float:
raise TypeError("a must be an integer")
if type(b) != int and type(b) != float:
raise TypeError("b must be an integer")
return int(a) + int(b)
| true |
4ff3c3cd3009d5a9984928b54a89748b7792bec5 | MyrPasko/python-test-course | /lesson11.py | 567 | 4.25 | 4 | # String formatting
name = 'Johny'
age = 32
title = 'Sony'
price = 100
print('My name is ' + name + ' and I\'m ' + str(age) + ' old.')
print('My name is %(name)s and I\'m %(age)d old.' % {'name': name, 'age': age})
print('My name is %s and I\'m %d old. %s' % (name, age, name))
print('Title: %s, price: %.2f' % ('Sony', 100))
# Modern method .format
print('Title: {1}, price: {0}'.format(title, price))
print('Title: {title}, price: {price}'.format(title=title, price=price))
# F-strings
print(f'Title: {title}, price: {price}. This is the most popular method.')
| true |
e23e20632d635370cf05b8e1f6c0079cf1e173c3 | FedoseevAlex/algorithms | /tests/insert_sorting_test.py | 1,750 | 4.1875 | 4 | #!/usr/bin/env python3.8
from unittest import TestCase
from random import shuffle
from algorithms.insert_sorting import increase_sort, decrease_sort
class InsertionSortTest(TestCase):
"""
Test for insertion sorting functions
"""
def test_increasing_sort_static(self):
"""
Testing insertion sort in increasing order implementation.
Check result using static array.
"""
input_array = [3, 1, 4, 5, 2, 6]
output_array = [1, 2, 3, 4, 5, 6]
result = increase_sort(input_array)
self.assertListEqual(output_array, result)
def test_decreasing_sort_static(self):
"""
Testing insertion sort in decreasing order implementation.
Check result using static array.
"""
input_array = [3, 1, 4, 5, 2, 6]
output_array = [6, 5, 4, 3, 2, 1]
result = decrease_sort(input_array)
self.assertListEqual(output_array, result)
def test_increasing_sort_random(self):
"""
Testing insertion sort in increasing order implementation.
Check result using random shuffled array.
"""
output_array = list(range(10000))
input_array = output_array.copy()
shuffle(input_array)
result = increase_sort(input_array)
self.assertListEqual(output_array, result)
def test_decreasing_sort_random(self):
"""
Testing insertion sort in decreasing order implementation.
Check result using random shuffled array.
"""
output_array = list(range(10000, -1))
input_array = output_array.copy()
shuffle(input_array)
result = decrease_sort(input_array)
self.assertListEqual(output_array, result)
| true |
29847749ede6139ce34c257e2aed969f03a0bd13 | srikanthpragada/PYTHON_03_AUG_2021 | /demo/libdemo/list_customers_2.py | 1,097 | 4.125 | 4 | def isvalidmobile(s):
"""
Checks whether the given string is a valid mobile number.
A valid mobile number is consisting of 10 digits
:param s: String to test
:return: True or False
"""
return s.isdigit() and len(s) == 10
def isvalidname(s):
"""
Checks whether the given name contains only Alphas and Spaces
:param s: String to test
:return: True or False
"""
for c in s:
if not (c.isalpha() or c == ' '):
return False
return True
f = open("customers2.txt", "rt")
customers = {}
for line in f.readlines():
parts = line.strip().split(",")
if len(parts) > 1:
name = parts[0]
mobile = parts[1]
if not (isvalidname(name) and isvalidmobile(mobile)):
continue
if name in customers:
customers[name].add(mobile) # Add mobile to existing set of mobiles
else:
customers[name] = {mobile} # Add a new entry with name and mobile
f.close()
for name, mobiles in sorted(customers.items()):
print(f"{name:15} {','.join(sorted(mobiles))}")
| true |
30e0997cb7359cd6f14b98717c68d409c6f68aec | dalexach/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/1-sensitivity.py | 684 | 4.3125 | 4 | #!/usr/bin/env python3
"""
Sensitivity
"""
import numpy as np
def sensitivity(confusion):
"""
Function that calculates the sensitivity for each class
in a confusion matrix
Arguments:
- confusion: is a confusion numpy.ndarray of shape (classes, classes)
where row indices represent the correct labels and column
indices represent the predicted labels
* classes is the number of classes
Returns:
A numpy.ndarray of shape (classes,) containing the sensitivity
of each class
"""
TP = np.diag(confusion)
FN = np.sum(confusion, axis=1) - TP
SENSITIVITY = TP / (TP + FN)
return SENSITIVITY
| true |
e62b085add02d42761f087761eeccfe1c55b53d4 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/4-moving_average.py | 608 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Moving average
"""
def moving_average(data, beta):
"""
Function that calculates the weighted moving average of a data set:
Arguments:
- data (list): is the list of data to calculate the moving average of
- beta (list): is the weight used for the moving average
Returns:
A list containing the moving averages of data
"""
moving_average = []
V = 0
t = 1
for d in data:
V = beta * V + (1 - beta) * d
correct = V / (1 - (beta ** t))
moving_average.append(correct)
t += 1
return moving_average
| true |
b01b43fb042dd2345fd2778fd4c75418b95b7a97 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/1-normalize.py | 621 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Normalize
"""
import numpy as np
def normalize(X, m, s):
"""
Function that normalizes (standardizes) a matrix
Arguments:
- X: is the numpy.ndarray of shape (d, nx) to normalize
* d is the number of data points
* nx is the number of features
- m: is a numpy.ndarray of shape (nx,) that contains the mean of
all features of X
- s: is a numpy.ndarray of shape (nx,) that contains the standard
deviation of all features of X
Returns:
The normalized X matrix
"""
standardizes = (X - m) / s
return standardizes
| true |
2e7755488ee4f5f74d8120d2d10ef04b0446c37b | Wet1988/ds-algo | /algorithms/sorting/quick_sort.py | 1,132 | 4.21875 | 4 | import random
def quick_sort(s, lower=0, upper=None):
"""Sorts a list of numbers in-place using quick-sort.
Args:
s: A list containing numbers.
lower: lower bound (inclusive) of s to be sorted.
upper: upper bound (inclusive) of s to be sorted.
Returns:
s
"""
if upper is None:
upper = len(s) - 1
# base case (1 element or less)
if lower >= upper:
return
# choose random index as pivot
pivot = random.randint(lower, upper)
# perform partitioning
left = lower
right = upper
done = False
while done is False:
while s[left] < s[pivot]:
left += 1
while s[right] > s[pivot]:
right += 1
if left >= right:
done = True
else:
s[left], s[right] = s[right], s[left]
left += 1
right += 1
# partition element
part = right
# recurse
quick_sort(s, lower, part)
quick_sort(s, part + 1, upper)
if __name__ == "__main__":
n = 100
s = [random.randint(0, n) for x in range(n)]
quick_sort(s)
print(s)
| true |
6d5fa9841aaed33cade266f564debefbd97e82a0 | JustinCee/tkinter-handout | /handout exercise.py | 1,103 | 4.375 | 4 | # this is to import the tkinter module
from tkinter import *
# this function is to add the numbers
def add_numbers():
r = int(e1.get())+int(e2.get())
label_text.set(r)
def clear():
e1.delete(0)
e2.delete(0)
root = Tk()
# the below is the size of the window
root.geometry("600x200")
root.title("Justin's simple calculator")
label_text = StringVar()
Label(root, text="Enter First Number:").grid(row=0, sticky=W)
Label(root, text="Enter Second Number:").grid(row=1, sticky=W)
Label(root, text="Result of Addition:").grid(row=3, sticky=W)
result = Label(root, text="", textvariable=label_text).grid(row=3, column=1, sticky=W)
e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
# below is the button and the labels on it
b = Button(root, text="Add", command=add_numbers)
b1 = Button(root, text="Clear", command=clear)
b2 = Button(root, text="Exit", command=root.destroy)
b.grid(row=5, column=1, sticky=W+E+N+S, padx=5, pady=5)
b1.grid(row=5, column=2, sticky=W+E+N+S, padx=5, pady=5)
b2.grid(row=5, column=3, sticky=W+E+N+S, padx=5, pady=5)
mainloop()
| true |
84e78624aa3c0171d05b430576946cad18360fdf | BC-CSCI-1102-S19-TTh3/example_code | /week10/dictionarydemo.py | 507 | 4.40625 | 4 | # instantiating a dictionary
mydictionary = {}
# adding key-value pairs to a dictionary
mydictionary["dog"] = 2
mydictionary["cat"] = 17
mydictionary["hamster"] = 1
mydictionary["houseplant"] = 5
# getting a value using a key
mycatcount = mydictionary["cat"]
# looping through keys in a dictionary
for k in mydictionary.keys():
print(k, mydictionary[k])
# looping through keys and values
for k,v in mydictionary.items():
print(k,v)
if "cat" in mydictionary:
print("cat is in the dictionary!")
| true |
3df5c17e536ddf072745ff1dca3aae6a7f265c51 | llamington/COSC121 | /lab_8_5.py | 1,783 | 4.34375 | 4 | """A program to read a CSV file of rainfalls and print the totals
for each month.
"""
from os.path import isfile as is_valid_file
def sum_rainfall(month, num_days, columns):
"""sums rainfall"""
total_rainfall = 0
for col in columns[2:2 + num_days]:
total_rainfall += float(col)
return month, total_rainfall
def process_data(data):
"""processes data"""
results = [] # A list of (month, rainfall) tuples
for line in data:
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])
results.append(sum_rainfall(month, num_days, columns))
return results
def print_rainfalls(results):
"""prints total rainfalls"""
print('Monthly total rainfalls')
for (month, total_rainfall) in results:
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
def get_filename():
"""receives filename"""
filename = input('Input csv file name? ')
while not is_valid_file(filename):
filename = input('Input csv file name? ')
print('File does not exist.')
return filename
def data_list(filename):
"""processes data into list"""
datafile = open(filename)
data = datafile.read().splitlines()
datafile.close()
return data
def main():
"""Prompt the user to provide a csv file of rainfall data, process the
given file's data, and print the monthly rainfall totals.
The file is assumed to have the month number in column 1, the number
of days in the month in column 2, and the floating point rainfalls
(in mm) for that month in the remaining columns of the row.
"""
filename = get_filename()
data = data_list(filename)
results = process_data(data)
print_rainfalls(results)
main()
| true |
cdf618d95d1d4e99aeccf6e67df08a96a7f812a7 | RSnoad/Python-Problems | /Problem 7.py | 588 | 4.125 | 4 | # Find the 10,001st prime number
from math import sqrt
# Function to find the nth prime in list using the isPrime function below.
def nthPrime(n):
i = 2
primeList = []
while len(primeList) < n:
if isPrime(i):
primeList.append(i)
i += 1
print(primeList[-1])
# Brute force method to check if a number is prime.
# Could also clean up to give error for certain input ( negatives, decimals etc)
def isPrime(n):
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
return False
return True
nthPrime(6)
nthPrime(10001)
| true |
685452c53ea915107f3f2a2ec2ef020a1702f132 | isaac-friedman/lphw | /ex20-2.py | 1,661 | 4.6875 | 5 | ####
#This file combines what we've learned about functionwas with what we've
#learned about files to show you how they can work together. It also
#sneaks in some more info about files which you may or may not know depending
#on if you did the study drills.
####
from sys import argv
#In some of my versions of the study drills, I access the arguments I want
#directly using [brackets]. Is this a good idea? Does it make any difference at
#all? Think about it.
script, input_file = argv
#read and print the whole file in one shot
def print_all(f):
print f.read()
#move the iterator to the beginning of the file specified.
#Is printing necessary? Why or why not?
def rewind(f):
print f.seek(0)
#Prints line line_count of file f
def print_a_line(line_count, f):
print line_count, f.readline()
#Get a file object
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print """
We printed using a iterator *aaahh!!! scary word*. That iterator is now at the
end of the file, so we have to rewind it like a tape.
"""
#What happens if you comment out this line?
rewind(current_file)
print "Let's print all the lines one by one."
current_line = 1
print "current_line is equal to %d" %current_line
print_a_line(current_line, current_file)
#If you think this repetition is silly, you're rights. Soon we will learn about
#loops which exist to solve this problem.
current_line = current_line + 1
print "current_line is equal to %d" %current_line
print_a_line(current_line, current_file)
current_line = current_line + 1
print "current_line is equal to %d" %current_line
print_a_line(current_line, current_file)
| true |
21e7a38cfa5194e6b321693cbe24008421ff0974 | isaac-friedman/lphw | /ex13-3_calc.py | 1,129 | 4.6875 | 5 | ####
#More work with argv
#This time we will use argv to collect two operands and then use raw input to
#ask for an arithmetic operation to perform on them. Effectively, we've just
#made a basic calculator
####
from sys import argv
####
#See how we aren't checking to make sure the arguments are numbers? That is a
#Very Bad Idea. Run the script with something other than numbers to find out
#why.
####
script, first, second = argv #script is always an argument
#input is like raw_input except that it reads a python expression
op = raw_input("Which arithmetic operation would you like to perform?")
####
#Making sure your input is the right kind of data, and knowing what to do if it
#isn't is called "validation". This is a very simple kind of validation to make
#sure we were given an arithmetic operator.
####
if op in ['+','-','*','/','%','**']: #all the arithmetic python supports
exp = first + op + second #makes an expression with our string in it
result = eval(exp) #eval takes a string and treats it like python code
print result
else:
print "bad operation. goodbye" #this is a horrible way to handle errors
| true |
d1c8dbc2a8c9ba6edff5ff330a826997c5c019dc | isaac-friedman/lphw | /ex15.py | 1,390 | 4.5 | 4 | ####
#This script prints a specified file to the screen. More specifically, it
#prints to something called "standard output" which is almost always the screen
#but could be something else. For now, think of 'print' as 'printing to the
#screen' and 'standard output' or 'stdio' etc as "the screen." It's easier and
#pretty much always true.
####
#get the argv to be able to access command line arguments
from sys import argv
#Unpack your variables. You will always have to unpack your script because
#argv reads (and counts) the arguments to the `python` command not to your
#script.
script, filename = argv
#txt is a 'file object'. You should google those because they're very important
#for I/O, and a good way to begin understanding how to use objects in
#programming
txt = open(filename)
print "Here is your file %r:" %filename
#Here, we call the `read` function OF the txt object. This function reads the
#file.
print txt.read()
#it is important to close files when you are done with them.
nxt_txt.close()
#We do the same thing again, this time asking for input with a prompt
print "Type another file, or the same one for all I care."
#This is a nested function. Instad of putting the input in a variable,
#you can call `open` on it directly. Remember to have the same number of open
#and closed parentheses
nxt_txt = open(raw_input('> '))
print nxt_txt.read()
nxt_txt.close()
| true |
209880bc58394e1b26637a150f957699452642e9 | gabcruzm/Basis-Python-Projects | /loops/loop_through.py | 493 | 4.40625 | 4 | #Loop through a string with For
def run():
# name = input("Write your name: ")
# for letter in name: #For letters in the name it will print each letter in each loop.
# #letter is the variable that will represent each character in each repetition in the for loop. The characters are taken from the name wich is a str.
# print(letter)
frase = input("Write a phrase: ")
for caracter in frase:
print(caracter.upper())
if __name__ == "__main__":
run() | true |
e471cb0845e9550d954db99e807ac0adebd115c0 | maimoneb/dsp | /python/q8_parsing.py | 1,295 | 4.3125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
from csv import reader
with open('football.csv', 'rb') as csvfile:
csv_reader = reader(csvfile, delimiter=',')
header = next(csv_reader) # skip first(header) row
data = [row for row in csv_reader]
def min_score_difference(data, goals_index, goals_allowed_index):
goals = [x[goals_index] for x in data]
goals_allowed = [x[goals_allowed_index] for x in data]
differences = [int(x) - int(y) for x, y in zip(goals, goals_allowed)]
minimum, min_index = min((val, index) for (index, val) in enumerate(differences))
return min_index
goals_index = header.index('Goals')
goals_allowed_index = header.index('Goals Allowed')
team_name_index = header.index('Team')
result_index = min_score_difference(data, goals_index, goals_allowed_index)
print data[result_index][team_name_index]
| true |
72e7171a13387c6fcd77caf8c2c3b03ddf82c155 | pratikv06/python-tkinter | /Entry.py | 520 | 4.1875 | 4 | from tkinter import *
root = Tk()
# Define a function for button4 to perform
def myClick():
msg = "Hello, " + e.get() + "..."
myLabel = Label(root, text=msg)
myLabel.pack()
# Create a entry i.e. input area
# setting width of the entry
# changing border width of the entry
e = Entry(root, width=50, borderwidth=10)
e.pack()
# Setting a default value of entry
e.insert(0, "Enter Something:")
myButton = Button(root, text="Click Me!", command=myClick)
myButton.pack()
root.mainloop() | true |
21cae5cdc5b43d27e62d161e20d46712ae3d7282 | mdelite/Exercism | /python/guidos-gorgeous-lasagna/lasagna.py | 1,467 | 4.34375 | 4 | """Functions used in preparing Guido's gorgeous lasagna.
Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
"""
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 2
def bake_time_remaining(elapsed_bake_time):
"""Calculate the bake time remaining.
:param elapsed_bake_time: int - baking time already elapsed.
:return: int - remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME'.
Function that takes the actual minutes the lasagna has been in the oven as
an argument and returns how many minutes the lasagna still needs to bake
based on the `EXPECTED_BAKE_TIME`.
"""
return EXPECTED_BAKE_TIME - elapsed_bake_time
def preparation_time_in_minutes(layers):
"""Calculate the preperation time
:param layers: int - the number of layers to prepare
:return: int - time (in minutes) to prepare the lasagna
Function that the number of layers and returns how many minutes to prepare
based on the 'PREPARATION_TIME'.
"""
return layers * PREPARATION_TIME
def elapsed_time_in_minutes(layers, time):
"""Calculate the time elapsed.
:param layers: int - the number of layers in hte lasagna.
:param time: int
:return: int - time (in minutes) that has elapsed.
Function that calculates the total time that has elapsed in the preperation of
the lasagna.
"""
elapsed = preparation_time_in_minutes(layers) + time
return elapsed
| true |
1216602668067d9a17e4dd59c896d8fe2250be54 | sssmrd/pythonassignment | /38.py | 238 | 4.28125 | 4 | #program to add member(s) in a set.
l=input("Enter some elements=").split();
s=set(l);
print(s)
c=int(input("How many elements to enter="))
for i in range(0,c):
n=input("Enter the element to be added in set=")
s.add(n);
print(s) | true |
55b8617e66a268c69ef5e2e14861dcc494034b11 | edwardyulin/sit_project | /sit_il/utils/moving_average.py | 623 | 4.15625 | 4 | import numpy as np
def moving_average(data: np.ndarray, window_size: int) -> np.ndarray:
"""Return the moving average of the elements in a 1-D array.
Args:
data (numpy.ndarray): Input 1-D array.
window_size (int): The size of sliding window.
Returns:
numpy.ndarray: Moving average of the elements in `data`.
Examples:
>>> data = np.array([10,5,8,9,15,22,26,11,15,16,18,7])
>>> moving_average(data, 4)
array([ 8. , 9.25, 13.5 , 18. , 18.5 , 18.5 , 17. , 15. , 14. ])
"""
return np.convolve(data, np.ones(window_size), "valid") / window_size
| true |
b5aa438957ab34145e3e8228f28ffddc91251e80 | joshisujay1996/OOP-and-Design-Pattern | /oop/employee_basic.py | 1,049 | 4.3125 | 4 | """
Basic OOD Example
In python everything is derived from a class and they have their own methods, like List, tuple, int, float, etc
Everything is an Object in PY and they have there own methods and attributes
we create instance out of the list class or tuple or etc
pop, append,__str__, remove are methods of th list class
"""
class MyEmployee:
def __int__(self):
pass
MyEmployee.branch = "NY" # will be attached to all the objects fo the class
my_emp = MyEmployee()
my_emp.name = "sujay"
my_emp.age = 23
print(my_emp.branch) # the branch data is attached to all the objects fo the MyEMployee class
print("printing my_emp", my_emp)
print("printing in dic format \t", my_emp.__dict__) # See branch data is not shown on the dic output;
# since its a class instance var not a obj instance var, its same for every object of MyEmployee
print("Printing the MyEmployee class dic \n", MyEmployee.__dict__)
"""
__str__ : used to give string representation of the object
similarly __repr__; read about it for more detail
"""
| true |
5b0d75ecbaebe98998a91200d2cb95d667a7d8d6 | dhobson21/python-practice | /practice.py | 1,794 | 4.1875 | 4 | # 11/19/19--------------------------------------------------------------------------------
"""Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
"""
# My Solution
def toJadenCase(string):
words = string.split()
finish = []
for word in words:
new = word.capitalize()
finish.append(new)
s = " "
return s.join(finish)
"""
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"
"""
# My Solution
def spin_words(sentence):
words = sentence.split()
final_words = []
for word in words:
if len(word) > 4:
# Slice word and reverse if word is more than 4 characters long
rev = word[::-1]
final_words.append(rev)
else:
final_words.append(word)
s = " "
last = s.join(final_words)
return last | true |
5654828bd965177fc7ef341aecaf1fb897e59a1e | weekswm/cs162p_week8_lab8 | /Car.py | 1,291 | 4.25 | 4 | #Car class
class Car:
'''Creates a class Car
attributes: make, color, and year
'''
def __init__(self, make = 'Ford', color = 'black', year = 1910):
'''Creates a car with the provided make, color, year.
Defaults to Ford black 1910.
'''
self.make = make
self.color = color
self.year = year
'''Getters and Setters for make, color, and year
'''
#Getter and Setter for make
def getMake(self):
return self.make
def setMake(self, newMake):
self.make = newMake
#Getter and Setter for color
def getColor(self):
return self.color
def setColor(self, newColor):
self.color = newColor
#Getter and Setter for year
def getYear(self):
return self.year
def setYear(self, newYear):
self.year = newYear
# Overloading equality operator
def __eq__(self, differentCar):
'''Overloaded equality operator.
Returns True if color, year, and make match
'''
return (self.make == differentCar.make and self.color == differentCar.color and self.year == differentCar.year)
def __str__(self):
#Returns string of color, year, and make of Car
return ("%s %s %s" % (self.color, self.year, self.make)) | true |
2034276de5f99ed60e9ab3fd0d3e8d667c3e5ba0 | mugwch01/Trie | /Mugwagwa_Trie_DS.py | 2,267 | 4.21875 | 4 | #My name is Charles Mugwagwa. This is an implementation of a Trie data structure.
class Trie:
def __init__(self):
self.start = None
def insert(self, item):
self.start = Trie.__insert(self.start, item+"$")
def __contains__(self,item):
return Trie.__contains(self.start,item+"$")
#using this function because the node can be None and recursion on self complicated
def __insert(node,item):
if item == "":
return None
if node == None:
node = Trie.TrieNode(item[0])
node.follows = Trie.__insert(node.follows,item[1:])
elif item[0] == node.item:
node.follows = Trie.__insert(node.follows, item[1:])
else:
node.next = Trie.__insert(node.next, item)
return node
def __contains(node,item):
if node == None:
return False
elif item[0] == node.item:
if node.item == "$" and len(item) == 1:
return True
return Trie.__contains(node.follows,item[1:])
elif item[0] != node.item:
if node.next != None:
return Trie.__contains(node.next,item)
else:
return False
class TrieNode:
def __init__(self,item,next = None, follows = None):
self.item = item
self.next = next
self.follows = follows
def main():
trie = Trie()
file = open('wordsEn.txt','r')
for line in file:
line = line[:-1]
trie.insert(line)
file.close()
file = open('declaration_of_independence.txt','r')
lineCount = sum(1 for line in file) #includes blank lines
file.seek(0)
for t in range(lineCount):
line = file.readline()
if line != "":
splitLine = line.split()
for word in splitLine:
if word[-1]==',' or word[-1]=='.' or word[-1]==';' or word[-1]==':':
word = word[:-1]
word = word.lower()
if word not in trie:
print(word)
if __name__ == '__main__':
main() | true |
c1940693fd3eface908ff33ad53698b00bccba0a | patrickbucher/python-crash-course | /ch07/pizza-toppings.py | 294 | 4.125 | 4 | prompt = 'Which topping would you like to add to your pizza?'
prompt += '\nType "quit" when you are finished. '
topping = ''
active = True
while active:
topping = input(prompt)
if topping == 'quit':
active = False
else:
print(f'I will add {topping} to your pizza.')
| true |
05a6e73545aba94442b52eb8cfcced8225292cad | qmisky/python_fishc | /3-3 斐波那契数列-递归.py | 372 | 4.21875 | 4 | def factorial(x):
if x==1:
return 1
elif x==2:
return 1
elif x>2:
result=int(factorial(x-1))+int(factorial(x-2))
return result
elif x<0:
print ("WRONG NUMBER!")
number=int(input("please enter a positive number:"))
result=factorial(number)
print("the %d'th month,the amount of the rabbits is:%d"%(number,result))
| true |
c3fbdb921f822e4d6ebfeeeb8c11459af4f8af50 | jasonwsvt/Python-Projects | /db_sub.py | 1,389 | 4.375 | 4 | """
Use Python 3 and the sqlite3 module.
Database requires 2 fields: an auto-increment primary integer field and a field with the data type “string.”
Read from fileList and determine only the files from the list which end with a “.txt” file extension.
Add those file names from the list ending with “.txt” file extension within your database.
Print the qualifying text files to the console.
Provide good comments.
"""
import sqlite3
fileList = ('information.docx', 'Hello.txt', 'myImage.png', 'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg')
def commit(stmt):
with sqlite3.connect('db_sub.db') as conn:
cur = conn.cursor()
try:
cur.execute(stmt)
conn.commit()
except:
print(stmt + ' is not a valid query.')
conn.close()
def fetchall(stmt):
with sqlite3.connect('db_sub.db') as conn:
cur = conn.cursor()
try:
cur.execute(stmt)
result = cur.fetchall()
except:
result = stmt + ' is not a valid query.'
print(result)
conn.close()
return result
commit("create table if not exists tbl_strings(id integer primary key autoincrement, col_string string)")
for file in fileList:
if file.endswith('.txt'):
commit("insert into tbl_strings('col_string') values('{}')".format(file))
print("{} inserted into database.".format(file))
print("\nAll records in database:")
for record in fetchall("select * from tbl_strings"):
print(record) | true |
c526f0b569465e0e1a3cd10674793bff1debd6bf | luzap/intro_to_cs | /cs013/lab.py | 1,389 | 4.21875 | 4 | import random
import helpers
#
# Each of the following functions have an arbitrary return value. Your
# job is to edit the functions to return the correct value. You'll
# know it's correct because when you run test.py, the program will
# print "PASS" followed by the function name.
#
# Any code you add outside of these functions (in the global
# namespace) should be commented out before running test.py
#
def exponentiate(base, power):
"""Recursively obtain the result of an exponentiation operation."""
if power > 0:
return base * exponentiate(base, power - 1)
else:
return 1
def get_nth(list_of, n):
"""Get nth element of a list without slicing."""
if n:
# Why does this need a return statement?
return get_nth(helpers.tail(list_of), n - 1)
else:
return helpers.head(list_of)
def reverse(list_of):
if len(list_of) == 2:
return helpers.tail(list_of) + [helpers.head(list_of)]
else:
return reverse(helpers.tail(list_of)) + [helpers.head(list_of)]
def is_older(date_1, date_2):
if len(date_1):
if helpers.head(date_1) < helpers.head(date_2):
return True
else:
return is_older(helpers.tail(date_1), helpers.tail(date_2))
else:
return False
def number_before_reaching_sum(total, numbers):
pass
def what_month(day):
return 0
| true |
ecddeb829aa78cd91843859c3e72093580f00279 | Antrikshhii17/myPythonProjects | /DataStructure_Algorithm/Count_occurrences.py | 485 | 4.28125 | 4 | """ Program to count number of occurrences of each element in a list.
Asked in Precisely interview for Software Engineer-I """
def count_occurrences(ourlist):
# return dict((i, ourlist.count(i)) for i in ourlist) # List comprehension approach
dicx = {}
for j in ourlist:
dicx.__setitem__(j, ourlist.count(j))
return dicx
if __name__ == '__main__':
ourlist = [5, 3, 9, 3, 1, 6, 6, 6, 1, 2, 2, 6, 9, 2]
print(count_occurrences(ourlist))
| true |
1838b979bbf1c1b6ee4f1e872367325f2e3ea6da | Antrikshhii17/myPythonProjects | /DataStructure_Algorithm/Bubble_sort.py | 516 | 4.3125 | 4 | """ Bubble sort. Time complexity-
Worst case = O(n^2) , when the array is in descending order.
Average case = O(n^2) , when the array is jumbled.
Best case = O(n) , when the array is already sorted. """
def bubblesort(list):
for i in range(len(list)):
for j in range(len(list) - i - 1):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j]
if __name__ == '__main__':
list = [31, 9, 5, 10, 6, 12, 8, 1]
bubblesort(list)
print(list)
| true |
aba880ab4100a7c30c4b9fe8dbc5fd52da08a225 | vkhalaim/pythonLearning | /tceh/lection2/list_task_2.py | 359 | 4.15625 | 4 | objectList = ["Pokemon", "Digimon", "Dragon", "Cat", "Dog"]
# first method
for i in objectList:
print("Element of list -> " + i + "[" + str(objectList.index(i)) + "]"
+ "(in square braces index of element)")
# enumarate
print("-------------------")
for index, element in enumerate(objectList):
print(str(element + "[" + str(index) + "]"))
| true |
94a22ec4cf15613bf3ccce939d29bf6ba89f4a51 | J-Gottschalk-NZ/Random_String_generator | /main.py | 721 | 4.21875 | 4 | import string
import random
# Function to check string length is an integer that is > 0
def intcheck(question):
error = "Please enter an integer that is more than 0 \n"
valid = False
while not valid:
try:
response = int(input(question))
if response < 1:
print(error)
else:
return response
except ValueError:
print(error)
# Create string including letters, digits and symbols
random_characters = string.ascii_letters + string.digits + string.punctuation
how_many = intcheck("How many characters? ")
random_string = ""
for item in range(0,how_many):
random_char = random.choice(random_characters)
random_string += random_char
print(random_string) | true |
07c883f8fc0c761e210688b095c5c0e0d5cd82c8 | MMGroesbeck/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 2,097 | 4.1875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
i = 0
a = 0
b = 0
while i < elements:
if a >= len(arrA):
merged_arr[i] = arrB[b]
b += 1
elif b >= len(arrB):
merged_arr[i] = arrA[a]
a += 1
else:
if arrA[a] < arrB[b]:
merged_arr[i] = arrA[a]
a += 1
else:
merged_arr[i] = arrB[b]
b += 1
i += 1
return merged_arr
# TO-DO: implement the Merge Sort function below recursively
import math
def merge_sort(arr):
# Your code here
if len(arr) < 2:
return arr
else:
mid = math.floor(len(arr) / 2)
return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))
# STRETCH: implement the recursive logic for merge sort in a way that doesn't
# utilize any extra memory
# In other words, your implementation should not allocate any additional lists
# or data structures; it can only re-use the memory it was given as input
def merge_in_place(arr, start, mid, end):
# Your code here
arr_end = len(arr)
a = start
b = mid
while a < mid or b < end:
if a < mid:
if b < end:
if arr[a] < arr[b]:
arr.append(arr[a])
a += 1
else:
arr.append(arr[b])
b += 1
else:
arr.append(arr[a])
a += 1
else:
arr.append(arr[b])
b += 1
for i in range(end - start):
arr[start + i] = arr[arr_end + i]
del arr[arr_end:]
def merge_sort_in_place(arr, l, r):
# Your code here
if arr == []:
return
if l >= r:
return
else:
mid = math.floor((l+r)/2)
if l < r-1:
merge_sort_in_place(arr, l, mid)
merge_sort_in_place(arr, mid, r)
merge_in_place(arr, l, mid, r + 1) | true |
a6079ca9dd18ad71ea9a3aee7159e14985c90d63 | serereg/homework-repository | /homeworks/homework7/hw2.py | 2,154 | 4.3125 | 4 | """
Given two strings. Return if they are equal when both are typed into
empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Examples:
Input: s = "ab#c", t = "ad#c"
Output: True
# Both s and t become "ac".
Input: s = "a##c", t = "#a#c"
Output: True
Explanation: Both s and t become "c".
Input: a = "a#c", t = "b"
Output: False
Explanation: s becomes "c" while t becomes "b".
"""
from itertools import zip_longest
from typing import Generator
def get_char_in_reserved_string(string: str) -> Generator[str, None, None]:
"""Generate sequence of chars from the given string.
Sequence of chars return in a backward order.
The '#' symbol means 'backspace'.
Example:
'asdfff##gh' -> 'h', 'g', 'f', 'd', 's', 'a'.
Args:
string: string, from which generates sequence
of symbols.
Returns:
str: symbol from string without 'backspaces'.
"""
string_reversed = reversed(string)
counter_deletes = 0
for s in string_reversed:
if s == "#":
counter_deletes += 1
continue
if counter_deletes > 0:
counter_deletes -= 1
continue
yield s
def backspace_compare(first: str, second: str) -> bool:
"""Compare two strings, with # as backspace symbol.
Args:
first: string for a comparison.
second: string for a comparison.
Returns:
bool: True, if strings are equal, False otherwise.
Examples:
if first is "ab#c" and second is "ad#c", then
output is True.
Both first and second become "ac".
If first is "a##c" and second is "#a#c", then
output is True.
Both become "c".
If first is "a#c" and second is "b", then
output is False.
First becomes "c" while second becomes "b".
"""
first_and_second = zip_longest(
get_char_in_reserved_string(first), get_char_in_reserved_string(second)
)
for f, s in first_and_second:
if f != s:
return False
return True
| true |
e10d7fa1b2457d129396d35cc6885d03f4dee095 | serereg/homework-repository | /homeworks/homework4/task_1_read_file.py | 1,784 | 4.1875 | 4 | """
Write a function that gets file path as an argument.
Read the first line of the file.
If first line is a number return true if number in an interval [1, 3)*
and false otherwise.
In case of any error, a ValueError should be thrown.
Write a test for that function using pytest library.
You should create files required for the testing inside the test run
and remove them after the test run.
(Opposite to previous homeworks when you reused files created manually
before the test.)
Definition of done:
- function is created
- function is properly formatted
- function has positive and negative tests
- tests do a cleanup and remove remove files generated by tests
You will learn:
- how to test Exceptional cases
- how to clean up after tests
- how to check if file exists**
- how to handle*** and raise**** exceptions in test. Use sample from
the documentation.
* https://en.wikipedia.org/wiki/Interval_(mathematics)#Terminology
** https://docs.python.org/3/library/os.path.html
*** https://docs.python.org/3/tutorial/errors.html#handling-exceptions
**** https://docs.python.org/3/tutorial/errors.html#raising-exceptions
"""
def read_magic_number(path: str) -> bool:
"""
Reads the first line of the file (path).
If first line is a number return true if number in an interval
[1, 3)*
and false otherwise.
In case of any error, a ValueError should be thrown.
"""
try:
with open(path) as fi:
line = fi.readline()
return 1.0 <= float(line) < 3.0
except FileNotFoundError:
raise ValueError("File not found")
except OSError:
raise ValueError(f"Error in opening {path}")
except ValueError:
raise ValueError(f"Exception in converting {line}")
# finally:
# return False
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.