text
stringlengths
37
1.41M
import random ''' users and credentials array are used to store all the user objects and credential respectively ''' users=[] credentials=[] class User: ''' used to create an object containing username and password ''' def __init__(self, username, password): self.username=username sel...
""" author: xzshi19 date: 2019.08.28 Aim: learn python's built-in functions """ # abs(x) --return the absolute value of a number; a complex number --> it's magnitude # all(iterable) --return true if all elements of the iterable are true(or empty) def all(iterable): for element in iterable: if n...
__author__ = 'wenychan' """ Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended w...
__author__ = 'wenychan' from time import sleep from random import random from threading import Thread, local # One important thing that everybody seems to neglect # to mention is that writing threadLocal = threading.local() # at the global level is required. Calling threading.local() # within the worker function will...
myDic={'key1':'value1','key2':'value2',('1','2'):'value3'} print("key1's value is %s" % myDic['key1']) print("key2's value is %s" % myDic.get('key2')) print("('1','2')'s value is %s" % myDic.get(('1','2'))) #============================================================ # Adding a key/value pair myDic['key4'] = 'value4'...
intType=2; # integer floatType=3.123 # float floatType1=324.42E-3 # float complexType=5+7j # complex complexType1=complex(1,2) # complex print(complexType1.real, ',', complexType1.imag) #============================================================= str1='Quote me on this' # String with single quotation str2="What's y...
''' Created on Mar 11, 2014 @author: wenychan ''' # must manually add (object) here. Reason: super in ChildClass3 class ParentClass(object): # static variables public_static_var = 1 _protected_static_var = 2 # cannot be seen "from ParentClass import *" __private_static_var = 3 var = 23 # different...
try: a=1 b=0 c=a/b print(c) except ZeroDivisionError: print('Meet ZeroDivisionError...') except: print('Meet other exception...') else: print('No exception...') #================================================ try: s = '12' if len(s) > 3: raise Exception() except: ...
for i in range(1, 5): print(i) else: print("The for loop's step is 1") #====================================================== for i in range(1, 8, 2): print(i) else: print("The for loop's step is 2") #====================================================== for i in [1,2,3,54,67,89,321,1]: ...
shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] print('shoplist is', shoplist) print('mylist is', mylist) # notice that both shoplist and mylist both print( the same list without # the 'apple' confirming that they point to t...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, ...
%matplotlib inline from matplotlib import pyplot as plt import numpy as np # define activation function and its derivative def sigmoid(x): return 1/(1+np.exp(-x)) def sigmoid_p(x): return sigmoid(x)*(1-sigmoid(x)) T = np.linspace(-5,5,100) plt.plot(T,sigmoid(T),c='r') plt.plot(T,sigmoid_p(T),c='b') ## Assi...
#%% Tokenizers # On ppt 'Challenges of sentence tokenization' from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize # Sentence tokenizer text = "this's a sent tokenize test. this is sent two. is this sent three? sent 4 is cool! Now it is your turn." sent_tokenize_list = sent_tokenize(text) #...
import math from runners.helpful_fn import PrimeGen #http://en.wikipedia.org/wiki/Fermat%27s_little_theorem def p026(): print("Reciprocal cycles") prms = PrimeGen(1000) longest = 0 maxd = 0 digit = 0 for i in prms: cnt = 0 remain = 10%i limit = 1000 while(remain...
""" Problem 19 Counting Sundays --------------------------------- let Sunday = 0 1st Jan 1901 (Tuesday) = 2 """ def p019(): print("Counting Sundays") #days in each month days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = 2 suns = 0 #1901 > 2000 (100 years) fo...
number1 = input("Enter first number:") number2 = input("Enter second number: ") if number1 > number2: number1bigger = True else: number1bigger = False print ("number1bugger:", number1bigger)
def bfs(v_from, v_to, graph): visited = set() queue = [v_from] while len(queue) > 0: v = queue.pop(0) if v in visited: continue visited.add(v) neighbors = graph[v] queue.extend(neighbors) return v_to in visited def bfs_distance(v_from, v_to, grap...
from heapq import heappush, heappop def dijkstra(v_from, v_to, graph): visited = dict() priority_queue = [(0, v_from)] while len(priority_queue) > 0: distance, v = heappop(priority_queue) if v in visited: continue visited[v] = distance neighbors = graph[v] ...
def linearSearch(arr, tgt): for i in arr: if i == tgt: print("Present") return print("Not Present") def binarySearch(arr, tgt, s, e): if(s > e): print("Not Present") return else: mid = (s + e) // 2 if arr[mid] == tgt: print("P...
# coding: utf-8 """Create a mother class Character and the children classes Mcgyver and Guardien""" class Character: """Create a class Character with attribute the character, and his x,y position""" def __init__(self, character, pos_x, pos_y): """Initialize the character and his position""" ...
# 클래스 - 관련 정보와 정보의 조작 함수 (메소드)를 묶어서 관리 # balance = 8000 # # def deposit(money): # global balance # balance += money # # def inquire(): # print(f"잔액은 {balance}원 입니다.") # # deposit(1000) # inquire() # class 키워드로 정의 - 사용하기 위해서는 인스턴스를 생성한 후 사용, 클래스명은 대문자로 시작 # class Account: # def __init__(self, balance)...
# 튜플 - 불변 자료 집합, 콤마가 중요 # 튜플은 여러개의 값을 리턴 import time # def main(): # score = 88, 95, 70, 100, 99 # print(score) # # score = 88, # print(score) # # score = 88 # print(score) # # main() # def main(): # a, b = 12, 45 # print(a, b) # # a, b = b, a # print(a, b) # # main() # 튜플 활용...
integer = int(input("Enter number: ")) if integer % 2 == 1: print(integer,"is odd") else: print(integer,"is even")
import calendar month = int(input("Enter month: ")) year = int(input("Enter Year: ")) print("Number of days in the month: ",calendar.monthrange(year,month)[1])
def chords_theory(): theory = '''\n _______________________________________________________________________________________________________________________ Introduction : Chords are a combination of three or more notes. When three notes are combined they are called 'Triads' and four o...
from sys import stdin # Carlos Saul Arboleda - ADA - Camilo Rocha # se implementa conjuntos disjuntos y pero hay un problema con el accert no se alcanzo a corregir # El problema se discutio con Mario Bolanos y Andres Felipe Achury # Incompleto # luego se implemento Kruskal con la clase de conjuntos disjuntos class dfo...
# Exercise 1 # Exerise 2 class Bus: count= 0 # Creating two methods where yoU can change the color # Keeping track of busses created def __init__(self, driver, seats, color): self.driver = driver self.seats = seats self.color = color self.update_count() def change_of_colo...
#neural network with 3 layers of neurons import numpy as np; inputs = [ 1.0, 2.0, 3.0, 2.5 ] #no. of inputs given to a Neuron weights = [ [ 0.2, 0.8, -0.5, 1 ], [ 0.5, -0.9, 0.26, -0.5 ], [ -0.26, -0.27, 0.17, 0.87 ] ] #each list of weight is for a particular neuron biases = [ 2.0, 3....
import random #插入排序 #对于未排序的数据,在已排序的数组从后向前扫描,插入到合适的位置 #在排序的时候,需要将已排序的元素一个一个的向后挪位置,为新元素腾地方 #在python的实现中,可以通过交换的方式,跟冒泡的实现很像 #但是冒泡是一个数据跟其他所有的数据都进行比较 #而插入排序只是相邻的进行比较 def InsertionSort(L: list) -> list: length = len(L) for i in range(1, length): for j in range(i, 0, -1): if L[j] < L[j-1]: L[j], L[j-1] = L[j-1], L...
import math # Purpose of histogram equalization is to raise the contrast in an image # to produce a better quality image ''' function: summation input: 1. accumulated counts of the pixels 2. current pixel intensity (0-255) 3. min accumulated count 4. max accumulted count returns: normalized accumuate...
class Set: def __init__(self, value = []): # Constructor self.data = [] # Manages a list self.concat(value) def intersection(self, other): # other is any sequence res = [] # self is the subject for x in self.data: if x ...
import os import sys import logging def check_dir(name): logger = logging.getLogger(__name__) logger.debug("Checking '{}' if is a directory".format(name)) """Check if name is directory. If not, exit the program.""" if not os.path.isdir(name): logger.critical("{} is not a directory".format(n...
""" Added a store. The hero can now buy a tonic or a sword. A tonic will add 2 to the hero's health wherease a sword will add 2 power. """ import random import time class Character(object): def __init__(self): self.name = '<undefined>' self.health = 10 self.power = 5 self.coins = 20...
#!/usr/bin/env python # coding: utf-8 # ### Part 1 Data preparation and visualization # # 1. Read the dataset # 2. Delete all the rows containing the missing data. Imputation is not necessary. # 3. Encode the data where necessary. # 4. Visualize the columns and their pairs. # 5. Produce the correlation matrix to ...
class Team: member = 7 def working_hour(self): return self.day def all_working_hour(self): self.day = 7 return self.member * self.day @staticmethod def calculate(x, y): return x * y @classmethod def get_member(cls): return cls.member myTeam1 = Te...
import itertools a1 = list('pqr') a2 = list('ABCDE') a3 = list('5678') c1 = itertools.chain(a1, a2, a3) print type(c1) for c in c1: print c, print print "again..." for c in c1: print c, print c2 = itertools.chain(a1, a2, a3) l1 = [c for c in c2] for l in l1: print l, print "\nagain...\n" for l in l1: ...
from datetime import datetime now = datetime.now() print "now with repr:", repr(now) print "now with str:", str(now) print now print (now,) print "remember the comma", (now) print [now, ] print [str(now), ] print {now, } print {'key': now}
#test sort import sys D={'d':1,'c':2,'b':3,'a':4} print D K=list(D.keys()) print K K.sort() print K for key in K: print (key,'=>',D[key]) L=list(D.values()) print L
#Game Idea: Have people pick etween 1 and 4. Randomly generate a numer to determine # the height of each number's bar. After choosing a bar, have the bar animate upwards. #A bar that animates in an angle x = 50 while(self._running): f...
import random def guess(x): random_number = random.randint(1, x) guess = 0 while guess != random_number: guess = int(input(f'Guess the number between 1 and {x}: ')) print(guess) if guess < random_number: print('sorry guess again, too low') elif guess > r...
from functools import wraps def add(a, b): return a + b def print_function_name(func): @wraps(func) def logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return logging @print_function_name def square(x): return x * x def n...
# -*- coding: utf-8 -*- """ @author: asalkanovic1 """ # Load Libraries import pandas as pd from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.met...
""" Implement queue operations enqueue, dequeue, isEmpty, size and front. Queue should store integers. Queue size is initialized to 0 >>> que = Q() >>> que.size() 0 >>> que.empty() True Enqueuing increases size by one >>> que.enqueue(1) >>> que.size() 1 >>> que.empty() False >>> que.enqueue(2) >>> que.size() 2 Eleme...
class Song: '''This class describe song''' def __init__(self,thename,thelength,thejanr): self.name=thename self.length=thelength self.janr=thejanr jazz=Song('Blues',10,'jaz') rockandroll=Song('Elvis',25,'rock and roll') def stugel(song): if song.name[0]=='B' and song.length>=2 a...
import random class Chatbot: '''This class describe chatbot''' def __init__(self, theStandardAnswers, theQuestionAnswers): self.StandardAnswers = theStandardAnswers self.QuestionAnswers = theQuestionAnswers def answer(self, text): if '?' in text: index = random.randint(...
#Print Prime Numbers between 1 to 50 #This is a python code #Test Smart Commit n = 2 while (n<51): is_prime = True i=2 while (i<n-1): if n%i==0: is_prime = False break i = i+1 if (is_prime): print(n) n=n+1
"""How do you find the middle element of a singly linked list in one pass?""" from typing import Any from linked_list.linked_list_iter import LinkedList def get_middle_of_linked_list(linked_list: LinkedList) -> Any: """ Find the middle element of a singly linked list in one pass. :param linked_list: ...
myUniqueList = [] myLeftovers = [] def addTomyUniqueListList(item): if item in myUniqueList: addTomyLeftovers(item) return False else: myUniqueList.append(item) return True def addTomyLeftovers(item): myLeftovers.append(item) print(myUniqueList) print(addTomyUniqueListList(...
import numpy as np import pygame import sys import math blue = (0,0,255) black = (0,0,0) red = (255,0,0) yellow = (255,255,0) row_count = 6 column_count = 7 def create_board(): board = np.zeros((row_count,column_count)) return board def drop_color_coin(board, row, col, coin): board[row][col] = coin def is_valid...
class Solution: def hasPathSum(self, root, sum): if not root: return False def check(root, cur): if not root.left and not root.right: if root.val + cur == sum: return True else: return False l...
# This program should use a main function and another function named makelist as follows: # in main, generate a random integer that is greater than 5 and less than 13. # print this number on its own line. # call the makelist function with the random integer as sole argument. # inside the makelist function: # make ...
#!/usr/bin/env python # _*_coding:utf-8 _*_ #@Time    :2019/5/7 0007 下午 3:32 #@Author  :喜欢二福的沧月君(necydcy@gmail.com) #@FileName: 2-1.py #@Software: PyCharm class People: """People类,属性有:姓名、性别、年龄""" def __init__(self, name,sex,age): self.name = name self.sex = sex self.age ...
#Buttons and Grids #Grid system for placement of widgets. Better than pack import tkinter root = tkinter.Tk() root.title('Buttons and Grids') root.geometry('500x500') root.resizable(0,0) name_button = tkinter.Button(root, text='Name') name_button.grid(row=0, column=0) #Rows and columns are defined on the fly time_b...
# Radio Button import tkinter from tkinter import IntVar, StringVar #These are used to track the radio button clicks # Define window root = tkinter.Tk() root.config(bg='#B2D2A4') root.title('Radio Buttons') root.geometry('500x500') img = tkinter.PhotoImage(file='D:/All_Git_Projects/Udemy_Art_of_Doing/Basics/shield.png...
#Entries for user input and functions import tkinter root = tkinter.Tk() root.title('Entries and Functions') root.geometry('500x500') root.config(bg='#FFA500') root.resizable(0,0) #Adding window icon img = tkinter.PhotoImage(file="D:/All_Git_Projects/Udemy_Art_of_Doing/Basics/shield.png") root.tk.call('wm', 'iconphot...
__author__ = 'farshadfahimi' class TitleRanking(): def __init__(self, search_string): self.search_terms = search_string.split(' ') self.search_string_length = len(search_string) def rank_title(self, title): # title ranking: the smaller the ranking it means that it is a better match ...
# V1 of Blackjack game - currently only gets user cards import random def blackjack(): cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 11] card_list = [] user_amount = 0 while True: user_choice = input("Card? ") if user_choice == "y": card_random = random.choice(card...
#! /usr/bin/env python import sys sys.stdin.readline() case_number = 1 for line in sys.stdin.readlines(): print "Case #%d:" % (case_number), for word in reversed(line.split()): print word, case_number = case_number + 1 print ''
from itertools import permutations import numpy def payment(coins): """ Calculate the total payment given an array of coins. """ return coins[0] + abs(numpy.diff(coins)).sum() def payment_permutations(n): """ Return all the possible coing permutations for a bag of coins of size `n`. """...
# Barbara Carline - # Bruno Henrique - # William Castro - 571644 # Arquivo que executa as classes disponiveis do compilador python # Importando analisadores from AnalisadorLexico import AnalisadorLexico from tabulate import tabulate import json # Realizando etapa de analise lexica lexico = AnalisadorLexico() fra...
from abc import ABC, abstractmethod from random import randint, choice import lib.parametros as pm # CHECK PARAMETERS IN PARAMETROS.PY # THEY MUST BE USED IN HERE (CHECK randints) class Vehiculo(ABC): """ Vehicle modeling class. Inherited by more specific subclasses (type of vehicle): - Automo...
class Card_Counter(): '''Class implementing various card counting strategies as well as enabling custom strategy input. Count will be updated every time a new card is dealt in the BlackJack class''' def __init__(self, blackjack_game, total_decks, strategy_name=None, custom_strategy...
from Tkinter import * import tkFileDialog import sys import os ''' will hopefully be a list making program should diplay checkboxes next to lines of text and allow them to be checked ''' class CheckList( Frame ): def __init__( self, parent, **options ): if options.has_key('rows'): self.rownumber = int(option...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ########## 匿名函数 ########### # 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便 # 在Python中,对匿名函数提供了有限支持 # 关键字lambda表示匿名函数,冒号前面的x表示函数参数 # 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果 print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) # 因为函数没有名字,不必担心函数名冲突。 # 此外,匿名函数也是一个函...
# ############## 输出 ############### print('hello word') # 打印多个字符串 print('The quick brown fox', 'jumps over', 'the lazy dog') # 打印数字 print(100) print('100 + 200 =', 100 + 200) # ############## 输入 ############### name = input('please enter your name') print('your name is ', name)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'test module' __author__ = 'ycn' # 第1行注释可以让这个hello.py文件直接在Unix/Linux/Mac上运行,第2行注释表示.py文件本身使用标准UTF-8编码; # 第4行是一个字符串,表示模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释; # 第6行使用__author__变量把作者写进去 # Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用 # 我们以内建的sys模块为例,编写一个hello的模块 import sys # 导入sys模块...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ########## 函数参数 ########### # 定义一个求q的n方函数 # 设置默认参数时,有几点要注意: # 一是必选参数在前,默认参数在后,否则Python的解释器会报错 # 二是如何设置默认参数,当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。 # 使用默认参数有什么好处?最大的好处是能降低调用函数的难度 def power(q, n=2): s = 1 while n > 0: n = n - 1 s = s * ...
import matplotlib.pyplot as plt cartas = [11, 18, 3, 1, 16, 12, 6, 19, 5, 0, 14, 4, 17, 9, 13, 7, 10, 15, 2, 8] # lista das cartas print("Lista original", cartas) # mostra escrito Lista original e depois mostra a lista de cartas inicial plt.figure() x = range (0, 20) plt.plot(x, cartas, 'ok') plt.title ('range-x-cartas...
class ObjectSize: """ Representing object size. Is able to convert relative sizes into real sizes. """ def __init__(self, w, h, info=None): """ :param w: object width :param h: object height :param info: InputInfo instance """ self.width = w sel...
import numpy as np from primitives import constants from primitives.coordinates import Coordinates from primitives.line import Line class VanishingPointError(Exception): pass class VanishingPoint: """ Class representing vanishing points. In most cases it is a point in scene (or outside the scene) ...
import re isValid = True errorMessage = "" def containsNumber(name): return any(char.isdigit() for char in name) def validateSingleQuotes(subStr): print("current substring: ", subStr) count = 0 singleQuotesFlag = False for char in subStr: count = count + 1 if (char...
import time import random value = int(input("Password length: ")) print("\n\nPossible symbols: \n1. only letters and numbers \n2. other symbols \n") types = int(input()) symbols = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '0',11: 'a', 12: 'b', 13: 'c', 14: 'd', 15: 'e', 16: 'f', 17: ...
""" Given an array A of n elements, and a permutation P, apply P to A. Do not use extra space. """ def apply_permutation(A, P): for i in range(len(A)): j = i while P[j] >= 0: A[i], A[P[j]] = A[P[j]], A[i] tmp = P[j] P[j] -= len(P) j = tmp P[:] = [...
""" Given an array of stock prices, compute the maximum profit that can be made by buying and selling a share at most twice. """ def buy_and_sell_stock_twice(prices): max_total_profit = 0 min_price_so_far = float('inf') first_buy_sell_profits = [0] * len(prices) # find first buy/sell profit going forwa...
import tkinter from tkinter import Frame from tkinter import Label from tkinter import Entry from tkinter import StringVar from tkinter import messagebox # so we can use sin, cos, pi, etc in our spreadsheet import math # we use this to make a deep copy of a dictionary import copy import dependencies class Cell(Label...
# -*- coding: utf-8 -*- """ Laplace.pyプログラム ラプラス方程式の解法プログラム 反復法によりラプラス方程式を解く """ # モジュールのインポート import math # 定数 LIMIT = 1000 # 反復回数の上限 N = 101 # x軸方向の分割数 M = 101 # y軸方向の分割数 #下請け関数の定義 # iteration()関数 def iteration(u): """1回分の反復計算""" u_next = [[0 for i in range(N)] for j in range(M)] #次ステップのuij # ...
# _*_ coding: utf-8 _*_ """ bidec.pyプログラム 2分法による方程式の解法プログラム 使い方  """ # グローバル変数 a = 2 # f(x)=X*X-a LIMIT = 1e-20 #終了条件 # 下請け関数の定義 # f()関数 def f(x): """関数値の計算""" return x * x - a # f()関数の終わり # メイン実行部 # 初期設定 xp = float(input("xpを入力してください:")) xn = float(input("xnを入力してください:")) # 繰り返し処理 while (xp...
# coding: utf-8 # All the recommandation logic and algorithms goes here from random import choice from app.User import User class Recommendation: def __init__(self, movielens): # Dictionary of movies # The structure of a movie is the following: # * id (which is the movie number, y...
x = "Hello world" #duomenu tipas String y = 42 #duomenu tipas Integer z = 55 #Integer a = 4.58 #Float b = True #Boolean c = None #None c = int(input("Iveskite skaiciu")) #d = int(input("Iveskite skaiciu 2")) print(c + d) if c >= 10 and c <= 50: print("C yra daugiau negu 10 ir maziau nei 50") elif c < 10: ...
def calculator(number1, number2, operator): '''Checks if operator token given is valid, and operates on the numbers based on given argument''' opers = ['+', '-', '*', '/', '//', '**'] if operator in opers: if operator==opers[0]: return float(number1+number2) if operator==opers[1...
# Link: Deep Learning with Python, TensorFlow, and Keras tutorial (https://www.youtube.com/watch?v=wQ8BIBpya2k) import tensorflow as tf import matplotlib.pyplot as plt import numpy as np mnist = tf.keras.datasets.mnist # 28x28 of hand-written digits 0-9 (x_train, y_train), (x_test, y_test) = mnist.load_data() # unpac...
# Faça um Programa que leia uma lista de 10 caracteres, e diga quantas consoantes foram lidas. # Imprima as consoantes. lista = ['t', 'a', 's', 's', 'i', 'a', 'l', 'a', 'i', 's'] vogais = ['a', 'e', 'i', 'o', 'u'] totConsoantes = 0 consoantes = [] for i in range(0, 10): if lista[i] not in vogais: consoant...
# Faça um Programa que leia 4 notas, mostre as notas e a média na tela. notas = [9.0, 7.5, 8.5, 10.0] media = sum(notas)/len(notas) print("Notas: ", notas) print("Media: ", media) # Pedindo a informação do usuário listaNotas = [] media = 0 print ('Informe as 4 notas') for i in range(4): listaNotas.append(float(...
class Student: # defining the properties ID = None GPA = None # creating an object of the Student class Peter = Student() # assigning values to properties of Peter Peter.ID = 3789 Peter.GPA = 3.5 # create a new attribute for Peter Peter.department = "Computer Science" # Create another Student object Jo...
class User: def __init__(self, username = None): self.__username = username # defined username as a private property def setUsername(self, x): self.__username = x def getUsername(self): return self.__username Steve = User('steve1') print('Before Setting: ', Steve.getUsername()) S...
import pandas as pd df = pd.read_excel('GSoC.xlsx') df1 = pd.DataFrame() cols = [] skills = ['YOUR SKILLS'] for col in df.columns: col_list = [] col_list = df[col].tolist() for skill in skills: if skill in col_list: print(col) cols.append(col)) df1 = df[cols] df1.t...
# Student Name: Bingqi Tang import time import random import matplotlib.pyplot as plt # define the attribute of each element in the Linked List class Node: def __init__(self, data): self.data = data self.next = None # define the overall structure and functions of the Linked List class Linked_List...
import datetime def get_all_dates(weeks=0): """Returns a list of all of the dates for the next week, starting with the most recent coming Sunday. Pass in direction of 'past or 'future' and how many weeks you'd like to move forward or backward.""" if weeks == 'favicon.ico': print('Fav!') ...
# 值传递:传递的是不可变类型 # string tuple number 是不可变的类型 def func1(num): print(id(num)) num = 10 print(id(num)) temp = 20 print(id(temp)) func1(temp) print(temp) # 引用传递:传递的可变类型 # list dict set 是可变的 def func2(lis): lis[0] = 100 li = [1,2,3,4,5] func2(li) print(li) a = 10 b = 10 b = 40 print(id(a), id(b)) c = 20 d = 3...
#encoding: UTF-8 #Autor: Adrian Tellez #Programas con fo from math import * from Graphics import * import time #Ejercicio 1(a).- Una funcion que dibuje cuadrados y circulos def dibujarCuadrados(): v = Window ("Cuadrados y Circulos", 400, 400) a=0 b=400 c=200 for f in range(20): a += 10 ...
def sum67(nums): tot = 0 found = False for i in range(len(nums)): if nums[i] == 6: found = True if not found: tot += nums[i] if nums[i] == 7 and found: found = False return tot
def near_ten(num): if num % 10 <=2: return True elif num % 10 >= 8 and num % 10 <=10: return True else: return False
# -*- coding: utf-8 -*- """ Created on Wed Aug 5 09:57:42 2020 @author: USER """ for i in range(1,10): for j in range(1,10): print(i, "x", j, "=", i*j)
import board_logic import random import sys class Ai_agent(): """This class holds the code to ai gameplay decision.""" # Get an instance of board logic class bl = board_logic.Board_logic() def __init__(self): pass def apply_move(self, board_state, move, side): # Method to apply ...
# 题目:输入某年某月某日,判断这一天是这一年的第几天? # 程序分析:以3月5日为例,应该先把前两个月的加起来, # 然后再加上5天即本年的第几天,特殊情况, # 闰年且输入月份大于2时需考虑多加一天: year = int(input('年份:\n')) month = int(input('月份:\n')) day = int(input('天数:\n')) summary = 0 months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334) if 0 < month <= 12: summary = months[month - 1] else:...
BULLET_POINTS = [ "a", "b", "c", "d", "e", "f" ] def number2letter(number): if number > len(BULLET_POINTS): raise Exception("Number is too high for available bullet points") return BULLET_POINTS[number - 1] def letter2number(letter): if letter not in BULLET_POINTS: return None lett...
#!/usr/bin/env python import os import argparse # https://stackoverflow.com/questions/287871/print-in-terminal-with-colors class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\0...
def sumDigits(n): print(n) if n < 10: return n else: return n%10 + sumDigits(n//10) no =eval(input("enter the number")) sum1=sumDigits(no) print(sum1,"is the sum")
# def binaryToHex(bv): # # for bv>0: # # dig=bv%10 + dig # # count=count+1 # # if count>=4: # # bintodec() # count=0 # for i in range(bv,0,-1): # p=bv[i] # dig = int(p)*10+dig # count=count+1 # tot=bv[i]*2**count # if tot >=10 or tot<17...
# def dectohex(s): # if s>=10: # c=s-10+ord('A') # print(s," this c",c) # print(chr(c)) # return chr(c) # else: # return s # def bintohex(bv): # print(bv+1) # arr=[] # i=0 # arr.append(0) # arr.pop() # while(bv>0): # arr.append(bv%10) # ...