text stringlengths 37 1.41M |
|---|
while True:
player_name = input("""
What is your name? > """)
if len(player_name) > 15 or len(player_name) < 3:
print("ass name")
elif input(f"Are you sure {player_name} is your name? > ").lower() == "yes":
break
else:
pass
print(f"Welcome {player_name}")
print("""
You wake up... |
m=int(input("enter no of rows"))
n=int(input("enter no of columns"))
a = []
print("enter elemnts")
for i in range(m):
l1=[]
for j in range(n):
b=int(input())
l1.append(b)
a.append(l1)
print(a)
|
class Temp:
''' Celsius to Fahrenheit: (°C × 9/5) + 32 = °F
Fahrenheit to Celsius: (°F − 32) x 5/9 = °C'''
@staticmethod
def temp_CtoF(c):
f=(c*9/5)+32
print(f)
@staticmethod
def temp_FtoC(fr):
c=(fr-32)*5/9
print(c)
|
import numpy as np
def func(x):
f = 0.2+25*x-200*np.power(x, 2)+675*np.power(x, 3)-900*np.power(x, 4)+400*np.power(x, 5)
return (f)
# a & b = limits of integration
# n = number of segments
def simpson(a, b, n):
h = (b - a) / n
x = []
y = []
for i in range(0, n+1):
x.ap... |
import numpy as np
from math import *
# np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
def quadFunc(x):
result = v2[0] + v2[1] * x + (v2[2] * np.power(x, 2))
return result
def cubFunc(x):
result = v2[0] + v2[1] * x + (v2[2] * np.power(x, 2)) + (v2[3] * np.power(x, 3))
... |
# Exercise 5.1
student_heights = input("Enter the list of Students height: ").split()
for x in range(0, len(student_heights)):
student_heights[x] = int(student_heights[x])
height = 0
for height1 in student_heights:
height += height1
#print(height)
total = 0
for total1 in student_heights:
t... |
n = int(input())
rballs = []
bballs = []
for _ in range(n):
number, color = map(str, input().split())
number = int(number)
if color == "R":
rballs.append(number)
else:
bballs.append(number)
# print(rballs, bballs)
rballs = sorted(rballs)
bballs = sorted(bballs)
for r in rballs:
print(r)
for b in ... |
ns = list(input())
for n in ns:
if n == "7":
print("Yes")
break
else:
print("No")
|
class FixLenIter(object):
def __init__(self, iterator, length):
self.iter = iterator
self.length = length
self.count = 0
def __next__(self):
if self.count < self.length:
self.count += 1
return next(self.iter)
else:
self.count = 0
raise StopIteration()
def __iter__(self... |
run_player1 =int(input("ENTER RUN SCORE BY PLAYER1 IN 60 BALLS :"))
run_player2 =int(input("ENTER RUN SCORE BY PLAYER2 IN 60 BALLS :"))
run_player3 =int(input("ENTER RUN SCORE BY PLAYER3 IN 60 BALLS :"))
STRIKE_RATE1 =run_player1 * 100 /60
STRIKE_RATE2 =run_player1 * 100 /60
STRIKE_RATE3 =run_player1 * 10... |
import sqlite3 as sql
import add
import display
import printTopdf
user_name=None
password=None
cur=None
flag=None
def sql_conn():
try:
conn=sql.connect("course_db.db")
cur=conn.cursor()
except Exception as e:
print(e)
print("Error")
query="create table if not e... |
import turtle
def make_paddle(coords):
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape("square")
paddle.color("white")
paddle.shapesize(stretch_wid=5, stretch_len=1)
paddle.penup()
paddle.goto(coords[0], coords[1])
return paddle
def make_ball():
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square... |
def add(a,b):
c = a + b
return c
def sub(a,b):
c = a - b
return c
def mult(a,b):
c = a * b
return c
def div(a,b):
c = a / b
return c
menu = '''
Simple calc made by Dave
01. Add \n
02. Subtract \n
03. Multiply \n
04. Divide
'''
print(menu)
# inputs
num1 = int(input('Enter a number:'))
num2 = i... |
from collections import Counter
n = int(input())
word = []
for o in range(n):
word.append(input())
counts = []
print(len(set(word)))
print(*Counter(word).values()) |
s = raw_input("enter a string")
lwr = ''
upp = ''
evn = ''
odd = ''
sorted_lower = ''
sorted_upper = ''
sorted_even = ''
sorted_odd = ''
new_s_sorted = ''
for t in s:
if t.islower() == True:
lwr += t
sorted_lower = sorted(lwr)
sorted_lower_string = ''.join(sorted_lower)
new_s_sorted += sorted_lower_string... |
# 4.23 friday
all_words = input("Type in: ")
all_words_split = all_words.split(' ')
single_words = []
for i in all_words_split:
if i not in single_words:
single_words.append(i)
else:
continue
single_words.sort()
print((' ').join(single_words)) |
def fab3(max):
n, a, b = 0, 0, 1
while n < max:
print('begin')
yield b
# print b
# yield from range(10)
# yield 'third'
print('+++')
a, b = b, a + b
n = n + 1
f=fab3(5)
print("f是一个可迭代对象,并没有执行函数")
print(f)
print('fab3返回的是一个iterable 对象,可以用for循环获取值')
... |
exp = input()
stack = []
for x in exp:
if x.isdecimal():
stack.append(int(x))
else:
num2 = stack.pop()
num1 = stack.pop()
if x == '+':
res = num1 + num2
elif x == '*':
res = num1 * num2
elif x == '/':
res = num1 / num2
... |
import abc
class Formatter(abc.ABC):
""" Base abstract class for formatters.
"""
@abc.abstractmethod
def emit(self, column_names, data):
""" Format and print data from the iterable source.
:param column_names: names of the columns
:type column_names: list
:param data: iterable data source, one tuple p... |
def multyply(A, B):
res = [[0 for i in range(len(A))] for j in range(len(B))]
for i in range(len(A)):
for j in range(len(B[0])):
res[i][j] = sum([A[i][k] * B[k][j] for k in range(len(B))])
return res
def fast_pow(a, m):
c = 1
while m > 0:
if m & 1:
c *= a
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os
import getpass
#作业要求编写登陆窗口
#输入用户名密码
#认证成功显示欢迎信息
#输错三次锁定
#登陆 注册
#user_name = open("User_Name.log","w") #创建一个用户名文件 只能用一种模式打开
#user_name.close()
#user_password = open("User_Password.log","w") #创建一个用户密码文件
#user_password.close()
#lock_user = open("Lock_... |
import random
#랜덤 숫자를 생성하거나 다양한 랜덤 관련 함수를 제공하는 모듈
min = 0
max = 99
flag = 0
answer = random.randrange(0,100) # 0부터 99까지의 난수를 발생시킨 뒤, answer에 저장한다
for i in range(1,11): # 기회를 10번 부여하기 때문에 구간을 range(1,11)로 설정
print("숫자 입력(범위: %d~%d): "%(min,max),end = '')
guess = int(input())
if(answer > gue... |
def sum(n): # 1부터 n까지의 합을 구하는 순환 알고리즘
print(n)
if n < 1:
return 0;
else:
return n + sum(n-1) # 재귀 호출
def asterisk(i): # 별을 출력하는 순환 알고리즘
if i > 1:
asterisk(i/2)
asterisk(i/2)
print("*",end='')
# asterisk(i)가 호출 될 때, i가 1보다 클 시 asterisk(i/2)를 두번 호출한다... |
#Read file and print in uppercase
fname = raw_input("Enter file name: ")
fh = open(fname)
fh = fh.read()
fupper = fh.upper()
fupper = fupper.rstrip()
print fupper |
def rev_of_str(string):
S = len(string)
arr = [None]*S
# print len(arr)
for i in string:
S = S - 1
arr[S] = i
print ''.join(arr)
T = int(raw_input())
for i in range(T):
rev_of_str(raw_input()) |
"""
Notes of interaction with contact
"""
class Note():
def __init__(self, note, datetime=None):
self.datetime = datetime
self.note = note
def __str__(self):
# dont assume note is str, cast; just first 7 chars
return str(self.note)[:7] + (
"..." if len(str(self.no... |
import unittest
import blackjack_class
class TestDeck(unittest.TestCase):
def test_deckcards(self):
"""
This test case tests function deck_cards of class Deck.
It returns the list of 52 shuffled deck of cards..
:return: None
"""
expected_list = [
'HA',... |
''' print out binary place value patterns '''
import argparse
def placevalue_patterner(function, height, width, placevalue, offset_y=0):
''' create a visualization of a place value pattern '''
visual = []
for i in range(offset_y, offset_y + height):
row = ''
for j in range(width):
... |
names = ['John', 'Kenny', 'Tom', 'Bob', 'Dilan']
## CREATE YOUR FUNCTION HERE
def sort_names(nombres):
nombres.sort()
return nombres
print(sort_names(names))
|
"""
https://onlinejudge.u-aizu.ac.jp/#/courses/lesson/1/ALDS1/11/ALDS1_11_C
"""
class Node():
def __init__(self, adjs=[], v=None):
self.adjacents = adjs
self.value = v
self.visited = False
self.distance = -1
class Graph():
def __init__(self, nodes=[]): #, head=None):
... |
cadena = input("Introduce una cadena a comparar: ")
cadena = cadena.lower()
if cadena[0] == cadena[-1]:
caracter_distintos = len(cadena) - cadena.count(cadena[0])
mensaje = f"La cadena introducida tiene {caracter_distintos} caracteres distintos a los de inicio y fin"
else:
caracteres_iguales_inicio = cade... |
inicio = 1
final =1000
def isPrime(num):
if (num < 1):
return False
elif (num == 2):
return True
else:
for i in range(2,num):
if (num%i == 0):
return False
return True
for numero in range(inicio, final):
if(isPrime(numero)):
print(num... |
class Vehiculo:
def __init__(self, CAR):
print("Objeto vehiculo creado")
self.__CAR = CAR
self.__encendido = False # __ pone los atributos en privado e igual con las funciones.
def __del__(self):
print("Destruye el objeto", self.__CAR)
def encender(self):
self.__e... |
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def names(arr):
for elem in range(len(arr)):
print arr[elem]["first_name"] + " " + a... |
import random
def coinToss(num):
recordList = []
heads = 0
tails = 0
count = 0
head_count = 0
tail_count = 0
for amount in range(num):
flip = random.randint(0, 1)
head_tail_str = "It's a head!" if flip == 0 else "It's a tail!"
if (flip == 0):
head... |
"""
This script is a basic look at the lifecycle of a Python class. A python class
has 4 main stages:
1. Definition
2. Initialization
3. Access and Manipulation
4. Destruction
"""
print('script start')
class basic():
print('Stage 1: class definition start')
prop1 = 1
def __init__(self):
print('... |
"""Build a sentiment analysis / polarity model
Sentiment analysis can be casted as a binary text classification problem,
that is fitting a linear classifier on features extracted from the text
of the user messages so as to guess wether the opinion of the author is
positive or negative.
In this examples we will use a mo... |
#! /usr/bin/python
import random
my_list = list(range(26))
print my_list
print random.choice(my_list)
print random.choice([(0,1), (2,3), (4,5), (6,7),(8,9)])
my_int = 4
my_iter = list(range(10))
def nchoices(my_iter, my_int):
ran_list = []
i = 0
while i < my_int:
ran_list.append(random.choice... |
#!/usr/bin/env python
my_string = "Hello there"
print my_string[1:5] #returns ello
print my_string[2]
my_list = list(range(1,6))
print my_list
print my_list[1:3]
print my_list[1:len(my_list)]
# the list has 5 items we need to use 4
# leave off the first number, we start at 0
# leave off the last number, we go... |
#!/usr/bin/env python
#Collections are variable types that collect bits of data together aka interables
#strings and lists
aList = [1,2,3]
aList.append([4,5]) #returns[1,2,3[4,5]]
print aList
# range method
our_list= list(range(10)) #returns 0-9
print our_list
print our_list + [10,11,12] #returns 0-12
print our_l... |
#! /usr/bin/python
import random
COLORS = ['yellow','blue','red','green','orange']
class Monster(object):
min_hit_pts = 1
max_hit_pts = 1
min_experience = 1
max_experience = 1
weapon = 'sword'
sound = 'snort'
def __init__(self, **kwargs):
self.hit_points = random.randint(self.mi... |
#imports the ability to get a random number (we will learn more about this later!)
from random import *
#Create the list of words you want to choose from.
first = ['Jason', 'Alison', 'Tim','Abcde', 'Luna','Harry','John' ,'Gabriel']
last = ['Todd', 'Nikols','Lovegood','Morozov','Reyes','Malfoy','Amari']
#Genera... |
"""Restaurant rating lister."""
import sys
def import_file(file_name):
"""Return file object"""
restaurant_ratings = open(file_name)
return restaurant_ratings
file_name = import_file(sys.argv[1])
def adding_to_restaurants_dict(file_name):
"""Adding restaurant names to dictionary"""
revie... |
import os # operating system, "os"為"標準函式庫"裡面就有的東西可以直接import進來"這個模組"
# Refactor 重構, 重新把架構都寫成funcion, 和有一個main() function程式的進入點
# 讀取檔案
def read_file(filename): # 把檔名設成參數比較靈活, 可讀別的檔案
products = [] # 先創一個空清單
with open(filename, 'r', encoding = 'utf-8') as f: #之前寫得檔案用utf-8寫, 所以讀取也要用utf-8才讀的到
for line in f: # 讀取檔案f, 會一行一... |
filename = open('words.txt', 'r')
lst = list(filename)
myword = 'silver'
for n in range(len(lst)):
diff = 0
for i in range(6):
if lst[n][i] != myword[i]:
diff = diff + 1
if diff == 1:
print(lst[n])
'''
def main():
word = "wallet"
parent = "XXXXX"
print(neighbors(word, parent))... |
def setUpCanvas(root):
root.title("Wolfram's cellular automata: A Tk/Python Graphics Program")
canvas = Canvas(root, width = 1270, height = 780, bg = 'black')
canvas.pack(expand = YES, fill = BOTH)
return canvas
def displayStatistics():
print('RUN TIME = %6.2F'% round(clock()-START_TIME, 2), 'seconds.')
root.ti... |
def diamond(height):
"""Return a string resembling a diamond of specified height (measured in lines).
height must be an even integer.
"""
outStr = ""
for i in range(1, height//2+1,1):
tmpStr = "/"*i + "\\"*i
outStr += tmpStr.center(height) + "\n"
for i in range(height//2, 0, -1):... |
""" Exercise 4 """
import hashlib
def genpasswd(password):
""" Accepts a password and generate new one """
sha1 = hashlib.sha1(password.encode('utf-8'))
hashstring = sha1.hexdigest()
return hashstring[:6]
def findcollision(x0):
""" Finds two input passwords which give the same output from genpas... |
# Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
# Also please include simple test function to test the class methods.
import unittest
class String():
def _init_(self):
self.str1 = ""
def get_String(self... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# start's with a string
before = "This is the euro symbol: €"
type(before)
# In[2]:
import numpy as np
import pandas as pd
# In[3]:
# encode it to a different encoding, replacing characters that raise errors
after = before.encode('utf-8', errors='replace')
type(... |
a = int(input("enter a number: "))
if a > 0 :
print (a)
else :
print(-a)
|
# example 3
# 2*x**2+6*x-20
a = 2
b = 6
c = -20
delta = b ** 2 - 4 * a * c
roots1 = (-b - delta ** 0.5) / (2 * a)
roots2 = (-b + delta ** 0.5) / (2 * a)
print ("roots1:", roots1)
print ("roots2:", roots2)
|
# example 4
celcius = float(input("temperature value : ", ))
fahrenheit = celcius * 1.8 + 32
print (fahrenheit)
|
# for i in range(100):
# print(i)
# range() 函数可创建一个整数列表,一般用在 for 循环中。
# start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5
# stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
# step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
for_list = ['a', 'b']
for a in for_list:
print(a)
data = [6, 3, 7, 9,... |
########################################################################
##
## CS 101 Lab
## Program #
## Name
## Email
##
## PROBLEM : Describe the problem
##
## ALGORITHM :
## 1. Write out the algorithm
##
## ERROR HANDLING:
## Any Special Error handling to be noted. Wager not less than 0. e... |
name = input("Hello Human what is your name? > ")
print(f"Hell {name}, nice to meet you")
|
import unittest #You need this module
import ordinal_drm #This is the script you want to test
class ordinal_drm_test(unittest.TestCase):
def identical_test(self):
self.assertEqual("1st", myscript.myfunction(1))
self.assertEqual("2nd", myscript.myfunction(2))
self.assertEqual("3rd", myscript.myfunction(3))
self... |
class Clock(object):
def __init__(self, hour, minutes):
self.minutes = minutes
self.hour = hour
@classmethod
def at(cls, hour, minutes=0):
return cls(hour, minutes)
def __str__(self):
return "The time is %s hours and %s minutes" % (self.hour, self.minutes)
def __add__(s... |
#control flow
#how to take input from a user
#multiple input - loops
var= input("how many apples")
print(var)
name= input("what is your name")
print(" hello" + name)
num= input()
#control flow includes----
# if statement
#elif statement
#else statement
#example-
grade='a'
if grade=='A' :
... |
userinput = input('Put in a phrase which you want converted into an acronym. ')
listt = userinput.split()
acronym = ''
for i in listt:
acronym = acronym + i[0].upper()
print (acronym) |
# Nama: Zaid
# NIM: 0110220085
# Kelas: TI 03
def jumlah_batas(nums, batas):
# Tulis kode fungsi jumlah_batas() di bawah ini
# Hapus pass jika implementasi sudah dibuat
jumlah = 0
for i in range(len(nums)):
if nums[i] > batas:
jumlah += nums[i]
return jumlah
def list_nonvokal(s):
# Tulis kode... |
PI = 3.14
radius = float(input('반지름을 입력하세요: '))
def circle_area_circum(radius):
area = PI * (radius ** 2)
length = 2 * PI * radius
return '원의 면적은 {}, 원의 둘레는 {} 입니다.' .format(area,length)
print(circle_area_circum(radius)) |
"""
CP5632 Practical 4
Warm-up with Lists
"""
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers[0] # 3
numbers[-1] # 2
numbers[3] # 1
numbers[:-1] # [3, 1, 4, 1, 5, 9]
numbers[3:4] # [1]
5 in numbers # True
7 in numbers # False
"3" in numbers # False
numbers + [6, 5, 3] # [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
# Change the ... |
"""
CP5632 Practical 3
Program to get password from user and display it as asterisks
"""
def main():
password = get_password()
display_asterisks(password)
def display_asterisks(password):
"""Replace password characters with asterisks"""
for i in range(0, len(password)):
print("*", end="")
... |
"""
CP5632 Practical 5
Program to count word occurences in a string provided by the user
"""
def main():
word_counts = {}
text_input = input("Text: ").lower()
word_list = text_input.split()
for word in word_list:
if word not in word_counts:
word_count = word_list.count(word)
... |
"""
CP5632 Practical 5
Program to get names and emails from the user and add them to dictionary
"""
def main():
email_collection = {}
email = input("Email: ")
while email != "":
parts = (email.split("@")[0].split("."))
name = " ".join(parts).title()
verify_name = input("Is your ... |
"""CP5632 Practical 6 - Client code for Guitar class"""
from prac_06.guitar import Guitar
def main():
"""Code to add guitars from user to a list and display the result"""
print("My guitars!")
guitars = []
is_loop_running = True
while is_loop_running:
name = input("\nName: ")
year ... |
import os
import pandas as pd
import numpy as np
import random
import time
#this method is meant to process the iris.csv data & get it ready for machine learning
def process():
#reading the data
os.chdir("/Users/64000340/Desktop/iris-species")
df = pd.read_csv("Iris.csv")
k = 3 #number of classes
... |
print("Welcome to BMI calculator.")
Gender = input("Put in your gender: ")
Weight = input("Put in your weight in KG: ")
Height = input("Put in your height in CM: ")
Weight = float(Weight)
Height = float(Height)
Height_Squared = Height * Height
BMI = Weight / Height_Squared
BMI_Formula_Completed = BMI * ... |
a = [1, 2, 3, 1, 5, 7, 8, 2, 3, 4] # Example of a row
n = len(a)
d = [] # Row holding max sequence for every digit in "a"
for i in range(n):
d.append(1)
for j in range(1, i):
if a[j] < a[i] and d[j] + 1 > d[i]:
d[i] = d[j] + 1
ans = 0
for i in range(1, n):
ans = max(ans, d[i])
print(a)... |
# toy dataset included to scify
from sklearn import datasets #importing datasets from sklearn
import numpy as np
iris = datasets.load_iris() #getting the iris flower dataset into iris
#check whether dataset loaded
#print(iris)
data = iris.data #data features 150*4 2D array
target = iris.target #target labels 150 1d... |
import random, pylab
# Helper function 1
def flip():
''' flip one coin '''
return random.choice(['H', 'T'])
def flipCoins(numCoins=1000):
''' flip numCoins coins 10 times each and return res per coin '''
res = []
for i in range(numCoins):
aCoin = []
for j in range(10): # flip each coin 10 times
aCoin.app... |
def f1(self, x, y):
return min(x,y)
def f2(self, x):
return x+10
class C:
f = f1
def g(self):
return repr(self) + "Hello world"
h = g
print(f1(0,1,2))
x = C();
print(x.f(4,5))
print(x.g())
print(x.h())
x.h = f2
print(x.h(0, 6))
|
#
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
fruit = set(basket)
print(fruit)
def judge(a, b):
if( a in b):
print(a, "in", b)
else:
print(a, "not in", b)
judge('orange', fruit)
judge("applee", fruit)
a = set('abcd')
b = set('cdef')
# 集合的简单操作
print(a)
print(b)
pr... |
#
def fib(n):
"""这个函数打印斐波那契数列"""
a,b = 0,1
while(a < n):
print(a, end = ' ')
a,b = b, a+ b
print()
def fib2(n):
"""这个函数返回斐波那契数列"""
result = []
a,b = 0,1
while(a < n):
result.append(a)
a,b = b, a+ b
return result
fib(100)
fib(1000)
res1 = fib2(100)
print(res1)
|
#
for num in range(2, 10):
if(num % 2 == 0):
print(num, "是一个偶数");
continue
print(num, "不是一个偶数")
|
import numpy as np
import matplotlib.pyplot as plot
import pandas
from prediction_parameters.cost import cost_function
from prediction_parameters.hypothesis import hypothesis
dataframe = pandas.read_csv('houses_data.csv')
# function to plot cost
def plot_cost(theta):
x2 = np.linspace(-0.5, 2.5)
y2 = [cost_fun... |
#!/usr/bin/env python
# coding: utf-8
# ### Note
# * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# In[9]:
# Dependencies and Setup
import pandas as pd
import numpy as np
# File to Load (Remember to Change These... |
import random
import board
class AI:
def __init__(self, acontroller):
'''
Initializes ai class
'''
self.controller = acontroller
self.board = board.Board(self.controller)
def initialize(self):
'''
Initializes the ai and creates a new board... |
# In this lesson we are taking a few steps back to look at linear regression,
# from a simple idea of fitting a straight line through data to ridge regression
# on our next lesson
# The boston dataset is perfect to play around with regression.
# The boston dataset has the median home price of several areas in Boston... |
#1.加總分(total), 排名(rank)
#2.使用subject為主
students = {
'Chang':
{
'Math': 90,
'Chinese': 85,
'English': 60
},
'Thang':
{
'Math': 85,
'Chinese': 70,
'English': 92
},
'Chen':
{
'Math': ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 22:24:42 2017
@author: bushnelf
"""
import Game
import CardSet
import RandomComputerPlayer
class RandomGame(Game.Game):
def __init__(self, numplayers, numrounds=10):
Game.Game.__init__(self, numplayers)
self._numrounds = numrounds
def playro... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 22 21:48:40 2017
@author: bushnelf
"""
import random
# import Player
class PlayerBoard(object):
"""
PlayerBoard - where a player's "in play", "recovery zone", and
discarded cards are kept, along with the player's victory points
and any special tokens (... |
a = [["abc0001","Bobby",100],
["abc0002","Larry",400],
["abc0003","Dan",150],
["abc0004","Billy",200],
["abc0005","Sid",350]]
def balance(v):
for b in a:
if (b[0] == v):
name=b[1]
bal=b[2]
print("Hello "+name)
print("Your balance is:... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
print("Hello")
# In[3]:
print("Hello python")
# In[6]:
print(""" Hello Every one
How are you?
How is everything going on""")
# In[7]:
""" Hello Every one
How are you?
How is everything going on"""
# In[8]:
print('Hello world')
# In[9]:
print... |
# Austin Whitley
# Assignment 4
# Birthday Dictionary
# Used as global to it can be used program wide
birthdayDictionary = {"Austin":"08/07/1994", "Nathan":"06/07/1994", "Blake":"06/18/1962","Brandy":"03/04/2964"}
def main():
functionDictionary = {"Look Up a Birthday": lookUpBirthday, "Add a New Birthday": addBi... |
import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print('Phone number found. Area code: ' + mo.group(1) + ' number: ' + mo.group(2))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 4 00:21:26 2019
@author: Anik Paul Gomes
"""
"""
This script reads text file which contains list of dictonary and converts into
csv file. So that validity of the calculations can be checked in excel for shorter
amount of data
"""
#Added square brackets in the beginni... |
#!/usr/bin/env python3
from PIL import Image
img = Image.open('./maps.jpg')
width = int(input("Enter the width: "))
height = int(input("Enter the height: "))
resized_img = img.resize((width, height), Image.ANTIALIAS)
resized_img.save('./maps_new.jpg')
|
#!/usr/bin/env python3
a = int(input("Введите число: "))
symb = input("Введите символ: ")
b = int(input("Введите второе число: "))
if symb == '+':
result = a + b
print(result)
print("Результат: ")
elif symb == '-':
result = a - b
print("Результат: ")
print(result)
elif symb == '*':
result = a * b
print("Резу... |
import pygame
import constants
import platforms
class Level():
""" This is a generic super-class used to define a level.
Create a child class for each level with level-specific
info. """
def __init__(self, player):
""" Constructor. Pass in a handle to player. Needed for when moving... |
from turtle import Screen
from snake import Snake # Importar la clase Snake
from food import Food # Importar clase food
from scoreboard import Scoreboard # Importar clase score
import time
screen = Screen() # Ventana
screen.setup(width=600, height=600) # Tamaño de la ventana
screen.bgcolor("black") #... |
"""
Quick go to work with denied persons list
Versions
01a - use a classic read file format, rather than an csv style
"""
import csv
def ascii_file_no_lines(filename):
"""
check how many lines in ascii file
# http://gsp.humboldt.edu/OLM/Courses/GSP_318/03_3_ReadingFiles.html
"""
TheFile = open(fil... |
"""
Data wrangling for this project.
DATA SOURCE FILES are given in code book. They have been downloaded and stored locally.
REPLICATING THIS?: Need to add your own correct file paths and file names.
"""
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# utili... |
"""
Quick function to split bills
"""
def split_bill(cost):
split_cost = cost / 2
print("{} dollars".format(split_cost))
return
# Split a 5 dinner cost
split_bill(5)
|
num=int(input("Enter the Year:"))
if num > 0:
if (num % 4) == 0:
if(num % 100) == 0:
if(num % 400) == 0:
print("{0} is a Leap Year".format(num))
else:
print("{0} is not a Leap Year".format(num))
else:
print("{0} is a Leap Year".format(num))
else:
print("{0} is not a Leap Year".format(num))
els... |
#!/usr/bin/python
# coding: utf-8
import unittest
import operator
from string_subtraction import StringNumber
# There are other ways to do this but thought it would be fun working out
# the problems of a class with dynamically created methods
class StringNumberEqualityTests(unittest.TestCase):
"""Shell class f... |
sum = 0.0
print(" i\t sum")
for i in range(1, 11):
sum += 1.0 / i
print("%2d %6.1f" % (i , sum))
'''
#using while loop
sum = 0.0
i = 1
while i < 11:
sum += 1.0 / i
print("%2d %6.1f" % (i , sum))
i +=1
''' |
#!/usr/bin/env python3
# FIXME -- convert into float
farenheit = 0
while farenheit <= 10:
celcius = (farenheit - 32)/1.8
print("Farenheit Celcius")
print("%d \t\t\t %d" %(farenheit, celcius))
farenheit = farenheit + 10
"""farenheit = 0.0
print("Farenheit Celcius")
while farenh... |
# Import csv and os modules
import csv
import os
# Identify file for analysis
PyBank_file = os.path.join(".", "Resources", "budget_data.csv")
# Identify file for output
output_file = os.path.join(".", "analysis", "PyBankAnalysis.txt")
# OPEN CSV FILE
with open(PyBank_file, 'r') as csvfile:
# READ CSV FILE
cs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.