blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
b900777c43b0910d9329b4a3e492e0da64aaf625
|
ooladuwa/cs-problemSets
|
/Week 2/027-WordPattern.py
| 1,640
| 4.21875
| 4
|
"""
Given a pattern and a string a, find if a follows the same pattern.
Here, to "follow" means a full match, such that there is a one-to-one correspondence between a letter in pattern and a non-empty word in a.
Example 1:
Input:
pattern = "abba"
a = "lambda school school lambda"
Output: true
Example 2:
Input:
pattern = "abba"
a = "lambda school school coding"
Output:
false
Example 3:
Input:
pattern = "aaaa"
a = "lambda school school lambda"
Output: false
Example 4:
Input:
pattern = "abba"
a = "lambda lambda lambda lambda"
Output: false
Notes:
pattern contains only lower-case English letters.
a contains only lower-case English letters and spaces ' '.
a does not contain any leading or trailing spaces.
All the words in a are separated by a single space.
"""
"""
Understand:
- take in a pattern and a string
- determine if string follows same structure as pattern
"""
def csWordPattern(pattern, a):
comp = {}
a = a.split()
# print(a)
if len(pattern) != len(a):
return False
if len(a) < 2 or len(pattern) < 2:
return True
for i in range(len(a)):
if pattern[i] not in comp:
if a[i] in comp.values():
return False
comp[pattern[i]] = a[i]
# print("first loop")
# print(comp)
else:
print(comp[pattern[i]])
print(a[i])
if comp[pattern[i]] != a[i]:
return False
# if comp[pattern[i]] == a[i]:
# continue
# if :
# return False
return True
| true
|
690ffbac5d76e55e2ce80ff075bc81f97defbbd8
|
Deepakat43/luminartechnolab
|
/variabl length argument method/varargmethd.py
| 460
| 4.15625
| 4
|
def add(num1,num2):
return num1+num2
res=add(10,20)
print(res)
#here 2 argumnts present
#what if there are 3,4,5 etc arguments present
#so we use ****variable length argument method****
def add(*args):
print(args)
add(10)
add(10,20)
add(10,20,30,40,50)
#using this frmat we get argmnts in a (tuple) frmat
#fr getting sum frm tupe frmat :
def add(*args):
res=0
for num in args:
res+=num
return res
print(add(10,20,30,40,50))
| true
|
01c8e2d62c8464e223d0e239bd08d9cd054966e4
|
arsh479/dv.pset
|
/0055 - Ascending or descending/0055.py
| 1,062
| 4.1875
| 4
|
import random
i = 1
print(' Welcome to find ascending or descending numbers')
print(end ='\n')
while i == 1:
x = int(input('Enter number: ')) #5 different inputs so to set conditions for each input with every other input
y = int(input('Enter number: '))
z = int(input('Enter number: '))
a = int(input('Enter number: '))
b = int(input('Enter number: '))
if (x < y) and (y < z) and (z < a) and (a < b): #setting basic ascending and descending criteria for each input
print(end='\n')
print("numbers are Ascending")
print('Press ctrl + c to exit')
print(end='\n')
continue
elif (x > y) and (y > z) and (z > a) and (a > b):
print(end='\n')
print('numbers are Descending')
print('Press ctrl + c to exit')
print(end='\n')
continue
else:
print(end='\n') #setting a neither Asc or Desc case
print('none')
print('Press ctrl + c to exit')
print(end='\n')
continue
| false
|
afb2f7f9f469e96b342930d31461d9b9fa259171
|
jpierrevilleres/python-math
|
/square_root.py
| 1,291
| 4.28125
| 4
|
import math #imports math module to be able to use math.sqrt and abs function
#Part 1 defining my_sqrt function
def my_sqrt(a): #Python code taken from Section 7.5
x = a / 2 #takes as an argument and uses it to initialize value of x
while True: #uses while loop as mentioned in Section 7.5
y = ( x + a / x ) / 2.0
if y == x:
break
x = y
return x #returns an estimated square root value
#Part 2 defining test_sqrt function
def test_sqrt():
print("a \t mysqrt(a) \tmath.sqrt(a) \tdiff \n" + "- \t --------- \t ------------ \t----" ) #header for the table
a = 1.0 #initializes the value of a to 1
while a < 26: #uses while loop to print a value from 1 to 25
#prints the values returned by my_sqrt for each value of a.
#prints the values from math.sqrt for each value of a.
#prints the absolute values of the differences between my_sqrt and math.sqrt for each value of a.
print ('%(a)d %(my_sqrt(a)).11f %(math.sqrt(a)).11f %(diff).11g' %
{"a": a, "my_sqrt(a)":my_sqrt(a), "math.sqrt(a)":math.sqrt(a), "diff":abs(my_sqrt(a) - math.sqrt(a))}) #computed data values for the table
a = a + 1 #increments the value of a by 1 for the while loop to work
| true
|
633b1ea1c5d61c406e9745dfe351f15cdf2b8bfd
|
markymauro13/CSIT104_05FA19
|
/Exam-Review-11-6-19/exam2_review3.py
| 490
| 4.3125
| 4
|
x = "Computational Concepts 1"
y = "MSU"
# What are the results of the following expressions?
# a. How many ‘o’ in string x?
# b. How can you find the substring “Concepts” in x?
# c. How can you check if y starts with “M”?
# d. How can you replace “MSU” in y with “Montclair State University”?
#a
print(x.count('o'))
#b
print(x.find("Concepts"))
#c
print(y.startswith('M'))
#d
print(y.replace("MSU", "Montclair State University"))
| true
|
2a499ffe9355bb49ff0ca6ff45b8648a1841af15
|
markymauro13/CSIT104_05FA19
|
/Assignment3/1_calculateLengthAndExchange.py
| 443
| 4.25
| 4
|
x = str(input("Enter a string: ")) # ask for input from user
if(len(x)>0):
print("The length of string is: " + str(len(x))) # print the length of the string
print("The resulted string is: " + str(x[-1]) + str(x[1:len(x) - 1]) + str(x[0])) # print the result of the modified string
else:
print("Try again, enter a valid string.") # need this because an error would happen if i didnt enter a string and just hit enter
| true
|
c9cece85db973eedfc69fb0d9e8592935d21232e
|
markymauro13/CSIT104_05FA19
|
/Exam-Review-11-6-19/exam2_review6.py
| 445
| 4.1875
| 4
|
#6
for i in range(1,7): # controls the numbers of rows
for j in range(1,i+1): # controls the numbers on those lines
print(j, end = '')
print()
print("------")
i = 1
while i <= 6:
for j in range(1, i+1):
print(j, end = '')
print()
i+=1
print("------")
i = 6
while i >= 1: # reversed
for j in range(1, i+1):
print(j, end = '')
print()
i-=1
| true
|
548c422e96d13360a458557f1e0e2a465bf3f782
|
AastikM/Hacktoberfest2020-9
|
/Python_Solutions/Q24_factorial(recursion).py
| 451
| 4.3125
| 4
|
#Function for calulating the factorial
def factorial(x):
if x == 1 or x== 0 : #base/terimination condition
return 1
elif(x < 0) :
print("Sorry, factorial does not exist for negative numbers")
else:
return (x * factorial(x-1)) #Recursive Call for function factorial
# main
num = int(input("Enter a Number :")) # To take input from the user (should be > = 0)
print("Factorial of", num, "is", factorial(num))
| true
|
2d1c82316be30bb1a893f9d6c58b4678137e6814
|
AastikM/Hacktoberfest2020-9
|
/Python_Solutions/Q2BinaryDecimal.py
| 521
| 4.53125
| 5
|
# Python program to convert binary to decimal
#Function to convert binary to decimal
def binaryToDecimal(n):
num=n;
decimal=0;
#Initializing base value to 1, i.e 2^0
base = 1;
temp = num;
while temp:
last_digit=temp%10;
temp//= 10;
decimal += last_digit * base;
base *= 2;
return decimal;
#Driver program to test above function
if __name__=="__main__":
num=int(input("Enter binary number: "))
print("Number in Decimal form: ",binaryToDecimal(num))
| true
|
bf8e19eae13001826a645bdb92e1897927875d54
|
davinpchandra/ITP_Assignments
|
/AssignmentPage46
| 1,747
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 10:11:08 2019
@author: davinpc
"""
# 3-4 GuestList
guest_list = ["Steve Jobs","Robert Downey Jr","Will Smith"]
for guest in guest_list:
print("Dear " + guest + ", please come to my dinner.")
print(" ")
# 3-5 ChangingGuestList
print(guest_list[0] + " can't come to the dinner.")
guest_list[0] = "Emilia Clarke"
for guest in guest_list:
print("Dear " + guest + ", please come to my dinner.")
print(" ")
# 3-6 MoreGuests
print("Dear Guests, we have found a bigger dinner table.")
guest_list.insert(0, "Dwayne Johnson")
guest_list.insert(2, "Gordon Ramsay")
guest_list.append("Walt Disney")
for guest in guest_list:
print("Dear " + guest + ", please come to my dinner.")
print(" ")
# 3-7 ShrinkingGuestList
print("Dear Guests, we can only invite two people to dinner.")
popped_guest1 = guest_list.pop()
print("Dear " + popped_guest1 + ", we're sorry we can't invite you to dinner.")
popped_guest2 = guest_list.pop()
print("Dear " + popped_guest2 + ", we're sorry we can't invite you to dinner.")
popped_guest3 = guest_list.pop()
print("Dear " + popped_guest3 + ", we're sorry we can't invite you to dinner.")
popped_guest4 = guest_list.pop()
print("Dear " + popped_guest4 + ", we're sorry we can't invite you to dinner.")
for guest in guest_list:
print("Dear " + guest + ", you are still invited to the dinner.")
del guest_list[1]
del guest_list[0]
print(guest_list)
print(" ")
# 3-8 SeeingTheWorld
places = ["USA","Greece","Dubai","Switzerland","Germany"]
print(places)
print(sorted(places))
print(places)
print (sorted(places,reverse=True))
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse=True)
print(places)
| true
|
5d1d39f36540615bb64b1b6aeb2907e3f76d4cd3
|
irk2adm/pythontutor
|
/01/07_SchoolDesks.py
| 982
| 4.1875
| 4
|
# В школе решили набрать три новых математических класса. Так как занятия по математике у них проходят в одно и то же время, было решено выделить кабинет для каждого класса и купить в них новые парты. За каждой партой может сидеть не больше двух учеников. Известно количество учащихся в каждом из трёх классов. Сколько всего нужно закупить парт чтобы их хватило на всех учеников? Программа получает на вход три натуральных числа: количество учащихся в каждом из трех классов.
a = int(input())
b = int(input())
с = int(input())
print((a // 2 + a % 2) + (b // 2 + b % 2) + (с // 2 + с % 2))
| false
|
bfbc32395535b56de1c2749b04614343afb18789
|
Dencion/practicepython.org-Exercises
|
/Exercise11.py
| 688
| 4.28125
| 4
|
def checkPrime(userNum):
'''
Checks if the users entered number is a prime number or not
'''
oneToNum = []#Creates a list starting from 1 - userNum
divisorList = []#Empty list to be filled with divisors form userNum
i = 1
while i <= userNum:
oneToNum.append(i)
i += 1
for number in oneToNum:
if userNum % number == 0:
divisorList.append(number)
#Check if list is prime
if divisorList[0] == 1 and divisorList[1] == userNum:
print("Number is prime")
else:
print("Number is composite")
userNum = int(input("Please choose a number to check for primality:"))
checkPrime(userNum)
| true
|
f455442985533db35f2a5b41219274d5e12ef36c
|
YaoLaiGang/LearnPython
|
/len_iterator_yield.py
| 858
| 4.3125
| 4
|
#Python中的迭代器和生成器(使用yield的函数)
#迭代器常使用iter()为构造方法 next()为遍历方法
x = list(range(5))
it = iter(x)
for i in it:
print(i)
#使用yield的函数称为迭代器生成器函数,这个函数的特点如下
#1、该函数返回一个迭代器,但调用时函数不会执行
#2、每依次访问该迭代器,函数就执行到yield的地方返回一个值,并暂停执行
#3、依次执行,函数也依次执行
def fibonacci(n):#需要检查N的合法性,此处省略
a , b = 0 ,1
for i in range(n):
yield b #这是一个暂存点
a , b = b , a + b
y = fibonacci(5)
type(y) #y是一个迭代器
for i in y:
print(i)
#何时使用yield? 当函数返回一个很大的LIST的时候,使用yield,把一个大的LIST分解成小的返回,以节省内存
| false
|
aefb7cc14cbf7df71feca90f6ea56a440b325da2
|
YaoLaiGang/LearnPython
|
/len_Tuple.py
| 1,028
| 4.3125
| 4
|
#元组的基本操作
"""
元组和列表类似,但是元组不能修改,且使用()
"""
tuple1 = ('abcd',787,2.33,'laigang',70.2)
tuple2 = (123,'laigang')
print(tuple1)
print(tuple1[0])
print(tuple1[1:3])
print(tuple1[2:])
print(tuple1*2)
print(tuple1+tuple2)
#我们可以把字符串看成特殊的元组
#元组的元素是不能更改的,但是元组内可以嵌套list可变数据结构
tuple1 = ([1,2,3],[4,5,6])
tuple1[0][1]=30
print(tuple1)
#下面是特殊的用法
tuple1 = () #空元组
tuple1 = (20,)#一个元素一定要放,
'''
如果不放逗号,(数字)会把括号当成普通的运算符处理
'''
#元组不允许删除元素,只能删除整个元组(del)
#当然我们可以把列表通过类型转变为元组
print(tuple([1,2,3]))
"""
小结
1、与字符串一样,元组的元素不能修改。
2、元组也可以被索引和切片,方法一样。
3、注意构造包含0或1个元素的元组的特殊语法规则。
4、元组也可以使用+操作符进行拼接。
"""
| false
|
92411f12036363a6056c85f71df242dbb9a119de
|
KenjaminButton/runestone_thinkcspy
|
/6_functions/exercises/6.13.3.exercise.py
| 629
| 4.25
| 4
|
# 6.13.3 Exercise:
# Write a non-fruitful function drawPoly(someturtle, somesides, somesize)
# which makes a turtle draw a regular polygon. When called with
# drawPoly(tess, 8, 50), it will draw a shape like this:
import turtle
# Initializing turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
# Changing colors and pensize for turtle
kendrick = turtle.Turtle()
kendrick.color("hotpink")
kendrick.pensize(3)
def drawPoly(someturtle, somesides, somesize):
for i in range(somesides):
kendrick.forward(somesize)
kendrick.left(360/somesides)
drawPoly(kendrick, 8, 50)
window.exitonclick()
| true
|
a9fae446d7e342cc7e4ffc014d00f42993877f62
|
KenjaminButton/runestone_thinkcspy
|
/14_web_applications/14.5.py
| 1,922
| 4.375
| 4
|
# Writing Web Applications with Flask
'''
In this section, you will learn how to write web applications using
a Python framework called Flask.
Here is an example of a Flask web application:
The application begins by importing the Flask framework on line 1.
Lines 6-11 define a function hello() that serves up a simple web page
containing the date and time. The call to app.run() on Line 14 starts
a small web server. The run() method does not return; it executes an
infinite loop that waits for incoming requests from web browsers.
When a web browser sends a request to the Flask web server, the server
invokes the hello() function and returns the HTML code generated by the
function to the web browser, which displays the result.
To see this in action, copy the code above into a text editor and save
it as flaskhello.py (or whatever name you like). Then, download the Flask
framework and install it on your computer. In many cases, you can
accomplish this using the pip command included with your Python distribution:
sudo pip3 install flask
Next, execute your flaskhello.py program from the command line:
pip flaskhello.py
You should see a message similar to the following appear on the console:
* Serving Flask app "sample" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 244-727-575
* Running on http://localhost:5000/ (Press CTRL+C to quit)
'''
from flask import Flask
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def hello():
return """<html><body>
<h1>Hello, world!</h1>
The time is {0}.</body></html>""".format(
str(datetime.now()))
# Launch the Flask dev server
app.run(host="localhost", debug=True)
# favicon.ico unavailable
| true
|
9ad02888fbdeb4a86afc10d8be138e173475e075
|
KenjaminButton/runestone_thinkcspy
|
/10_lists/10.12.cloning_lists.py
| 603
| 4.34375
| 4
|
# 10.12 Cloning Lists
'''
If we want to modify a list and also keep a copy of the original,
we need to be able to make a copy of the list itself, not just the
reference. This process is sometimes called cloning, to avoid the
ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator.
Taking any slice of a creates a new list. In this case the slice
happens to consist of the whole list.
'''
a = [81, 82, 83]
b = a[:] # make a clone using slice
print(a == b) # <<< True
print(a is b) # <<< False
b[0] = 5
print(a) # <<< [81, 82, 83]
print(b) # <<< [5, 82, 83]
| true
|
1ee694e9e288b104b3f6054b511fb9768e71a535
|
KenjaminButton/runestone_thinkcspy
|
/9_strings/9.9.strings_are_immutable.py
| 899
| 4.34375
| 4
|
# 9.9 Strings Are Immutable
'''
One final thing that makes strings different from some other Python collection
types is that you are not allowed to modify the individual characters in the
collection. It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in a string. For
example, in the following code, we would like to change the first letter
of greeting.
'''
greeting = "Hello, world!"
# greeting[0] = 'J' # <<< ERROR!
print(greeting)
'''
Instead of producing the output Jello, world!, this code produces the
runtime error TypeError: 'str' object does not support item assignment.
Strings are immutable, which means you cannot change an existing string.
The best you can do is create a new string that is a variation on
the original.
'''
print("\n")
greeting = "Hello, world!"
newgreeting = "J" + greeting[1:]
print(newgreeting)
| true
|
9435b6fa5b480be9729ec52eaa5b87f7207401e5
|
KenjaminButton/runestone_thinkcspy
|
/10_lists/10.17.lists_and_loops.py
| 1,006
| 4.46875
| 4
|
# 10.17 Lists and Loops
'''
'''
fruits = ["apple", "orange", "banana", "cherry"]
for afruit in fruits: # by item
print(afruit)
'''
In this example, each time through the loop, the variable position
is used as an index into the list, printing the position-eth element.
Note that we used len as the upper bound on the range so that we can
iterate correctly no matter how many items are in the list.
'''
print("\nNew Example:")
fruits = ["apple", "orange", "banana", "cherry"]
for position in range(len(fruits)): # by index
print(fruits[position])
'''
Any sequence expression can be used in a for loop. For example,
the range function returns a sequence of integers.
This example prints all the multiples of 3 between 0 and 19.
'''
print("\nNew Example:")
for number in range(20):
if number % 3 == 0:
print(number)
'''
'''
print("\nNew Example:")
numbers = [1, 2, 3, 4, 5]
print(numbers)
for i in range(len(numbers)):
numbers[i] = numbers[i] ** 2
print(numbers)
| true
|
d7c00c2393c1b3df29c77d606ccd92e456f5a5d9
|
KenjaminButton/runestone_thinkcspy
|
/11_files/exercises/11.9.4.py
| 2,501
| 4.25
| 4
|
'''
Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair. Write a function called plotRegression that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas:
𝑦=𝑦¯+𝑚(𝑥−𝑥¯)
𝑚=∑𝑥𝑖𝑦𝑖−𝑛𝑥¯𝑦¯∑𝑥2𝑖−𝑛𝑥¯2
where 𝑥¯ is the mean of the x-values, 𝑦¯ is the mean of the y- values and 𝑛 is the number of points. If you are not familiar with the mathematical ∑ it is the sum operation. For example ∑𝑥𝑖 means to add up all the x values.
Your program should analyze the points and correctly scale the window using setworldcoordinates so that that each point can be plotted. Then you should draw the best fit line, in a different color, through the points.
'''
from turtle import Turtle, Screen
def plotRegression(data):
x_list, y_list = [int(i[0]) for i in data], [int(i[1]) for i in data]
x_list, y_list = [float(i) for i in x_list], [float(i) for i in y_list]
x_sum, y_sum = sum(x_list), sum(y_list)
x_bar, y_bar = x_sum / len(x_list), y_sum / len(y_list)
x_list_square = [i ** 2 for i in x_list]
x_list_square_sum = sum(x_list_square)
xy_list = [x_list[i] * y_list[i] for i in range(len(x_list))]
xy_list_sum = sum(xy_list)
m = (xy_list_sum - len(x_list) * x_bar * y_bar) / (x_list_square_sum - len(x_list) * x_bar ** 2)
# best y
y_best = [(y_bar + m * (x_list[i] - x_bar)) for i in range(len(x_list))]
# plot points
turtle = Turtle()
for i in range(len(x_list)):
turtle.penup()
turtle.setposition(x_list[i], y_list[i])
turtle.stamp()
# plot best y
turtle.penup()
turtle.setposition(0, 0)
turtle.color('blue')
for i in range(len(x_list)):
turtle.setposition(x_list[i], y_best[i])
turtle.pendown()
return (min(x_list), min(y_list), max(x_list), max(y_list))
screen = Screen()
screen.bgcolor('pink')
f = open("labdata.txt", "r")
plot_data = []
for aline in f:
x, y = aline.split()
plot_data.append((x, y))
# This next line should be something like:
# screen.setworldcoordinates(*plotRegression(plot_data))
# but setworldcoordinates() is so tricky to work with
# that I'm going to leave it at:
print(*plotRegression(plot_data))
# and suggest you trace a rectangle with the return
# values to get an idea what's going to happen to
# your coordinate system
screen.exitonclick()
| true
|
af4d0611190081213e50361f1913ee68f694257e
|
KenjaminButton/runestone_thinkcspy
|
/2_simple_python_data/2.7.operators_and_operands.py
| 1,457
| 4.53125
| 5
|
# Operators and Operands
print("\n----------------------------")
print(2 + 3) # <<< 5
print(2 - 3) # <<< -1
print(2 * 3) # <<< 6
print(2 ** 3) # <<< 8
print(3 ** 2) # <<< 9
print("\n----------------------------")
minutes = 645
hours = minutes / 60
print(hours) # <<< 10.75
print("\n----------------------------")
print(7 / 4) # <<< 1.75
print(7 // 4) # <<< 1
minutes = 645
hours = minutes // 60
print(hours) # <<< 10
print("\nThis is the integer division operator:")
# This is the integer division operator
quotient = 7 // 3
print(quotient) # <<< 2
remainder = 7 % 3
print(remainder) # <<< 1
print("\nTime Example:")
total_seconds = 7684
hours = total_seconds // 3600 # 1 hour holds 3600 seconds
seconds_remaining = total_seconds % 3600 # Modulo returns the remainder
minutes = seconds_remaining // 60 # Integer division operator
seconds_finally_remaining = seconds_remaining % 60
print("\ntotal_seconds:")
print(total_seconds)
print("hours:")
print(hours)
print("minutes:")
print(minutes)
print("seconds")
print(seconds_finally_remaining)
print("\nChecking answer:")
print((3600*2) + (8 * 60) + 4 )
print("\ndata-7-1: What value is printed when the following statement executes?")
print(18 / 4)
# Answer: <<< 4.5
print("\ndata-7-2: What value is printed when the following statement executes?")
print(18 // 4)
# Answer: <<< 4
print("\ndata-7-3: What value is printed when the following statement executes?")
print(18 % 4)
# Answer: <<< 2
| true
|
aec94d7f54cc24921ab10dabc07957947fa8f212
|
KenjaminButton/runestone_thinkcspy
|
/4_python_turtle_graphics/4.1.hello_little_turtles.py
| 1,538
| 4.84375
| 5
|
# 4.1 Hello Little Turtles
'''
There are many modules in Python that provide very powerful features that we can use in our own programs. Some of these can send email or fetch web pages. Others allow us to perform complex mathematical calculations. In this chapter we will introduce a module that allows us to create a data object called a turtle that can be used to draw pictures.
Turtle graphics, as it is known, is based on a very simple metaphor. Imagine that you have a turtle that understands English. You can tell your turtle to do simple commands such as go forward and turn right. As the turtle moves around, if its tail is down touching the ground, it will draw a line (leave a trail behind) as it moves. If you tell your turtle to lift up its tail it can still move around but will not leave a trail. As you will see, you can make some pretty amazing drawings with this simple capability.
'''
# Note
'''
The turtles are fun, but the real purpose of the chapter is to teach ourselves a little more Python and to develop our theme of computational thinking, or thinking like a computer scientist. Most of the Python covered here will be explored in more depth later.
'''
import turtle
wn = turtle.Screen() # creates a graphic window
alex = turtle.Turtle() # Create a turtle named Alex.
alex.color("green")
alex.pensize(5)
alex.forward(150) # Tell alex to move foward 150 units
alex.left(90) # Turn by 90 degrees
alex.forward(150) # Tell alex to move forward 150 units
wn.exitonclick() # wait for a user click on the canvas
| true
|
dba922ce03038984d3c5e5faa6b557ec54243e53
|
KenjaminButton/runestone_thinkcspy
|
/4_python_turtle_graphics/4.11_11_exercise.py
| 661
| 4.25
| 4
|
'''
# 11. Write a program to draw some kind of picture.
Be creative and experiment with the turtle methods provided in Summary of Turtle Methods.
https://runestone.academy/runestone/books/published/thinkcspy/PythonTurtle/SummaryofTurtleMethods.html#turtle-methods
'''
import turtle
window = turtle.Screen()
ken = turtle.Turtle()
window.bgcolor("lightblue")
ken.color("pink")
ken.pensize(4)
# ken.shape("line")
# Letter 'N'
ken.left(90)
ken.forward(80)
ken.right(155)
ken.forward(90)
ken.left(155)
ken.forward(80)
# Letter 'O'
ken.penup()
ken.backward(75)
ken.right(90)
ken.forward(50)
ken.pendown()
ken.circle(20)
ken.penup()
window.exitonclick()
| false
|
dbd691354cf51c9b8c5ec66617d41ad250ca51cd
|
KenjaminButton/runestone_thinkcspy
|
/12_dictionaries/exercises/12.7.1.exercise.py
| 1,064
| 4.25
| 4
|
'''
Write a program that allows the user to enter a string. It then prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. A sample run of the program might look this this:
Please enter a sentence: ThiS is String with Upper and lower case Letters.
a 2
c 1
d 1
e 5
g 1
h 2
i 4
l 2
n 2
o 1
p 2
r 4
s 5
t 5
u 1
w 2
'''
def letterCountSort(text):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
text = text.lower()
# Empty dictionary
letter_count = {}
for char in text:
if char in alphabet:
if char in letter_count:
letter_count[char] = letter_count[char] + 1
else:
letter_count[char] = 1
# Below will return a counted dictionary
# return letter_count
# Sorting the alphabet of the dictionary printed.
keys = letter_count.keys()
for char in sorted(keys):
print(char, letter_count[char])
letterCountSort("How are you?")
| true
|
90e719b77b8664dd93f4b8a09b9fd822f5d64a5d
|
KenjaminButton/runestone_thinkcspy
|
/2_simple_python_data/2.8.input.py
| 887
| 4.25
| 4
|
# Input
n = input("Please enter your name: ")
print("\nHello", n)
print("\n--------------------------")
string_seconds = input("Please input the number of seconds you wish to convert: ")
total_seconds = int(string_seconds)
hours = total_seconds // 3600
seconds_still_remaining = total_seconds % 3600
minutes = seconds_still_remaining // 60
seconds_finally_remaining = seconds_still_remaining % 60
print("hours = {}, minutes = {}, seconds = {}".format(hours, minutes, seconds_finally_remaining))
print("\n--------------------------")
# data-8-1: What is printed when the following statements execute?
n = input("Please enter your age: ")
# user types in 18
print ( type(n) )
# <<< class 'str'
print("\n--------------------------")
# data-8-2: Click on all of the variables of type `int` in the code below
# data-8-3: Click on all of the variables of type `str` in the code below
| true
|
9b12a2e9f5566691a9b1b6799dcdd4f5c0d08cb1
|
KenjaminButton/runestone_thinkcspy
|
/6_functions/6.1.functions.py
| 2,493
| 4.15625
| 4
|
# Functions
'''
def name( parameters ):
statements
'''
'''
import turtle
def drawSquare(turt, size):
# Make turtle aka turt draw a square and with size of the side
for i in range(4):
turt.forward(size)
turt.left(90)
# Setting up windows and its attributes
window = turtle.Screen()
window.bgcolor("lightblue")
kendrick = turtle.Turtle() # Create turtle named kendrick
drawSquare(kendrick, 50)
window.exitonclick()
'''
'''
import turtle
def drawSquare(t, sz):
"""Make turtle t draw a square of with side sz."""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightgreen")
alex = turtle.Turtle() # create alex
drawSquare(alex, 50) # Call the function to draw the square
alex.penup()
alex.goto(100,100)
alex.pendown()
drawSquare(alex,75) # Draw another square
wn.exitonclick()
'''
import turtle
def drawMulticolorSquare(t, sz):
"""Make turtle t draw a multi-colour square of sz."""
for i in ['red','green','purple','orange']:
t.color(i)
t.forward(sz)
t.left(90)
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightblue")
tess = turtle.Turtle() # create tess and set some attributes
tess.pensize(4)
size = 20 # size of the smallest square
for i in range(30):
drawMulticolorSquare(tess, size)
size = size + 5 # increase the size for next time
tess.forward(10) # move tess along a little
tess.right(18) # and give her some extra turn
wn.exitonclick()
# func-1-1: What is a function in Python?
# Answer: A. A named sequence of statements.
# func-1-2: What is one main purpose of a function?
# Answer: B. To help the programmer organize programs into chunks that match how they think about the solution to the problem.
# ✔️ While functions are not required, they help the programmer better think about the solution by organizing pieces of the solution into logical chunks that can be reused.
# func-1-3: Which of the following is a valid function header (first line of a function definition)?
# Answer: A. def drawCircle(t):
# ✔️ A function may take zero or more parameters. It does not have to have two. In this case the size of the circle might be specified in the body of the function.
# func-1-4: What is the name of the following function?
# Answer:
| false
|
36755b3f1801a8ed276545370b54deaa06eeda2d
|
KenjaminButton/runestone_thinkcspy
|
/17_classes_and_objects_basics/exercises/17.11.2.exercise.py
| 553
| 4.125
| 4
|
'''
Add a method reflect_x to Point which returns a new Point, one which is
the reflection of the point about the x-axis.
For example, Point(3, 5).reflect_x() is (3, -5)
'''
import math
class Point:
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def reflect_x(self):
return self.x * -1, self.y
print("\nExample 1:")
print(Point(3, 5).reflect_x()) # <<< (-3, 5)
print("\nExample 2:")
print(Point(-5, 10).reflect_x()) # <<< (5, 10)
print("\nExample 3:")
print(Point(0, 0).reflect_x()) # <<< (0, 0)
| true
|
a7e1aa3372a75ce887a35011f0669cf329db940d
|
KenjaminButton/runestone_thinkcspy
|
/4_python_turtle_graphics/4.11_13_exercise.py
| 709
| 4.3125
| 4
|
'''
# 13 A sprite is a simple spider shaped thing with n legs coming out from a center point. The angle between each leg is 360 / n degrees.
Write a program to draw a sprite where the number of legs is provided by the user.
'''
number_of_legs = input("input a number of legs (choose between 0 and 360): ")
number_of_legs_int = int(number_of_legs)
if number_of_legs_int == 0:
print("\tZero doesn't draw anything. Please try again.")
import turtle
window = turtle.Screen()
ken = turtle.Turtle()
window.bgcolor("lightblue")
ken.color("pink")
ken.pensize(4)
for i in range(number_of_legs_int + 1):
ken.forward(100)
ken.backward(100)
ken.left(360 / number_of_legs_int)
window.exitonclick()
| true
|
36a370c8100c4b59b269f1eec97f1f6f9966c02b
|
KenjaminButton/runestone_thinkcspy
|
/6_functions/exercises/6.13.11.exercise.py
| 602
| 4.5
| 4
|
# Extend the star function to draw an n pointed star.
# (Hint: n must be an odd number greater or equal to 3).
# n pointed star
import turtle
# Initializing turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
# Changing colors and pensize for turtle
kendrick = turtle.Turtle()
kendrick.color("hotpink")
kendrick.pensize(2)
def draw_N_Star(kendrick, n):
# Formula for n star is left(180 - 180/n)
# In order to close the star, use an odd number.
for i in range(n):
kendrick.forward(100)
kendrick.left(180 - 180/n)
draw_N_Star(kendrick, 8)
window.exitonclick()
| true
|
f70d6eb25a2ea7a650c3309478a51c881c8eeb37
|
KenjaminButton/runestone_thinkcspy
|
/6_functions/exercises/6.13.6.exercise.py
| 662
| 4.34375
| 4
|
# Write a non-fruitful function drawEquitriangle(someturtle, somesize) which
# calls drawPoly from the previous question to have its turtle draw a
# equilateral triangle.
import turtle
# Initializing turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
# Changing colors and pensize for turtle
kendrick = turtle.Turtle()
kendrick.color("hotpink")
kendrick.pensize(3)
def drawPoly(someturtle, somesides, somesize):
# kendrick.penup()
# kendrick.backward(somesize / 2)
# kendrick.pendown()
for i in range(3):
kendrick.forward(somesize)
kendrick.left(360 / somesides)
drawPoly(kendrick, 3, 100)
window.exitonclick()
| true
|
327dac896917535638efe1b3cca6bf3fb5727d11
|
KenjaminButton/runestone_thinkcspy
|
/11_files/exercises/11.9.3.py
| 477
| 4.15625
| 4
|
'''
Using the text file studentdata.txt (shown in exercise 1) write a
program that calculates the minimum and maximum score for each
student. Print out their name as well.
'''
def min_and_max():
f = open('studentdata.txt', 'r')
for i in f:
items = i.split()
# print(items[1:])
minimum = float(min(items[1:]))
maximum = float(max(items[1:]))
print("Name: %s, Min: %.2f, Max: %.2f" % (items[0], minimum, maximum))
min_and_max()
| true
|
95f96088c1d431c2ef6a1d6d8b1864c4a27c0b20
|
eoinpayne/Python
|
/Lab2circle.py
| 277
| 4.15625
| 4
|
from math import pi
r = 12
area = pi * r ** 2
circumference = 2*pi*r
#circumference = 2*pi*r... ca calculate on the fly or define the sum up here.
print ("The area of a circle with radius", r, "is", area)
print ("The circumference of a circle with radius" , r, "is", 2*pi*r)
| true
|
1c13bb45f9fe5ef9b7eedd2d4e02575119566751
|
eoinpayne/Python
|
/Lab2average.py
| 1,297
| 4.40625
| 4
|
__author__ = 'D15123620'
#(1 point) Write a program average.py that calculates and prints the average of three
#numbers. Test it with 3, 5 and 6. Does it make a difference if you treat the input strings as
#float or int? what about if you print the output result as float or an int?
'''def what_is_average (num_1, num_2, num_3): ###original way of doing it required that i enter in how many numbers there were
average = ((num_1 + num_2 + num_3)/3) ### to be averaged
return average
'''
def what_is_average (num_1, num_2, num_3):
numbers_to_average = [num_1, num_2, num_3]## this line sets list of numbers to be averaged
to_divide_by = len(numbers_to_average) ##this line counts the amount of items in list above
average = ((num_1 + num_2 + num_3)/to_divide_by) ## this line divides list by the variable that counted the list
return average
def main():
num_1 = float(input("Enter number 1: "))
num_2 = float(input("Enter number 2: "))
num_3 = float(input("Enter number 3: "))
average = what_is_average(num_1, num_2, num_3)
print("%.2f" % average)
main()
'''
numstoAvg = [num1, num2, num3] ## array / list
=len(mnumbstoAvg) ##this counts how many in the list. this result can then be used to calculate as the dividing number.
'''
| true
|
82c53d6b7907cee15e954d16089ad4d3f04d9bd8
|
svamja/learning_assignments
|
/2-fibonacci.py
| 242
| 4.125
| 4
|
n = int(input("Enter the number: "))
x = 0
y = 1
count = 0
total = 0
print("Fibonacci Number: ")
while count < n:
if count % 2 == 0:
total += count
x = y
y = count
count = (x + y)
print(count)
| false
|
45b5235a525b2007c4124fd16fb894f7f10f9c0f
|
ivyostosh/algorithm
|
/data_structure/queue.py
| 1,921
| 4.5
| 4
|
# Queue Implementation (https://www.educative.io/blog/8-python-data-structures
"""
We can use append() and pop() to implement a queue, but this is inefficient as lists must shift elements one by one.
Instead, the best practice is to use a deque from collections module.
Deques (double-ended queue) allow you to access both sides of the queue through popleft() and popright()
Important methods to remember:
queue.append(), queue.appendleft(),
queue.pop(), queue.popleft()
"""
########################################################################
print("===============Create a deque===============")
from collections import deque
# Initialize a deque
# Option 1: Empty deque
q = deque()
# Option 2: deque with values
q = deque(['a', 'b', 'c'])
print(q)
########################################################################
print("\n===============Add to a deque===============")
# Add element to the right end of deque: using append()
q.append('d')
q.append('e')
q.append('f')
print("\nAdd to a queue using append()")
print(q)
# Add element to the left end of deque: using appendleft()
q.appendleft(1)
q.appendleft(2)
print("\nAdd to a queue using appendleft()")
print(q)
print("\nNote deque can hold different types of elememt as shown above")
########################################################################
print("\n===============Delete from a deque===============")
# Delete element from the right end of deque: using pop()
q.pop()
q.pop()
print("\nDelete from the right end of the queue using pop()")
print(q)
# Delete element from the left end of deque: using popleft()
q.popleft()
print("\nDelete from the left end of the queue using popleft()")
print(q)
########################################################################
# Common queue interview questions in Python
"""
Reverse first k elements of a queue
Implement a queue using a linked list
Implement a stack using a queue
"""
| true
|
b0debf7de24d42f2106213afda16edb349e0c4dd
|
bikegirl/NLP-Nitro
|
/Word.py
| 878
| 4.34375
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Word class holds the properties of a word:
token, part_of_speech, and frequency.
Has a method for computing complexity
"""
import math
class Word:
def __init__(self, word, part_of_speech, frequency = 0):
self.__word = word
self.__part_of_speech = part_of_speech
self.__frequency = frequency
def set_frequency(self, frequency):
self.__frequency = frequency
# Get word
def get_word(self):
return self.__word
def get_part_of_speech(self):
return self.__part_of_speech
def get_frequency(self):
return self.__frequency
def compute_complexity_score(self):
""" Word complexity = exp(-frequency)
Return:
complexity(float)
"""
return math.exp(-self.__frequency)
| true
|
c9af8dd04b7a7cbac9ac159c22379174525ebc9a
|
suriyaaws2020/Python
|
/Create/NewfolderPython/python_101.py
| 807
| 4.34375
| 4
|
#variable declaration
X=2, Y=-3, Z=0.4
#above declares the variables under respective variable type#
#example X=2 is an integar, Z=0.4 is an float type#
#print function is used to print the value#
print(type(x))
#the above prints the value of X as 2. Output will be 2
#below command shows how to assign values into a variable and also determines the variable type of y
P=type(y)
#here the output will be an integar
print(p)
#== operator checks whether the values are same. comparative operator
X==Y
print(X==Y)
#the output will be true or false
#below command gets the input from user and store in the variable a and b respectively
a=input("Enter the 1st number")
b=input("Enter the 2nd number")
#below command make the sum of above two values received
c=a+b
#below command prints the value of sum
print(c)
| true
|
5d41a7c7404af46e3d985142f487373e60a3f206
|
usn1485/TipCalculator
|
/TipCalculator.py
| 2,422
| 4.3125
| 4
|
#Import the required Modules
import math
import os
#Take user input for bill amount.
bill=float(input("Enter the bill Amount:"))
# Write function to calculate tip.
def tipCalculator(bill,percent):
# convert the percent input to whole number if it is given as 0.15
if(percent<1):
tipPercent=percent*100
tip = bill*( tipPercent / 100 )
else:
tip = bill*( percent / 100 )
return tip
# Verify if bill amount is Positive else throw error
if(bill>0):
#Take user input for tip Percent
percent=float(input("Enter the tip Percent:"))
# Verify if Percentage is Positive else throw error
if(percent>0):
# Calculate Tip for the given Bill Amount.
tip = tipCalculator(bill,percent)
#Check if user want to split the tip amount.
splitBool=(input("Do you want to split the tip? y/n?").strip().upper())
#Verify if user wants to split and then split the tip amount.
if splitBool=="Y":
# Take user input for no of people they want to split tip between.
noOfppl=int(input("Enter the No. of ppl you want to split the tip in:"))
#If no of people are more than 1 then do the calculation to divide tip equally.
if(noOfppl>1):
FinalTip= round(( tip/noOfppl),2)
print(f"tip Split for {noOfppl} people is ${FinalTip}cents each.")
#If user changes mind and decides not to split.
elif (noOfppl==1):
print(f"tip for this table is ${round(tip,2)}cents.")
# if user enters 0 or something else.
else :
print("tip should be paid by 1 or more people. Please check the input.")
# If user doesn't want to split the tip amount, calculate the tip for per table
elif splitBool=="N":
print(f"tip for this table is ${round(tip,2)}cents")
#If user enters Other than Y/ N characters, print warning.
else:
print("Please Enter Y or N characters only.")
#if user enters Negative or 0 Percent value, print warning
else:
print("Percent must be positive")
#If user enters the bill amount 0 or negative, print warning
else:
print("The bill amount must be greater than zero")
| true
|
d684aacc8759a7a4eb3b3e039e4813934624d407
|
campjordan/Python-Projects
|
/Numbers/pi.py
| 1,243
| 4.28125
| 4
|
'''
Find PI to the Nth Digit - Enter a number and have the program generate PI
up to that many decimal places. Keep a limit to how far the program will go.
'''
def arctan(x, one=1000000):
"""
Calculate arctan(1/x)
arctan(1/x) = 1/x - 1/3*x**3 + 1/5*x**5 - ... (x >= 1)
This calculates it in fixed point, using the value for one passed in
"""
power = one // x # the +/- 1/x**n part of the term
total = power # the total so far
x_squared = x * x # precalculate x**2
divisor = 1 # the 1,3,5,7 part of the divisor
while 1:
power = - power // x_squared
divisor += 2
delta = power // divisor
if delta == 0:
break
total += delta
return total
# Calculate pi
def pi(one):
return 4*(12*arctan(18, one) + 8*arctan(57, one) - 5*arctan(239, one))
pi = str(pi(10000000000000000000000000000000000000000000000000000000000000000))
pi = pi[:1] + "." + pi[1:] # adds the decimal point
def get_pi(digit):
if digit <=0 or digit > 64:
print "Your number must be greater than 0 and no more than 64."
get_pi()
else:
print pi[:digit + 1]
get_pi(int(raw_input("How many digits of pi would you like?")))
| true
|
c2d9a1ac9c8ce3a8f2c63b1fa8768ffc5400f68f
|
rulesrmnt/python
|
/calc.py
| 350
| 4.34375
| 4
|
print (2+3) #addition
print (2*3) #multiplication
print (2-3) # substraction
print (2/3) #float division
print (2//3) #integer division
print (3%2) # Module, gives remainder
print (2%2)
print(round(2/3,2)) #round function
print (2**5) # exponent i.e. 2 to the power 5
print (2**5**2) # associative rule i.e exponents are calculated from right to left
| true
|
4355be5058d5d5a3858c4cee03ea4a219a35293b
|
jwarlop/UCSD
|
/Extension/Cert_DM_Adv_Analytics/2018Win_Py4Info/Homework/A06/URL_reader.py
| 1,267
| 4.125
| 4
|
# Assignment 6
# Network Programming
# John M Warlop
# Python 3.x
# Due 3/4/2018
from urllib.request import urlopen
url = input("type url(ex: www.ibm.com): ")
url = "http://"+url
try:
res=urlopen(url)
except:
print("Could not open "+url)
size=0
Chunk = 512
flag = False
while True:
chunk = res.read(Chunk)
size += len(chunk)
if not chunk:
break
if size >= 3000:
if not flag:
print(chunk[0:440])
flag = True
if size < 3000:
print(chunk)
print("Size is: "+str(size))
'''
http://constitutionus.com
1. Rename the socket1.py to URL_reader.py
2. Modify URL_reader.py to use urllib, size is still 512
3. Add code to prompt for any URL
4. Add error checking(try/except)
5. Count number of chars received and stop showing any text when 3000 chars seen
6. Continue to receive all of document, print the total number of char
Deliverable: Two files 1) URL_reader.py and png of successful running of program
Location of test file: https://www.usconstitution.net/const.txt
import urllib.request
req = urllib.request.Request('http://constitutionus.com/')
response = urllib.request.urlopen(req)
thePage = response.read()
print(thePage)
pageLength = len(thePage)
print("The length of page is: "+str(pageLength))
'''
| true
|
72611838082c1243f1fb63fab711af4c832459ab
|
vijayramalingom/SYSC-1005-Introduction-to-Software-Development-
|
/math_quiz_v3.py
| 1,776
| 4.25
| 4
|
"""
Version 3 of a math quiz program.
Adapted from a programming problem by Jeff Elkner.
dlb Dept. of Systems and Computer Engineering, Carleton U.
Initial release: October 21, 2014 (SYSC 1005)
Revised: November 4, 2015 (SYSC 1005)
The user is prompted to enter a command ("T" or "Q").
If the user types "Q", the program finishes.
If the user types "T", 10 addition problems are presented, then the
user is prompted to enter another command. This continues until
"Q" is entered.
"""
import random
def ask_questions():
""" (None) -> int
Ask 10 addition problems with random integer operands between 1 and 10.
Return the number of questions that were answered correctly.
"""
ok = 0 # Number of correct answers so far
for question in range(1, 11):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
correct_result = num1 + num2
prompt = ("Question " + str(question) + ". What's " +
str(num1) + " plus " + str(num2) + "? ")
answer = int(input(prompt))
if answer == correct_result:
print("That's right -- well done.")
ok += 1
else:
print("No, I'm afraid the answer is", correct_result)
return ok
if __name__ == "__main__":
done = False
while not done:
command = input("Take the quiz or Quit (T, Q): ")
if command == 'T':
correct = ask_questions()
print("I asked you 10 questions.", end = " ")
print("You got", correct, "of them right.")
elif command == 'Q':
done = True
else: # The user typed a command other than Q or T
print(command, "is not a recognized command")
| true
|
512746e85cd9cc1c4b18b29fd05a103e4a915db1
|
dtingg/Fall2018-PY210A
|
/students/C_Farris/session03/list_lab.py
| 1,272
| 4.25
| 4
|
#!/usr/bin/env Python3
"""
Date: November 11, 2018
Created by: Carol Farris
Title: list Lab
Goal: learn list functions
"""
def displayPfruits(myFruit):
for x in myFruit:
if x.lower().startswith('p'):
print(x)
else:
print(x + " doesn't start with p")
def addUsingInsert(myFruit):
myFruit.insert(0, 'Pineapple')
print(myFruit)
def addToBeginningOfList(myFruit):
singleList = ['Mango']
myFruit = singleList + myFruit
print(myFruit)
addUsingInsert(myFruit)
print(myFruit)
return myFruit
def askforAFruit():
newFruit = input("Please enter a different fruit ==>")
newFruit.strip() # strip any whitespace
myFruit.append(newFruit)
print(myFruit)
def askForANumber():
fruitNumb = 100
fruitLength = len(myFruit) - 1
textInput = "Please select an integer from 0-{} ==>".format(fruitLength)
while not fruitNumb <= fruitLength:
fruitNumb = int(input(textInput))
gotThatFruit = myFruit[fruitNumb]
print(fruitNumb, gotThatFruit)
if __name__ == '__main__':
myFruit = ['Apples', 'Pears', 'Oranges', 'Peaches']
print(myFruit)
askforAFruit()
askForANumber()
addToBeginningOfList(myFruit)
displayPfruits(addToBeginningOfList(myFruit))
| true
|
8ce538d1282639c0040cc9101cf9ca1750192fcf
|
dtingg/Fall2018-PY210A
|
/students/ZidanLuo/session02/printGrid.py
| 602
| 4.125
| 4
|
import sys
def print_grid(x,y):
count = 1
#count all the possible number of lines
lines = (y + 1) * x + 1
plus = "+"
minus = "-"
shu = "|"
empty = " "
#draw the horizontal and vertical lines
Horizontal = (plus + y * minus) * x +plus
Vertical = (shu + y * empty) * x + shu
#Use while loop to loop through all the possible lines
while count <= lines :
if (count % (y + 1)) == 1:
print (Horizontal)
else:
print (Vertical)
count += 1
#Take arguments in Command Lines
print_grid(int(sys.argv[1]),int(sys.argv[2]));
| true
|
3ea0e0bef450bd1adf0135bbc54775a7aade1fb4
|
dtingg/Fall2018-PY210A
|
/students/ericstreit/session03/list_lab.py
| 2,511
| 4.15625
| 4
|
#Lesson03
#String Exercises ##
#
#!/usr/bin/env python3
#define variables
mylist = ["Apples", "Pears", "Oranges", "Peaches"]
#define function
def myfunc(n):
"""Update the DocString"""
pass
#series 1
print("The list currently contains: ", mylist)
additem = input("Pleaes enter another item: ")
mylist.append(additem)
print("The list currently now contains: ", mylist)
l = len(mylist)
listitem = int(input("Enter a list item from 1 to {} and I will show it to you: ".format(l)))
print(mylist[(listitem-1)])
print()
pause = input("OK, let's add Kiwis to the list!")
newlist = ["Kiwis"]
mylist = newlist + mylist
print(mylist)
pause = input("Now adding Mangos to the beginning of the list!")
mylist.insert(0,"Mangos")
print(mylist)
pause = input("Now displaying all items that begin with the letter 'P'")
for i in mylist:
if i[0] == "P":
print(i)
pause = input("Press any key to continue to series 2 exercise")
#series 2
print()
print()
print("The list currently contains items: ",mylist)
print("Removing the last item, {}, from the list ".format(mylist[-1]))
mylist.pop()
print("The list now contains: ",mylist)
toremove = input("Please enter an item you would you like to remove : ")
mylist.remove(toremove)
print("The list now contains: ",mylist)
#series 3
#there is a bug in this section - if an item is removed then it skips the following item
#I suspect because it changes the index value
print("OK, let's move on to series 3!")
print()
copy_listXXXXXXXX = mylist
print(id(mylist))
print("here is the copied list")
print(copy_listXXXXXXXX)
print(id(copy_listXXXXXXXX))
for i in copy_listXXXXXXXX:
choice = input("Do you like {}?: (y/n)".format(i))
if choice == "y":
continue
elif choice == "n":
mylist.remove(i)
print("Removing {} from the list!".format(i))
#bug if 'n' is selected it skips the next item in the list, even if I use a copy of the list..
else:
while choice != "y" or "n":
choice = input("Hm, I don't understand '{}' please enter 'y' or 'n' ".format(choice))
break
print(mylist)
#series 4
#start
print("Let's start series 4!")
print("The list currently contains: ", mylist)
l = len(mylist)
newlist = []
for i in mylist:
newlist.append(i[::-1])
print("The original list is {} minus the last item.".format(mylist[0:l-1]))
print("The original list items spelled backwards is {}: ".format(newlist))
pause = input("Press any key to exit")
#for testing
if __name__=="__main__":
pass
| true
|
cc81bbb1e52a93c61b9f96b60930e38bf18f02cb
|
dtingg/Fall2018-PY210A
|
/students/KannanSethu/session8/circle.py
| 1,237
| 4.28125
| 4
|
#!/usr/bin/env python3
import math
'Create a circle using classes'
class Circle:
def __init__(self, radius):
self.radius = radius
_diameter = None
@property
def diameter(self):
self._diameter = self.radius * 2
return self._diameter
@diameter.setter
def diameter(self, diameter):
self._diameter = diameter
self.radius = int(self._diameter / 2)
return self._diameter
_area = None
@property
def area(self):
self._area = math.pi * (self.radius**2)
return self._area
@classmethod
def from_diameter(cls, diameter_value):
'Create circle using diameter'
self = cls(int(diameter_value/2))
return self
def __str__(self):
return f'Circle with radius: {self.radius}'
def __repr__(self):
return f'Circle({self.radius})'
def __add__(self, other):
return Circle(self.radius + other.radius)
def __mul__(self, other):
return Circle(self.radius * other.radius)
def __lt__(self, other):
return self.radius < other.radius
def __gt__(self, other):
return self.radius > other.radius
def __eq__(self, other):
return self.radius == other.radius
| false
|
50f8171ffe7f7bb9e9b7b531314acfa999c88933
|
dtingg/Fall2018-PY210A
|
/students/student_framllat/session02/series.py
| 1,600
| 4.125
| 4
|
a = int(input("How many nums shall I calculate for you? "))
def fibonacci(n):
"""This function calculates the nth value of a Fibonacci number
starting at the zero index
"""
if n < 0:
return None
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 2) + fibonacci(n - 1)
def lucas(n):
"""This function calculates the nth value of a Lucas Number
starting at the zero index
"""
if n < 0:
return None
elif n == 0:
return 2
elif n == 1:
return 1
else:
return lucas(n - 2) + lucas(n - 1)
def sum_series(n, n0=0, n1=1):
"""This function attempts to calculate the nth value of a Series
starting at the zero index
"""
if n < 0:
return None
elif n == 0:
return n0
elif n == 1:
return n1
else:
return sum_series(n - 1, n0, n1) + sum_series(n - 2, n0, n1)
fib_res = fibonacci(a)
luc_res = lucas(a)
#sum_res = sum_series(a, 0, 1)
sum_res = sum_series(a, 2, 1)
print("The Fibonacci -> ",fib_res)
print("The Lucas -> ",luc_res)
print("The Series -> ",sum_res)
if __name__ == "__main__":
## Tests to validate
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert lucas(4) == 7
assert lucas(5) == 11
## Tests for the sum_series--With LUCAS params
assert sum_series(5,2,1) == lucas(5)
assert sum_series(1,2,1) == lucas(1)
## Tests for the sum_series--With FIBONACCI params
assert sum_series(0,0,1) == 0
assert sum_series(7,0,1) == fibonacci(7)
print("SUCCESS")
| false
|
ab2aed6b36ee8a39a05d108704db93cad76a1311
|
dtingg/Fall2018-PY210A
|
/students/ZackConnaughton/session03/list_lab.py
| 709
| 4.15625
| 4
|
#!/usr/bin/env python
def series1():
"""
Shows what can be done with a simple list of fruitsself.
"""
fruits = ['Apples', 'Pears', 'Oranges', 'Peaches']
print(fruits)
response = input('Input another Fruit: ')
fruits.append(response)
print(fruits)
fruit_number = input('Enter the number fruit you want to see (from 1 '
'to ' + str(len(fruits)) + '):')
print(fruits[int(fruit_number) - 1])
fruits = ['Plum'] + fruits
print(fruits)
fruits.insert(0, 'Banana')
print(fruits)
p_fruits = []
for f in fruits:
if f[0] == 'P':
p_fruits.append(f)
print(p_fruits)
if __name__ == '__main__':
series1()
| true
|
a0619210034948ccc632e944142c72e302bfd522
|
dtingg/Fall2018-PY210A
|
/students/KannanSethu/session3/slicing_functions.py
| 1,324
| 4.28125
| 4
|
"""some functions that take a sequence as an argument, and return a copy of that sequence"""
A_STRING = "this is a string"
A_TUPLE = (2, 54, 13, 12, 5, 32)
def exchange_first_last(seq):
""" with the first and last items exchanged """
return seq[-1:] + seq[1:-1] + seq[0:1]
assert exchange_first_last(A_STRING) == "ghis is a strint"
assert exchange_first_last(A_TUPLE) == (32, 54, 13, 12, 5, 2)
def every_other_removed(seq):
"""with every other item removed"""
return seq[0::2]
assert every_other_removed(A_STRING) == "ti sasrn"
assert every_other_removed(A_TUPLE) == (2, 13, 5)
def remove_first_last_n(seq):
""" with the first and last 4 items removed, and every other item in between """
return seq[4:-4:2]
assert remove_first_last_n(A_STRING*2) == " sasrnti sas"
assert remove_first_last_n(A_TUPLE*2) == (5, 2)
def exchange_reverse(seq):
""" with the elements reversed"""
return seq[::-1]
assert exchange_reverse(A_STRING) == "gnirts a si siht"
assert exchange_reverse(A_TUPLE) == (32, 5, 12, 13, 54, 2)
def mixed_third(seq):
""" with the last third, then first third, then the middle third in the new order """
return seq[len(seq)//3:]+seq[:len(seq)//3]
assert mixed_third(A_STRING) == "is a stringthis "
assert mixed_third(A_TUPLE) == (13, 12, 5, 32, 2, 54)
| false
|
e07217f51ac1b0401635329a3ae81a54495135a7
|
dtingg/Fall2018-PY210A
|
/students/DiannaTingg/Session05/comprehensions_lab.py
| 2,453
| 4.4375
| 4
|
# Lesson 05 Exercise: Comprehensions Lab
# Count Even Numbers
# Using a list comprehension, return the number of even integers in the given list.
def count_evens(l):
return len([i for i in l if i % 2 == 0])
assert count_evens([2, 1, 2, 3, 4]) == 3
assert count_evens([2, 2, 0]) == 3
assert count_evens([1, 3, 5]) == 0
# Revisiting the Dictionary and Set Lab
food_prefs = {"name": "Chris", "city": "Seattle", "cake": "chocolate", "fruit": "mango",
"salad": "greek", "pasta": "lasagna"}
# Print dictionary using a string format method
print("{name} is from {city} and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta."
.format(**food_prefs))
# Using a list comprehension, build a dictionary of numbers from zero to fifteen and the hexadecimal equivalent (string)
# the hex() function gives you the hexidecimal representation of a number as a string
def hex_dictionary():
my_dict = dict([(i, hex(i)) for i in range(16)])
return my_dict
print(hex_dictionary())
# Make another hex dictionary, but use a one line dictionary comprehension
def better_hex_dictionary():
return {key: hex(key) for key in range(16)}
print(better_hex_dictionary())
# Using the food_prefs dictionary: Make a dictionary using the same keys but with the number of ‘a’s in each value.
def a_values_dict(original_dict):
return {key: value.count("a") for key, value in original_dict.items()}
print(a_values_dict(food_prefs))
# Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible 2, 3 and 4.
s2 = set(i for i in range(21) if i % 2 == 0)
s3 = set(i for i in range(21) if i % 3 == 0)
s4 = set(i for i in range(21) if i % 4 == 0)
print("s2:", s2)
print("s3:", s3)
print("s4:", s4)
# Create a sequence that holds all the divisors you might want – could be any number of divisors.
# Loop through that sequence to build the sets up. You will end up with a list of sets – one set for each divisor.
def make_sets(divisor_list):
sets = []
for x in divisor_list:
subset = set(i for i in range(21) if i % x == 0)
sets.append(subset)
return sets
print(make_sets([2, 3, 4, 5]))
# Extra credit: do it all as a one-liner by nesting a set comprehension inside a list comprehension.
def make_better_sets(divisor_list):
return [set(i for i in range(21) if i % number == 0) for number in divisor_list]
print(make_better_sets([2, 3, 4, 5]))
| true
|
29c93f8ba7065b60a30ea4264f4678eb90e8301a
|
dtingg/Fall2018-PY210A
|
/students/ZachCooper/session01/break_me.py
| 1,139
| 4.125
| 4
|
#!/usr/bin/env python
# I tried a couple of error exceptions that I commonly ran into during my Foundations class
# Example of ZeroValueError
def divide_things(num1, num2):
try:
print(num1 / num2)
except ZeroDivisionError:
print("Ummm...You totally can't divide by 0")
raise ZeroDivisionError
divide_things(12, 0)
# Example of ValueError
try:
num = float(input("Enter a number: "))
except ValueError:
print("That was not a number!!")
else:
print("Your number is:")
# Example of FileError
try:
fakefile = open('fake.txt', 'r')
fakefile.read()
except FileNotFoundError:
print("Sorry your file doesn't exist...")
except Exception as e:
print(e)
print("Unknown error, sorry!")
# Example of KeyError
seahawks_dict = {'Russell Wilson': 'Quarterback', 'Doug Baldwin': 'Wide Receiver', 'Pete Carrol': 'Coach',
'BobbyWagner': 'Linebacker'}
def seahawks_exception():
try:
print(seahawks_dict[1])
print(seahawks_dict[2])
print(seahawks_dict[4])
except KeyError:
print("That is not a key in the Seahawks Dictionary!")
seahawks_exception()
| true
|
f6a456ba4595fcbbf2e3a4143b2c0ca4f131df96
|
dtingg/Fall2018-PY210A
|
/students/HABTAMU/session02/printer_Grid_Ex.py
| 2,344
| 4.125
| 4
|
#!/usr/bin/env python3
# Goal:
# Write a function that draws a grid like the following:
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | |
# + - - - - + - - - - +
# Option 1
# Here, I tried to eliminate, change hard coded number with name 'n', to fit for any number 'n', but it needs to be multiple of 5.
def print_rectangle(n) :
for i in range(n+1) :
for j in range(n+1):
if ((i in range (0,n+5,5) and j%5 == 0)) :
print("+", end=" ")
elif ((i in range(0,n+5,5) and j > 0 and j < n)) :
print("-", end=" ")
elif ((j in range(0,n+5,5) and i > 0 and i < n)) :
print("|", end=" ")
else :
print("", end=" ")
print()
n = 25
print_rectangle(n)
# Option 2
# def print_rectangle(row, col) :
# for i in range(11) :
# for j in range(11):
# if ((i in range (0,15,5) and j%5 == 0)) :
# print("+", end=" ")
# elif ((i in range(0,15,5) and j > 0 and j < 10)) :
# print("-", end=" ")
# elif ((j in range(0,15,5) and i > 0 and i < 10)) :
# print("|", end=" ")
# else :
# print("", end=" ")
# print()
# Driver program for above function
# row = 10
# col = 10
# print_rectangle(row, col)
# Option 3
# def print_rectangle(row, col) :
# for i in range(11) :
# for j in range(11):
# if ((i == 0 and j%5 == 0) or (i == 5 and j%5 == 0) or i == 10 and j%5 == 0) :
# print("+", end=" ")
# elif ((i == 0 and j > 0 and j < 10) or (i == 5 and j > 0 and j < 10) or (i == 10 and j > 0 and j < 10)) :
# print("-", end=" ")
# elif ((j == 0 and i > 0 and i < 10) or (j == 5 and i > 0 and i < 10) or (j == 10 and i > 0 and i < 10)) :
# print("|", end=" ")
# else :
# print("", end=" ")
# print()
# # Driver program for above function
# row = 10
# col = 10
# print_rectangle(row, col)
| false
|
91d188d6e4655d7d88dddef897aeec6d4a0ced09
|
dtingg/Fall2018-PY210A
|
/students/DrewSmith/session05/comprehension_exercise.py
| 2,266
| 4.4375
| 4
|
"""
Comprehension exercise solutions
"""
from collections import defaultdict
def count_evens(nums):
"""
Return number of even integers in nums
:param nums: sequence of integers
"""
return len([num for num in nums if num % 2 == 0])
def print_dict(food_prefs):
"""
Print a dictionary using a format string
:param food_prefs: food pref dictionary to print
"""
print("{name} is from {city}, and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta".format(**food_prefs))
def hex_dict():
"""
Generate a dictionary using integers with hex version values
"""
return {num: hex(num) for num in range(16)}
def dict_count_a(input_dict):
"""
Create dictionary of input_dict value 'a' count
:param dict_count_a: dictionary to read value 'a's
"""
return {k: v.count('a') for k, v in input_dict.items()}
def set_divisors(nums, divisors):
"""
Create a list of sets of divisors for an integer set
:param nums: set of integers
:param divisors: set of integers that are divisors for num list
"""
# first attempt with dict loop
# return_dict = {}
# for divisor in divisors:
# return_dict[divisor] = {num for num in nums if num % divisor == 0}
# return return_dict
# Build dictionary of divisors/set values with comprehension...sort of
# return_dict = {}
# { return_dict.setdefault(divisor, set()).add(num) for divisor in divisors for num in nums if num % divisor == 0 }
# return return_dict
# One liner dictionary
return { divisor: { num for num in nums if num % divisor == 0 } for divisor in divisors }
# One-liner list of sets
# return [ { num for num in nums if num % divisor == 0 } for divisor in divisors ]
if __name__ == '__main__':
assert count_evens([2, 1, 2, 3, 4]) == 3
assert count_evens([2, 2, 0]) == 3
assert count_evens([1, 3, 5]) == 0
food_prefs = {"name": "Chris",
"city": "Seattle",
"cake": "chocolate",
"fruit": "mango",
"salad": "greek",
"pasta": "lasagna"}
print_dict(food_prefs)
print(hex_dict())
print(dict_count_a(food_prefs))
print(set_divisors(range(21), {2, 3, 4}))
| false
|
340220654fed7bc3d3de00da2a5f3fd4fc230121
|
dtingg/Fall2018-PY210A
|
/students/JugalKishore/Session_3/slicing_lab.py
| 2,432
| 4.15625
| 4
|
#!/usr/bin/env python3
def exchange_first_last(seq):
"""
:param: sequence
:return: sequence with first and last item exchanges and all other item remain same
"""
if len(seq) <= 1:
return seq
return seq[-1:] + seq[1:-1] + seq[:1]
def other_item_removed(seq):
"""
:param: sequence
:return: sequence with every other item removed
"""
return seq[::2]
def remove_4(seq):
"""
:param: sequence
:return: sequence with the first 4 and the last 4 items removed,
and then every other item in the remaining sequence.
"""
return seq[4:-4:2]
def reversed(seq):
"""
:param: sequence
:return: sequence with the elements reversed
"""
return seq[::-1]
def exchange_third(seq):
"""
:param: sequence
:return: sequence with the last third, then first third, then
the middle third in the new order
"""
return seq[-(len(seq) // 3):] + seq[:(len(seq) // 3)] + seq[(len(seq) // 3):-(len(seq) // 3)]
if __name__ == "__main__":
# run tests
# exchange_first_last tests
assert exchange_first_last("this is a string") == "ghis is a strint"
assert exchange_first_last((2, 54, 13, 12, 5, 32)) == (32, 54, 13, 12, 5, 2)
assert exchange_first_last([2, 54, 13, 12, 5,32]) == [32, 54, 13, 12, 5, 2]
assert exchange_first_last('') == ''
assert exchange_first_last('a') == 'a'
# other_item_removed tests
assert other_item_removed("this is a string") == "ti sasrn"
assert other_item_removed((2, 54, 13, 12, 5, 32)) == (2, 13, 5)
assert other_item_removed([2, 54, 13, 12, 5,32]) == [2, 13, 5]
assert other_item_removed('') == ''
assert other_item_removed('a') == 'a'
# remove_4 tests
assert remove_4("this is a string") == " sas"
assert remove_4((2, 54, 13, 12, 5, 32)) == ()
assert remove_4([2, 54, 13, 12, 5,32]) == []
assert remove_4('') == ''
assert remove_4('a') == ''
# reversed tests
assert reversed("this is a string") == "gnirts a si siht"
assert reversed((2, 54, 13, 12, 5, 32)) == (32, 5, 12, 13, 54, 2)
assert reversed([2, 54, 13, 12, 5,32]) == [32, 5, 12, 13, 54, 2]
assert reversed('') == ''
assert reversed('a') == 'a'
# exchange_third tests
assert exchange_third("this is a string") == "tringthis is a s"
assert exchange_third((2, 54, 13, 12, 5, 32)) == (5, 32, 2, 54, 13, 12)
assert exchange_third([2, 54, 13, 12, 5,32]) == [5, 32, 2, 54, 13, 12]
assert exchange_third('') == ''
assert exchange_third('a') == 'a'
#if all tests pass then print
print("All Tests Passed")
| false
|
f3348cba2eaaa6e973b8a28497d0cd5d942389a4
|
dtingg/Fall2018-PY210A
|
/students/HABTAMU/session04/dict_lab.py
| 2,076
| 4.125
| 4
|
#!/usr/bin/env python3
"""Dictionaries 1"""
# Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate”
# (so the keys should be: “name”, etc, and values: “Chris”, etc.)
my_dict = {"name": "Chris","city": "Seattle","cake": "Chocolate"}
# Display the dictionary.
print("{name} is from {city}, and likes {cake} cake.".format(**my_dict))
# Delete the entry for “cake”.
my_dict.popitem()
del my_dict["cake"]
print(my_dict)
# Add an entry for “fruit” with “Mango” and display the dictionary.
dict = my_dict
my_dict['fruit'] = 'Mango'
print(my_dict)
# Display whether or not “cake” is a key in the dictionary (i.e. False) (now).
print('cake' in my_dict)
# Display whether or not “Mango” is a value in the dictionary (i.e. True).
print('Mango' in my_dict.values())
# Dictionaries 2
# Using the dictionary from item 1:
# Make a dictionary using the same keys but with the number of ‘t’s in each value as the value(consider upper and lower case?).
d = {}
for k, v in my_dict.items():
d[k] = v.count('t')
print(d)
# Sets
# Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible by 2, 3 and 4.
s2 = set()
s3 = set()
s4 = set()
for i in range(21):
if not i % 2:
s2.add(i)
if not i % 3:
s3.add(i)
if not i % 4:
s4.add(i)
print(s2)
print(s3)
print(s4)
# Display the sets.
# Display if s3 is a subset of s2(False)
print(s3.issubset(s2))
# and if s4 is a subset of s2 (True).
s4.issubset(s2)
# Sets 2
# Create a set with the letters in ‘Python’ and add ‘i’ to the set.
s1 = set('Python')
s1.add('i')
s1
print(s1)
# Create a frozenset with the letters in ‘marathon’.
f = frozenset('marathon')
# display the union and intersection of the two sets.
x = s1.union(f)
y = f.union(s1)
print("union", x)
print("union with", y)
z = s1.intersection(f)
zz = f.intersection(s1)
print("intersection", z)
print("intersection with", zz)
| true
|
b74f0019166cd600f9a17433f5b1807b7f94548b
|
dtingg/Fall2018-PY210A
|
/students/DiannaTingg/Session04/get_languages.py
| 2,111
| 4.40625
| 4
|
# Lesson 04 Exercise: File Exercise
# File reading and parsing
# Write a program that takes a student list and returns a list of all the programming languages used
# Keep track of how many students specified each language
# It has a header line and the rest of the lines are: Last, First: Nicknames, languages
def get_lines(my_file):
"""
Returns formatted lines using a text file
:param my_file: a text file
:return: list of lines with endings stripped, commas replaced with empty strings, and header removed
"""
with open(my_file, "r") as infile:
lines = infile.readlines()
strip_lines = [l.strip() for l in lines]
words = [l.replace(",", "") for l in strip_lines]
del words[0]
return words
def stuff_after_colon(lines):
"""
Returns a list of split lines
:param lines: list of formatted lines that contain a colon
:return: list of lines with only the text after the colon
"""
stuff = []
for x in lines:
try:
langs = x.split(": ")[1]
stuff.append(langs)
except IndexError:
pass
return stuff
def print_dictionary(my_dict):
"""
Prints the dictionary contents using a formatted string
:param my_dict: dictionary with language as the key and number of students as the value
:return: an alphabetized, formatted list of computer languages and number of students
"""
print("Computer Languages Used by Students")
for key in sorted(my_dict.keys()):
print("{}: {}".format(key.capitalize(), my_dict[key]))
def get_languages(filename):
languages = {}
strip_lines = get_lines(filename)
stuff = stuff_after_colon(strip_lines)
for lines in stuff:
for item in lines.split():
if item == "nothing" or item[0].isupper():
continue
else:
if item in languages:
languages[item] += 1
else:
languages[item] = 1
print_dictionary(languages)
if __name__ == "__main__":
get_languages("students.txt")
| true
|
63a2168eeeddcc102e648ea5130a40d888569a7d
|
dtingg/Fall2018-PY210A
|
/students/JonSerpas/session02/series.py
| 1,395
| 4.25
| 4
|
def fibonacci(n):
#first create our list with starting integers
fiblist = [0,1]
#appends to the end list of integers the sum of the previous two integers
#this will loop until the length of the list is n long
#finally we return the n value of the list
while len(fiblist) < n:
fiblist.append(sum(fiblist[-2:]))
return fiblist[n-1]
print(fibonacci(7))
print(fibonacci(9))
print(fibonacci(5))
def lucas(n):
#first create our list with starting integers
lucaslist = [2,1]
#appends to the end list of integers the sum of the previous two integers
#this will loop until the length of the list is n long
#finally we return the n value of the list
while len(lucaslist) < n:
lucaslist.append(sum(lucaslist[-2:]))
return lucaslist[n-1]
print(lucas(7))
print(lucas(9))
print(lucas(5))
def sum_series(n, x=0, y=1):
#first create our list with starting integers
sum_list = [x , y]
#appends to the end list of integers the sum of the previous two integers
#this will loop until the length of the list is n long
#finally we return the n value of the list
while len(sum_list) < n:
sum_list.append(sum(sum_list[-2:]))
return sum_list[n-1]
print(sum_series(7))
print(sum_series(9,2,1))
print(sum_series(5,6,4))
#here we write our unit tests.
#no Assertion Errors mean the code is working as expected
assert fibonacci(7) == 8
assert lucas(7) == 18
assert sum_series(5,6,4) == 24
| true
|
e571de78c6e4fd094bcf760e2f2f522ff53958aa
|
dtingg/Fall2018-PY210A
|
/students/Adolphe_N/session03/slicing.py
| 1,307
| 4.5
| 4
|
#! python3
a_string = 'this is a string'
a_tuple = (2,54,13,12,5,32)
name = 'Seattle'
'''
prints the list with the last item first and first item last
'''
def exchange_first_last():
#this will exchange the first and last character of the string
print(a_string)
print ('{}{}{}'.format(a_string[-1], a_string[1:-1], a_string[0]))
print(a_tuple)
print ('({}, {}, {}, {}, {}, {})'.format(a_tuple[-1], a_tuple[1],a_tuple[2], a_tuple[3],a_tuple[4],
a_tuple[0]))
'''
first and last 4 items removed along with every other item
'''
def remove(n):
len_str = len(n)
print (a_string)
print (n[4:(len_str-4):2])
'''
prints the reversed list
'''
def reverse(n):
len_str = len(n)
print(a_string)
print (n[::-1])
'''
prints the last third of the list first, then the first third then the middle third
'''
def new_order(n):
len_str = len(n)
third = (len_str // 3)
print(a_string)
print("{}, {}, {}".format(n[(third)::], n[0:third], n[third:(third)]))
print("{}, {}, {}".format(n[(third * 2)::], n[0:third], n[third:(third*2)]))
if __name__ == '__main__':
exchange_first_last()
remove(a_string)
reverse(a_string)
new_order(name)
| true
|
8dc90534107673e7574626c9816423f8c72bf4f2
|
Miriam-Hein/pands-problem-sheet
|
/es.py
| 710
| 4.125
| 4
|
# es.py
# This program reads in a text file and outputs the number of e's it contains.
# Author: Miriam Heinlein
# Import library (System-specific parameters and functions)
import sys
# Function to read letter e in the file from an arugment in the command line
def readText():
with open(sys.argv[1], "r") as f: #sys.argv reads the textfile from the command line whereby argv [1] refers to file names passed as argument to the function in index 1
text = f.read() # store content of the file in a variable
totalEs = text.count('e') #counts the e's in the textfile and stores them in the variable totalEs
# Display the number of e's counted
print(totalEs)
# Calling function
readText()
| true
|
12b5743215371715e3fb8437c64f2c76ebb68cef
|
michaelkmpoon/Pandhi_Ayush_-_Poon_Michael_Assignment1_CTA200H
|
/question_1/find_replace.py
| 962
| 4.15625
| 4
|
#!/usr/bin/env python3
import os
def find_replace(find: str, replace: str): # type check, only strings allowed as input
os.makedirs(replace) # make directory called replace in working directory
for file_name in os.listdir("."):
if file_name.endswith(".txt"):
file = open(file_name, "r")
for line in file: # for every line
if find in line:
file.close() # close file and reopen to read from first line
file = open(file_name, "r")
transfer = file.read()
transfer = transfer.replace(find, replace)
new_file = open(".\\" + replace + "\\" + file_name, "w+")
new_file.write(transfer)
new_file.close()
break
file.close()
find = input("Enter the word to find: ")
replace = input("Enter the word to replace: ")
find_replace(find, replace)
| true
|
8a2eb6e733d29afad05b36566efd71406ca57fbc
|
pankajnimgade/Python_Test101
|
/Function_Installation_and_Conditionals/code_with_branches_1_.py
| 1,574
| 4.25
| 4
|
phone_balance = 9
bank_balance = 100000000
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print("Phone Balance: " + str(phone_balance))
print("Bank Balance: " + str(bank_balance))
weight_in_kg = 55
height_in_m = 1.2
if 18.5 <= weight_in_kg/(height_in_m**2) < 25:
print("BMI is considered 'normal'.")
number = 10
if number % 2 == 0:
print("{} is even.".format(number))
else:
print("{} is odd.".format(number))
def garden_calendar(season):
if season == "spring":
print("Current season is {}. time to plant the garden!".format(season))
elif season == "summer":
print("Current season is {}. time to water the garden!".format(season))
elif season == "autumn" or season == "fall":
print("Current season is {}. time to harvest the garden!".format(season))
elif season == "winter":
print("Current season is {}. time to stay indoors and drink tea!".format(season))
else :
print("Don't recognize the season.")
garden_calendar("winter")
print("\n\n")
#Third Example
#change the age to experiment with the pricing
age = 35
#set the age limits for bus fares
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65
#set bus fares
concession_ticket = 1.25
adult_ticket = 2.50
#ticket price logic
if age <= free_up_to_age:
ticket_price = 0
elif age <= child_up_to_age:
ticket_price = concession_ticket
elif age >= senior_from_age:
ticket_price = concession_ticket
else:
ticket_price = adult_ticket
message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age,ticket_price)
print(message)
| true
|
2076032e181ef578181ea02b669853c79006da38
|
Programacion-Algoritmos-18-2/ejercicios-clases2bim-002-paxasaval
|
/tutoria-2-sc/manejo_archivos/paquete_modelo/mimodelo.py
| 2,922
| 4.1875
| 4
|
"""
creación de clases
"""
class Persona(object):
"""
"""
def __init__(self, n, ape, ed, cod, nota1, nota2):
"""
"""
self.nombre = n
self.edad = int(ed)
self.codigo = int(cod)
self.apellido = ape
self.nota1=int(nota1)
self.nota2=int(nota2)
def set_nota1(self,nota1):
self.nota1=nota1
def get_nota1(self):
return self.nota1
def set_nota2(self,nota2):
self.nota2=nota2
def get_nota2(self):
return self.nota2
def agregar_nombre(self, n):
"""
"""
self.nombre = n
def obtener_nombre(self):
"""
"""
return self.nombre
def agregar_edad(self, n):
"""
"""
self.edad = int(n)
def obtener_edad(self):
"""
"""
return self.edad
def agregar_codigo(self, n):
"""
"""
self.codigo = int(n)
def obtener_codigo(self):
"""
"""
return self.codigo
def obtener_apellido(self):
"""
"""
return self.apellido
def __str__(self):
"""
"""
return "%s - %s - %d - %d - %d - %d" % (self.nombre, self.apellido,\
self.edad, self.codigo, self.get_nota1(), self.get_nota2())
class OperacionesPersona(object):
"""
"""
def __init__(self, listado):
"""
"""
self.listado_personas = listado
def obtener_promedio_n1(self):
""" """
suma=0
for n in self.listado_personas:
suma=suma+n.get_nota1()
promedio=suma/len(self.listado_personas)
return promedio
def obtener_promedio_n2(self):
""" """
suma=0
for n in self.listado_personas:
suma=suma+n.get_nota2()
promedio=suma/len(self.listado_personas)
return promedio
def obtener_notas1_menores_n(self,x):
""" """
lista=[]
for n in self.listado_personas:
if n.get_nota1()<x:
#print("%sNombre: %s %-30sNota 1: %d\n"%(cadena,n.obtener_nombre(),n.obtener_apellido(),n.get_nota1()))
lista.append(n)
return lista
def obtener_notas2_menores_n(self,x):
""" """
lista=[]
for persona in self.listado_personas:
if persona.get_nota2()<x:
lista.append(persona)
return lista
def listar_por_caracter(self,x):
lista=[]
for persona in self.listado_personas:
if persona.obtener_nombre()[0]==x:
lista.append(persona)
return lista
def __str__(self):
""" """
cadena=""
for n in self.listado_personas:
cadena="%s%s %s\tNota1: %d\tNota2:%d\n"%(cadena,n.obtener_nombre(),n.obtener_apellido(),n.get_nota1(),n.get_nota2())
return cadena
| false
|
6ffe379e6968c1f0262bef8eace517928f4d4849
|
dimmonblr/pythonProject2
|
/pythonProject3/01_days_in_month.py
| 894
| 4.125
| 4
|
# -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
calendar = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
user_input = input("Введите, пожалуйста, номер месяца: ")
month = int(user_input)
if 1 <= month <= 12:
print('Вы ввели', month)
print('Количество дней в данном месяце -', calendar[month])
else:
print("Номер месяца некорректен")
| false
|
9b5ad1db488ceb425f57abc3cac88fefa8d581c5
|
Prathamdoshi/UC-Berkeley-Data-Analytics-Bootcamp-Module-Exercises
|
/Python/Netflix.py
| 1,405
| 4.125
| 4
|
instructions ="""
# Netflix lookup
Finding the info to some of netlfix's most popular videos
## Instructions
* Prompt the user for what video they are looking for.
* Search through the `netflix_ratings.csv` to find the user's video.
* If the CSV contains the user's video then print out the title, what it is rated and the current user ratings.
* For example "Pup Star is rated G with a rating of 82"
* If the CSV does not contain the user's video then print out a message telling them that their video could not be found.
"""
# Modules
import os
import csv
# Prompt user for video lookup
video = input("What show or movie are you looking for? ")
# Set path for file
cwd = os.getcwd()
csvpath = os.path.join(cwd, "Python/data/netflix_ratings.csv")
# Bonus
# ------------------------------------------
# Set variable to check if we found the video
# Try: Zootopia; Gossip Girl
found = False
# Open the CSV
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# Loop through looking for the video
for row in csvreader:
if row[0].lower() == video.lower():
print(row[0]+ " is rated "+ row[1] + " with a rating of " + row[6])
found = True
break
# If the video is never found, alert the user
if found == False:
print("Sorry about this, we don't seem to have what you are looking for!")
| true
|
f2d5ef31396ecea22e9fd495bf7d3538c5d63c96
|
damuraiz/python_gb
|
/lesson2/task02_2.py
| 834
| 4.28125
| 4
|
#Для списка реализовать обмен значений соседних элементов,
# т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
size = int(input('Введите количество элементов в списке: '))
my_list = []
for i in range(size):
my_list.append(input(f"Введите {i} элемент списка: "))
for i in range(1,len(my_list),2):
(my_list[i], my_list[i-1])=(my_list[i-1], my_list[i])
for item in my_list:
print(item)
| false
|
90ec7904e768152ea28f5d2538a8c1b919671848
|
damuraiz/python_gb
|
/lesson3/task03_6.py
| 1,039
| 4.28125
| 4
|
"""
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв
и возвращающую его же, но с прописной первой буквой.
Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием.
В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в нижнем регистре.
Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.
Необходимо использовать написанную ранее функцию int_func()
"""
def int_func(text):
return text.capitalize()
in_str = input('Введите входную строку:\n')
for s in in_str.split():
in_str = in_str.replace(s, int_func(s))
print(in_str)
| false
|
8507cee32a92b1d19214e08ac731be5a10bc8bb4
|
daviddwlee84/LeetCode
|
/Python3/LinkedList/MergeTwoSortedLists/Better021.py
| 892
| 4.125
| 4
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from ..ListNodeModule import ListNode
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Declare a temporary head, because we aren't sure l1 or l2 is None or Head
tempHead = node = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
if not l1:
# If l1 is empty, then connect the rest of l2 to node
node.next = l2
else:
# Vice versa
node.next = l1
return tempHead.next
| true
|
009fb7f3db4c51738566e83de7ae32ecd2e813f6
|
daviddwlee84/LeetCode
|
/Python3/LinkedList/InsertionSortList/Naive147.py
| 1,124
| 4.1875
| 4
|
from ..ListNodeModule import ListNode
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
fakeRoot = ListNode(-1)
current = fakeRoot.next = head
while current and current.next:
if current.val <= current.next.val:
# already sorted
current = current.next
else:
# delete current.next and save as temp
temp = current.next
current.next = current.next.next
# iterate from the start to find the position to insert
previous = fakeRoot
while previous.next.val <= temp.val:
previous = previous.next
# insert after previous node
temp.next = previous.next
previous.next = temp
return fakeRoot.next
# Runtime: 200 ms, faster than 67.41% of Python3 online submissions for Insertion Sort List.
# Memory Usage: 14.7 MB, less than 100.00% of Python3 online submissions for Insertion Sort List.
| true
|
df797407e5c699b19a92585715a093d50f867c99
|
Kiddiflame/For_Assignment_5
|
/Documents/Forritun/max_int.py
| 590
| 4.59375
| 5
|
#1. Initialize with git init
#2. input a number
#3. if number is larger than 0, it becomes max-int
#4. if number is greater than 0, user can input another number
#5. repeat step 3 and 4 until negative number is given
#6. if negative number is given, print largest number
num_int = int(input("Input a number: "))# Do not change this line
max_int = 0
if num_int > 0:
max_int = num_int
while num_int > 0:
num_int = int(input("Input a number: "))
if num_int > max_int:
max_int = num_int
print("The maximum is", max_int) # Do not change this line
| true
|
d5deb525066d1bd891b52c84f63f4033bdcedae8
|
andrew-yt-wong/ITP115
|
/ITP 115 .py/Labs/ITP115_L8_1_Wong_Andrew.py
| 1,568
| 4.28125
| 4
|
# Andrew Wong, awong827@usc.edu
# ITP 115, Spring 2020
# Lab 8-1
# Wants to continue function that checks whether the user is going to continue
def wantsToContinue():
# Loop until a valid response is given
validResponse = False
while not validResponse:
# Retrieve the response and capitalize it
response = input("Do you want to continue (y/n)? ").upper()
# Check whether we continue or not, if it is invalid we will loop
if response == "Y":
validResponse = True
return True
elif response == "N":
validResponse = True
return False
# Converts a given temperature given the type of conversion and temp
def temperatureConverter(conversionType, inputTemperature):
# Check which type of conversion if any and return the value
if conversionType == 1:
return (inputTemperature - 32) * 5 / 9
elif conversionType == 2:
return (inputTemperature * 9 / 5) + 32
else:
print("Invalid conversion code")
return 0
# Main Function that calls the other two functions
def main():
# Continue while the user wants to
cont = True
while cont:
print("Welcome to the Temperature Converter 1.0")
conversionType = int(input("Enter 1 for F->C, or 2 for C->F: "))
inputTemperature = int(input("Enter input temperature: "))
convertedTemp = temperatureConverter(conversionType, inputTemperature)
print("The converted temperature is", convertedTemp)
cont = wantsToContinue()
print("")
main()
| true
|
622b729bde772c0a296e1db8e9c6a84b6f3859e4
|
andrew-yt-wong/ITP115
|
/ITP 115 .py/Labs/ITP115_L6_2_Wong_Andrew.py
| 1,059
| 4.125
| 4
|
# Andrew Wong, awong827@usc.edu
# ITP 115, Spring 2020
# Lab 6-2
def main():
# Get the words and convert them into various lists
firstWord = input("Please enter a word or statement: ").replace(" ", "").lower()
secondWord = input("Please enter a second word or statement: ").replace(" ", "").lower()
firstWordList = list(firstWord)
fRevCopy = firstWordList[:]
fCopy = firstWordList[:]
secondWordList = list(secondWord)
sCopy = secondWordList[:]
sRevCopy = secondWordList[:]
fCopy.sort()
sCopy.sort()
fRevCopy.reverse()
sRevCopy.reverse()
# Compare all the lists
if fCopy == sCopy:
print("The two words you entered are anagrams")
else:
print("The two words you entered are not anagrams")
if firstWordList == fRevCopy:
print("The first word is a palindrome")
else:
print("The first word is not a palindrome")
if secondWordList == sRevCopy:
print("The second word is a palindrome")
else:
print("The second word is not a palindrome")
main()
| true
|
b22ff6b7640b969d1721193139810d2534d00298
|
banga19/TKinter-Tutorials
|
/mouse_click_events.py
| 443
| 4.1875
| 4
|
from tkinter import *
# when you click the left mouse button it displays the "left" on the console
# the same happens to when you click the right and middle mouse button
root = Tk()
def RightClick(event):
print("Right")
def LeftClick(event):
print("Left")
frame = Frame(root, width=500, height=300)
frame.bind("<button-1>", RightClick)
frame.bind("<button-2>", LeftClick)
frame.pack()
root.mainloop()
| true
|
267f66a3f4e5cbedb9cc20533236f7a730a17a27
|
silverbowen/COSC-1330-Intro-to-Programming-Python
|
/William_Bowen_Lab5b.py
| 843
| 4.375
| 4
|
## I used global constants for ease of modding
## in case we return to this program later
## START, END,and INCREMENT set the
## dimensions of the pyramid
START = 10
END = 1
INCREMENT = -1
## SYMBOL sets what the pyramid is made of
## I added spaces on either side of
## the star, to make it nicer
SYMBOL = ' * '
## main is a nested loop that prints
## a pyramid of SYMBOLS
def main():
## first loop, sets terms for each row
for count in range(START, END - 1, INCREMENT):
## second loop, nested
## sets number of stars in row,
## based on inverse column number
for count in range(count, END - 1, INCREMENT):
## print each individual symbol
print(SYMBOL , end='')
## back to first loop, new line
## to make it prettier
print('\n')
## call main
main()
| true
|
959174c94e9050e2455c72f02567bab5a088a118
|
silverbowen/COSC-1330-Intro-to-Programming-Python
|
/William_Bowen_lab4a.py
| 2,417
| 4.40625
| 4
|
## Define main
def main():
## get measurements to convert, checking for useability
miles = float(input('How many miles would you like to convert? '))
if miles < 0:
print('\nError! You must enter a positive number of miles!\n')
else:
print('')
fahren = float(input('How many fahrenheit degrees would you like to convert? '))
if fahren > 1000:
print('\nError! You must enter fahrenheit degrees equal to or less than 1,000!\n')
else:
print('')
gallon = float(input('How many gallons would you like to convert? '))
if gallon < 0:
print('\nError! You must enter a positive number of gallons!\n')
else:
print('')
lbs = float(input('How many pounds would you like to convert? '))
if lbs < 0:
print('\nError! You must enter a positive number of pounds!\n')
else:
print('')
inch = float(input('How many inches would you like to convert? '))
if inch < 0:
print('\nError! You must enter a positive number of inches!\n')
else:
print('')
## call all the conversion/printing functions
MilesToKm(miles)
FahToCel(fahren)
GalToLit(gallon)
PoundsToKg(lbs)
InchesToCm(inch)
#calculate and print result for miles to km
def MilesToKm(miles):
kilos = miles * 1.6
print('It turns out that', miles, 'miles =', kilos, 'kilometers!\n')
#calculate and print result for fahrenheit to celsius
def FahToCel(fahren):
celsi = (fahren - 32) * 5/9
print('It turns out that', fahren, 'fahrenheit =', celsi, 'celsius!\n')
#calculate and print result for gallons to liters
def GalToLit(gallon):
liters = gallon * 3.9
print('It turns out that', gallon, 'gallons =', liters, 'liters!\n')
#calculate and print result for pounds to kilograms
def PoundsToKg(lbs):
kgrams = lbs * .45
print('It turns out that', lbs, 'pounds =', kgrams, 'kilograms!\n')
#calculate and print result for inches to centimeters
def InchesToCm(inch):
centi = inch * 2.54
print('It turns out that', inch, 'inches =', centi, 'centimeters!\n')
main()
| true
|
9a0cd7c3f79ad55ce32a7f771f4b146e8ef5aa8a
|
paripon123/DSC-430-Python
|
/Hw4/test.py
| 1,281
| 4.125
| 4
|
def random_list(i):
"""Random list of number from 0 - 100"""
import random
num_list = sorted(random.sample(range(0, 100), i))
return num_list
def sum_pair_search(lst,number): # O(log N) Binary Search
"""This is the function that do the binary search and the prove the calculation"""
# The list must be sorted!! Important!!!!
#O(log N)
num_lst = random_list(lst)
low = 0 # index of the lowest number
high = len(num_lst) - 1 # index of the highest number
# Binary search
while low <= high:
mid = (low + high) // 2
if num_lst[low] + num_lst[high] == number: # Check if the pair are added up to the target number.
print('Found It!')
print(num_lst[low],'+',num_lst[high],'=',number)
return True
elif number < num_lst[mid]: # Adjust high : Go search lower half portion
high = mid - 1
else:
low = mid + 1 # Adjust low : Go search upper half portion
print('No Pair Found in this Particular list of number.')
return False
def main():
while True:
num = random_list(20)
if sum_pair_search(num,20):
break
if __name__ == '__main__':
main()
| true
|
323d64b2cd937ab44ba6450a603b8387563e1b55
|
RamiroAlvaro/desafios
|
/maximum_subarray.py
| 1,941
| 4.125
| 4
|
"""
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
For example, given the array [−2, 1, −3, 4, −1, 2, 1, −5, 4],
the contiguous subarray [4, −1, 2, 1] has the largest sum = 6.
"""
def max_subarray_quadratic(list_):
if not list_:
return list_, 0
stop = len(list_)
sum_ = list_[0]
result = [sum_]
start = 1
for index_start, _ in enumerate(list_):
for index_stop in range(start, stop + 1):
if sum_ < sum(list_[index_start:index_stop]):
sum_ = sum(list_[index_start:index_stop])
result = list_[index_start:index_stop]
start += 1
return result, sum_
assert max_subarray_quadratic([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == ([4, -1, 2, 1], 6)
assert max_subarray_quadratic([10, -1, -3, -4, -1, 2, 1, -5, 4]) == ([10], 10)
assert max_subarray_quadratic([1, -1, -3, -4, -1, 2, 1, -5, 9]) == ([9], 9)
assert max_subarray_quadratic([]) == ([], 0)
assert max_subarray_quadratic([11]) == ([11], 11)
assert max_subarray_quadratic([1, 2, 3, 4]) == ([1, 2, 3, 4], 10)
assert max_subarray_quadratic([-1, -2, -3, -4]) == ([-1], -1)
assert max_subarray_quadratic([-1, -2, 3, -3, -4]) == ([3], 3)
def max_subarray_linear(list_):
if not list_:
return 0
result = list_[0]
sum_ = list_[0]
stop = len(list_)
for index in range(1, stop):
sum_ = max(list_[index], sum_ + list_[index])
result = max(result, sum_)
return result
assert max_subarray_linear([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
assert max_subarray_linear([10, -1, -3, -4, -1, 2, 1, -5, 4]) == 10
assert max_subarray_linear([1, -1, -3, -4, -1, 2, 1, -5, 9]) == 9
assert max_subarray_linear([]) == 0
assert max_subarray_linear([11]) == 11
assert max_subarray_linear([1, 2, 3, 4]) == 10
assert max_subarray_linear([-1, -2, -3, -4]) == -1
assert max_subarray_linear([-1, -2, 3, -3, -4]) == 3
| false
|
e1a789720b6d0a025f2244347927cdc65c741658
|
RafaelNGP/Curso-Python
|
/min_max_aula.py
| 976
| 4.28125
| 4
|
"""
Min e Max
max() - Retorna o maior valor em um iteravel ou o maior de dois ou mais elementos.
min() - Retorna o menor item em um iteravel ou o menor de dois ou mais elementos.
"""
# Exemplos
lista = [1, 8, 4, 99, 34, 129]
print(max(lista))
dicionario = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129}
print(max(dicionario))
print(max(dicionario.values()))
print(max(3, 34))
nomes = ['Arya', 'Samson', 'Dora', 'Tim', 'Ollivander']
print(max(nomes))
print(min(nomes))
print(max(nomes, key=lambda nome: len(nome)))
print(min(nomes, key=lambda nome: len(nome)))
# Desafio: Imprimir somente o titulo da musica mais e menos tocada.
musicas = [
{'Titulo': 'Eye of the Storm', 'tocou': 30},
{'Titulo': 'The last Fight', 'tocou': 25},
{'Titulo': 'Alone', 'tocou': 40},
{'Titulo': 'Waking the Demon', 'tocou': 22}
]
print(max(musicas, key=lambda musica: musica["tocou"]).get("Titulo"))
print(min(musicas, key=lambda musica: musica["tocou"]).get("Titulo"))
| false
|
50d722aa3751ae1ef216b25ad73bd2fc69f4d64a
|
RafaelNGP/Curso-Python
|
/tipo_booleano.py
| 690
| 4.21875
| 4
|
"""
Tipo Booleano
2 constantes = Verdadeiro ou falso
True ou False
OBS: Sempre com a inicial maisucula.
# >>> num2 = 2
# >>> num3 = 4
# >>> num2 > num3
# False
# >>> num3 <= num2
# False
# >>> type(True)
# <class 'bool'>
"""
print("Atribuindo valor True para 'ativo'")
ativo = True
logado = False
print(ativo)
"""
Operacoes basicas
"""
# Negacao (not)
print("Printando a negacao do valor de ativo")
print(not ativo)
# Ou (or)
"""
>>> True or True = True
>>> True or False = True
>>> False or True = True
>>> False or False = False
"""
print(ativo or logado)
# E (and)
"""
>>> True and True = True
>>> True and False = False
>>> False and True = False
>>> False and False = False
"""
| false
|
7ca8e7a0cae3175b9ce91c9026d09e37d29f6cda
|
RafaelNGP/Curso-Python
|
/reduce_aula.py
| 1,448
| 4.3125
| 4
|
"""
Reduce
OBS: A partir do Python3+ a funcao reduce() nao eh mais uma funcao integrada (built-in)
Agora precisamos importa-la a partir do modulo 'functools'
Guido van Rossum: utilize a funcao reduce() se voce realmente precisa dela, em 99% das vezes um
loop for eh mais legivel.
Para entender o reduce()
Imagine que voce tem uma colecao de dados
dados = [a1, a2, a3 ... an]
e voce tem uma funcao que recebe dois parametros
def funcao(x, y):
return x * y
Assim como map() e filter(), a funcao reduce() recebe dois parametros:
reduce(funcao, dados)
A funcao reduce() funciona da seguinte forma:
passo 1: res1 = f(a1, a2) - Aplica a funcao nos dois primeiros elementos da colecao e guarda o resultado.
passo 2: res2 = f(res1, a3) - Aplica a funcao passando o resultado do passo1 + o terceiro elemento e quarda o resultado.
passo n: resn = f(resn, an)
Ou seja, em cada passo ela aplica a funcao passando como primeiro argumento o resultado da aplicacao
anterior. No final, reduce() ira retornar o resultado final.
Alternativamente, poderiamos ver a funcao reduce() como:
funcao(funcao(funcao(a1, a2), a3), a4), ... an)
"""
from functools import reduce
# Vamos utilizar a funcao reduce() para multiplicar todos os numeros de uma lista.
dados = [2, 3, 4, 5, 7, 11, 13, 17, 19, 23, 29]
print(reduce(lambda x, y: x * y, dados))
# Utilizando um loop for
res = 1
for numero in dados:
res *= numero
print(res)
| false
|
3dc6b2bebf4a1fcf58586237d14c458075356708
|
RafaelNGP/Curso-Python
|
/modulo_random.py
| 1,653
| 4.28125
| 4
|
"""
Modulo Random e o que sao modulos?
- em Python, nada mais sao que outros arquivos Python.
- Todos os arquivos que foram criados ate agora sao considerados modulos.
- Deixar os programas mais simples e permitir a reutilizacao do codigo.
- Modulo Random -> Possui varias funcoes para geracao de numeros pseudo-aleatorios.
Existem duas formas de se utilizar um modulo ou funcao deste.
Forma 1 - Importando o modulo inteiro. (NAO RECOMENDADO)
import random
Ao realizar o import, todas as funcoes, atributos, classes e propriedades que estiverem
dentro do modulo ficarao disponiveis em memoria.
Testando no console:
import random
numero = random.random()
numero
Forma 2 - Importando uma funcao especifica do modulo
Ao realizar a importacao da funcao especifica (random) do modulo random.
from random import random
for i in range(10):
print(random())
"""
from random import random
for i in range(10):
print(random())
print()
from random import uniform
# Gerar um numero pseudo-aleatorio entre os valores estabelecidos
for i in range(10):
print(uniform(1, 7))
from random import randint
# Gerando um numero pseudo-aleatorio inteiro
for i in range(6):
print(randint(1, 60), end=" ")
print()
from random import choice
# mostra um valor aleatorio entre um iteravel.
jogadas = ["Pedra", "Papel", "Tesoura"]
for i in range(3):
print(choice(jogadas))
from random import shuffle
# Tem a funcao de embaralhar dados.
cartas = ["K", "Q", "J", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
print(cartas)
shuffle(cartas)
print(cartas.pop())
print(cartas)
| false
|
2771c02c3f512cd85dbd8603ecc7b3279d7b02a5
|
RafaelNGP/Curso-Python
|
/list_comprehension_p1.py
| 1,251
| 4.5625
| 5
|
"""
List Comprehension
- Utilizando List Comprehension, nos podemos gerar novas listas com dados processados a partir de
outro iteravel.
# Sintaxe
[ dado for dado in iteravel ]
"""
def quadrado(valor):
return valor ** 2
# Exemplos
numeros = [1, 2, 3, 4, 5]
res = [numero * 10 for numero in numeros]
print(res)
"""
Para entender melhor o que esta acontecendo, devemos dividar a expressao em duas partes:
- A primeira parte: for numero in numeros
- A segunda parte: numero * 10
"""
res = [quadrado(numero) for numero in numeros]
print(res)
print(len(res))
# List Comprehension VS Loop
# Loop
numeros = [1, 2, 3, 4, 5]
numeros_dobrados = []
for numero in numeros:
numeros_dobrados.append(numero * 2)
print(numeros)
print(numeros_dobrados)
# List Comprehension
print([numero * 2 for numero in numeros])
# Outros exemplos
# 1
nome = 'Geek University'
print([letra.upper() for letra in nome])
# 2 - Exemplo proprio
amigos = ['maria', 'julia', 'pedro', 'guilherme', 'vanessa']
print([amigo.title() for amigo in amigos])
# 3 - Ja fiz um teste do Range na aula de For
print([numero * 3 for numero in range(1, 10)])
# 4
print([bool(valor) for valor in [0, [], '', True, 1, 3.14]])
# 5
print([str(numero) for numero in numeros])
| false
|
9ee7d5d8f9ceb691d5a2883cce950a6272c9a2d0
|
RafaelNGP/Curso-Python
|
/dicionarios_aula.py
| 2,387
| 4.28125
| 4
|
"""
Dicionarios
Em algumas linguagens de programacao, os dicionarios sao conhecidos como mapas.
Dicionarios sao:
- colecoes do tipo chave/valor
- representados por chaves {}
- class <dict>
- 'chave': 'valor'
- Pode ser de qualquer tipo de dado.
"""
paises = {'br': 'Brasil', 'us': 'Estados Unidos', 'py': 'Paraguai'}
print(paises)
print(type(paises))
# Acessando elementos
# Forma 1 - Acessando via chave, da mesma forma que lista/tupla
print(paises['br'])
print(paises['py'])
# Forma recomendada (encontrei fucando)
print(paises.get('br'))
print(paises.get('ru'))
print(paises.get('py'))
russia = paises.get('ru', 'Nao encontrado')
# primeiro valor para verdadeiro, segundo para caso falso
if russia:
print("Encontrei o Pais!")
else:
print("Ainda n foi adicionado")
#
print()
# Verificando se as chaves sao encontradas no dicionario
print('br' in paises)
print('ru' in paises)
print('Estados Unidos' in paises)
print()
# Podemos utilizar qualquer tipo de dado (int, float, str, boolean), inclusive listas, tuplas, dicionarios etc...
localidades = {
(35.6895, 39.6917): "Escritorio em Tokyo",
(40.7128, 74.0060): "Escritorio em Nova York",
(35.7749, 122.4194): "Escritorio em Sao Paulo"
}
print(localidades)
print(type(localidades))
print()
# Adicionar elementos em um dicionario
receita = {'jan': 100, 'fev': 120, 'mar': 300}
print(receita)
print(type(receita))
# forma 1
receita['abr'] = 350
print(receita)
#
print()
# Forma 2
novo_dado = {'mai': 500}
receita.update(novo_dado)
print(receita)
# Atualizando dados em um dicionario
# Forma 1
receita['mai'] = 550
print(receita)
# Forma 2
receita.update({'mai': 600})
print(receita)
# A forma de adicionar novos elementos ou atualizar dados em um dicionario eh a mesma.
# Em dicionarios, nao podemos ter chaves repetidas.
# Remover dados de um dicionario
# Forma 1
print(f'Elemento removido: {receita.pop("mar")}')
print(receita)
# Forma 2
del receita['fev']
print(receita)
print()
#
# carrinho = []
# produto1 = ['Playstation 4', 1, 230.00]
# produto2 = ['God of War 4', 1, 150.00]
# carrinho.append(produto1)
# carrinho.append(produto2)
# print(carrinho)
#
carrinho = []
produto1 = {"nome": "Playstation 4", "quantidade": 1, "preco": 2300.00}
produto2 = {"nome": "God of War 4", "quantidade": 1, "preco": 150.00}
carrinho.append(produto1)
carrinho.append(produto2)
print(carrinho)
| false
|
5170b1ccf7a5e61e25cb0211d1f3c52a08f67472
|
altareen/csp
|
/05Strings/asciicode.py
| 2,511
| 4.3125
| 4
|
# convert from a symbol to an ASCII number
numcode = ord("P")
print(numcode)
# convert from ASCII to a symbol
letter = chr(105)
print(letter)
# using the equality operator with strings
password = "basketball"
if password == "basketball":
print("login successful")
# digits come before lowercase letters
if "999" < "thousand":
print("access granted")
# uppercase letters come before lowercase
if "PIZZA" < "burger":
print("dinner time")
num = len("pizza")
print(num)
# using the capitalize method
dinner = "pizza"
result = dinner.capitalize()
print(result)
# applying the lower() method
lunch = "CHEESEburger"
result = lunch.lower()
print(result)
# puts all the letters into uppercase
fruit = "strawberry"
result = fruit.upper()
print(result)
# check that all characters are letters
vegetable = "cauliflower"
result = vegetable.isalpha()
print(result)
dessert = "423chocolates"
result = dessert.isalpha()
print(result)
# check that all characters are numbers
meter = "29387392"
result = meter.isdigit()
print(result)
drink = "58waters"
result = drink.isdigit()
print(result)
# remove whitespace from a string
beverage = " coffee\n\n\n\n"
result = beverage.strip()
print(result)
# remove whitespace from the right hand side
soda = "sprite\n\n\n\n\n\n\n\n\n\n\n"
result = soda.rstrip()
print(result)
# find a substring within another string
candy = "chocolate"
location = candy.find("cola")
print(location)
location = candy.find("pizza")
print(location)
pastry = "jampieapplepiekiwipieraspberrypie"
location = pastry.find("pie", 13)
print(location)
dinner = "beefstewandburgerswithsalad"
result = dinner.replace("burgers", "pizza")
print(result)
bakery = "strawberryjamorangejamkiwijam"
result = bakery.count("jam")
print(result)
menu = "pizzaburgersfriessoda"
result = menu.startswith("pizza")
print(result)
greetings = "hello\n\n\n\n\nworld\n\n\n"
print(greetings)
# inserting the double quotation mark
prose = "She said, \"Hello\" to everyone."
print(prose)
# using the backslash character
path = "C:\\Documents\\homework\\notes.py"
print(path)
# creating tables with the tab character
print("Product\tWeight\tPrice")
print("kiwi\t0.15kg\t2.95")
# f-strings only work with Python 3.7 or greater
#amount = 5
#food = "pizza"
#result = f"I had {amount} servings of {food}."
#print(result)
# Exercise 6.14
score = "X-DSPAM-Confidence:0.8475"
location = score.find(":")
num = score[location+1:]
num = float(num)
print(location)
print(num)
print(type(num))
"hi".
| true
|
dbf4427d8e35dfb7930df9a865c93603e2106255
|
altareen/csp
|
/05Strings/stringindexes.py
| 659
| 4.1875
| 4
|
# extracting a single letter from a string
fruit = "watermelon"
first = fruit[0]
print(first)
letter = fruit[5]
print(letter)
letter = "pizza"[1]
print(letter)
last = fruit[9]
print(last)
last = fruit[-1]
print(last)
letter = fruit[-10]
print(letter)
vegetable = "cauliflower"
quantity = len(vegetable)
print(quantity)
last = vegetable[quantity-1]
print(last)
# string slicing
dessert = "chocolate"
drink = dessert[3:7]
print(drink)
breakfast = "pineapple"
tree = breakfast[0:4]
cone = breakfast[:4]
print(tree)
print(cone)
flavor = "strawberry"
snack = flavor[5:10]
food = flavor[5:]
print(snack)
print(food)
icecream = flavor[:]
print(icecream)
| true
|
a24a893b62dcf1015c15aaa3d18f92d1cdea35b6
|
silviu20/fzwork
|
/PythonWork/codeexer/reverse_integer.py
| 481
| 4.25
| 4
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
"""
class Solution:
# @return an integer
def reverse(self, x):
if x>0:
y_str = str(x)
y_str = y_str[::-1]
return int(y_str)
elif x<0:
x = -x
y_str = str(x)
y_str = y_str[::-1]
return -int(y_str)
else:
return 0
| true
|
c263dcbc053d4e0ad67b8e898c559501723b964f
|
ChocolatePadmanaban/AlgosAndDs
|
/mit_6.0001/ps1/ps1c.py
| 1,415
| 4.15625
| 4
|
import random
# Get the input
annual_salary= float(input("Enter the starting annual salary: "))
monthly_salary= annual_salary/12
# Fixed Parameters
semi_annual_raise=.07
r=0.04
portion_down_payment = .25
total_cost=1000000
down_payment = total_cost*portion_down_payment
#set problem parameters
epsilon = 100
bisection_search_steps = 0
max_portion = 10000
min_portion = 1
# Check if payment is possible
if monthly_salary < down_payment/36:
print("It is not possible to pay the down payment in three years.")
else:
while True:
portion_saved = random.randint(min_portion,max_portion)
monthly_salary= annual_salary/12
bisection_search_steps+=1
month_count=0
current_savings=0
while current_savings < down_payment:
current_savings += current_savings*r/12
current_savings += monthly_salary*portion_saved/10000
month_count += 1
if month_count % 6 == 0:
monthly_salary += monthly_salary*semi_annual_raise
present_epsilon= current_savings - down_payment
if month_count == 36 and abs(present_epsilon) < epsilon:
break
elif month_count > 36 :
min_portion = portion_saved + 1
else :
max_portion = portion_saved - 1
print("Best savings rate:", portion_saved/10000)
print("Steps in bisection search:", bisection_search_steps)
| true
|
425329f129d00e0607da7c566853e4876df5d628
|
Feolips/ADS18A.10-Paradigma-Orientado-a-Objetos
|
/Listas de Exercício/POO Atividade 02 - Questões 07 e 08.py
| 2,901
| 4.25
| 4
|
# Aluno: Felipe Souza Vieira
# Atividade 02 para 12/02/2021
# Questões 07 e 08
'''
1. Crie uma classe com três variáveis: nome, sobrenome e salário mensal.
Defina um construtor para iniciar essas variáveis. Então, demonstre o
salário anual de três objetos da sua classe. OBS: inserir comentários
nos trechos de código informando que tipo de conceito está sendo usado,
por exemplo: na linha de código que um objeto está sendo instanciado
coloque um comentário identificando essa ação.
'''
# Classe contendo todas as funções (init, def_set e def_get):
class salario:
# Construtor - função init
def __init__(self,nome=None,sobrenome=None,sMensal=0.0):
self.setNome(nome)
self.setSobrenome(sobrenome)
self.setsMensal(sMensal)
# Função set para atribuir valor à variável 'nome':
def setNome(self, nome):
self.nome = nome
return
# Função get para recuperar o valor contido em 'nome':
def getNome(self):
return self.nome()
# Função set para atribuir valor à variável 'sobrenome':
def setSobrenome(self, sobrenome):
self.sobrenome = sobrenome
return
# Função get para recuperar o valor contido em 'sobrenome':
def getNome(self):
return self.sobrenome()
# Função set para atribuir valor à variável 'sMensal':
def setsMensal(self,sMensal):
self.sMensal = sMensal
return
# Função get para recuperar o valor contido em 'sMensal':
def getsMensal(self):
return self.sMensal()
# Função get para recuperar o salário anual:
def getsAnual(self):
return (self.getsMensal() * 12.0)
# Função get para recuperar o aumento de 45% sobre o anual:
def getsAnualAumento(self):
return(self.getsAnual() * 1.45)
# Fim da Classe.
# ============Início do programa principal (main)============
# Laço para a criação de 3 objetos:
for i in range(1,4,1):
# Instanciamento da classe:
novoEmpregado = salario()
# Entrada dos dados nome, sobrenome e salário mensal:
novoEmpregado.setNome(str(input('Informe o primeiro nome do {}º funcionário: '.format(i))))
novoEmpregado.setSobrenome(str(input('Informe o sobrenome de {}: '.format(novoEmpregado.getNome()))))
novoEmpregado.setsMensal(float(input('Informe o salário mensal de {}: R$'.format(novoEmpregado.getNome))))
# Retorno do salário anual, aumento e fim do laço:
print('O salário anual de {} (fora 13º e outros benefícios) é de R${:.2f}.'.format(novoEmpregado.getNome(), novoEmpregado.getsAnual()))
print('Com um aumento de 45%% o salário anual de {} passará a R${:.2f}.'.format(novoEmpregado.getNome(),novoEmpregado.getsAnualAumento()))
print('=' * 40)
print('Fim do programa')
# ============Fim do programa principal (main)============
| false
|
94b55dc0a52f6788bf1649786a0f8a776c5697f3
|
mariocpinto/0008_MOOC_Getting_Started_with_Python
|
/Exercises/Week_07/assignment_5.1.py
| 702
| 4.21875
| 4
|
# Write a program that reads a list of numbers until "done" is entered.
# Once done is entered, print count, total and avergae of numbers.
# If the user enters anything other than a number,
# print an error message and skip to the next number.
# Initialize count & sum
count = 0
sum = 0
while True :
input_num = input('Enter a number: ')
if input_num == 'done' :
break
try:
num = float(input_num)
except:
print('Invalid Input')
continue
count = count + 1
sum = sum + num
print('Count = ',count)
print('Total = ',sum)
if count != 0 :
print('Average = ',sum/count)
else:
print('Average = 0')
| true
|
37ecbf35cc9dabbaf94e13628ced1e53501a63cc
|
VladimirBa/python_starter_homework
|
/003_Conditional Statements/003_practical_2.py
| 775
| 4.15625
| 4
|
X_ODD_MESSAGE = "нечётное"
X_EVEN_MESSAGE = "чётное"
X_NEGATIVE_MESSAGE = "отрицательное"
X_POSITIVE_MESSAGE = "положительное"
x = float(input("Введите число: "))
x_length = len(str(abs(int(x))))
if x == 0:
print('Число: ', x)
elif x % 2 == 0 and x < 0:
print(x, f"{X_EVEN_MESSAGE} {X_NEGATIVE_MESSAGE} число.", end=" ")
elif x % 2 != 0 and x < 0:
print(x, f"{X_ODD_MESSAGE} {X_NEGATIVE_MESSAGE} число.", end=" ")
elif x % 2 == 0 and x > 0:
print(x, f"{X_EVEN_MESSAGE} {X_POSITIVE_MESSAGE} число.", end=" ")
elif x % 2 != 0 and x > 0:
print(x, f"{X_ODD_MESSAGE} {X_POSITIVE_MESSAGE} число.", end=" ")
print(f"Знаков перед запятой: {x_length}" if x else "")
| false
|
7ef3e6b2bf9ed19c2853b541b16abadf1cc8b971
|
DynamicManish/Guessing_game
|
/guessing_game.py
| 1,448
| 4.15625
| 4
|
import random as r
import time as t
random_value = r.randint(2,9)
guesses = 0 #user haven't made any guess yet!
value = 0
user_name = input('Howdy?May I know your name? ').strip().capitalize()
t.sleep(1)
print("Hello,"+"{}!".format(user_name))
t.sleep(1)
ques_choice = input('Are you ready to guess?[Y/N]:').strip()
if ques_choice == 'y':
print('Hello,'+"{}".format(user_name))
t.sleep(1)
print("I am thinking of a number between 1 to 10!")
t.sleep(1)
elif ques_choice == 'n':
print("We're sorry, Will meet you later!")
t.sleep(1)
exit()
else:
print("Wrong input!")
t.sleep(1)
exit()
while not (random_value == value):
number = int(input('Enter your guess here: '))
guesses = guesses+1
if number == random_value:
t.sleep(0.75)
print("Brilliant!")
print("You guessed it correctly,the correct number is {}".format(random_value))
if guesses == 1:
print("It took you {}".format(guesses)+" try in total!")
t.sleep(1)
else:
print("It took you {}".format(guesses)+" tries in total!")
t.sleep(1)
exit()
elif number < random_value:
t.sleep(1)
print("Guess higher")
elif number > random_value:
t.sleep(1)
print("Guess lower")
else:
t.sleep(1)
print("Wrong inputs!")
exit()
| true
|
a99e65bc94d699eedf234968d4d1d4b6fd70f2ad
|
Fractured2K/Python-Sandbox
|
/tuples_sets.py
| 1,029
| 4.34375
| 4
|
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
# Simple tuple
fruit_tuple = ('Apple', 'Orange', 'Mango')
print(fruit_tuple)
# Using constructor
fruit_tuple_constructor = tuple(('Apple', 'Orange', 'Mango'))
print(fruit_tuple_constructor)
# Get value by index
print(fruit_tuple[1])
# Can not change values in tuple
# fruit_tuple[1] = 'Grape'
# Tuples with one value should have a trailing comma
fruit_tuple_trailing = ('Apple',)
print(fruit_tuple_trailing)
# Delete tuple
del fruit_tuple_trailing
# length
print(len(fruit_tuple))
# A Set is a collection which is unordered and unindexed. No duplicate members.
fruit_set = {'Apple', "Orange", 'Mango', 'Apple'}
print(fruit_set)
# Check if in set
print('Apple' in fruit_set) # True
print('Apples' in fruit_set) # False
# Add to set
fruit_set.add('Grape')
print(fruit_set)
# Remove from set
fruit_set.remove('Grape')
print(fruit_set)
# Clear set
fruit_set.clear()
print(fruit_set)
# Delete set
# del fruit_set
# print(fruit_set)
| true
|
dc1b1e6fd9a2a88bdb48ab9ac21d806939640ed7
|
HyperPalBuddy/Rando-Python-Codes
|
/Python_stacks.py
| 1,090
| 4.21875
| 4
|
def createStack():
stack = []
return stack
def isEmpty(stack):
return len(stack) == 0
def push(stack, number):
if len(stack) == size:
print("Stack Overflow")
return
stack.append(number)
def pop(stack):
if isEmpty(stack):
print("Stack Underflow")
return
return stack.pop()
def peek(stack):
if isEmpty(stack):
print("Stack Is Empty")
return
else:
n = len(stack)
print("Peek Element is:", stack[n - 1])
def display(stack):
print(stack)
stack = createStack()
size = int(input("Enter The Size Of Stack"))
print("Menu\n1.push(p)\n2.pop(o)\n3.peek(e)")
choice = 1
while choice != 'q':
print("Enter Your Choice")
ch = input()
choice = ch.lower()
if choice == 'p':
push(stack, int(input("Enter Input Value")))
display(stack)
elif choice == 'o':
pop(stack)
display(stack)
elif choice == 'e':
peek(stack)
else:
print("Enter Proper Choice Or q to Quit")
| true
|
3a864c7b963ab09cc0cce9f326c1fa6ca80f1a7a
|
lucianoww/Python
|
/pybrexer0005.py
| 304
| 4.4375
| 4
|
'''
Solução para exercicios https://wiki.python.org.br/EstruturaSequencial
#05)Faça um Programa que converta metros para centímetros.
'''
metro = 100
valorcm = float(input('Digite valor em centimetros:'))
print('{} centimetros equivale a {} metros'.format(valorcm, valorcm/metro))
| false
|
af3df83e40ec18a4433cbe8b3d35f86bf9d67655
|
PHOENIXTechVault/Beginner-Python-Codes
|
/functions.py
| 1,855
| 4.375
| 4
|
# Manually printig out hello welcome without the use of a function
print("hello welcome")
print("hello welcome")
print("hello welcome")
print("hello welcome")
print("hello welcome")
def print_welcome_messsage(): #definig a function to print out the welcome message 5 times
print("Hello welcome\n"*5)
def ask_name():
print("whats your name?")
print_welcome_messsage() #calling the function
ask_name() #calling the function
# Built-in functions
print(), str(), abs()
# lambda functions
out = lambda message : message*5 #writting the lambda function form of our previouse written function
print(out("hello welcome\n"))
# User defined functions
def ask_name(person): #creating your own function thus user defined functions
print("Welcome " + person)
print("whats your name?" + person)
# Arguments & Parameters
ask_name("Janet")
ask_name("Joe")
ask_name("Kevin")
ask_name("Josh") #calling each function and passing in an argument
# return values and return statement
def ask_name(age):
new_age = age * 10
age2 = new_age + 100
if new_age > 50:
return "Welcome Granny"
elif new_age <= 40:
return "hi you are welcomed"
else:
return "You are a youth"
print(ask_name(80))
print(ask_name(10))
print(ask_name(8))
print(ask_name(4))
# local scopes and Global scopes
a = 45
def ask_age(age):
# Global statement. This helps declare a local variable as a global variable which then can be used outside of functions and in other functions
global new_age
global age2
new_age = age * a
age2 = new_age + a
print(new_age)
print(age2)
def greet(name):
print("Hello " + name)
print(new_age)
print(age2)
ask_age(5)
greet("Sam")
print(new_age)
print(age2)
| true
|
ee1b6cde06a6d04938042060fe2dade87224e5df
|
PHOENIXTechVault/Beginner-Python-Codes
|
/logical-operators.py
| 920
| 4.15625
| 4
|
# AND
a = 5
b = 5
c = 7
print(a == b and c > b) #return True since both conditions are True
print((a != b and c > b) and c > a) #return False since one of the conditions is False
# OR
print(a == b or c > a) #return True since both conditions are True
print(a != b or c > b) #return True since one of the conditions is True
print(a == c or c < b) #return False since both conditions are False
# NOT
a = False
b = not a #will return the opposite value of False which is True
print(b)
c = True
d = not c #will return the opposite value of True which is False
print(d)
sex = "male"
age = 18
if sex == "male" and age >= 18:
print("You are allowed to come to the party")
else:
print("You not allowed")
if sex == "male" or age >= 18:
print("You are allowed to come to the party")
else:
print("You not allowed")
| true
|
f25e37f28903a6986791b7162058af0ed17dffe8
|
fredyulie123/Python-Programming
|
/Yifeng HE Exam2.py
| 2,532
| 4.125
| 4
|
# Exam 2 Yifeng He
# Trip Planner
planner_name = 'C:/Users/Yifeng He/Desktop/graduated/2nd graduate semester/Python/Trip Planner.txt' # create file path
print('Welcome to the road trip planner!')
## recording trip details
allstation = [] # prepare for append trip details
gasprice = 3 # gas per gallon price
mpg = 35 # mile per gallon
total_cost = 0
ready = input('Are you ready for make a trip plan (Enter \'n\' for no)?\n>>')
affirmative = ['Yes', 'Y', 'yes', 'y', 'yup', 'Yup', 'Sure', 'sure']
if ready in affirmative:
# ask for starting location
start_loc = str(input('Please enter your starting location:\n>>'))
origin_loc = start_loc # departure place
# ask for destination location
desti_loc = str(input('From '+ start_loc + ', where will you travel?\n>>'))
# ask for distance
distance = float(input('How far away is ' + desti_loc + ' from ' + start_loc +'?\n>>'))
# calculate the cost
cost = (distance/mpg)*gasprice
total_cost = total_cost + cost
# append trip detail
allstation.append([start_loc, desti_loc, round(distance,2), round(cost,2)])
# ask if have another plan
ready = input('Will you be travelling beyond ' + desti_loc + ' (Enter \'n\' for no)?\n>>')
# ask for another plan
while ready in affirmative:
start_loc = desti_loc
desti_loc = str(input('From '+ start_loc + ', where will you travel?\n>>'))
distance = float(input('How far away is ' + desti_loc + ' from ' + start_loc +'?\n>>'))
cost = (distance/mpg)*gasprice
total_cost = total_cost + cost
# append trip detail
allstation.append([start_loc, desti_loc, round(distance,2), round(cost,2)])
ready = input('Will you be travelling beyond ' + desti_loc + ' (Enter \'n\' for no)?\n>>')
final_loc = desti_loc # destination place
#write down overview
overview = 'Your entire trip from ' + origin_loc + ' to ' + final_loc + ' will cost $' + str(round(total_cost,2)) + '\n'
with open (planner_name,'w', encoding='utf-8') as pn:
pn.write(overview)
else:
print('Please restart the trip planner when you\'re ready. ')
# write down details
for p in range(0,len(allstation)):
start_station = allstation[p][0]
desti_station = allstation[p][1]
per_cost = allstation[p][3]
detail = start_station + ' to ' + desti_station + ' will cost $' + str(round(per_cost,2)) + '\n'
with open (planner_name,'a', encoding='utf-8') as pn:
pn.write(detail)
| true
|
696432da440dea2a60515d028a5e75fa1dc66528
|
kamit17/Python
|
/W3Resource_Exercises/Strings/6.py
| 733
| 4.625
| 5
|
#6. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Go to the editor
#Sample String : 'abc'
#Expected Result : 'abcing'
#Sample String : 'string'
#Expected Result : 'stringly'
def string_end(given_string):
length_given_string = len(given_string)
if length_given_string > 2:
if given_string[-3:] == 'ing': #if last 3 chars are ing
given_string += 'ly'
else:
given_string += 'ing'
return given_string
print(string_end('ab'))
print(string_end('string'))
print(string_end('happily'))
| true
|
25ee3fc42087fd87633e5b9bd84834716f7e4e0d
|
kamit17/Python
|
/AutomateTheBoringStuff/Chapter7/password_checker.py
| 764
| 4.125
| 4
|
'''
A strong password is defined as one
that is at least eight characters long,
contains both uppercase and lowercase characters,
and has at least one digit.
You may need to test the string against multiple regex patterns to validate its strength.
'''
#Program to detect if password is strong or not
import re
#TODO: create Regex for password which mathes all the criteria above
pass_regex= re.compile(r'''
[a-zA-Z0-9@]{8,}
''',re.VERBOSE)
#TODO: Function to test above password regex
def pass_strength(pw):
if re.match(pass_regex,pw):
return True
else:
return False
#check if password is strong or not
if __name__ == '__main__':
pw = input('Enter your password: ')
if pass_strength(pw):
print('Strong password!')
else:
print('Weak Password')
| true
|
1d0d569f1d6d2693964cb452ebc2ef9b5628f1e7
|
kamit17/Python
|
/Think_Python/Chp7/Exercise/ex6.py
| 407
| 4.34375
| 4
|
#Count how many words occur in a list up to and including the first occurrence of the word “sam”. (Write your unit tests for this case too. What if “sam” does not occur?)
def sam_count(names):
counter = 0
for name in names:
if name != 'sam':
counter += 1
else:
break
return counter
print(sam_count(['Harry','Bob','Dylan','Chris','sam','bill']))
| true
|
45c70edbcf891323fca8d4fe90816adca83b4b1e
|
kamit17/Python
|
/Think_Python/Chp7/Examples/collatz_sequence_1.py
| 1,072
| 4.28125
| 4
|
def next_collatz(n):
if n % 2 == 0:
return n // 2
else:
return 3 * n + 1
def collatz_sequence(n):
""" assembles a list based on next collatz function and then prints that list. """
assert type(n) == int
assert n > 0
sequence = [n]
while n != 1:
n = next_collatz(n)
sequence.append(n)
return sequence
def collatz_steps(n):
"""For an integer n returns the number of steps before the Collatz function terminates at 1."""
steps = 0
while n !=1:
n = next_collatz(n)
steps +=1
return steps
#for i in range(1,10):
# print(collatz_sequence(i))
#for x in range (1,10):
# print("{} takes {} steps to resolve.".format(x,collatz_steps(x)))
for x in range(1,100):
if collatz_steps(x) > 100:
print("{} takes {} steps to resolve.".format(x,collatz_steps(x)))
# print(collatz_steps(x))
break
high = 0
for x in range(1,10**6):
this_result = collatz_steps(x)
if this_result > high:
high = this_result
print(x,"takes",high,"steps")
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.