text stringlengths 37 1.41M |
|---|
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[-3:])
print('Here are the first three players on my team:')
for player in players[:3]:
print(player.title())
print("\nThe first three items in the list are:")
for i in players[:3]:
print(i.title())
print("\nThree... |
# Testing AND,OR,NOT
bool_one = False or not True and True
bool_two = False and not True or True
bool_three = True and not (False or False)
bool_four = not not True or False and not True
bool_five = False or not (True and True)
print(str(bool_one) + " " + str(bool_two) + " " + str(bool_three) + " " + str(bool_four... |
from datetime import datetime
import time
current = datetime.fromtimestamp(time.time()).timestamp()
print("enter your day of birthday")
birthday = input("DD/MM/YY")
startdate = int(datetime.strptime(birthday,"%d/%m/%y").timestamp())
print(int((current-startdate)/604800))
age = int(input("how many years do you plan to... |
import re
class Solution:
def lengthOfLastWord(self, s: str) -> int:
pattern = re.compile(r'[^\s]+$')
word = re.findall(pattern, s)
if len(word) == 0:
return 0
else:
return len(word[0])
class Solution2:
def lengthOfLastWord(self, s: str) -> int:
... |
# 给定一个 n × n 的二维矩阵表示一个图像。
# 将图像顺时针旋转 90 度。
# 说明:
# 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
# 示例 1:
# 给定 matrix =
# [
# [1,2,3],
# [4,5,6],
# [7,8,9]
# ],
# 原地旋转输入矩阵,使其变为:
# [
# [7,4,1],
# [8,5,2],
# [9,6,3]
# ]
# 示例 2:
# 给定 matrix =
# [
# [ 5, 1, 9,11],
# [ 2, 4, 8,10],
# [13, 3, 6, 7],
# [1... |
# 举个例子:11 除以 3 。
# 首先11比3大,结果至少是1, 然后我让3翻倍,就是6,
# 发现11比3翻倍后还要大,那么结果就至少是2了,
# 那我让这个6再翻倍,得12,11不比12大,吓死我了,差点让就让刚才的最小解2也翻倍得到4了。
# 但是我知道最终结果肯定在2和4之间。也就是说2再加上某个数,这个数是多少呢?
# 我让11减去刚才最后一次的结果6,剩下5,我们计算5是3的几倍,也就是除法,看,递归出现了
# 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。
# 本题中,如果除法结果溢出,则返回 2^31 − 1。
import math
class Soluti... |
# 递归思路
# 1 函数是干什么的 想明白功能
# 2 递归出口
# 3 找出函数的等价关系式
from typing import List
# 用一个新函数递归 方便传参
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def func(string, L, R):
if L == 0 and R == 0:
res.append(string)
return
... |
class Solution:
def isPalindrome(self, x: int) -> bool:
# 特殊情况:
# 如上所述,当 x < 0 时,x 不是回文数。
# 同样地,如果数字的最后一位是 0,为了使该数字为回文,
# 则其第一位数字也应该是 0
# 只有 0 满足这一属性
if x < 0 or (x % 10 == 0 and x != 0):
return False
# 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字... |
class person:
def __init__(self,name , age):
self.name = name
self.age = age
def greet(Print_func):
def hello(a):
print('this is hello start!')
Print_func(a)
print('this is the end.')
return hello
@greet
def print(self):
pri... |
from tkinter import *
class Maze(object):
# Creating mazes(easy, medium and hard)
maze1= '\n'+ \
"XXXXXXXXXXXXXXXXXXSSX\n" +\
"X X X\n" +\
"X XXXXXXXXXXXX X X\n" +\
" O X X X X\n" +\
" X X X X\n" +\
... |
print("welcome to python \n")
# def funcName():
# # print("str message")
# return "pakistan is my beloved land"
# #end of function
# # var1 = funcName() # function call
# print(funcName())
# def add():
# n1= int(input("ENter number one: "))
# n2=int(input("ENter number two:... |
print("\n welcome to Python")
# x=5.3
# y=2.6
# print(x, type(x))
# print(y,type(y))
# # convert into string
# x=str(x)
# print(x , type(x))
# print(str(y) , type(str(y)))
# z=x//y
# print(z , type(z))
# x="33"
# x=int(x)
# y=int("20")
# print(x + y) #120
# print(type( x+y ))
... |
def func( pr1 ):
print("list before eddit {}" .format(pr1)) # 20
pr1 = [1,2,3,4,5 ,6,7,7]
print("list after eddit {}" .format(pr1)) # 20
#end of func
pr1 = 20
func(pr1)
print(pr1)# 20
|
print("\n welcome to python operators \n ")
# a=5
# b=2
# summ =a+b
# sub=a-b
# mul=a*b
# # simple floating includded division
# sdiv=a/b
# # print(sdiv)
# # int division
# idiv=a//b # 2
# # print(sdiv , "\n " , idiv )
# power=a**b
# # print(power)
# rem = a%b
# print("The remainder of 5%2 == ... |
num = input()
num = int(num)
if (num % 2 == 0):
print('False')
else :
print('True')
|
from random import *
def théme():
"""
permet à l'utilisateur de choisir son théme entre le 2048 'normal', 2048 en chiffre romain, l'alphabéte et la chimie
"""
return input("Ton théme?, N(2048), R(2048 en chiffre romain), A(alphabéte), C(chimie)")
Théme={"N":"2048 CLASSIQUE","R": "2048 EN CHIFFRE R... |
import sys
def reverse_word(given_word):
if (given_word == ""):
return given_word
else:
return reverse_word(given_word[1:]) + given_word[0]
word = sys.argv[1]
reversed = reverse_word(word)
if(word == reversed):
print True
else:
print False
|
import sys
def magic(num,arr,first,last):
if((first+1==last) and (arr[first] != num)):
return "not found"
else:
if(num == arr[(last + first)/2]):
return (last+first)/2 # sporno + 1
elif(num < arr[(last+first)/2]):
... |
"""
This file is responsible for input management in the program.
The main.py file uses the Runner class to run the program.
"""
from MNHeap import *
# the Runner class.
# the 'alive' attribute of it is a term for the main loop in main.py.
# initializer: gets a valid MNHeap as an input.
class Runner:
def __init_... |
#file to generate samples using generateRV.py
import random
import math
import statistics
import matplotlib.pyplot as plt
import scipy.stats as scipy
from collections import Counter
import generateRV as gen
from scipy.stats import norm
from collections import defaultdict
def plot(x, bins=10):
#plots a historgram of e... |
#1818123 Hariprasath S
inf = 9999
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
#[[0, 4, 4, 0, 0, 0], [4, 0, 2, 0, 0, 0], [4, 2, 0, 3, 1, 6], [0, 0, 3, 0, 0, 2], [0, 1, 0, 0, 0, 3], [0, 0, 6, 2, 3, 0]]
for i in range(self.V):
inner... |
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __repr__(self):
return f"{self.last_name.title()}, {self.first_name.title()}"
# x = Person("Jack","Ryan")
# print(x) |
class GreedyAlgorithms(object):
""" Greedy Algorithms."""
def __init__(self):
pass
def get_change(self, money):
"""(GreedyAlgorithms, integer) -> integer
Return minimum number of coins with denominations 1, 5, and 10 that changes money.
... |
# Name: Ghasadiya Manthan
# ID: 201951065
# Section: 2-B
import random
import time
def countingSort(array , n , position):
#find maximum element in array
Max = max(array)
# count array of size 10 (because 0 to 9) and with all elements 0
count = (10)*[0]
# final array ... |
#!/usr/bin/env python3
def guess_language(filename):
with open(filename, encoding='utf-8') as textfile, open('data.csv', encoding='utf-8') as data:
(_, *letters), *rows = zip(*[line.split(',') for line in data.read().splitlines()])
text = ''.join(filter(letters.__contains__, textfile.read().casefol... |
def partition(arr, l, r):
x, i = arr[r], l
for j in range(l, r):
if arr[j] <= x:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[r] = arr[r], arr[i]
return i
def quickselect(arr, k, l, r):
if k > 0 and k <= r - l + 1:
index = partition(arr, l, r)
... |
def main():
entrada = list(map(int, input("Entradas: ").split()))
pesos = list(map(int, input("Pesos: ").split()))
bias = int(input("Bias: "))
def func_ativação(parametro):
if parametro > 0:
return 1
elif parametro < 0:
return 0
soma = 0
for valor1, peso1 in zip(entrada, pesos):
so... |
def merge_overlapping_lst(lst):
# input: lst of sublists. recursively merge all sublists with intersection. input lst will be altered
out = []
original_lst = lst.copy() # for comparision with output
while True:
current_lst = lst[0]
if len(lst) == 1:
out.append(current_lst) # ... |
#!/usr/bin/env python3
"""
Part 1: Taxicab (non-Euclidean) distance from origin following relative
directions on a plane.
Starting direction is North.
Part 2: Taxicab distance to the first crossing of the walked path.
Example:
- Input: R5, L5, R5, R3
- Output: 12
Solution: Mealy finite state machine determines mo... |
#-*- coding: UTF-8 -*-
#如何进行拆分含有多种分割符的字符串
#ps aux :查看系统当前进程
import re
def mysplit(s,ds):
res=[s]
for d in ds:
t=[]
map(lambda x:t.extend(x.split(d)),res)
res=t
#return res
return [x for x in res if x]
if __name__=='__main__':
s='wshe 3266 0.0 0.1 24336 5360 pts/4 ... |
print("""
Write a short Python program that takes two arrays a and b of length n
storing int values, and returns the dot product of a and b. That is, it returns
an array c of length n such that c[i] = a[i] · b[i], for i = 0,...,n−1.
""")
import sys
sys.path.append("..")
from others.helpers import get_list_integers
p... |
print("""
Python’s random module includes a function choice(data) that returns a random element from a non-empty
sequence. The random module includes a more basic function randrange, with parameterization similar to
the built-in range function, that return a random choice from the given range.
Using only the randrange ... |
print("""
Write a Python program that repeatedly reads lines from standard input
until an EOFError is raised, and then outputs those lines in reverse order
(a user can indicate end of input by typing ctrl-D).
""")
outputs = list()
not_eof = True
while not_eof:
try:
line = input('Type here: ')
... |
print("""
Write a short Python function, is multiple(n, m), that takes two integer
values and returns True if n is a multiple of m, that is, n = mi for some
integer i, and False otherwise.
""")
def is_multiple():
n = int(input('Enter an integer value: '))
m = int(input('Enter another integer value: '))
ret... |
# Addition Problem
# Student C
x = input("Enter x: ").strip()
y = input("Enter y: ").strip()
if len(x) > 0 and (x[0] == '-' or x[0].isdigit()) and (len(x) < 2 or x[1:].isdigit()) and len(y) > 0 and (y[0] == '-' or y[0].isdigit()) and (len(y) < 2 or y[1:].isdigit()):
print(int(x) + int(y))
else:
print('Error')
|
# Wikipedia
def merge(left: list, right: list) -> list:
res = []
while(left and right):
res.append(left.pop(0) if left[0] < right[0] else right.pop(0))
if(left):
res += left
if(right):
res += right
return res
def merge_sort(L: list) -> list:
if(len(L) <= 1):
r... |
from random import randint
def main():
l = []
for i in range (3):
film = input("Vnesi film: ")
l.append(film)
print (result(l))
def result(l):
return l[randint(0,2)]
main()
|
#functions
def addTwo (x): #this function takes the parameter x and adds 2 onto it
return x+2
def subTwo (number):
return number - 2 #this function takes the parameter x and subtracks 2 from it
Newnumber = subTwo(2)
print(addTwo(4))
print(Newnumber)
def printstring(string):
print(string[1:5]) #this functi... |
class MyArrayList:
"""
ArrayList abstracts built-in list functionality.
Attributes:
data (list): A list of data
size (int): The length of 'data'
"""
size = None
def __init__(self, data):
self.data = data
self.size = len(data)
def removeFront(self, k):
... |
#!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
from datetime import datetime
class Logmaker():
"""-= Log Maker =-
What is this you may ask? Well it's in the name.
This program creats a developer log that would
print out the message and the timecode. This is
to help when bug testing programs as it will store
the long in a .txt file that people can acess... |
x = 17
# integer
y1 = x
print('y1 is a ' ,type(y1))
print('y1 = ',y1)
# float
y2 = float(x)
print('y2 is a ' ,type(y2))
print('y2 = ',y2)
# string
y3 = str(x)
print('y3 is a ' ,type(y3))
print('y3 = ',y3)
# Boolean, '17 > 16'
y4 = bool(x > 16)
print('y4 is a ' ,type(y4))
print('y4 = ',y4)
text = 'The ' + 'value ' ... |
for i in range(1,50):
if i%3 == 0 or i/2<=5:
continue
print(i)
print("bye") |
"""
Ejercicio 2 : Clase 4 Manejo de colecciones y Tuplas
Autor = @davisalex22
Encontrar : [("a",(30,1)),("b",(100,2)),("c",(20,4))]
"""
# Declaracion de Listas
lista = [(100, 2), (20, 4), (30, 1)]
lista2 = ["b", "a", "c"]
# Muestra en pantalla de resultados y Uso de list, zip y sorted
print(list(zip(sorted(lista2),... |
#build a pure fram
import tkinter as tk
#it is grapic (visual)
#from tkinter import ttk (not nessary needed if have tkinter import)
window = tk.Tk()
window.geometry("300x200")
alabel = tk.Label(text ="Apple")# create a str & need a location
alabel.grid( column = 0, row = 0)# help you use sth in colum... |
import random
from mainmenu import *
cowsandbulls()
words=["rate","fail","cake","sore","tear","calm","rage","time","face","swan"]
rand=random.randrange(0,10)
word=words[rand]
cnt=0
while(cnt<15):
s=input("Enter string:")
if s=="-1":
print("Thank you!")
return... |
import random
def comp(card):
return int(card.value)
class Card:
suit = ""
value = ""
def __init__(self, suit, value):
self.suit = suit
self.value = value
class Deck:
cards = []
def __init__(self, new_deck = True):
if (new_deck):
for x in range(1, 15):
self.cards.append(Card("C", str(x)))
s... |
#!/usr/bin/python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
DATA_FILE_NAME = './dataset/1_linearinput.csv'
# load data
df = pd.read_csv(DATA_FILE_NAME)
# plot data
df.plot(x='x', y='y', legend=False, marker='o', style='o', mec='b', mfc='w')
# expected line... |
#Formar un json de un diccionario en python
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
person_dict = json.loads(person)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print( person_dict)
# Output: ['English', 'French']
print(person_dict['languages'])
#fuente: https://www.pr... |
import tkinter
from tkinter import *
from tkinter import filedialog as fd
def quit(ev):
global root
root.destroy()
def encode_vienera(ev):
text = textbox.get(1.0, END).lower()
key = entry_key.get().lower()
key_len = len(key)
if len(key) < len(text):
for i in range(key_len, len(text)... |
import pandas, re, os, datetime
def cleansing(dataFromMongo):
data = pandas.DataFrame(dataFromMongo)
columns = list(data.columns)
pat_id = '[0-9]+[A-Z]+[0-9]+'
# Handle the empty row in USER FULL NAME
data.loc[data["User full name"]=="-", "User full name"] = "Admin"
for row in range(len(da... |
'''
定义函数时,需要确定函数名和参数个数;
如果有必要,可以先对参数的数据类型做检查;
函数体内部可以用return随时返回函数结果;
函数执行完毕也没有return语句时,自动return None。
函数可以同时返回多个值,但其实就是一个tuple。
'''
import os
x=3
print x
print range(1,3)
print range(0,3)
print range(-5,-3)
l=[]
for x in range(1,11):
l.append(x*x)
print l
print [x*x for x in range(1,11) if x %2==0]
print... |
#!/usr/bin/env python
# coding=utf-8
"""An interactive testing tool for validating A* algorithm in Search Path Service.
This script reads in given map file, and shows the map in GUI. The user can 'right-click' any reasonable point to
specify it as the starting point or the goal point (in this order), and then it will... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 09:04:32 2019
@author: binhnguyen
"""
import random
#Importing genfrags - a function created that is similar to the sim1end
print ('--------------------------------------')
print ('Lab 3 Part 2')
print ('--------------------------------------')
... |
def string_array(array, searchstr):
print(array.count(searchstr))
string_array(('banana is an good ann food banana for banana ann'), 'an')
from collections import defaultdict
words = "apple banana apple strawberry banana lemon"
d = defaultdict(int)
for word in words.split():
d[word] += 1
print(d)
def... |
# In this example, we read the temperature and humidity from a DHT22 sensor and
# display it on an LCD.
# The circuit:
# LCD's SDA -> Pico Pin 0
# LCD's SCL -> Pico Pin 1
# DHT22's data -> Pico Pin 12
from DHT22 import DHT22
import utime
import machine
from machine import I2C, Pin
from i2c_lcd import *
# The first a... |
# Timers can be used to periodically execute tasks without having to worry
# about them in the main thread. In this example, we move the tasks of
# blinking an LED to a timer callback. Timers are backed by real hardware
# timers that various microcontrollers generally have. You need to check
# the manual of the microco... |
def compare(first_number, second_number):
if first_number > second_number:
return f"{first_number} is greater than {second_number}"
elif first_number < second_number:
return f"{first_number} is less than {second_number}"
else:
return "numbers are the same"
|
import random
class Node:
def __init__(self, val):
self.val = val
self.next = None
class Singly_Linked_List:
def __init__(self):
self.head = None
# My populateRandom method uses add_front, so I'd better paste it here.
def add_front(self, val):
new_head = Node(val)
... |
# Singly Linked List
# Day 1
class Node:
def __init__(self, val):
self.val = val
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
# SLList: Add Front
# Given a value, create a new node, add it to the front of the singly linked list, and return the ... |
import random
class Arr_Stack:
def __init__(self, items = []):
self.items = items
# ArrStack: Push
# Create push(val) that adds val to our stack.
def push(self, item):
self.items.append(item)
return self
def populate_random(self, max, length):
for i in range(length... |
def preorder(node):
if node is None:
return
print(node.val)
preorder(node.left)
preorder(node.right)
def inorder(node):
if node is None:
return
inorder(node.left)
print(node.val)
inorder(node.right)
def postorder(node):
if node is None:
return
postorde... |
# 검색 트리의 일종
# 일반적으로 키가 문자열인, 동적 배열 또는 연관 배열을 저장하는 데 사용되는 정렬된 트리 자료구조
from collections import defaultdict
class TrieNode:
def __init__(self):
self.word = False
self.children = defaultdict(TrieNode)
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
... |
def z_func(n, r, c):
global number
# 2가 최소값임
if n == 2:
if r == R and c == C:
print(number)
return
number += 1
if r == R and c+1 == C:
print(number)
return
number += 1
if r+1 == R and c == C:
print(number)
... |
from collections import deque
def isPalindrome(head):
q = deque([])
# head가 없는 경우
if not head:
return True
node = head
# 리스트 반환
while node:
# 현재 노드 추가
q.append(node.val)
# 다음 노드 저장
node = node.next
while len(q) > 1:
# 좌우 뽑기
if q.po... |
# n = sec 추가되는 초
def solution(t, n):
time_type, time = t.split()
hour, min, sec = map(int, time.split(':'))
def add_time(time_type, hour, min, sec, n):
if time_type == 'PM':
hour += 12
added_sec = sec + n
if added_sec >= 60:
added_sec %= 60
min +... |
from collections import deque
n = input()
var_list = list(map(str, n.split(',')))
first_list = var_list[0].split(' ')
common = first_list[0]
last = var_list[-1][-1]
var_list[0] = ' ' + first_list[1]
var_list[-1] = var_list[-1][0:-1]
def func(var):
var = list(var.split(' '))
if len(var) == 1:
var[0] =... |
class TreeNode:
def __init__(self, left, right):
self.left = left
self.right = right
def array_to_BST(nums):
if not nums:
return None
mid = len(nums) // 2
# 분할 정복으로 이진 검색 결과 트리 구성
node = TreeNode(nums[mid])
node.left = array_to_BST(nums[:mid])
node.right = array_t... |
# heap
import heapq
n = int(input())
heap = []
for i in range(n):
data = int(input())
heapq.heappush(heap, data)
result = 0
while len(heap) != 1:
# 최소값 2개
a = heapq.heappop(heap)
b = heapq.heappop(heap)
sum = a + b
result += sum
# 최소값 더한 값 힙에 넣음
heapq.heappush(heap, sum)
print(r... |
# 투 포인터 활용
def reverse_string(s):
left, right = 0, len(s)-1
while left < right:
s[left], s[right] = s[right], s[left] # SWAP
left += 1
right -= 1
# Pythonic Way
def reverse_string2(s):
s.reverse()
|
def array_pair_sum(nums):
sum = 0
pair = []
nums.sort()
for n in nums:
# 앞에서부터 오름차순으로 페어를 만들어 합 계산
pair.append(n)
if len(pair) == 2:
sum += min(pair)
pair = []
return sum
def array_pair_sum2(nums):
sum = 0
nums.sort()
for i, n in enumer... |
def odd_even_list(head):
# 예외 처리
if head is None:
return None
odd = head
even = head.next
even_head = head.next
# 반복해서 홀짝 노드 처리
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
# 홀수 노드의 마지막을 짝수 헤드로 연결... |
"""
OOP method of solving sudoku
"""
from sudoku import *
# to solve a sudoku defined in data directory
solve("m18.data")
pass
# to solve a sudoku and just using the methods which level <= 15 and if can't solve, don't use guess method
solve("m3.data", level_limit=15, use_try=False)
pass
# to solve... |
"""
1. Characterize the structure of an optimal solution.
For the maximum subarray problem,
an optimal solution consists of the max value in a series of sums
of various combinations of elements from the starting array.
The various combinations occurr in two groups:
-Combinations made from consecutive elements.
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#这个脚本用来测试class 的继承和多态
class Animal(object):
def run(self):
print 'Animal is running...'
#当我们需要编写Dog和Cat类时,就可以直接从Animal类继承:
#当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这样,我们就获得了继承的另一个好处:多态。
class Dog(Animal):
def run(self):
p... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。
try:
print 'try...'
r = 10 / 0
print 'result:', r
except ZeroDivisionError, e:
print 'except:', e
finally:
print 'finally...'
print... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#为了编写单元测试,我们需要引入Python自带的unittest模块,编写mydict_test.py如下:
import unittest
from mydict import Dict
#编写单元测试时,我们需要编写一个测试类,从unittest.TestCase继承。
class TestDict(unittest.TestCase):
def setUp(self):
print 'setUp start test...'
def tearDown(self):
print 't... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import math
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
xx=float(raw_input(u'请输入一个自然数:'.encode('utf-8')).decode('utf-8'))
print '%.2f' % my_abs(xx)
def move(x... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#动态绑定允许我们在程序运行的过程中动态给class加上功能
class Student(object):
pass
#给实例绑定一个属性name
s = Student()
s.name = 'Michael'
print s.name
#还可以尝试给实例绑定一个方法:
def set_age(self, age):
self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s, Student) #给实例绑定一个方法
s.s... |
# Alexandra's program
import math
# import
ColumnCoins = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}
NumberXO = {}
orderOrder = []
for columns in range(6, -1, -1):
for rows in range(7):
orderOrder.append(columns + rows * 7)
print(orderOrder)
def write_grid(XOList):
'''prints the current playing grid'''
p... |
# Python Class 1548
# Lesson 12 Problem 1
# Author: peaches1210 (202437)
#Connect4#
#Lists & Dictionaries & variables
ColumnCoins = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}
PlaceValueXO = {}
ColumnToRow = []
anyOneWon = False
#FUNCTIONS
def write_grid(XsANDOs):
'''input: list of XO*'s
output: grid of Xs and Os'''... |
#Lists & Dictionaries
ColumnCoins = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}
PlaceValueXO = {}
ColumnToRow = []
#FUNCTIONS
def write_grid(XsANDOs):
for row in range(7):
for individual in range(7):
print(XsANDOs[(row*7) + individual] + ' ', end='')
print('\n')
#fill up ColumnToRow
for rowStar... |
#cherry pick vowels from word
def pick_vowels(word):
unorderedVowels = ''
vowelsConsonants = []
for letter in word:
if letter in 'aeiouy':
unorderedVowels += letter
word = word.replace(letter, '', 1)
vowelsConsonants.append(unorderedVowels)
vowelsConsonants.append(wo... |
# Python Class 1548
# Lesson 9 Problem 6
# Author: peaches1210 (202437)
import turtle
turtle.setup(800,600) # Change the width of the drawing to 800px and the height to 600px.
wn = turtle.Screen()
sammy = turtle.Turtle()
inFile = open('directions_turtle.txt', 'r')
lista = inFile.readlines()
for UPG in lista:
U... |
import pygame
from pygame.sprite import Sprite
from random import randint
class Pinata(Sprite):
"""A class to represent a single pinata."""
def __init__(self, ai_game):
"""Initialize the pinata and set its starting position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings... |
import unittest
from main import insere_dados
teste = insere_dados()
class MyTestCase(unittest.TestCase):
def testa_nome_vazio(self):
self.assertFalse(teste.Nome == "", "Nome em branco")
def testa_nome_inicia_com_maiuscula(self):
self.assertTrue(teste.Nome[0].isupper(), "Nome não inicia com... |
#面向对象编程
__author__='Fan Xin'
__date__='2019-06-17'
#定义类Student
class Student(object):
def __init__(self, name, score):
self.__name = name
# self.name = name
self.score = score
def print_score(self):
print(self.name, self.score)
def get_name(self):
return self.__nam... |
# This has to be executed only when you set up the beer-bot for the very first time.
import sqlite3
# create database
conn = sqlite3.connect('../beerbot_database.db')
# create a cursor
c = conn.cursor()
# create the table journal, where every transaction i stored
c.execute("""CREATE TABLE journal (
user_... |
name = input("Hello, what is your first name? : ").strip().capitalize()
eye_colour = input(f"{name} huh, what a lovely name! What colour are your eyes? : ").strip().lower()
hair_colour = input("Beautiful! What about the colour of your hair? : ").strip().lower()
age = int(input (f"Gorgeous! And finally {name},... |
__author__ = 'Hernan Y.Ke'
from itertools import compress
# 1. using list comprehension
arr = range(1,10)
print(x for x in list(arr) if x %2==0) #still fails.
pos = (x for x in list(arr) if x %2==0) #must add parentheses
for x in pos:
print(x)
# 2.using filter
def is_even(val):
try:
return v... |
__author__ = 'Hernan Y.Ke'
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta
#doing arithmetic
a= timedelta(days=2,hours=3) #using plural
b = timedelta(hours=1)
c=a+b
print(c.days,c.seconds,c.total_seconds(),c.seconds) #total_seconds: with day seconds: within day
n = datetim... |
__author__ = 'Hernan Y.Ke'
from collections import ChainMap
a = {
'A': 100,
'B': 10}
b={
'B': 20,
'D': 50
}
c = ChainMap(a,b) # Check first map first Do c['B']=10
print(list(c.keys())) # ABD
print(list(c.values())) #100 10 50
#del c['D'] #can not delete key in first map
#others. new_child mer... |
__author__ = 'Hernan Y.Ke'
#inplement __reversed__ to use reversed function
class Func:
def __init__(self,time):
self.time= time
def __iter__(self):
n = self.time
while n>0:
yield n
n-=1
def __reversed__(self):
n=1
while n<=self.time:
... |
__author__ = 'Hernan Y.Ke'
import itertools
def count(x):
while True:
yield x
x += 1
ct = count(0) # base case
for x in itertools.islice(ct, 5, 10): # memorize this syntax
print(x)
|
#-*-coding:UTF-8-*-
'''
Created on 2017年5月16日
@author: Ayumi Phoenix
Reinforcement learning maze example.
Red rectangle: explorer.
Black rectangles: hells [reward = -1].
Yellow bin circle: paradise [reward = +1].
All other states: ground [reward = 0].
This script is the main p... |
__author__ = 'Rolando'
##################################################
### Perkovic Intro to Python ###
#### CH 4: Text Data, Files, and exceptions ####
##### PG 95 CH 4 #####
##################################################
excuse = 'I\'m "sick"'
print(excuse)
poe... |
__author__ = 'Rolando'
#############################################
### Perkovic Intro to Python ###
#### CH 6: Containers and Randomness ####
##### PG 198 CH 6 Case Study #####
#############################################
import random
def shuffledeck():
"""
:return: shuffled d... |
def temperature(t):
'prints message based on temperature value t'
if t > 86:
print('It is hot!')
elif t > 32:
print('It is cool.')
else: # t <= 32
print('It is freezing!')
def sorted(lst):
'returns True if sequence lst is increasing, False otherwise'... |
def growthrates(n):
'prints values of below 3 functions for i = 1, ..., n'
print(' i i**2 i**3 2**i')
formatStr = '{0:2d} {1:6d} {2:6d} {3:6d}'
for i in range(2, n+1):
print(formatStr.format(i, i**2, i**3, 2**i))
def numChars(filename):
'returns the number of characters in file file... |
from tkinter import Tk, Button, LEFT, RIGHT
from time import strftime, localtime, gmtime
def greenwich():
'prints Greenwich day and time info'
time = strftime('Day: %d %b %Y\nTime: %H:%M:%S %p\n',
gmtime())
print('Greenwich time\n' + time)
def local():
'prints local day and time i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.