blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0633fefb8c5bc1d1399916ffc86e4e1c3e0cbc28 | kgomathisankari/PythonWorkspace | /beautiful_soup_programs/develop_flipkart_scraping/menu.py | 645 | 4.28125 | 4 | from app import *
user_choice = """
Enter :
- 'h' to know the commands
- 'a' to list all the Laptops
- 'b' to list the best Laptops
- 'c' to list the cheapest Laptops
- 'q' to quit
"""
print(user_choice)
user_input = input("Enter Here : ")
user_input = user_input.strip().lower()
while user_input != 'q':
if user_input == 'h':
print(user_choice)
elif user_input == 'a':
all_laptops()
elif user_input == 'b':
best_laptops()
elif user_input == 'c':
cheapest_laptops()
else:
print("Wrong Command")
user_input = input("Enter Here : ")
user_input = user_input.strip().lower()
| false |
b6c8d7f466056cd4f5ed7d8a7fcd5cddf908ef2f | kgomathisankari/PythonWorkspace | /function_and_class_programs/arthimetic_program.py | 845 | 4.15625 | 4 | user_input = input("Enter what Arithmetic operator you want to preform : ")
user_input = user_input.strip()
user_input = user_input.upper()
input_num1 = int(input("Enter a number : "))
input_num2 = int(input("Enter another number : "))
def addition(num1, num2) :
return num1 + num2
def subtraction(num1, num2) :
return num1 - num2
def multiplication(num1, num2) :
return num1 * num2
def divison(num1, num2) :
return num1 / num2
def checking(user_input) :
if user_input == "ADDITION" :
print(addition(input_num1, input_num2))
elif user_input == "SUBTRACTION" :
print(subtraction(input_num1, input_num2))
elif user_input == "MULTIPLICATION":
print(multiplication(input_num1, input_num2))
elif user_input == "DIVISION":
print(divison(input_num1, input_num2))
checking(user_input)
| false |
80282dbf6abf81960e5714850eb1455cd147009a | kgomathisankari/PythonWorkspace | /function_and_class_programs/palindrome_calling_function_prgram.py | 561 | 4.25 | 4 | user_input = input("Enter your name : ")
def reverseString(user_input) :
reverse_string = ""
for i in range (len(user_input) - 1, -1 , -1) :
reverse_string = reverse_string + user_input[i]
return reverse_string
def isPalindrome(user_input) :
palindrome = "What you have entered is a Palindrome"
not_palindrome = "What you have entered is not Palindrome"
reverseString(user_input)
if reverseString(user_input) == user_input :
return palindrome
else:
return not_palindrome
print(isPalindrome(user_input)) | true |
b61cc6e6fbac22a3444fd6827d4cbf84cc554924 | kgomathisankari/PythonWorkspace | /for_loop_programs/modified_odd_and_even_program.py | 503 | 4.3125 | 4 | even_count = 0
odd_count = 0
getting_input = int(input("How many numbers do you want to enter? "))
for i in range (getting_input) :
getting_input_2 = int(input("Enter the number : "))
even = getting_input_2 % 2
if even == 0 :
even_count = even_count + getting_input_2
elif even != 0 :
odd_count = odd_count + getting_input_2
print ("The Sum of Even numbers that you have entered is : ", even_count)
print ("The Sum of Odd numbers that you have entered is : ", odd_count) | true |
f4ad192198588faed881318cbee95bed57fbbdd2 | kgomathisankari/PythonWorkspace | /for_loop_programs/largest_smallest_program.py | 421 | 4.21875 | 4 | no_count = int(input("How many numbers do you want to enter? "))
list = []
for i in range (no_count) :
num = int(input("Enter the number : "))
list.append(num)
largest = list[0]
smallest = list[1]
for j in list :
if largest < j :
largest = j
elif smallest > j :
smallest = j
print("The largest number you entered is : " , largest)
print("The smallest number you entered is : " , smallest) | true |
ccf69b387d5b3feba7885fa215ec73d4a6995231 | kgomathisankari/PythonWorkspace | /dictionary_programs/dictionary_sample.py | 1,584 | 4.4375 | 4 | month = {'JANUARY' : 31 ,
'FEBRUARY': 28 ,
'MARCH' : 31 ,
'APRIL': 30 ,
'MAY' : 31 ,
'JUNE' : 30 ,
'JULY' : 31 ,
'AUGUST': 31 ,
'SEPTEMBER' : 30 ,
'OCTOBER' : 31 ,
'NOVEMBER' : 30 ,
'DECEMBER' : 31}
month_input = input("Enter a month to find its days : ")
capital = month_input.upper()
checking = capital in month
if checking == True :
value = month.get(capital)
print('The month' , month_input , 'has' , value , 'days')
elif checking == False :
remove_whitespace = month_input.strip()
capital_2 = remove_whitespace.upper()
checking_2 = capital_2 in month
if checking_2 == True :
value2 = month.get(capital_2)
print ('The month' , remove_whitespace , 'has' , value2 , 'days')
elif checking_2 == False :
while checking_2 == False :
input_2 = input("Please enter the month name properly : ")
capital_2 = input_2.upper()
checking_2 = capital_2 in month
value_3 = month.get(capital_2)
if checking_2 == True :
print('The month' , input_2 , 'has' , value_3 , 'days')
quit()
else:
remove_whitespace = input_2.strip()
capital_2 = remove_whitespace.upper()
checking_2 = capital_2 in month
if checking_2 == True:
value2 = month.get(capital_2)
print('The month', remove_whitespace, 'has', value2, 'days')
quit() | false |
fe9366843f9bdeac7a0687b6bb2abb26357007aa | vTNT/python-box | /test/func_doc.py | 290 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
def printmax(x, y):
'''print the max of two numbers.
the two values must be integers.'''
x = int(x)
y = int(y)
if x > y:
print x, 'is max'
else:
print y, 'is max'
printmax(3, 5)
#print printmax.__doc__
| true |
d331f247e1ad6183997de06a8323dd27f56794ad | vTNT/python-box | /app/Tklinter2.py | 932 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from Tkinter import *
class LabelDemo( Frame ):
"""Demonstrate Labels"""
def __init__( self ):
"""Create three Labels and pack them"""
Frame.__init__( self ) # initializes Frame instance
# frame fills all available space
self.pack( expand = YES, fill = BOTH )
self.master.title( "Labels" )
self.Label1 = Label( self, text = "Label with text" )
# resize frame to accommodate Label
self.Label1.pack()
self.Label2 = Label( self,
text = "Labels with text and a bitmap" )
# insert Label against left side of frame
self.Label2.pack( side = LEFT )
# using default bitmap image as label
self.Label3 = Label( self, bitmap = "warning" )
self.Label3.pack( side = LEFT )
def main():
LabelDemo().mainloop() # starts event loop
if __name__ == "__main__":
main()
| true |
658a3ba9560615ba04aebaa444e09e91f763c668 | dscheiber/CodeAcademyChallenge | /binaryconversion.py | 2,185 | 4.46875 | 4 | # 3. Convert a decimal number into binary
# Write a function in Python that accepts a decimal number and returns the equivalent binary number.
# To make this simple, the decimal number will always be less than 1,024,
# so the binary number returned will always be less than ten digits long.
##author note: ok, so i hardly understand binary besides the crash course i received in calculating binary vs IP address for
##properly establishing VPC subnets. with that said, i checked my work against a calculator and it's all good.
##i didn't need to make it simple and did not limit it to <1024.
## simple ask for number w input validation.
def getNumber():
number = 0
numberValidation = None
while numberValidation == None:
number = input('Choose a number to be converted to binary. \n')
try:
number = int(number)
if number >= 0: #and number <= 1024: ##removed bc i didn't need
numberValidation = True
else:
print('Not a valid input.')
except:
print('Not a valid input.')
return number
## determines the number of digits necessary for the final value. builds a list of n^2 multiples such that it can be used
## for determining the actual digits later on
def digitDetermination(number):
digit = 2
binaryLength = [0]
while number >= digit:
#print(number, digit)
binaryLength.append(digit)
digit += digit
binaryLength.reverse()
return binaryLength
## starting from the "left most digit", calculates the digit by determining the remainder of current number and n^2 multiple
def calculateBinaryValues(number, binaryLength):
binaryList = []
for value in binaryLength:
remainder = number - value
if remainder >= 0 and number != 0:
binaryList.append('1')
number = remainder
else:
binaryList.append('0')
return binaryList
def mainLoop():
value = getNumber()
testDigits = digitDetermination(value)
binaryValues = calculateBinaryValues(value, testDigits)
binaryString = ''.join(binaryValues)
return binaryString
print(mainLoop())
| true |
206bfc1fc295e7803c04d70a69ee8445ad308201 | yellowb/ml-sample | /py3_cookbook/_1_data_structure/deduplicate_and_maintain_order.py | 979 | 4.125 | 4 | """ Sample for removing duplicated elements in list and maintain original order """
import types
names = ['tom', 'ken', 'tim', 'mary', 'ken', 'ben', 'berry', 'mary']
# Use `set()` for easy deduplicate, but changes the order
print(set(names))
# Another approach: use loop with a customized hash function
def dedupe(items, hash_func=None):
deduped_items = []
seen_keys = set()
for e in items:
if hash_func is not None and isinstance(hash_func, types.FunctionType):
key = hash_func(e)
else:
key = e
if key not in seen_keys:
seen_keys.add(key)
deduped_items.append(e)
return deduped_items
print(dedupe(names)) # No customized hash function, use the elements' default hash function directly
print(dedupe(names, lambda e: e[0])) # Think them as duplicated if the 1st char is the same
print(dedupe(names, lambda e: e[-2:-1])) # Think them as duplicated if the last 2 chars are the same
| true |
892801363f4edc79ed1ed9ce38f9bdbd483ab02d | wjaneal/ICS3U | /WN/Python/VectorField.py | 1,295 | 4.34375 | 4 | #Vector Field Program
#Copyleft 2013, William Neal
#Uses Python Visual Module to Display a Vector Field
#as determined by an equation in spherical coordinates
#Import the required modules for math and graphics:
import math
from visual import *
#Set a scale factor to determine the time interval for each calculation:
Scale = 0.001
#Calculates and returns the magnitude of a gravitational field
#Given G, the Gravitational constant, M and r
def GravitationalField(G, M, r):
return G*M/(r*r)
def r(x,y,z):
return sqrt(x**2+y**2+z**2)
'''#Set up conversion from spherical coordinates to cartesian coordinates
def Spherical_to_Cartesian(r, theta, phi):
x = r*sin(phi)*cos(theta)
y = r*sin(phi)*sin(theta)
z = r*cos(phi)
return (x,y,z)
'''
#Draw points to show where the fly has been:
P = points(pos = [(0.000001,0,0)], size = 1, color = color.red)
#Draw a vector to show where the fly is:
Field = [arrow(pos = (0.000001,0,0), axis = (0,0,1), shaftwidth = 0.1, length = 1)]
#Draw a sphere to represent the surface on which the fly flies:
ball = sphere(pos=(0,0,0), radius=1, opacity = 0.4)
for x in range(-10,10):
for y in range(-10,10):
for z in range(-10,10):
Field.append(arrow(pos=(x,y,z), axis = (0,0,1),shaftwidth = 0.1,length = GravitationalField(1,100,0.0011+r(x,y,z))))
| true |
ae30d9d7532905ac7e32a7b728a9a42c24c55db8 | shripadtheneo/codility | /value_part_array/same_val_part_arr.py | 910 | 4.1875 | 4 | """
Assume the input is an array of numbers 0 and 1. Here, a "Same Value Part Array" means a part of
an array in which successive numbers are the same.
For example, "11", "00" and "111" are all "Same Value Part Arrays" but "01" and "10" are not.
Given Above, implement a program to return the longest "Same Value Part Array" for any array
input. e.g. "011011100"
"""
def long_same_part_arr(sequence):
longest = (0, 0)
curr = (0, 0)
first, last = 0, 0
for i in range(1, len(sequence)):
if sequence[i] == sequence[i - 1]:
last = i
curr = first, last
else:
first, last = i, i
if curr[1] - curr[0] > longest[1] - longest[0]:
longest = curr
return sequence[longest[0]:longest[1] + 1]
if __name__ == '__main__':
print "Please input the array: "
sequence = raw_input()
print (long_same_part_arr(sequence))
| true |
12f98922c3aaeaed6e05d773976ac18892897b27 | aishwarya-narayanan/Python | /Python/Turtle Graphics/turtleGraphicsAssignment.py | 812 | 4.34375 | 4 | import turtle
# This program draws import turtle
# Named constants
START_X = -200
START_Y = 0
radius = 35
angle = 170
ANIMATION_SPEED = 0
#Move the turtle to its initial position.
turtle.hideturtle()
turtle.penup()
turtle.goto(START_X, START_Y)
turtle.pendown()
# Set the animation speed.
turtle.speed(ANIMATION_SPEED)
# Draw 36 lines, with the turtle tilted by 170 degrees after each line is drawn.
for x in range(18):
turtle.pensize(2)
turtle.color ("red")
turtle.forward(500)
turtle.color ("blue")
turtle.circle(radius)
turtle.color ("red")
turtle.left(angle)
for x in range(18):
turtle.pensize(2)
turtle.color ("green")
turtle.forward(500)
turtle.color ("magenta")
turtle.circle(radius)
turtle.color ("green")
turtle.left(angle)
| true |
c40cce2d02c26b5c48bbc0e8f2f6f35c702d6be2 | lkogant1/Python | /while_str.py | 272 | 4.15625 | 4 | #strong number or not
#sum of each digit factorial is equal to given number
n = int(input("enter #: "))
t = n
s = 0
while(n>0):
d = n%10
f = 1
i = 1
while(i<=d):
f = f*i
i = i+1
s = s+f
n = int(n/10)
if(s == t):
print("strong #")
else:
print("not a strong #") | false |
a035fc1998182c99f9b9d3f6a007f023584f532e | LeviMollison/Python | /PracticingElementTree.py | 2,682 | 4.4375 | 4 | # Levi Mollison
# Learning how to properly use the XML Tree module
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
try:
# Python 2.5, this is the python we currently are running
import xml.etree.cElementTree as etree
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
print("running with ElementTree")
except ImportError:
print("Failed to import ElementTree from any known place")
# Let's begin by making our own element
root = etree.Element("root")
# Can append children to elements as you would ITEMS to a LIST
root.append( etree.Element("OneChild") )
# but an easier way to create children is to use a subele factory them. This is done with the subelement list which returns the desired child
# it looks like this: child = etree.SubElement(parent, child tag name)
child2 = etree.SubElement(root, "Child2")
child3 = etree.SubElement(root, "Child3")
# Now that the elements are created, you can pretty print the xml doc you made
# print (etree.tostring( root) )
# elements are organized as closely to lists as possible. so many list functions work on xml trees
child = root[0]
# print child.tag
# print len(root)
# in order to go through the tree like a list, you need to turn it into a list
children = list(root)
#for element in children:
# print element.tag
# You can also insert elements at certain places that you wish using root.insert
root.insert(0, etree.Element("Child0"))
start = root[:1]
end = root[-1:]
"""
print start[0].tag
print end[0].
"""
# There is more than just tags, there is also attribute manipulation
# attributes are stored like dictionaries in elements, and are used the same way
root = etree.Element("root", interesting="Totally")
print etree.tostring(root)
# can also set them in an already created element
root.set("hello","huhu")
# get searches the element for the desired attribute value
# print root.get("hello")
# can order , sort and search for attributes exactly like keys
# print sorted(root.keys())
# Accessing text
root.text = "TEXT"
# print root.text
# Playing with XPath needs
| true |
6fea835bad3e56232e2c9dfd965f8834fe1b7ceb | topuchi13/Res_cmb | /res.py | 952 | 4.125 | 4 | try:
file = open ("./list.csv", "r")
except FileNotFoundError:
print ("*** The file containing available resistor list doesn't exist ***")
list = file.read().split('\n')
try:
target = int(input("\nPlease input the target resistance: "))
except ValueError:
print("*** Wrong Value Entered!!! Please enter only one integer, describing the resistor value ***")
# def combiner():
# if target in list:
# return "You already have that kind of resistor dummy"
# for a in range(len(list)):
# for b in range(len(list)):
# for c in range(len(list)):
# if list[a]+list[b]+list[c] == target:
# print( "resistor 1: " + list[a] + "resistor 2: " + list[b] + "resistor 3: " + list[c])
# if list[a]+list[b] == target:
# return "resistor 1: " + list[a] + "resistor 2: " + list[b]
# return "no possible combinations were found"
# print (combiner())
| true |
224cebe24edb6007f91782c94bfbcc61210a2604 | kzd0039/Software_Process_Integration | /Assignment/makeChange.py | 1,261 | 4.15625 | 4 | from decimal import Decimal
def makeChange(amount = None):
"""
Create two lists:
money: store the amount of the bill
To perform exact calculations, multiply all the amount of bills by 1000,
which should be [20,10,5,1,0.25,0.1,0.05,0.1] at first, then all the calculations
and comparisons are done among integers.
result: empty list used to store the output
"""
money, result = [20000, 10000, 5000, 1000, 250, 100, 50, 10], []
#If there is no input or the input is string or the input is out of range[0,100), return empty list
if amount == None or type(amount) == str or amount <0 or amount >= 100:
return result
# Multiply the amount by 1000, and keep the integer part(keep the digits till thousands places)
amount = int(Decimal(str(amount)) * 1000)
# Scan the money list, calculate the number of bills one by one and append the result to the output list
for x in money:
result.append(amount // x)
amount = amount % x
#If amount is no less than 5(thousands places is no less than 5), add one penny, else do nothing
if amount >= 5:
result[-1] += 1
#return result to universe
return result
| true |
3adbd132cc9b8ebefb006fd7868a41ff1d9c485c | BadAlgorithm/juniorPythonCourse1 | /BitNBites_JuniorPython/Lesson3/trafficLightProgram.py | 1,292 | 4.3125 | 4 | # %%%----------------Standard task------------------%%%
lightColour = input("Light colour: ")
if lightColour == "green":
print("go!")
elif lightColour == "orange":
print("slow down")
elif lightColour == "red":
print("stop")
else:
print("Invalid colour (must be; red, orange or green)")
# %%%----------------Extension task------------------%%%
# Logical operators
userColour = input("Light colour: ")
lightColour = userColour.upper()
if lightColour == "GREEN" or lightColour == "G":
print("go!")
elif lightColour == "ORANGE" or lightColour == "O":
distance = input("Are you near or far away from the lights? ")
distanceUpper = distance.upper()
if distanceUpper == "NEAR" or distanceUpper == "N":
print("Keep going")
elif distanceUpper == "FAR" or distanceUpper == "F":
print("Prepare to stop")
else:
print("Stop...")
# String indexing
userColour = input("Light colour: ")
lightColour = userColour.upper()
if lightColour[0] == "G":
print("go!")
elif lightColour[0] == "O":
distance = input("Are you near or far away from the lights? ")
distanceUpper = distance.upper()
if distanceUpper[0] == "N":
print("Keep going")
elif distanceUpper[0] == "F":
print("Prepare to stop")
else:
print("Stop...")
| true |
ed993bfb13aa74509c73311863700c762421b622 | clearlove-LeBron/python_work | /Python编程从入门到实践/chapter_4/numbers.py | 1,057 | 4.28125 | 4 | # coding=gbk
# ӡֵ5
for value in range(1,5):
print(value)
# ʹlistɽһϵתб
numbers = list(range(1,5))
print(numbers)
# rangeָ
# ӡ1-10ż
even_numbers = list(range(2,11,2))
print(even_numbers)
# һб1-10ƽ
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
# ʹбʵִһб1-10ƽ
pingfangs = [value**2 for value in range(1,11)]
print(pingfangs)
# ʹһforѭӡ1-20
for value in range(1,21):
print(value)
# һб1-1000000ٽЩִӡ,ҳֵ,Сֵ,1000000ֵĺ
number_list = [value for value in range(1,1000001)]
for number in number_list:
print(number)
print("The largest number is " + str(max(number_list)))
print("The smallest number is " + str(min(number_list)))
print("The sum of the numbers is " + str(sum(number_list)))
| false |
a47d166561f94e27e1759b83b6c9a62e585de59e | KevinKnott/Coding-Review | /Month 02/Week 01/Day 02/d.py | 2,222 | 4.1875 | 4 | # Binary Tree Zigzag Level Order Traversal: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
# Definition for a binary tree node.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# My first thought on this problem is actually to create the levels in a bfs and pass a empty node to represent a break
# or to count the number of nodes added and just flip flop if you add left right or right left of node
class Solution:
def zigzagLevelOrder(self, root: TreeNode):
if not root:
return
result = []
q = deque()
q.appendleft((root, 1))
while q:
nodesLeft = len(q)
temp = deque()
for _ in range(nodesLeft):
node, level = q.pop()
if level % 2 == 1:
temp.append(node.val)
else:
temp.appendleft(node.val)
if node.left:
q.appendleft((node.left, level + 1))
if node.right:
q.appendleft((node.right, level + 1))
result.append(temp)
return result
# My first thought to change the order of how we append the nodes to the queue actually fails because I wasn't using the level that I am using now
# so it would switch but on the third round or so it would mess up. To fix this I just took advantage of the deque for appending to my list
# Now is this an optimal solution? I believe it would be while it is o(N) and o(N+W) where W is the widest width I suppose that you could also do this
# with a dfs but honestly it would be convoluted and normally a level order or moving out from a fixed point is the main purpose of a BFS
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 20
# Was the solution optimal? This is optimal
# Were there any bugs? See my first blurb after my code
# 5 5 5 3 = 4.5
| true |
ecd2a22e759163ce69be192752e81a19f023f98e | KevinKnott/Coding-Review | /Month 03/Week 01/Day 02/a.py | 1,059 | 4.125 | 4 | # Invert Binary Tree: https://leetcode.com/problems/invert-binary-tree/
# Given the root of a binary tree, invert the tree, and return its root.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# This problem seems simple enough you go down the tree with a dfs and at every node
# you point the children to the opposite side
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
def dfs(node):
if node:
# Swap sides
node.left, node.right = node.right, node.left
# Traverse down
dfs(node.left)
dfs(node.right)
dfs(root)
return root
# The above solution is very simple but it runs in O(N) time and O(1) space as we are simply editing in place
# Score Card
# Did I need hints? N
# Did you finish within 30 min?5
# Was the solution optimal? Yeah
# Were there any bugs? None
# 5 5 5 5 = 5
| true |
7f886aacfb48d99bcfe6374cc0c819a24d90bc02 | KevinKnott/Coding-Review | /Month 02/Week 03/Day 05/a.py | 2,835 | 4.34375 | 4 | # Convert Binary Search Tree to Sorted Doubly Linked List: https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
# Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
# You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
# We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
# For this problem we will have to do a simple dfs and then as we go down we should store the node that we are push the current node to the next
# This is because as we go down the tree to the left we will get the prev node right then as we come back up that node should point
# to the next node
# Also the first time we reach the very end to the left we need to set it to the head and at the end point it to the last and vice versa to make it
# a circle
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if root is None:
return
self.first = None
self.last = None
# This is a basic in order traversal
def dfs(node):
if node is not None:
# Traverse left side
dfs(node.left)
# If there is a node
# Check if we have a last node so we can point it to the next node
if self.last is not None:
self.last.right = node
node.left = self.last
# One you have updated the pointer check if we need to update first
else:
self.first = node
self.last = node
dfs(node.right)
# Run through the automation
dfs(root)
# Point first to last and vice versa
self.first.left = self.last
self.last.right = self.first
return self.first
# The above works pretty well as it is a simple dfs with an in order traversal
# At the the only tricky part is figuring out when we need to update when we have the first node
# This will run in o(N) Time and space as we have to put every node on the stack and visit it
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 15N (45 or so)
# Was the solution optimal? See above
# Were there any bugs? Nope
# 5 5 5 5 = 5
| true |
1d8e25cdf7d3725c40c4f4f156fb1e13d375ed2b | KevinKnott/Coding-Review | /Month 03/Week 03/Day 03/b.py | 1,363 | 4.25 | 4 | # Symmetric Tree: https://leetcode.com/problems/symmetric-tree/
# Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# In this problem will take the tree and at every point make sure if we swap the left and the right
# that they both return the reccurnce relationship that they are equal (the left and right being swapped)
class Solution:
def isSymmetric(self, root):
if root is None:
return
def swapSides(node1, node2):
if node1 and node2:
return node1.val == node2.val and swapSides(node1.left, node2.right) and swapSides(node1.right, node2.left)
if node1 and not node2:
return False
if node2 and not node1:
return False
return True
return swapSides(root, root)
# This works and is basically making sure you understand how exactly you can move through trees with a recurrence
# Our code runs in O(N) as it will have to visit every node
# Score Card
# Did I need hints? Y
# Did you finish within 30 min? 5
# Was the solution optimal? Y
# Were there any bugs? N
# 5 5 5 5 = 5
| true |
53b49618af403a3a0d416f3297e7e2a9ca9db70f | KevinKnott/Coding-Review | /Month 03/Week 02/Day 06/a.py | 2,135 | 4.15625 | 4 | # Merge k Sorted Lists: https://leetcode.com/problems/merge-k-sorted-lists/
# You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
# Merge all the linked-lists into one sorted linked-list and return it.
# This problem can be broken down into two steps one merging two separate linked lists together
# this is easy as it is the same as the merge sort method and secondly updating the n lists
# until you only have one the easy way to do this is to use extra space and return a new list
# from every merge you do and then keep iterating until there is only one list left and return it.
# However the optimal solution is to actually update these in place by overwritting the A array
# every time and iterating log(n) times
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwo(self, A, B):
dummy = ListNode()
cur = dummy
while A and B:
if A.val <= B.val:
cur.next = A
A = A.next
else:
cur.next = B
B = B.next
cur = cur.next
if A:
cur.next = A
if B:
cur.next = B
return dummy.next
def mergeKLists(self, lists):
if lists is None or len(lists) == 0:
return None
while len(lists) > 1:
temp = []
for i in range(1, len(lists), 2):
temp.append(self.mergeTwo(lists[i-1], lists[i]))
if len(lists) % 2 == 1:
temp.append(lists[-1])
lists = temp
return lists[0]
# The above is pretty optimal it runs in O(nlogn) time and uses o(N) space you could slightly improve by just updating
# the lists in real time but it would be more complicated and would give you O(1) space
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 15
# Was the solution optimal? Almost just need to improve space but I have limited time today
# Were there any bugs? No bugs
# 5 5 5 5 = 5
| true |
b1e501d257b5fb3c6f9c13e3aee3d9899f93da72 | beidou9313/deeptest | /第一期/杭州-冬/第二次任务/dict_eg.py | 1,240 | 4.21875 | 4 | #--coding:--utf-8--
#关于dict
##dict用键-值对(key-vaue)存放元素对象,通过key找到对应value,速度比较快,好比查字典
##其中key不能重复,可以是tuple str 数字,不能是list
##value 可重复,可以是任何定义的py对象
if __name__=="__main__":
dict_1={1:"a",2:"b"}
#内置函数:len() str()
##len():dict长度 即key总数
print(len(dict_1))
print(dict_1)
##str():相当于在dict前后加"",以字符串方式输出dic
str_dict=str(dict_1)
print(dict_1)
print(type(str_dict))
#dict_1[1]="a"
#print(dict_1)
#dict增删改
##通过key新增数据
dict_1[3]="c"
print(dict_1)
##通过key删除/更改数据
dict_1.pop(3)
del dict_1[1]
print(dict_1)
dict_1[2]="bb"
print(dict_1)
##查
##get(key,d=Noe):返回key对应的value key不存在返回None或指定值
print(dict_1.get(3,-1))
## in 判断key是否存在
print(3 in dict_1)
## items 以tuple的形式返回 多用于for循环
print(type(dict_1.items()))
for i,j in dict_1.items():
print("%s:%s" %(i,j))
##keys() values(),以list形式返回所有的key value
print(type(dict_1.keys()))
print(dict_1.values()) | false |
a8249f2a68300a74ad88874878844e0d3a0b9e71 | beidou9313/deeptest | /第一期/广州_Cc果冻_龄/006tupleTest.py | 717 | 4.15625 | 4 | #coding=utf-8
if __name__ == "__main__":
tuple1 = (1,2,3,4,5,6)
tuple2 = ('a','b','c','d')
list1 = [1,2,3,4,5,6,7]
print("tuple1元组个数:")
print(len(tuple1))
print("tuple1元组最大值:")
print(max(tuple1))
print("tuple1元组最小值:")
print(min(tuple1))
print("tuple1和tuple2合并:")
print(tuple1+tuple2)
print("将列表转换成元组")
print(tuple(list1))
print("读取第二个元素")
print(tuple1[1])
print("读取倒数第二个元素")
print(tuple1[-2])
print("截取第二个元素开始的所有元素")
print(tuple1[1:])
print("截取第二到第四个元素")
print(tuple1[1:4])
| false |
5632e5ddb31c6a0b3f56e1b8215b779fd6cfc425 | beidou9313/deeptest | /第二期/上海_Igor/第一次任务/四则运算.py | 1,304 | 4.3125 | 4 | #实现一个四则运算的类,要求实现任意两个数的加减乘除运算
class Calc:
# 初始化
def __init__(self, a, b):
self.a = a
self.b = b
# 加法
def add(self):
return self.a + self.b
# 减法
def sub(self):
return self.a - self.b
# 乘法
def mul(self):
return self.a * self.b
# 除法
def div(self):
try:
if self.b == 0 :
print("除数不能为0")
except ValueError:
print("除数不能为0")
return self.a // self.b
def calc_sum(calc):
sum = calc.add()
print("a+b=%d" % sum)
def calc_sub(calc):
sub = calc.sub()
print("a-b=%d" % sub)
def calc_mul(calc):
mul = calc.mul()
print("axb=%d" % mul)
def calc_div(calc):
div = calc.div()
print("a÷b=%d" % div)
if __name__ == "__main__":
a = int(input("输入a:"))
b = int(input("输入b:"))
select = input("请选择加减乘除:")
calc = Calc(a,b)
if select == "加":
calc_sum(calc)
elif select == "减":
calc_sub(calc)
elif select == "乘":
calc_mul(calc)
elif select == "除":
calc_div(calc)
else:
print('只能输入加减乘除,输入错误无法计算结果!')
| false |
d8c1e84aed8f82ae5bb29c29c86161e2be7986bc | beidou9313/deeptest | /第一期/苏州-早安阳光/第2次作业/kehouxiti/009-1.py | 332 | 4.15625 | 4 | '''
Created on 2018年1月21日
@author: 早安阳光
'''
# 循环打印练习,in、range
# range(10) 转换成list(range(0,10))
for i in range(0,10):
print('我爱Python')
for i in list(range(0,10)):
print('测试是一种挑战')
for i in range(0,10,2):
print('编程改变命运')
| false |
b74afd16bdd41c9a4a4f8fa8917c0acfd8442637 | beidou9313/deeptest | /第一期/广州-33/快学python3示例练习代码/list_cut.py | 694 | 4.15625 | 4 | # coding = utf-8
# 列表运用python的切片机制
if __name__ == "__main__":
print("列表切片的示例:")
list1 = ["This", "is", "a", "sample", "for", "list"]
# 读取第二个元素is,注意索引下表从0开始
e = list1[1]
print("列表第二个元素是:")
print(e)
# 读取倒数第二个for
e = list1[-2]
print("列表倒数第二个元素是:")
print(e)
# 切片,读取从第2个元素开始后的所有元素
e = list1[1:]
print("读取从第2个元素开始后的所有元素:")
print(e)
# 切片,读取第2-4个元素
e = list1[1:4]
print("读取第2-4个元素:")
print(e) | false |
25a5779e6803e9f2ded1321be53a5074307bd30f | beidou9313/deeptest | /第一期/深圳-大霞/Task3/第二天/day2_json.py | 2,422 | 4.1875 | 4 | """
json解析
JSON 语法规则:在javascript语言中,一切都是对象。因此,任何支持的类型都可以通过json来表示,例如字符串、数字、对象、数组等。
但是对象和数组是比较特殊且常用的两种类型:
对象表示为键值对
数据由逗号分隔
花括号保存对象
方括号保存数组
"""
# python json解析模块
# 第一步,导入json模块
import json
"""
python json解析常用函数:
json.dumps:将python对象编码成json字符串
json.loads:将已编码的json字符串解码为pthon对象
"""
class jjson:
#封装一个json函数,解析通用类
def json_read(self,file):
fp=open(file,'r')
json_data=json.load(fp)
print(json_data)
fp.close()
def json_writer(self,file,writer_data):
fp=open(file,'w')
json.dump(writer_data, fp, sort_keys=True, indent=4, separators=(',', ':'))
fp.close()
if __name__=="__main__":
print("将python对象转换成json对象")
data = [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]
json_data=json.dumps(data)#将python对象编码成json字符串
print("python对象类型:%s"% type(data))
print("json对象类型:%s"%type(json_data))
print(" ")
#将json转换成python对象
python_data=json.loads(json_data)
print(type(json_data))
print(type(python_data))
print(python_data)
print("python json串格式化实例")
data = [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]
json_data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
# 打印格式化的json串
print(json_data)
print("python 读取json内容文件转化python对象实例")
# fp = open('D:/json_read.json', 'r')
# json_data=json.load(fp)
# print(type(json_data))
# print(json_data)
# fp.close()
#
# print("python 写json串实例")
# data = [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]
# fp=open('D:/json_write.json','w')
# # 以可读性格式写入json_write.json文件中
# json.dump(data, fp, sort_keys=True, indent=4, separators=(',', ': '))
# fp.close()
print("读取json文件为python实例对象")
jsData=jjson()
f='D:/json_read.json'
jsData.json_read(f)
print("写入json文件实例")
write_data = [{'a': 223, 'b': 22, 'c': 22, 'd': 22, 'e': 22}]
ff='D:/json_write.json'
jsData.json_writer(ff,write_data)
| false |
56aeaf90cfc098a579365ed8f87809f8f9ad986e | beidou9313/deeptest | /第一期/深圳-大霞/Task2/day2_for.py | 1,686 | 4.1875 | 4 | """
在Python中for循环可以遍历任何序列,例如元组、列表、字符串、字典、集合等等
for 变量 in 序列:
# 代码块
else:
# 代码块
# 通常情况下,我们不用else
"""
if __name__=="__main__":
tuple1=(1,2,3,4,5,6,7,8,9,0)
for t in tuple1:
print(t,end=" ")
print(" ")
list1=[1,2,3,4,5,6,7,8,9,0]
for l in list1:
print(l,end=" ")
print(" ")
#for遍历字典
dict1={"Deeptest":"开源优测","python":"快学python"}
for (key,value) in dict1.items():
print("%s:%s"% (key,value))
"""
结合range()函数使用 本节说明下如何结合range函数来使用。
range(start, end, step)
功能说明:以指定步长生成一个指定范围的数值序列
参数说明: start: 数值序列的起始数值(默认为0) end: 数值序列的终止数值 step : 数值序列中数值的间距(默认为1)
注:range生成的序列半闭半开区间
"""
for i in range(5):
print(i,end=',')#0,1,2,3,4
print(" ")#换行
# 指定范围生成序列进行遍历
for i in range(3,10):
print(i,end=',')#3,4,5,6,7,8,9,
print(" ") # 换行
# 带步长方式生成序列进行遍历
for i in range(2,10,2):
print(i,end=',')#2,4,6,8
print(' ')
#嵌套循环
#九九乘法表
for i in range(1,10):
for j in range(i,10):
print("%d * %d = %2d"% (i,j,i*j),end=' ')
print(' ')
#while和for循环 九九乘法表实例
n=1
while n<=9:
for m in range(n,10):
print("%d * %d =%2d"% (n,m,n*m),end=" ")
print(' ')
n=n+1
| false |
13fbf1e32680e049002157b86db2899b0f87f801 | beidou9313/deeptest | /第一期/广州-33/快学python3示例练习代码/tuple_sample.py | 462 | 4.125 | 4 | # coding=utf-8
# 内置函数用于元组
if __name__ == "__main__":
tuple_demo = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
# 计算tuple_deom中元素个数
print(len(tuple_demo))
# 返回tuple_demo中最大值的元素
print(max(tuple_demo))
# 返回tuple_demo中最小值的元素
print(min(tuple_demo))
# 将list转换成元组
list = [1, 2, 3, 4, 5, 6]
tuple1 = tuple(list)
# 打印转换后的元组
print(tuple1) | false |
950021f0226231e91991a29cb3e722e79f5706af | beidou9313/deeptest | /第一期/杭州-冬/第二次任务/datetime_eg.py | 1,647 | 4.15625 | 4 | #--coding:utf-8-
#本折是关于日期时间处理.在py的datetime包中.常见的三个处理类:date time dattime
from datetime import date
from datetime import time
from datetime import datetime
if __name__=="__main__":
#date类提供日期处理
##其类方法常有 today()
##其类属性有 max min等 实例属性有 year month day
##实例方法如 weekday() isoweekday() replace()
#得到datetime允许的最大的日期和最小的日期
print(date.max)
print(date.min)
#得到今天日期——年月日
today_date=date.today() #一个date对象
print("今天日期是 %s" % today_date)
#根据实例属性得到单独的年月日
print("今天面月日分别是 %s %s %s" %(today_date.year,today_date.month,today_date.day))
#根据实例方法算出今天星期几--返回对应的整数序号
print(today_date.weekday()) #0-6
print(today_date.isoweekday()) #1-7
#将当前日期替换成目标日期
print(today_date.replace(2002,12,12))
#替换成string形式的日期
print(today_date.ctime())
#time属性方法和date很类似
#构造一个time对象--hour<24 min<60 sec<60 microsec<1000000毫秒
t=time(12,13,14,999)
print("系统允许最大time %s" %t.min)
print("系统允许最小time %s" %t.max)
#获取单独的 时 分 秒 毫秒
print("hour %s" % t.hour)
print("minute %s" % t.minute)
print("second %s" % t.second)
print("microsecond %s" % t.microsecond)
#替换成指定time
t.replace(22) #可接受 小时 分 秒 毫米4个参数
#生成string的time
t.isoformat() | false |
ea7d70f36d68d9f544b31b6e0419d643aed7826e | VEGANATO/Learned-How-to-Create-Lists-Code-Academy- | /script.py | 606 | 4.1875 | 4 | # I am a student trying to organize subjects and grades using Python. I am organizing the subjects and scores.
print("This Year's Subjects and Grades: ")
subjects = ["physics", "calculus", "poetry", "history"]
grades = [98, 97, 85, 88]
subjects.append("computer science")
grades.append(100)
gradebook = list(zip(grades, subjects))
gradebook.append(("visual arts", 93))
print(gradebook)
last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)]
full_gradebook = gradebook + last_semester_gradebook
print("Last Year's Subjects and Grades: ")
print(full_gradebook)
| true |
2fdd7901f6ff2b80df39194d6c47e81d2e9cf9c8 | dilayercelik/Learn-Python3-Codecademy-Course | /8. Dictionaries/Project-Scrabble.py | 1,800 | 4.25 | 4 | #Module: Using Dictionaries - Project "Scrabble"
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
#Question 1 Create a dictionary regrouping the two lists "letters" and "points", with elements of "letters" as keys and elements of "points" as values of the dictionary
letter_to_points = {letter:point for letter, point in zip(letters, points)}
print(letter_to_points)
#Question 2 Add a key:value pair to letter_to_points
letter_to_points[" "] = 0
print(letter_to_points)
#Question 3-4-5-6 Create a function to compute the score of any word
def score_word(word):
point_total = 0
for letter in word:
if letter in letter_to_points:
point_total += letter_to_points[letter]
else:
point_total += 0
return point_total
#example with word "LIFE"
print(score_word("LIFE"))
#Question 7-8
brownie_points = score_word("BROWNIE")
print(brownie_points)
#Question 9
player_to_words = {"player1": ["BLUE", "TENNIS", "EXIT"], "wordNerd": ["EARTH", "EYES", "MACHINE"], "Lexi Con": ["ERASER", "BELLY", "HUSKY"], "Prof Reader": ["ZAP", "COMA", "PERIOD"]}
print(player_to_words)
#Question 10
player_to_points = {}
#Question 11-12-13-14
for player, words in player_to_words.items():
player_points = 0
for word in words:
player_points += score_word(word)
player_to_points[player] = player_points
print(player_to_points)
#Question 15 - BONUS
def play_word(player, word):
for value in player_to_words.values():
value.append(word)
play_word('player1', 'STUPID')
print(player_to_words)
## Bonus 2
for letter in letters:
letters.append(letter.lower())
print(letters)
| true |
69c588b6f00b5cb6ce9ab31141b6f9d0e8639854 | HaydnLogan/GitHubRepo | /algorithms/max_number.py | 547 | 4.21875 | 4 | # Algorithms HW1
# Find max number from 3 values, entered manually from a keyboard.
# using built in functions
# 0(1) no loops
def maximum(a, b, c):
list = [a, b, c]
# return max(list)
return max(a, b, c)
# not using built in functions
def find_max(a, b, c):
if a > b and a > c:
return a
if b > a and b > c:
return b
return c
x = int(input('number 1: '))
y = int(input('number 2: '))
z = int(input('number 3: '))
print(f'Maximum Number is', maximum(x, y, z))
print(f'Max number is', find_max(x, y, z))
| true |
b3fd7bfe7bf698d287bb30ce2d5e161120f83f2e | HaydnLogan/GitHubRepo | /algorithms/lesson_2/anagrams.py | 1,004 | 4.21875 | 4 | """
Write a function to check whether two given strings are anagram of each other or not.
An anagram of a string is another string that contains the same characters, only the order
of characters can be different. For example, "abcd" and "dabc" are an anagram of each other.
"""
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2) # Ture False
def is_anagram2(ss1, ss2):
if len(ss1) != len(ss2):
return False
count = {} # dictionary with all the characters
for letter in ss1:
if letter in count:
count[letter] += 1
else:
count[letter] = 1
for letter in ss2:
if letter in count:
count[letter] -= 1
else:
count[letter] = 1
for i in count:
if count[i] != 0:
return False
return True
str1 = "abcccd"
str2 = "abccdc"
print(f'Anagrm 1:"', is_anagram(str1, str2))
print(f'Anagrm 2:"', is_anagram2(str1, str2)) | true |
3f58e4c513b95f514573d106db25fb6edbb82f7a | yilinanyu/Leetcode-with-Python | /implementstack.py | 974 | 4.15625 | 4 | #push(x) -- 使用queue的push to back操作.
#pop() -- 将queue中除队尾外的所有元素pop from front然后push to back,最后执行一次pop from front
#top() -- 将queue中所有元素pop from front然后push to back,使用辅助变量top记录每次弹出的元素,返回top
#empty() -- 使用queue的is empty操作.
class Stack:
# initialize your data structure here.
def __init__(self):
self.queue = []
# @param x, an integer
# @return nothing
def push(self, x):
self.queue.append(x)
# @return nothing
def pop(self):
for x in range(len(self.queue) - 1):
self.queue.append(self.queue.pop(0))
self.queue.pop(0)
# @return an integer
def top(self):
top = None
for x in range(len(self.queue)):
top = self.queue.pop(0)
self.queue.append(top)
return top
# @return an boolean
def empty(self):
return self.queue == [] | false |
a6ddcc0a48091c5608ab62a905d2216b8a56944b | elOXXO/Tarea-04 | /Ventadesoftware.py | 2,217 | 4.125 | 4 | #encoding: UTF-8
#Autor: Alberto López Reyes
#Descripción: Este programa imprime el total a pagar de acuerdo a un descuento calculado basado en el número de paquetes otorgados.
#Esta función calcula el descuento -también lo imprime- y cuánto se debe de pagar de acuerdo al número de paquetes otorgados.
def CalcularPagoTotal(intNumPaquetes):
if intNumPaquetes > 0 and intNumPaquetes < 10:
fltTotalDescontado = 0
print("No se aplica descuento,")
elif intNumPaquetes > 9 and intNumPaquetes < 20:
fltTotalDescontado = float(intNumPaquetes) * 1500 * .2
print("Se aplica un descuento del 20%.")
print("Se descontará un total de: $"+format(fltTotalDescontado, '.2f'))
elif intNumPaquetes > 20 and intNumPaquetes < 50:
fltTotalDescontado = float(intNumPaquetes) * 1500 * .3
print("Se aplica un descuento del 30%.")
print("Se descontará un total de: $"+format(fltTotalDescontado, '.2f'))
elif intNumPaquetes > 50 and intNumPaquetes < 100:
fltTotalDescontado = float(intNumPaquetes) * 1500 * .4
print("Se aplica un descuento del 40%.")
print("Se descontará un total de: $"+format(fltTotalDescontado, '.2f'))
elif intNumPaquetes > 100:
fltTotalDescontado = float(intNumPaquetes) * 1500 * .5
print("Se aplica un descuento del 50%.")
print("Se descontará un total de: $"+format(fltTotalDescontado, '.2f'))
else:
print("""===========================""")
print("""ERROR: EL NÚMERO DE PAQUETES NO DEBE SER MENOR DE 0.
EL PROGRAMA TERMINARÁ.""")
exit()
fltPagoTotal = float(intNumPaquetes * 1500) - fltTotalDescontado
return fltPagoTotal
#Esta función pide el número de paquetes que se quieren comprar para otorgárselos a la función "CalcularPagoTotal"
#para recibir y luego imprimir el total a pagar.
def main():
print("""""")
print("""===========================""")
print("Número de paquetes.")
intNumPaquetes = int(input("Teclea el número de paquetes a comprar: "))
fltPagoTotal = CalcularPagoTotal(intNumPaquetes)
print("""===========================""")
print("El total a pagar: $"+format(fltPagoTotal, '.2f'))
main()
| false |
a98f95088d163de04f30c58ce03e8ee770ec4a63 | meagann/ICS4U1c-2018-19 | /Working/Classes Practice/practice_point.py | 1,302 | 4.375 | 4 | """
-------------------------------------------------------------------------------
Name: practice_point.py
Purpose:
Author: James. M
Created: 21/03/2019
------------------------------------------------------------------------------
"""
import math
class Point(object):
def __init__(self, x, y):
"""
Create an instance of a Point
:param x: x coordinate value
:param y: y coordinate value
"""
self.x = x
self.y = y
def get_distance(self, other_point):
"""
Compute the distance between the current object and another point
:param other_point: Point object to find the distance to
:return: float
"""
distance_x = other_point.x - self.x
distance_y = other_point.y - self.y
distance = math.sqrt(distance_x**2 + distance_y**2)
# distance = math.sqrt((other_point.x - self.x)**2 + (other_point.y - self.y)**2)
# distance = (distance_x**2 + distance_y**2)**0.5
return distance
def main():
"""
Program demonstrating the creation of point instances and calling class methods
"""
point1 = Point(3, 4)
point2 = Point(4, 7)
print("The distance between the points is", round(point1.get_distance(point2), 2))
main()
| true |
5e71075642c7ed5f4315d0a0cf4192a3b76d3fe6 | suryakiranmg/Hello-Python | /hellopython_4.py | 1,504 | 4.21875 | 4 | import random
import sys
import os
'''Conditional Statements -----------------
if else elif == != > >= <= and or not
white space used to group blocks of code
-------------------------------------------'''
age = 30
if age >= 21:
print('You are old enough to drive a tractor trailer')
elif age >= 16:
print('You are old enough to drive a car')
else:
print('You are not old enough to drive')
if ((age>=1) and (age <= 18)):
print('You get a birthday')
elif((age == 21) or (age >= 65)):
print("You get a birthday")
elif not(age == 30):
print("You don't get a party :( ")
else:
print('You get a birthday party yeah :) ')
print('\n'*0)
''' Loop for 10 times: ----------------------
perform action from 0 to 10 but not 10-------'''
for x in range(0,10):
print(x,' ', end="")
print('\n')
grocery_list = ['Juice','Tomatoes','Potatoes','Bananas']
for y in grocery_list:
print(y)
for x in [1,3,5,7,9]:
print(x)
print('\n')
num_list = [[1,2,3],[10,20,30],[100,200,330]]
for x in range(0,3):
for y in range(0,3):
print(num_list[x][y])
print('\n')
random_num = random.randrange(0,20)
while(random_num != 15):
print(random_num)
random_num = random.randrange(0, 20)
print('\n')
i=0
while(i <= 20):
if(i%2 == 0):
print(i)
elif(i == 11):
break
else:
i += 1 # i=i+1
continue #Skip all from this in while loop, goto begin
i += 1
| false |
5b494b06748c5e2a319d8bcaf82668c02c7cd5cc | amdslancelot/stupidcancode | /questions/group_shifted_strings.py | 1,672 | 4.15625 | 4 | """
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Note: For the return value, each inner list's elements must follow the lexicographic order.
"""
class Solution(object):
'''
1. Use Tuple to display the distance of each char to first char
2. map(sorted, {})
'''
def groupStrings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
r = {}
for x in strings:
t = tuple((ord(c)-ord(x[0]))%26 for c in x)
if t in r:
r[t].append(x)
else:
r[t] = [x]
return map(sorted, r.values())
s = Solution()
r = s.groupStrings(["az","yx"])
print "ans:", r
'''
["fpbnsbrkbcyzdmmmoisaa"
"cpjtwqcdwbldwwrryuclcngw"
"a"
"fnuqwejouqzrif"
"js"
"qcpr"
"zghmdiaqmfelr"
"iedda"
"l"
"dgwlvcyubde"
"lpt"
"qzq"
"zkddvitlk"
"xbogegswmad"
"mkndeyrh"
"llofdjckor"
"lebzshcb"
"firomjjlidqpsdeqyn"
"dclpiqbypjpfafukqmjnjg"
"lbpabjpcmkyivbtgdwhzlxa"
"wmalmuanxvjtgmerohskwil"
"yxgkdlwtkekavapflheieb"
"oraxvssurmzybmnzhw"
"ohecvkfe"
"kknecibjnq"
"wuxnoibr"
"gkxpnpbfvjm"
"lwpphufxw"
"sbs"
"txb"
"ilbqahdzgij"
"i"
"zvuur"
"yfglchzpledkq"
"eqdf"
"nw"
"aiplrzejplumda"
"d"
"huoybvhibgqibbwwdzhqhslb"
"rbnzendwnoklpyyyauemm"]
'''
| true |
eacc496766f745c8df335d462d8846427f04d229 | jtambe/Python | /ArrayOfPairs.py | 503 | 4.3125 | 4 | # this function checks if all elements in array are paired
# it uses bitwise XOR logic
def IsArrayOfPairs(arr):
var = arr
checker = 0
for i in range(len(arr)):
checker ^= ord(arr[i])
if checker == 0:
print("All pairs")
else:
print("At least one odd entry")
def main():
arr = ['A','A','B','B','N','N','M','M',]
IsArrayOfPairs(arr)
arr = ['A', 'A', 'B', 'B', 'N', 'N', 'M', 'X', ]
IsArrayOfPairs(arr)
if __name__ == '__main__':
main()
| true |
3236f07ea6ae2d19f9fbaf3b219e9d6c64f1d9d8 | jtambe/Python | /PyFibonacci.py | 956 | 4.21875 | 4 |
#fibonacci series using dynamic programming
# O(n)
def fibonacci(length):
#create array of length
values = [0]*length
values[0] = 0
values[1] = 1
for i in range(2,length):
values[i] = values[i-1]+ values[i-2]
print(values)
def fiboRecursive(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fiboRecursive(n-1)+ fiboRecursive(n-2)
def fibonacciShort(n):
# dual assignment
a, b = 0, 1
for i in range(n):
# print horizontally
# print(a, end = " ")
a, b = b, a+b
return b
# Generator style
def fibonacciGenrator(n):
a,b = 0,1
print("")
for i in range(n):
yield a
a,b = b, a+b
def main():
#fibonacci(10)
#print(fiboRecursive(9))
print(fibonacciShort(8181))
# for eachYieldResult in fibonacciGenrator(10):
# print(eachYieldResult, end=" ")
if __name__ == '__main__':
main() | false |
f0968a9c1fbc572a482ba161d0c19d2d846d8f41 | greece57/Reinforcement-Learning | /cardgame/player.py | 2,346 | 4.25 | 4 | """ Abstract Player """
class Player():
""" This class should not be initialized. Inherit from this to create an AI """
def __init__(self, name):
""" Initialize Variables """
self.name = name
self.cards = []
#inGame
self.last_enemy_move = -1
self.points = 0
#afterGame
self.last_game = 0.0
#overAll
self.won_games = 0
self.lost_games = 0
self.tied_games = 0
self._init()
def init_for_game(self, total_cards, points):
""" Initialize Player for a new Game """
self.cards = total_cards
self.points = points
def enemy_played(self, move):
""" save enemys move """
self.last_enemy_move = move
def won_round(self):
""" Called by the Game to inform about round Outcome
You played a higher card then the other player. """
self.points += 1
self._won_round()
def lost_round(self):
""" Called by the Game to inform about negative round Outcome
You played a lower card then the other player."""
self._lost_round()
def tie_round(self):
""" Called by the Game to inform about equal round Outcome.
Both players played the same card """
self._tie_round()
def perform_move(self):
""" Called by the Game to ask for the next Move of the Player """
move = self._choose_move()
self.cards.remove(move)
return move
def won_game(self):
""" Called by the Game to inform about positive Game Outcome """
self.won_games += 1
self.last_game = 1
self._game_over()
def lost_game(self):
""" Called by the Game to inform about negative Game Outcome """
self.lost_games += 1
self.last_game = -1
self._game_over()
def tie_game(self):
""" Called by the Game to inform about equal Game Outcome """
self.tied_games += 1
self.last_game = 0
self._game_over()
### TO BE IMPLEMENTED ###
def _init(self):
pass
def _choose_move(self):
pass
def _won_round(self):
pass
def _lost_round(self):
pass
def _tie_round(self):
pass
def _game_over(self):
pass
def finalize(self):
pass
| true |
b8414a54bb25b12fed98ebd497433d10eae8c591 | tjnovak58/cti110 | /M6T1_Novak.py | 473 | 4.6875 | 5 | # CTI-110
# M6T1 - Kilometer Converter
# Timothy Novak
# 11/09/17
#
# This program prompts the user to enter a distance in kilometers.
# It then converts the distance from kilomters to miles.
#
conversion_factor = 0.6214
def main():
kilometers = float(input('Enter the distance traveled in kilometers:'))
show_miles(kilometers)
def show_miles(km):
miles = km * conversion_factor
print('Distance traveled in miles = ', miles)
main()
| true |
1bc7f7295f1c8ad8d8f3cf278a976cedcef64895 | tjnovak58/cti110 | /M2HW1_DistanceTraveled_TimothyNovak.py | 581 | 4.34375 | 4 | # CTI-110
# M2HW1 - Distance Traveled
# Timothy Novak
# 09/10/17
#
# Define the speed the car is traveling.
speed = 70
# Calculate the distance traveled after 6 hours, 10 hours, and 15 hours.
distanceAfter6 = speed * 6
distanceAfter10 = speed * 10
distanceAfter15 = speed * 15
# Display the distance traveled after 6 hours, 10 hours, and 15 hours.
print('The number of miles traveled after 6 hours is ', distanceAfter6)
print('The number of miles traveled after 10 hours is ', distanceAfter10)
print('The number of miles traveled after 15 hours is ', distanceAfter15)
| true |
75e0f2685f912d3fa048ef83ecdfd0eb11dca378 | NiamhOF/python-practicals | /practical-13/p13p5.py | 1,073 | 4.46875 | 4 | '''
Practical 13, Exercise 5
Program to illustrate scoping in Python
Define the function f of x:
print in the function f
define x as x times 5
define y as 200
define a as the string I'm in a function
define b as 4 to the power of x
print the values of x, y, z, a and b
return x
define values for x, y, z, a and b
print the values of x, y, z, a and b before the function
define z as the function f(x)
print the values of x, y, z, a and b after this
'''
def f(x):
'''Function that adds 1 to its argument and prints it out'''
print ('In function f:')
x *= 5
y = 200
a = "I'm in a function"
b = 4 ** x
print ('a is', a)
print ('x is', x)
print ('y is', y)
print ('z is', z)
print ('b is', b)
return x
x, y, z, a, b = 5, 10, 15, 'Hello', 'Bye'
print ('Before function f:')
print ('a is', a)
print ('x is', x)
print ('y is', y)
print ('z is', z)
print ('b is', b)
z = f(x)
print ('After function f:')
print ('a is', a)
print ('x is', x)
print ('y is', y)
print ('z is', z)
print ('b is', b)
| true |
5e11d2d9c14c56b9ad0686eff5b6754b7989b50d | NiamhOF/python-practicals | /practical-9/p9p2.py | 685 | 4.21875 | 4 | '''
Practical 9, Exercise 2
Ask user for a number
Ensure number is positive
while number is positive
for all integers in the range of numbers up to and including the chosen number
add each of these integers
print the total of these integers
ask the user to enter a number again
If the number is less than zero, tell the user and stop the program
'''
num = int (input ('Enter a positive integer: '))
add = 0
while num > 0:
for i in range (0, num + 1, 1):
add += i
print ('The sum of the integers up to', num, 'is', add)
add = 0
num = int (input ('Enter a positive integer: '))
if num < 0:
print ('Number is less than zero')
| true |
29856ffe797d9b60da6735c46773a9d005f7d59d | NiamhOF/python-practicals | /practical-9/p9p5.py | 1,958 | 4.125 | 4 | '''
Practical 9, Exercise 5
Ask user for number of possible toppings
Ask user for numer of toppings on standard pizza
Get the number of the possible toppings minus the number of toppings on a pizza
Tell the user if either number is less than 0 or if the difference is less than zero
else:
calculate factorial of all possible toppings
if toppings is equal to 0, factorial is 1
else:
define factn as 1
for all numbers between 1 and number
get factn = factn * each number
if toppings on a standard pizza is equal to 0, factorial is 1
else:
define factk as 1
for all numbers between 1 and number
get factk = factk * each number
get the factorial of the difference between the two
if the difference is equal to 1
factj is 1
else:
define factj as 1
for all numbers between 1 and number
get factj = factj * each number
get facti by multiplying factk and factj
Print the possible numbers of combinations which is factn/facti
'''
top = int (input ('Enter the number of possible toppings: '))
top_stand = int (input ('Enter the number of toppings offered on standard pizza: '))
diff = top - top_stand
if top < 0 or top_stand < 0:
print ('Number entered was less than 0')
elif diff < 0:
print ('Number of possible toppings must be greater than the number of toppings offered on a standard pizza')
else:
if top == 1 or top == 0:
factn = 1
else:
factn = 1
for i in range (1, top + 1):
factn *= i
if top_stand == 1 or top_stand == 0:
factk = 1
else:
factk = 1
for j in range (1, top_stand + 1):
factk *= j
if diff == 1 or diff == 0:
factj = 1
else:
factj = 1
for k in range (1, diff + 1):
factj *= k
facti=factk * factj
print ('The number of possible combinations is:', (factn//facti))
| true |
22cf0ac6f1532d8bce0c66d1f95201a092b3680a | NiamhOF/python-practicals | /practical-9/p9p4.py | 849 | 4.1875 | 4 | '''
Practical 9, Exercise 4
Ask user for a number
while the number is greater than or equal to 0
if the number is 0, the factorial is 1
if the number is 1, the factorial is 1
if the number is greater than 1:
define fact as 1
for all numbers i of the integers from 1 to number
fact is fact times i
tell the user the factorial
ask for another number
if the number is less than 0, tell the user
'''
num = int (input ('Enter a positive integer: '))
while num >= 0:
if num == 0:
fact = 1
elif num == 1:
fact = 1
else:
fact = 1
i = 1
while i <= num:
fact *= i
i += 1
print ('The factorial of', num, 'is', fact)
num = int (input ('Enter a positive integer: '))
if num < 0:
print ('Number entered was less than 0')
| true |
7b698768332c8b9d5a78dd1baee6b3e0c0f65ac9 | NiamhOF/python-practicals | /practical-2/p2p4.py | 630 | 4.34375 | 4 | #Practical 2, exercise 4
#Note: index starts at 0
#Note: going beyond the available letters in elephant will return an error
animal='elephant'
a=animal[0]
b=animal[1]
c=animal[2]
d=animal[3]
e=animal[4]
f=animal[5]
g=animal[6]
h=animal[7]
print ("The first letter of elephant is: " + a)
print ("The second letter of elephant is: " + b)
print ("The third letter of elephant is: " + c)
print ("The fourth letter of elephant is: " + d)
print ("The fifth letter of elephant is: " + e)
print ("The sixth letter of elephant is: " + f)
print ("The seventh letter of elephant is: " + g)
print ("The eight letter of elephant is: " + h)
| true |
63f49c0b8878c2cf5871e726c2115a10acfc51c9 | NiamhOF/python-practicals | /practical-18/p18p5-2.py | 1,500 | 4.125 | 4 | '''
Practical 18, Exercise 5 alternate
Define a function hasNoPrefix that takes two parameters index and s:
if index is equal to zero return true
else if the index position - 1 is a period return False
else:
return True
Define a function is XYZ that takes the parameter s:
assign containsXYZ the value false
if the length of the string is greater than 2:
for all values of i in the range 0 to length of string -2:
if the first position of i is x and the second position of i is y and the third position of i is z:
if passing i and the string through hasNoPrefix is true:
containsXYZ is assigned the value true
break once this has been shown to be true
return containsXYZ if the above is not true
Ask user to input a string
print the function isXYZ with the parameter word
'''
def hasNoPrefix(index, s):
'''takes an index and a string and checks for a period'''
if index == 0:
return True
elif s[index - 1] == '.':
return False
else:
return True
def isXYZ (s):
'''takes string and checks if xyz is in it'''
containsXYZ = False
if len (s) > 2:
for i in range (0, len(s) - 2):
if s [i] == 'x' and s [i + 1] == 'y' and s[i + 2] == 'z':
if hasNoPrefix(i, s):
containsXYZ = True
break
return containsXYZ
word = input ('Enter a string: ')
print (isXYZ(word))
| true |
db81b3d2fc46faaf6bc940c3a8532d3fb486374d | preity788/200240126017 | /biggestnumber.py | 344 | 4.1875 | 4 | number1 = int(input("Enter number 1: "))
number2 = int(input("Enter number 2: "))
number3 = int(input("Enter number 3: "))
if (number1>number2 ) and (number1>number3):
largestNumber = number1
elif(number2>number1) and (number2>number3):
largestNumber = number2
else:
largestNumber = number3
print("Largest number: ",largestNumber)
| false |
12fd6a2bee1337443c7f2dbc7d1948aad581622c | PrimoWW/mooc | /hamming_distance.py | 437 | 4.125 | 4 | """
return hamming distance
eg:
input(1, 4)
return 2
because 1(0001) 4(1000) they have two different bits.
思路很简单,python提供轮子了。xy做异或找到不相同的位,再统计1出现的个数
"""
def hamming_distance(x, y):
"""
:param x: int
:param y: int
:return: int
"""
return bin(x ^ y).count('1')
if __name__ == "__main__":
x = 2 ** 30
y = 123
print(hamming_distance(x, y))
| false |
686e88a30cbd711f849a7610e87a7be7950091d4 | Irissf/Python_Inicio | /Tuplas.py | 859 | 4.125 | 4 | #se ejecutan más rápido que las listas
#puede no llevar paréntesis, pero mejor ponerlos
from typing import List
tuplaEjemplo = ("Iris",22,True,'a',"Iris")
print(tuplaEjemplo[:])
#convertir tupla a lista, se puede al revés
miLista = list(tuplaEjemplo)
print(miLista[:])
#de lista a tupla sería -> miTuple = tuple(miLista) <-
#comprobar si hay elementos con in
print("Iris" in tuplaEjemplo)
#contar cuantas veces aparece un elemento
print(tuplaEjemplo.count("Iris"))
#el número de elementos que hay en la tupla
print(len(tuplaEjemplo))
#tupla unitaria, con un solo elemento, debe llevar una coma al final
tuplaUni = ("Iris",)
#podemos asignar los elementos de una tupla a variables "desempaquetado de tuplas"
tuplaVar = ("iris",34,"Acuario")
nombre,edad,horoscopo = tuplaVar
#phyton asigana cada elemento de la tupla a una variable
print(nombre)
| false |
eb7d25ee8fd40c35ab061dde337f1b185b01607f | edwardmoradian/Python-Basics | /List Processing Part 1.py | 290 | 4.1875 | 4 | # Repetition and Lists
Numbers = [8,6,7,5,3,0,9]
# Using a for loop with my list of numbers
for n in Numbers:
print(n,"",end="")
print()
# Another example, list processing
total = 0
for n in Numbers:
Total = n + Total
print ("Your total is", Total) | true |
4b600ba28bb297ca75b0880b746510576afcc4d6 | edwardmoradian/Python-Basics | /Read Lines from a File.py | 645 | 4.21875 | 4 | # read lines from a file
# steps for dealing with files
# 1. Open the file (r,w,a)
# 2. Process the file
# 3. Close the file ASAP.
# open the file
f = open("words.txt", "r")
# process it, remember that the print function adds a newline character - two different ways to remove newline character
line1 = f.readline() # read the first line
print(line1, end="") # show it to you
line2 = f.readline() # read the second line
print(line2, end="") # show it to you
line3 = f.readline() # read the thid line
line3 = line3.rstrip("/n")
print(line3) # show it to you
# close it
f.close()
| true |
cbb70013b4ff8ee5d2218244d58d67180aa4d2d1 | edwardmoradian/Python-Basics | /List Methods and Functions.py | 1,735 | 4.59375 | 5 |
# Let's look at some useful functions and methods for dealing with lists
# Methods: append, remove, sort, reverse, insert, index
# Access objects with dot operator
# Built-in functions: del, min, max
# Append = add items to an existing list at the end of the list
# takes the item you want added as an argument
a = [8,6,7]
print(a)
a.append(4) # add a 4 to the end of the list
a.append(3)
print(a)
# Index = Takes an value you want to search for in the list as an argument
# If it's found , returns the index where it's found. If it's not found, it will raise an exception.
index = a.index(6)
print(index)
index = a.index(-1)
print(index)
# Insert = Another way to grow your list, but this let's you specify where the new item goes.
# moves everyone over one space to make room.
print(a)
a.insert(1,12)
print(a)
# Sort = Arranges the values in the list in ascending order.
a.sort()
print(a)
# Remove = the first way we can remove something from a list
# Take a copy of the value you want to remove from the list as it's argument
# Removes the first copy it finds starting at element 0
a.remove(7)
print(a)
# Reverse = puts the list in reverse order
a.reverse()
print(a)
# Del = a built-in function that can be used to remove items in a list by index
del(a[3])
print(a)
# Min = a built-in function that takes a list as an argument and returns the smallest value in the list
smallest = min(a)
print("The smallest value in the list is", smallest)
# Max = a built-in function that takes a list as an argument and returns the biggest value in the list
biggest = max(a)
print("The biggest value in the list is", biggest)
| true |
dc1d00f4d881c456baff43f1a54cb24bd34392f1 | Sandip-Dhakal/Python_class_files | /class7.py | 824 | 4.1875 | 4 | # String formating using % operator and format method
# name='Sam'
# age=20
# height=5.7
# txt='Name:\t'+name+"\nAge:\t"+str(age)+"\nHeight:\t"+str(height)
# print(txt)
# txt="Name: %s Age: %d Height: %f"%(name,age,height)
# print(txt)
# num=2.54
# txt="Numbers in different decimal places %f,%.1f,%.2f,%.3f"%(num,num,num,num)
# print(txt)
# #format method
# txt="My name is {}".format('Sam')
# print(txt)
# txt="My name is {name} {cast}".format(name='Sam', cast='Dhakal')
# print(txt)
# txt="Name: {0} Age: {1} Height: {2}".format(name,age,height)
# print(txt)
pi= 3.1415
radius = float(input("Enter a radius: "))
area = pi*radius**2
print("Area of circle with radius %.2f is %.2f"%(radius,area))
name = input("Enter your name: ")
age = input("Enter your age: ")
print('Your name is {} and age is {}'.format(name,age)) | true |
d72fb44e0d0b9d0e7fbcb16a11cb76fd9b66f605 | dragonsarebest/Portfolio | /Code/5October2020.py | 1,535 | 4.3125 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Function to print the list
def printList(self):
node = self
output = ''
while node != None:
output += str(node.val)
output += " "
node = node.next
print(output)
# Iterative Solution
def reverseIteratively(self, head):
# Implement this.
previousNode = None
node = self
while(node != None):
temp = node
node = node.next
temp.next = previousNode
previousNode = temp
# Recursive Solution
def reverseRecursively(self, head):
if(currentNode.next):
#if not the tail
self.reverseRecursively(head.next)
#pass along next node
#ex: head = 4, next = 3
head.next.next = head
#3's next now = 4
head.next = None
#4's next now = none
# Test Program
# Initialize the test list:
testHead = ListNode(4)
node1 = ListNode(3)
testHead.next = node1
node2 = ListNode(2)
node1.next = node2
node3 = ListNode(1)
node2.next = node3
testTail = ListNode(0)
node3.next = testTail
print("Initial list: ")
testHead.printList()
# 4 3 2 1 0
#testHead.reverseIteratively(testHead)
testHead.reverseRecursively(testHead)
print("List after reversal: ")
testTail.printList()
# 0 1 2 3 4
| true |
8d532130ed4482209e92f343cb947eafdd639357 | francisrod01/udacity_python_foundations | /03-Use-classes/Turtle-Mini_project/drawing_a_flower.py | 660 | 4.25 | 4 | #!~/envs/udacity-python-env
import turtle
def draw_flower(some_turtle):
for i in range(1, 3):
some_turtle.forward(100)
some_turtle.right(60)
some_turtle.forward(100)
some_turtle.right(120)
def draw_art():
window = turtle.Screen()
window.bgcolor("grey")
# Create the turtle Brad - Draws a square
brad = turtle.Turtle()
brad.shape("turtle")
brad.speed(20)
brad.color("yellow")
# Put draw of square in loop to draw a flower
for i in range(0, 36):
draw_flower(brad)
brad.right(10)
brad.setheading(270)
brad.forward(400)
window.exitonclick()
draw_art()
| true |
e8b187cf82b994c099b135796eb251459f17b1e9 | Aryank47/PythonProgramming | /sanfoundary.py | 377 | 4.125 | 4 | # sanfoundary program to add element to a list
n=int(input("Enter the no of elements to be read:"))
a=[]
for i in range(0,n):
y=int(input("Enter the elements: "))
a.append(y)
print(a)
# sanfoundary program to print the multiplication table of the input number
res=sum(a)/n
print(res)
n=int(input("Enter the number: "))
for i in range(1,11):
print(n,"*",i,"=",n*i)
| true |
747991d9889ebfa7f627f7a54e706e8d7ba1eaa3 | AbhishekBabuji/Coding | /Leetcode/balaned_paranthesis.py | 1,832 | 4.1875 | 4 | """
The following contains a class and methods
to check for a valid patanthesis
"""
import unittest
class ValidParanthesis:
"""
The following class contains a static method
to check for valid paranthesis
"""
def check_paran(self, input_paran):
"""
Args:
input_paran(str): The string for which one must check if it is valid paranthesis
Returns:
Boolean (True or False): True of the paranthesis id valid, False otherwise
"""
openbrace_set = set(('(', '{', '['))
matching_paran_set = set((('(', ')'), ('{', '}'), ('[', ']')))
stack = []
for brace in input_paran:
if brace in openbrace_set:
stack.append(brace)
else:
if stack:
openbrace = stack.pop()
closedbrace = brace
if tuple((openbrace, closedbrace)) in matching_paran_set:
continue
else:
return False
else:
return False
return not stack
class Test(unittest.TestCase):
"""
The class contains test cases to check for valid paranthesis
"""
def test1(self):
"""
'()[]{}]'
False
"""
example1 = ValidParanthesis()
self.assertEqual(example1.check_paran('()[]{}]'), False)
def test2(self):
"""
'{}['
False
"""
example2 = ValidParanthesis()
self.assertEqual(example2.check_paran('()[]{}'), True)
def test3(self):
"""
'('
False
"""
example3 = ValidParanthesis()
self.assertEqual(example3.check_paran('('), False)
if __name__ == '__main__':
unittest.main()
| true |
4e914e273e91739c55e8f9f95532e2dcfa778e3d | ioqv/CSE | /Edgar lopez Hangman.py | 1,198 | 4.28125 | 4 | """
A general guide for Hangman
1.Make a word bank - 10 items
2.Pick a random item from the list
3.Hide the word (use *)4.Reveal letters already guessed
5.Create the win condition
"""
import string
import random
guesses_left = 10
list_word = ["School", "House", "Computer", "Dog", "Cat", "Eat", "Hospital", "supreme", "pencil","truck", "Soccer"]
random_word = random.choice(list_word)
letters_guessed = []
ranged_word = len(random_word)
print(random_word)
guess = ""
correct = list(random_word)
guess = ""
while guess != "quit":
output = []
for letter in random_word:
if letter in letters_guessed:
output.append(letter)
else:
output.append("*")
print(" ".join(list(output)))
guess = input("Guess a letter: ")
letters_guessed.append(guess)
print(letters_guessed)
if guess not in random_word:
guesses_left -= 1
print(guesses_left)
if output == correct:
print ("You win")
exit(0)
if guesses_left == 0:
print("you loose")
Guesses = input("Guesses a letter:")
print("These are your letter %s" % letters_guessed)
lower = Guesses.lower()
letters_guessed.append(lower) | true |
fbb5cf72b35858269f21e8fd8e0803ae966bc791 | Crolabear/record1 | /Collatz.py | 1,078 | 4.1875 | 4 | # goal: write a program that does the following...
# for any number > 1, divide by 2 if even, and x3+1 if odd.
# figure out how many steps for us to get to 1
# first try:
import sys
class SomeError( Exception ): pass
def OneStep(number, count):
#number = sys.argv[0]
if type(number) is int:
if number%2 is 1:
number=number*3+1
else:
number = number/2
else:
ex= SomeError( "Input Not Integer" )
number =0
count = 0
raise ex
return (number,count+1)
def recur(number,count):
#num = sys.argv[0]
#num = 5
#ct = 0
if number ==1:
return (number,count)
else:
if number%2 ==1:
print number
return recur(number*3+1,count+1)
else:
print number
return recur(number/2,count+1)
def main():
try:
num = int(sys.argv[1])
N,count = recur(num,0)
print "The number of steps is %d" %(count)
except ValueError:
print "Not integer"
if __name__ == "__main__":
main() | true |
1540db701ceb4907f050bef4dd59922ddd8d3e44 | connorhouse/Lab4 | /lists.py | 1,855 | 4.1875 | 4 | stringOne = 'The quick brown fox jumps over the lazy dog'
print(stringOne.lower())
def getMostFrequent(str):
NO_OF_CHARS = 256
count = [0] * NO_OF_CHARS
for i in range(len(str)):
count[ord(str[i])] += 1
first, second = 0, 0
for i in range(NO_OF_CHARS):
if count[i] < count[first]:
second = first
first = i
elif (count[i] > count[second] and
count[i] != count[first]):
second = i
# return character
return chr(second)
if __name__ == "__main__":
str = "The" "quick" "brown" "fox" "jumps" "over" "the" "lazy" "dog"
res = getMostFrequent(str)
if res != '\0':
print("The most frequent character is:", res)
else:
print("No most frequent character")
def uniqueLetters(stringOne):
y = []
for b in stringOne:
if b not in y:
y.append(b)
return y
print(uniqueLetters(stringOne))
# Create a file called lists.py. Complete the following in lists.py:
# Create a list by calling the list() function with the following string "The quick brown fox jumps over the lazy dog." Convert all letters to lowercase before calling the list() function.
# Sort the list.
# Create a function called getMostFrequent() that outputs which letter(s) (excluding spaces) occurs the most often in the sentence. Indicate which letter and the in README.md.
# Create another function called uniqueLetters() that creates a list of all unique characters in the string/list. Then it should ouput each unique character in order. | true |
2bac1697c0a3d09092b86088c84ba7e7418094e3 | Dipeoliver/python_class | /estrutura_controle_projetos/Class_93_Fibo.py | 529 | 4.25 | 4 | #!/usr/local/bin/python3
# fibonacce -- sequencia de numeros somados ao seu antecessor.
# exemplo
# 0, 1, 1, 2, 3, 5, 8, 13, 21 ...
# vou determinar a quantidade de repetições que quero
def fibonacci(quantidade):
resultado = [0, 1]
for i in range(2, quantidade):
resultado.append(sum(resultado[-2:]))
return resultado
if __name__ == '__main__':
# listar os 20 primeiros números da sequência.
for fib in fibonacci(int(input('Defina a quantidade de repetições do loop: '))):
print(fib)
| false |
71a8b714ed0be13af16a9ec2f62360a62c5c6593 | Dipeoliver/python_class | /Fundamentos/Class_46_Listas.py | 431 | 4.34375 | 4 | # tupla e uma estrutura indexada
lista=[1,2,3,4,5,6,7,8]
print(lista)
print(lista[::-1]) # inverter a lista
lista.append(1) # adiciona itens na lista
lista.append(5) # adiciona itens na lista
print(lista)
nova_lista = [1,5,'Ana', "bia"] # lista pode ser hetereogenia
print (nova_lista)
nova_lista.remove(5) # removeu o numero 5 da lista
print (nova_lista)
nova_lista.reverse() # inverter a lista
print (nova_lista)
| false |
1a064c17ae1d941a9a055ad6c768d4ea78e7f9dc | anishverma2/MyLearning | /MyLearning/Advance Built In Functions/useofmap.py | 510 | 4.6875 | 5 | '''
The map function is used to take an iterable and return a new iterable where each iterable has been modified according to some function
'''
friends = ['Rolf', 'Fred', 'Sam', 'Randy']
friends_lower = map(lambda x: x.lower(), friends)
friends_lower_1 = (x.lower for x in friends) #can also be used as a generator comprehension
print(friends_lower) #returns that this object is a map object, and we can get the elements using next, as a generator
print(next(friends_lower))
print(next(friends_lower))
| true |
f656b8af133e150be6ee518d0528122a399afbc7 | DanaSergali/kili | /bonus/4.py | 428 | 4.1875 | 4 | print("Кирпичный язык это..")
letters=set("ЁУЕЫАОЭЯИЮёуеыаоэяию")
word=input("Введите слово или фразу, и прога переведет его на «кирпичный язык: ")
for letter in letters:
word=word.replace(letter,letter+"c"+letter)
#replace заменяет все вхождения одной строки на другую
print(word)
| false |
646bf608be98acbf0b0f8d14501c8c0549fe71e5 | laboyd001/python-crash-course-ch6 | /people.py | 743 | 4.3125 | 4 | # add 3 dictionaries of people. loop through the list. print everything you know abou the person.
people = {
'person1': {
'first_name': 'jenn',
'last_name': 'kuhlman',
'city': 'nashville',
},
'person2': {
'first_name': 'kathy',
'last_name': 'boyd',
'city': 'owensboro',
},
'person3': {
'first_name': 'jeane',
'last_name': 'phillips',
'city': 'fordsville',
},
}
for key, value in people.items():
print("\n" + key.title() + ":")
full_name = value['first_name'] + " " + value['last_name']
city = value['city']
print("\tFull name: " + full_name.title())
print("\tCity: " + city.title())
| false |
b0cd65ee2540ec7abbece259639628d808672c81 | brianjgmartin/codingbatsolutions | /String-1.py | 1,158 | 4.1875 | 4 | # Solutions to Python String-1
# Brian Martin 14/04/2014
# Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!".
def hello_name(name):
return "Hello " + name + "!"
# Given two strings, a and b, return the result of putting them together in
# the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".
def make_abba(a, b):
return a + b + b + a
# The web is built with HTML strings like "<i>Yay</i>"
# which draws Yay as italic text. In this example, the "i" tag makes
# <i> and </i> which surround the word "Yay". Given tag and word strings,
# create the HTML string with tags around the word, e.g. "<i>Yay</i>".
def make_tags(tag, word):
return "<"+tag+">"+word+"</"+tag+">"
# Given an "out" string length 4, such as "<<>>", and a word,
# return a new string where the word is in the middle of the out string,
# e.g. "<<word>>".
def make_out_word(out, word):
return out[:2]+word+out[2:4]
# Given a string,
# return a new string made of 3 copies of the last 2 chars of the original string.
# The string length will be at least 2.
def extra_end(str):
return str[len(str)-2:len(str)]*3
| true |
7db18f6d7a61e5a2d802a5a417e5dbfc0acd6a6a | mcgarry72/mike_portfolio | /knights_tour_problem.py | 2,595 | 4.125 | 4 | # this is an example recursion problem
# classic: given a chessboard of size n, and a starting position of x, y
# can the knight move around the chessboard and touch each square once
import numpy as np
def get_dimension_input():
cont_processing = True
have_received_input = False
while not have_received_input:
chessboard_dim_string = input("Please enter chessboard dimension, or q to quit ")
if chessboard_dim_string.lower() == "q":
have_received_input = True
cont_processing = False
chessboard_dim_int = 0
else:
try:
chessboard_dim_int = int(chessboard_dim_string)
if chessboard_dim_int > 0:
have_received_input = True
else:
print("Please enter a positive integer")
except:
print("Invalid entry, please try again ")
return cont_processing, chessboard_dim_int
def get_knight_starting(dim):
cont_processing = True
have_received_input = False
while not have_received_input:
knight_row_str = input("Please enter the starting row, or q to quit ")
knight_col_str = input("Please enter the starting column, or q to quit ")
if knight_row_str.lower() == "q" or knight_col_str.lower() == "q":
have_received_input = True
cont_processing = False
knight_row = 0
knight_col = 0
else:
if not knight_row_str.isdigit() or not knight_col_str.isdigit():
print("row and column must be integers")
else:
knight_row = int(knight_row_str)
knight_col = int(knight_col_str)
if knight_row < 0 or knight_col < 0:
print("starting positions must be positive. remember, we start counting at zero")
elif knight_row >= dim or knight_col >= dim:
print("starting positions must be less than the size of the chessboard")
else:
have_received_input = True
return cont_processing, knight_row, knight_col
def try_knight_tour(x, y, z):
my_array = np.zeros((x, x))
my_array[y, z] = 1
print(my_array)
if 0 in my_array:
return False
else:
return True
continue_proc, chessboard_dim = get_dimension_input()
if continue_proc:
continue_proc, start_row, start_col = get_knight_starting(chessboard_dim)
if continue_proc:
result = try_knight_tour(chessboard_dim, start_row, start_col)
print(result)
| true |
a4511d2618f04c1f44b75c855c24fd051a97346d | HidoiOokami/Projects-Python | /Basico/String.py | 742 | 4.15625 | 4 | '''
String
'''
nome = "Ana Paula"
nome[0] # Tras A
nome[6] # Tras u
nome[-3] # Tras Au começa de tras para frente
nome[4:] # Começando apartir do 4 Paula
nome[-5:] # Começa de tras para frente tras Paula também
nome[:3] # Começa do 3 mas ele mesmo não conta tras Ana indice 0 1 e 2
nome[2:5] #tras a P porque o 5 não entra
nome[::] #tras todos
nome[::2] #Pulando dois em dois
nome[1::2] #começando 1 e saltando de 2 em 2
nome[::-1] #inverte a String passo nesse caso e negativo
'''
Consigo usar operador membro em str
'''
frase = 'Python'
'py' not in frase # True
len(frase) # tamanho da frase
frase.lower() # tudo minusculo
frase.upper() # tudo maiusculo
frase.split() #quebra a frase nos espaços
frase.split('y') #quebra no y | false |
06bc5434592a0904879bba3ca8aeeb9eb17d3990 | HidoiOokami/Projects-Python | /Funcoes/packing.py | 749 | 4.125 | 4 |
#Retornando lista e Dicionarios de uma função
# poderia passar da seguinte forma
"""
nums = (1,2,3) # poderia ser uma lista
print(soma(*nums)) #Nesse caso iria desempacotar e somar a tupla para passar os dados
"""
def soma(*numeros): #Como aqui espera uma tupla empacotamento
soma = 0
for n in numeros:
soma += n
return soma
'''
Dicionario ou seja passando com **kwargs
'''
def resultado(**podium):
for posicao, piloto in podium.items():
print(f'{posicao} -> {piloto}')
if __name__ == '__main__':
#print(soma(1))
#print(soma(1, 3)) # Posso passar quantos valores quiser
# chave valor dicionario
resultado(primeiro='Bed',
segundo='Kirudinha',
terceiro='Nagui')
| false |
bac727960b8e93f16d210ebc60dae8e576e8aa10 | Andida7/my_practice-code | /45.py | 2,148 | 4.46875 | 4 | """Write a program that generates a random number in the range of 1 through 100, and asks
the user to guess what the number is. If the user’s guess is higher than the random number,
the program should display “Too high, try again.” If the user’s guess is lower than the
random number, the program should display “Too low, try again.” If the user guesses the
number, the application should congratulate the user and generate a new random number
so the game can start over.
Optional Enhancement: Enhance the game so it keeps count of the number of guesses that
the user makes. When the user correctly guesses the random number, the program should
display the number of guesses."""
"""
STEPS
- should generate a random number between 1 and 100
- ask the user
- if guess is high say high
- if guess is low say low
- count the guesses made
FUNCTIONS
-main
-random_num
-dispaly
"""
import random
#create a main function
def main():
print('We created a random number between 1 and 20, try guessing it.')
num = random_num()
guess(num)
def guess(num):
stop = 'y'
count = 0
while stop == 'y' or stop == 'Y':
guess = int(input("Enter your guess: "))
if guess > num:
print('Too high, try again.')
count+=1
continue
elif guess < num:
print('Too low, try again.')
count+=1
continue
elif guess == num:
if count == 0:
print('Congrats! You get it immidietly.')
else:
print('Congrats! You get it after',count+1, 'guesses.')
stop = input("Enter 'y' if you want to play again: ")
if stop == 'y' or stop == 'Y':
count = 0
num = random_num()
print('We again created a random number between 1 and 20, try guessing it.')
continue
else: break
#create a random number
def random_num():
num = random.randint(1,20)
return num
main() | true |
164a205f30278d2ca0e01cb7e38f8fd39f481ec8 | JeffGoden/HTSTA2 | /python/homework 1-8/task3.py | 742 | 4.21875 | 4 | number1= int(input("Enter 1 number"))
number2= int(input("Enter a 2nd number"))
if(number1 == number2):
print("Its equal")
else:
print("Its notr equal")
if(number1!= number2):
print("Its not equal")
else:
print("its equal")
if(number1>number2):
print("number 1 is greater than number 2")
else:
print("number 1 is smaller than number 2")
if(number1<number2):
print("number 1 is smaller than number 2")
else:
print("number 1 is greater than number 2")
if(number1>=number2):
print("number 1 is greater or equal number 2")
else:
print("number 1 is smaller or equal number 2")
if(number1<=number2):
print("number 1 is smaller or equal number 2")
else:
print("number 1 is greater or equal number 2") | true |
2f5befb1e3213da290381566175cf6e63a1f735b | DeenanathMahato/pythonassignment | /Program4.py | 593 | 4.28125 | 4 | # Create a program to display multiplication table of 5 until the upper limit is 30
# And find the even and odd results and also find the count of even or odd results and display at the end. (using do while loop,for loop,while)
# 5 x 1 = 5
# 5 x 2 = 10
# 5 x 30 = 150
e= []
o= []
for a in range(1,31):
if (a*5)%2==0:
print(5,' X ',a,' = ',5*a,' is even')
e.append(a*5)
else:
print(5,' X ',a,' = ',5*a,' is odd')
o.append(a*5)
print('even results ',e)
print('odd results ',o)
print('count of even results ',len(e))
print('count of odd results ',len(o)) | true |
c317b5a617d4c84d83762e8f6eafe87995ad9fba | velicu92/python-basics | /04_Functions.py | 1,301 | 4.21875 | 4 |
##############################################################################
####################### creating a basic Function ##########################
##############################################################################
def sumProblem(x, y):
sum = x + y
print(sum)
sentence = 'The sum between {} and {} is {}'.format(x, y, sum)
print(sentence)
sumProblem(2, 3)
def f(x):
return x * x
print(f(3))
print(f(3) + f(4))
##### solving math problems
def CircleArea(r, measure):
pi = 3.14159265
area = pi * r*r
if measure == 'm':
message = 'The Area of an circle with radius = {} m is {} square meters'.format(r, area)
elif measure == 'cm':
message = 'The Area of an circle with radius = {} cm is {} square centimeters'.format(r, area)
print(message)
##### Arguments of the function: radius and measure.
CircleArea(3, 'cm')
#### building another function, more general aproach.
def CircleArea2(r, measure):
pi = 3.14159265
area = pi * r*r
message = 'The Area of an circle with radius r = {} {} is {} square {}'.format(r, measure, area, measure)
print(message)
##### Arguments of the function: radius and measure.
CircleArea2(3, 'cm')
CircleArea2(5, 'km')
| true |
d163ea2611bfefb44382b904d0ae992e22ca1b52 | nishantchy/git-starter | /dictionary.py | 487 | 4.3125 | 4 | # accessing elements from a dictionary
new_dict = {1:"Hello", 2:"hi", 3:"Hey"}
print(new_dict)
print(new_dict[1])
print(new_dict.get(3))
# updating value
new_dict[1] = "namaste"
print(new_dict)
# adding value
new_dict[4] = "walla"
print(new_dict)
# creating a new dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
# remove a particular item
print(squares.pop(4))
# remove an orbitary item
print(squares.popitem())
# delete a particular item
del squares[2]
print(squares)
| true |
55becfe8359b724322ec2693f382a4096150efd5 | NatSuraden/Problem-Solving-01 | /3D/3.py | 278 | 4.125 | 4 | def reverse_while_loob(s):
sl = " "
length = len(s)-1
while length >= 0:
sl = sl+s[length]
length = length-1
return sl
input_str = "INE-KMUTNB"
if __name__ == "__main__":
print('Reverse String using for loob =',reverse_while_loob(input_str))
| false |
c0ca1b30858f14f0ce0ef5d1ca63ff293936a4b4 | allenabraham999/Bubble-sort | /bubble sort.py | 789 | 4.21875 | 4 | # bubble sort
import random
def bubble_sort(arr):
length = len(arr)
for j in range(length):
for i in range(1, length):
if arr[i - 1] > arr[i]:
temp = arr[i - 1]
arr[i - 1] = arr[i]
arr[i] = temp
print(f"array after {j} sort is:")
print_array(arr)
def print_array(arr):
for i in range(8):
print(arr[i], end="")
def fill_array(arr):
for i in range(8):
arr.append(random.randint(1, 9))
print("the array that will be worked on is:")
for j in range(8):
print(arr[j], end="")
array = []
fill_array(array)
bubble_sort(array)
print(" ")
print("THE FINAL SORTED ARRAY IS")
for i in range(8):
print(array[i], end="")
| false |
36fe9d6331cbba021979ee032d176fb6b000436e | Syldori/modulo2_0 | /02 - Funciones.py | 1,224 | 4.34375 | 4 | '''
Funciones:
-bloque de código al que le hemos puesto un nombre y unos parámetros (que pueden ser de distintos tipos) (devuelve un resultado)
-Tipos:
-primera clase: son aquellas que pueden trabajrse con ellas como con los valores/son equivalentes a los datos > es decir pueden asignarse, meterse en funciones, pasarse a otras funciones ...
-Funciones de nivel superior: es aquella que admite funciones en los parametros de entrada o cuyo resultado da una funcion
>> esto solo lo hacen algunos códigos, como Phyton
'''
def sumaTodos (limiTo):
resultado = 0
for i in range (0, limiTo+1):
# (0, limiTo+1, 2) >> esto haría que sumase solo los pares
resultado += i
return resultado
def sumaTodosLosCuadrados(limitTo):
resultado = 0
for i in range (limitTo+1): # si no se pone inicio, es 0
resultado += i*i
return resultado
print(sumaTodos(100))
print (sumaTodosLosCuadrados(3))
'''
Ejemplo de funcion de primera clase:
-asignar la funcion a una variable y ahora se puede llamar a esa variable como la función
addAll = sumaTodos
addAll(4)
'''
'''
ejemplo de funcion de nivel superior: En Ejmplo funcion nivel superior
'''
| false |
376f4ec3b329664db6648f5ea0cb81f219215ad4 | feihu-jun/beginning | /autohello.py | 324 | 4.21875 | 4 | #自动给输入姓名的人hello程序01#
name = input ('please enter your name:')
print('\n' * 5)
print('heelo,',name)
print('\n' * 2)#此处可以写成 n=5 | print ('\n'*n)
input('enter to <close>')#为了解决直接闪退设置的。还可以raw_input() 随机输入的意思。因为python运行完就直接关闭了 | false |
9ed6b0d01e7e6329a7bf8e04ac10e426175b91f2 | Rafaelbarr/100DaysOfCodeChallenge | /day018/001_month_number.py | 2,320 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def run():
# Variable declaration
months = 'JanFebMarAprMayJunJulAugSepOctNovDec'
done = False
# Starting the main loop
while done == False:
# Ask the user for a numeric input of a number
month_number = int(raw_input('Enter the number of a month to show it\'s abreviation: '))
# Validating cases:
if month_number < 1 or month_number > 13:
print('\nInvalid number, try within the range of 1 and 12')
month_number = int(raw_input('Enter the number of a month to show it\'s abreviation: '))
elif month_number == 1:
print'The month number {} is: '.format(month_number), months[0:3]
elif month_number == 2:
print'The month number {} is: '.format(month_number), months[3:6]
elif month_number == 3:
print'The month number {} is: '.format(month_number), months[6:9]
elif month_number == 4:
print'The month number {} is: '.format(month_number), months[9:12]
elif month_number == 5:
print'The month number {} is: '.format(month_number), months[12:15]
elif month_number == 6:
print'The month number {} is: '.format(month_number), months[15:18]
elif month_number == 7:
print'The month number {} is: '.format(month_number), months[18:21]
elif month_number == 8:
print'The month number {} is: '.format(month_number), months[21:24]
elif month_number == 9:
print'The month number {} is: '.format(month_number), months[24:27]
elif month_number == 10:
print'The month number {} is: '.format(month_number), months[27:30]
elif month_number == 11:
print'The month number {} is: '.format(month_number), months[30:33]
elif month_number == 12:
print'The month number {} is: '.format(month_number), months[33:36]
# Asking the user to quit the program
option = str(raw_input('Do you want to quit? [Y/N]: ')).lower()
if option.lower() == 'y':
done == True
print('Thanks for using our software!')
break
else:
continue
if __name__ == '__main__':
run() | true |
ccb9b7391c5237afac9114c268bf44c68f7ca450 | lubing1101/brandon | /040.py | 561 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串
print counter
print miles
print name
print '------+++++++'
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = 'Hello World!'
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第五个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串
| false |
33607951f930f0bc40e7b3dbf5b14f081507a695 | ferry-luo/ferry_pycharm_projects | /ferry_devel/views/practice/类型转换.py | 1,311 | 4.1875 | 4 | #encoding:utf-8
#Python字典、列表、字符串之间的转换
#1.列表与字符串转换
#列表转字符串:
x = ['a','b','c']
s = ''.join(x)
print(str(x))
print(s)
#字符串转列表:
s = "['a','b','c']"
x = eval(s) #eval()函数用来执行一个字符串表达式,并返回表达式的值。
print(x)
#2.列表与字典转换
#两个列表转成字典
x1 = ['a','b','c']
x2 = [1,2,3]
x3 = zip(x1,x2) #zip返回 打包为元组的列表,如[('a',1),('b',2),('c',3)]
print(x3)
d = dict(zip(x1,x2))
print(d)
#字典中键、值转为列表
d = {'a':1,'b':2}
l1 = list(d.keys())
l2 = list(d.values())
print(d.keys())
print(d.values())
print(l1)
print(l2)
#3.字典与字符串转换
#字符串转字典:用eval
s = "{'dateUpdated':20181111}"
d = eval(s) #eval()函数用来执行一个字符串表达式,并返回表达式的值。
print(d)
#字典转字符串:用str
datas = {"dateUpdated":20181111}
s = str(datas) #str()函数返回一个对象的string格式。
print(s)
#eval() 函数用来执行一个字符串表达式,并返回表达式的值。
a = 7
print(eval('3 * a'))
#join函数 语法:'sep'.join(seq) 以sep作为分隔符,将seq所有的元素合并成一个新的字符串
#sep:分隔符,可以为空
#seq:要连接的元素序列、字符串、元组、列表
| false |
16ff87190cf9599da27b7dc5e912cb376959f1e4 | the-mba/progra | /week 5/exercise4.py | 520 | 4.3125 | 4 | valid = False
number_of_colons = 0
while not valid:
attempt = input("Please enter a number: ")
valid = True
for c in attempt:
if c == '.':
number_of_colons += 1
elif not c.isdigit():
valid = False
break
if number_of_colons > 1:
valid = False
if not valid: print("That was not a valid number.")
if number_of_colons == 1:
number = float(attempt)
else:
number = int(attempt)
print("Your number squared is: " + str(number * number))
| true |
e203bc43e7d2fac93785b8ad563c742084e80a6b | Dave-dot-JS/LPHW | /ex15.py | 376 | 4.125 | 4 | from sys import argv
script, filename = argv
# opens the specific file for later use
txt = open(filename)
# reads the designated file
print(f"Here's your file {filename}:")
print(txt.read())
# re-takes input for file name to open
print("Type the filename again:")
file_again = input("> ")
# opens new file
txt_again = open(file_again)
#reads new file
print(txt_again.read())
| true |
1e2ea00b37d89d7763805e8a7a0a57c2f1da7d3d | Socialclimber/Python | /Assesment/untitled.py | 1,684 | 4.1875 | 4 | def encryption():
print("Encription Function")
print("Message can only be lower or uppercase letters")
msg = input("Enter message:")
key = int(input("Eneter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32: #check if char is a space
encrypted_text += chr(ord(msg[i])) # cocncatenate back our text, space not encrypted
elif ord(msg[i]) + key > 122:
# after 'z' move back to 'a', 'a' = 97, 'z' = 122
temp = (ord(msg[i])+ key) - 122 # this will return a lower int
# we can now add 96 to tempt and convert it back to a char
encrypted_text += chr(96 + temp)
elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):
# move back to 'A' after 'Z'
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)
else:
# in case of letters a-z and A-Z
encrypted_text += chr(ord(msg[i]) + key)
print("Encripted Text: "+ encrypted_text);
# Let's implement the decryption function
def decryption():
print("Decryption Function")
print("Message can only be lower or uppercase letters")
msg = input("Enter message:")
key = int(input("Eneter key(0-25): "))
dct_msg = ""
for i in range(len(msg)):
if ord(msg[i]) == 32: #check if char is a space
dct_msg += chr(ord(msg[i])) # cocncatenate back our text, space not encrypted
elif (ord(msg[i]) - key > 90) and (ord(msg[i]) - key < 97):
# move back to 'A' after 'Z'
temp = (ord(msg[i]) - key) + 26
dct_msg += chr(temp)
elif (ord(msg[i]) - key) < 65:
temp = (ord(msg[i]) - key) + 26
dct_msg += chr(temp)
else:
# in case of letters a-z and A-Z
dct_msg += chr(ord(msg[i]) - key)
print("Decrypted Text: "+ dct_msg);
encryption()
decryption()
| true |
50a092982e0f3182094714e2c3cf565226545900 | jerster1/portfolio | /class2.py | 1,080 | 4.28125 | 4 | #lesson 1
#firstName = raw_input("what is your name? ")
#lasttName = raw_input("what is your last name? ")
#address = raw_input("what is your address? ")
#phonenumber = raw_input("what is your phone number? ")
#age = input("How old are you? ")
#
#lesson 2
#firstname = raw_input("what is ur name? ")
#
#print "Your name is %s characters long." % (len(firstname))
#
#Lesson 3
#
#userinput = raw_input("LmFaO RawR Eks DeEe")
#print userinput.lower()
#print userinput.upper()
#
#Lesson 5
#var1 = 'string ges here'
#var2 = 2
#var3 = 3.6
#
#print "your variable's type is %s" % (type(var3))
#
#print "the type of this thing is %s" % (type(str)(var2))
myList = []
num = 0
while num is not None:
try:
num = input('(blank line to quit)\nGive me a number: ')
myList.append(num)
except SyntaxError:
num = None
print "your input it %s" % (myList)
print "the biggest number is %s" % (max(myList))
print "your input backwords is %s" % (list(reversed(myList)))
print "Your input in order is %s" % (sorted(myList))
| true |
925a2c4ad9b411c4da3704b21792a5e33a024e4d | bmarco1/Python-Journey | /yup, still going.py | 1,117 | 4.21875 | 4 | def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
print("\n")
def build_person(first_name, last_name, age=''):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
print("\n")
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
print("\n")
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
print("\n")
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("-" + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
| true |
a702d1f6fe1d827965529dd0fe6a6abbdbf24f7b | marianopettinati/test_py_imports | /car.py | 2,303 | 4.46875 | 4 | class Car():
"""A simple attemp to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.marca = make
self.modelo = model
self.año = year
self.odometro = 0
def get_descriptive_name(self):
"""Return a neatly formatted name."""
nombre_completo = str(self.año) + ' ' + self.marca + ' ' + self.modelo
return nombre_completo.title()
def read_odometer (self):
"""Prints a statement showing the car mileage"""
print ("Este auto tiene " + str(self.odometro) + ' kms')
def update_odometer(self, kms):
"""Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if kms >= self.odometro:
self.odometro = kms
else:
print("You can't roll back an odometer!")
def increment_odometer(self, kms):
"""Add the given amount to the odometer reading."""
self.odometro += kms
class Battery ():
"""A simple attempt to model a battery for an electric car"""
def __init__(self, battery_size = 70):
"""Initialize th battery's attributes"""
self.battery_size = battery_size
def describe_battery (self):
"""Print a statement describing the battery size"""
print ("This car has a " + str(self.battery_size) + "-kWh battery.")
def upgrade_battery (self):
"""Checks the battery size and sets the capacity to 85"""
if self.battery_size != 85: self.battery_size =85
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Represents the aspects of a car specific to electric vehicles"""
def __init__(self, make, model, year):
"""Initializes the attributes of the parent class.
Then initializes the attributes specific to an electric car"""
super().__init__(make, model, year)
self.battery = Battery () | true |
45322acef06cfee51721433fb4f101e46cb96458 | dtheekshanalinux/rock_paper_scissor_game | /rps.py | 982 | 4.21875 | 4 | # import the random module to create the random numbers
# Hellow world
while(True):
import random
# gui for user interface
print("you have three choices they are")
print("rock paper scissors")
# variables
c_won = "computer won!"
u_won = "Congratulation you won!"
# assign computer choices
computer = random.choice(["rock","paper","scissors"])
# gets the user choice
user = input("Enter your choice ").lower()
# play the game
if computer == user:
print("Tie.")
elif computer == "rock":
if user == "scissors":
print(c_won)
else:
print(u_won)
elif computer == "paper":
if user == "rock":
print(c_won)
else:
print(u_won)
elif computer == "scissors":
if user == "paper":
print(c_won)
else:
print(u_won)
answer = input("enter your choice yes or no (y/n) ")
if answer == "n":
break | false |
617cab393cb8f65cb4f60fb554452b00ef99f78e | Artimbocca/python | /exercises/python intro/generators/exercises.py | 865 | 4.21875 | 4 | # Write an infinite generator of fibonacci numbers, with optional start values
def fibonacci(a=0, b=1):
"""Fibonacci numbers generator"""
pass
# Write a generator of all permutations of a sequence
def permutations(items):
pass
# Use this to write a generator of all permutations of a word
def w_perm(w):
pass
# Use the Fibonacci generator to create another one that only generates fib numbers with a given factor
def fib_div(d):
pass
# Alternatively, write a generator expression that achieves the same result
# Write generator that puts a user-specified limit on the number of items generated by any given generator
def first(n, g):
pass
# Again, you could also write a generator expression that achieves the same result
if __name__ == "__main__":
print(*permutations(['r', 'e', 'd']))
print(*w_perm('game'))
#etc.
| true |
42a836d108a4933a59e3609c40d2502919b18f11 | Artimbocca/python | /exercises/python intro/google/calculator.py | 657 | 4.4375 | 4 | # You can use the input() function to ask for input:
# n = input("Enter number: ")
# print(n)
# To build a simple calculator we could just rely on the eval function of Python:
# print(eval(input("Expression: "))) # e.g. 21 + 12
# Store result in variable and it can be used in expression:
while True:
exp = input("Expression: ") # e.g. 21 + 12, or m - 7
m = eval(exp)
print(m)
# HOWEVER, using eval is a very bad, as in dangerous, idea. If someone were to enter: os.system(‘rm -rf /’): disaster.
# So, let's quickly get rid of this eval and make our own much more specific eval that only excepts some basic mathematical expressions
| true |
f5185b0c3426961a3577c5a8aca34a1de250f50d | KAZURYAN/python-study-0 | /study_four/kadai1.py | 1,242 | 4.15625 | 4 | ### 商品クラス
class Item:
def __init__(self,item_code,item_name,price):
self.item_code = item_code
self.item_name = item_name
self.price = price
def get_price(self):
return self.price
## オーダークラス
class Order:
def __init__(self,item_master):
self.item_order_list = []
self.item_master = item_master
def add_item_order(self,item_code):
self.item_order_list.append(item_code)
# 商品コードと価格の表示を実行する
def view_item_list(self):
for master in self.item_master:
for item in self.item_order_list:
if master.item_code == item:
print(f"商品コード:{item}|価格:{master.price}")
## メイン処理
def main():
# アイテムマスタ準備
item_master = []
item_master.append(Item("001","りんご",100))
item_master.append(Item("002","なし",200))
item_master.append(Item("003","みかん",150))
# オーダー登録
order=Order(item_master)
order.add_item_order("001")
order.add_item_order("002")
order.add_item_order("003")
# オーダー表示
order.view_item_list()
if __name__ == "__main__":
main() | false |
9483b859d50c28ecf5c0edaf4114a63b111eab8c | francisaddae/PYTHON | /FillBoard.py | 2,322 | 4.4375 | 4 | # NAME OF ASSIGNMENT: To display a tic-tac-toe borad on a screen and fill the borad with X
# INPUTS: User inputs of X's
# OUTPUTS: Tic-Tac-Toe board with X
# PROCESS (DESCRIPTION OF ALGORITHM): The use of nested for loops and while loops.
# END OF COMMENTS
# PLACE ANY NEEDED IMPORT STATEMENTS HERE:
import string
import random
def displayBoard(board):
print(board[0],'|',board[1],'|',board[2],'| ')
print(board[3],'|',board[4],'|',board[5],'| ')
print(board[6],'|',board[7],'|',board[8],'| ')
value = 0
i = 0
while i < len(board):
if board[i] == 'X':
value +=1
i +=1
elif board[i] != 'X':
break
return value
def filled(board):
for i in range(len(board)):
if board[i] == 'X':
return True
elif board[i] != 'X':
return False
# MAIN PART OF THE PROGRAM
def main():
board = ['_', '_', '_', '_', '_', '_', '_', '_', '_']
i = 0
while i < len(board):
board[i] = board.index(board[i]) + 1
i+=1
displayBoard(board)
Move = int(input('Enter move for x (1-9): '))
print(Move)
check = 0
while check <= 8:
if not(Move in range(1,10)):
print('Please enter a valid position number 1 through 9')
displayBoard(board)
filled(board)
Move = int(input('Enter move for x (1-9): '))
print(Move)
elif (Move in range(1,10)):
if board[Move-1] == Move:
board[Move-1] = 'X'
displayBoard(board)
filled(board)
check +=1
if check > 8:
break
else:
Move = int(input('Enter move for x (1-9): '))
print(Move)
filled(board)
elif board[Move-1] == 'X':
print('That position is filled! Try again!')
displayBoard(board)
filled(board)
Move = int(input('Enter move for x (1-9): '))
print(Move)
print('End of game!')
main()
''' This fuction works but you do have to observe the final portion of it since the instrctor did some specifications to it.
# INCLUDE THE FOLLOWING 2 LINES, BUT NOTHING ELSE BETWEEN HERE
if __name__ == "__main__":
main()
# AND HERE'''
| true |
649392e5c71d432b2c6dfb738f76bed0c4b90c42 | J4rn3s/Assignments | /MidtermCorrected.py | 2,166 | 4.375 | 4 | #################################################################
# File name:CarlosMidterm.py #
# Author: Carlos Lucio Junior #
# Date:06-02-2021 #
# Classes: ITS 220: Programming Languages & Concepts #
# Instructor: Matthew Loschiavo #
# This is a Midterm #
# Create a game to teach kindergartners how to sum #
#################################################################
def playNo():
print("If you do not play you will not get a lollipop. Do you want to play?")
# Condition if, in case of Negative answer, causing one time loop insisting the kid to play a game#
play = input("Y/N?")
play = play.upper()
return play
def playYes():
print("Let's do it kiddos!!")
firstnumber = int(input("Choose a number beween 1 and 9. Please enter your choice now!"))
secondnumber = int(input("Good job! Now choose another one."))
result = int(input("Great. Now let's sum both numbers! What is the result?"))
n = 0
score = firstnumber + secondnumber
# print(score) #Used this line for testing purposes#
# print(result) #Used this line for testing purposes#
while n != 1:
if score == result:
print("You got it and you won a lollipop! High five!")
n = 1
else:
print("")
result = int(input("Ops, this is not the right answer, try again! What is the result?"))
return
def prompttoplay():
print("Today we are going to learn Math! Let's play a game shall we?")
play = input("Y/N?")
play = play.upper() # Here I used the example for correct the lower and upper case letter answer#
return play
play = prompttoplay()
if play == "N":
play = playNo()
if play == "Y":
playYes()
if play != "N" and play != "Y":
print('You didn\'t answer Y or N')
#print("You didn't answer Y or N")
prompttoplay()
else: ## code for X to exit
print("That is so sad :( ! Good bye!!") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.