text
stringlengths
37
1.41M
#!/usr/bin/env python #-*- coding: utf-8 -*- def my_count(s, ch): c = 0 for i in s: if i == ch: c += 1 return c def reverse(s): """ >>> reverse('happy') 'yppah' >>> reverse('Python') 'nohtyP' >>> reverse("") '' >>> reverse("P") 'P' ...
# Print to canvas ################################################### # Student should add code where relevant to the following. import simplegui # Draw handler def draw(canvas): canvas.draw_text("It works!",[120, 112], 48, "Red") # Create frame and assign callbacks to event handlers frame = ...
#Realizar un programa que lea cuatro valores numéricos e informar su suma y promedio num1 = int(input("Digitar el primer numero: ")) num2 = int(input("Digitar el segundo numero: ")) num3 = int(input("Digitar el tercero numero: ")) num4 = int(input("Digitar el cuarto numero: ")) suma = num1 + num2 + num3 + num4 promed...
#Calcular el sueldo mensual de un operario conociendo la cantidad de horas trabajadas y el valor por hora valorHora = int(input("Digite el valor por hora del operario: ")) horaTrabajada = int(input("Digite las horas trabajadas: ")) sueldo = valorHora * horaTrabajada print("El sueldo del trabajaor es: ") print(sueldo...
scores = [] done = False while not done: score = int(input("Enter a score: ")) if score < 0: done = True elif score > 100: print("Invalid score... re-enter") else: scores.append(score) print("---------------------------------") print("Number of scores: %d" %len(scores)) scores =...
## Maximum values out of list def maxValue( vals ): if len(vals) == 1: return vals[0] else: if vals[0] > vals[-1]: return maxValue(vals[:-1]) else: return maxValue(vals[1:])
# Decimal to Binary Conversion # Juhwan Park (3917664) Lab sec 5 num = int(input('Enter an integer value: ')) binary_backward = '' while num < 0: print('Input must be greater or equal to zero!') num = int(input('Enter an integer value: ')) if num == 0: print('Base-2 equivalent: 0') else: while num > ...
# Selection Sort import random n = int(input('Enter the number of elements you want: ')) lst = list(range(n)) random.shuffle(lst) print(lst) m = 0 x = m + 1 while m != len(lst) - 1: while x < len(lst) and lst[m] < lst[x]: x += 1 if x < len(lst): lst[m], lst[x] = lst[x], lst[m] x += ...
## Warm-up 2 filename = input("Enter a filename you want to open: ").lower() file = open(filename, 'r') maximum = -2001 for i in file: i = i.strip().split(',') j = float(i[1]) if j > maximum: maximum = j print(maximum) file.close() file = open(filename, 'r') minimum = 2001 for k in file: k = k...
## Summary Statistics ## Juhwan Park (3917664) ## Constructing list scores = [] i = 0 done = False while not done: score = int(input('Enter a score: ')) if score < 0: done = True elif score > 100: print('Invalid score... re-enter') elif 0<= score <= 100: scores.append(score) ...
a = int(input()) b = int(input()) indeks = a while indeks <= b: if indeks%2 == 0: print(indeks) indeks += 1 for a in range(b): if a%2 == 0: print(a)
### PyBank/main.py ### ## Imports ## import os import csv from statistics import mean # Opening the csv: budget_data.csv budget_path = os.path.join("./", "Resources/", "budget_data.csv") with open(budget_path) as budget_file: # open file as csv with csv.reader budget_csv = csv.reader(budget_file) ...
# 使用input函数获取一个标准输入的字符串,赋值给变量temp。另外,变量的命名可以包括字母、数字、下划线,但是不能以数字开头。 temp = input("请输入一个数字:") # 使用int函数将字符串类型的变量temp转换为整型,如果不转的话,“if temp == 9:”就要换成“if temp == "9":”,因为:9 不等于 "9" i = int(temp) # 做if判断,没有括号、以冒号结尾 if i == 9: # 打印输出,注意缩进,很重要。针对字符串,可以用双引号括起来,也可以用单引号括起来,但不可以一边单引号、一边双引号 print('猜对了') # else,以冒号结尾 else: ...
import sys per=input("enter your percentage") if per>=80: print("first division honors") elif per>=60: print("first division") elif per>=50: print("second division") elif per>=40: print("third division ") else: print"fail"
# import threading import time ## ############################################################ # Meta-resource -- in reality there is some resource being # updated and _then_ the sequence (seq) counter is # semi-atomically updated. # # Assumption: a SINGLE updating thread. # class Resource(object): def __init_...
"""Homework 2.1. Analyze text. """ import string from typing import List def get_longest_diverse_words(file_path: str) -> List[str]: """Find 10 longest words with unique chars. Args: file_path: file to be analyzed directory Returns: max_words. list of 10 longest words """ with open(fil...
"""Homework 8.1.""" from typing import Any, Union class KeyValueStorage: """Class create object of storage, and we can get attributes of storage through . and [].""" def __init__(self, filepath: str) -> None: self.dic = {} with open(filepath, "r") as f: text = f.read() for...
"""Homework 4.4. FizzBuzz numbers. """ import doctest from typing import List def fizzbuzz(n: int) -> List[str]: r"""Get fizzbuzz numbers. Args: n: number up to get fizzbuzz numbers Returns: list of fizzbuzz up to n - Install Python 3.8 (https://www.python.org/downloads/) - Install pyt...
"""Homework 1.5. Given a list of integers numbers "nums". You need to find a sub-array with length less equal to "k", with maximal sum. The written function should return the sum of this sub-array. """ from typing import List def find_maximal_subarray_sum(nums: List[int], k: int) -> int: """Find maximal subarray...
import nmap def port_scanner(ports): nm = nmap.PortScanner() # print(nm.scan(ports, '21-1000')) nm.scan(ports, '21-1000') print(ports) print(nm.all_hosts()) for host_names in nm.all_hosts(): print(ports) ports = nm[host_names].get('tcp') print(ports) write_to_fi...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(ne...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: hbasriaykol import pandas as pd import numpy as np datas = pd.read_csv("/your_data_address") data = datas.iloc[:,:].values from sklearn.impute import SimpleImputer imputer = SimpleImputer() data[:,1:6] = imputer.fit_transform(data[:,1:6]) #SimpleI...
print("hola, Ingrese su nombre") nombre = input("su nombre:") if nombre == "George": print("Hola, George") else: print("Hola, desconocido")
# Faça uma pergunta e o programa te dará a resposta import random class decidaPorMim: def __init__(self): self.respostas = [ ['Faça isso com certeza!'], ['Acho que vc deveria pensar no que está dizendo'], ['Tem coisas que vc precisa deixar rolar'], ['Se tiver com medo, vá com medo mesmo']...
#!/usr/bin/python import math # Head ends here def next_move(posr, posc, board): if board[posr][posc] == 'd': print("CLEAN") return else: mdist = 0; shortest = 25; for i in range(0,5): for j in range(0,5): if board[i][j] == 'd': ...
import random class Matrix: def __init__(self,r,c): self.rows = r self.cols = c self.data = [] for i in range(r): self.data.append([]) for j in range(c): self.data[i].append(0) def random(self): for i in range(self.rows): ...
# header file imported from bs4 import BeautifulSoup from selenium import webdriver # path = path of the chrome drive from the folder and r is raw file path= r"C:\\Users\\Jothi\\Desktop\\Mukilan\\chromedriver\\chromedriver.exe" driver = webdriver.Chrome(executable_path = path) # creating a file name file = "Details.c...
from Stacks import StackByLList as Stack class BSTMap: def __init__(self): self.__root = None self.__size = 0 def __len__(self): return self.__size def __iter__(self): return _BSTMapIterator(self.__root) def __contains__(self, key): return self._search(self._...
from Data_Structures.Queues import QueueByLList as Queue class ExpressionTree: def __init__(self, exp_str): self._expTree = None self._build_tree(exp_str) def evaluate(self, var_map): return self._eval_tree(self._expTree, var_map) def __str__(self): return self._build_str...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/7/30 16:10 # 文件名称 : class_test.PY # 开发工具 : PyCharm # #1) # class Restaurant(): # # def __init__(self,restaurant_name,cuisine_type): # self.name = restaurant_name # self.type = cuisine_type # # def describe_restaurant(self): #...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/8/6 11:42 # 文件名称 : deque.PY # 开发工具 : PyCharm from collections import deque dq = deque(['a','b','c']) dq.append('x') dq.appendleft('y') print(dq) d = deque('ghi') for elem in d : print(elem.upper()) print("*" * 20) d.append('j') d.appendlef...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/7/17 17:33 # 文件名称 : day03HomeWork.PY # 开发工具 : PyCharm #1 # #1) # if __name__ == "__main__": # score = [] # # #2) # if __name__ == "__main__": # score.append(68) # score.append(87) # score.append(92) # score.append(100) # s...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/9/4 13:47 # 文件名称 : pandasTest.PY # 开发工具 : PyCharm import pandas as pd df = pd.Series([1,2,3,4]) print(df) print(df[3]) df[4] = 5 df[5] = 10,11 print(df)
# _*_ coding : UTF-8 _*_ # 开发人员 : longyh # 开发时间 : 2019/8/8 15:54 # 文件名称 : singletonDemo1.PY # 开发工具 : PyCharm def singleton(cls): instance = {} def getInstance(*args, **kwargs): if (cls not in instance) : instance[cls] = cls(*args, **kwargs) return instance[cls] ret...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/7/22 16:33 # 文件名称 : regularExpression.PY # 开发工具 : PyCharm import re #替换字符串 pattern = r"1[34578]\d{9}" string = "中奖号码为:86538712 联系电话为:13699973788" result = re.sub(pattern,"13833331111",string) print(result) string = "life is shrot,i need python" pa...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/8/1 10:51 # 文件名称 : class_reflect.PY # 开发工具 : PyCharm # #反射 hasattr getattr # # def not_define(self): # print("我也很迷茫啊。。。") # # class Person(): # def __init__(self,name): # self.name = name # # def walk(self): # print("%...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/7/19 13:48 # 文件名称 : guessNumber.PY # 开发工具 : PyCharm #猜数字 import random if __name__ == "__main__" : total = [] print("开始游戏,按Q退出") while True : if(total) : print("开始第%d局游戏。"%(len(total) + 1)) else: ...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/8/1 15:04 # 文件名称 : class_CitysInfo.PY # 开发工具 : PyCharm city_info = {} class CitysInfo: def __init__(self,name): self.citys = dict() self.name = name def add_city(self,city): self.citys[self.name] = city def...
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/7/30 11:36 # 文件名称 : def_demo.PY # 开发工具 : PyCharm #生成器 -- 就是根据需要生成数据,而不是一股脑的把数据给你。 # aLst = [x for x in range(10)] # # if __name__ == '__main__': # g = (x for x in range(10)) # # while True : # print(g.__next__()) #斐波拉契数列 --- 兔子...
usr = int(input("Enter a number ")) if usr % 2 == 0: print("Its even") else: print("Its odd")
""" A collection of essential utilities and sometimes just single powerful functions""" def parity1(x): """ Find the parity of a given number x The parity is the oddness or evenness of a number a number with an odd number of bits set 1 has odd parity and the function outputs 1 while even number of ...
class ListNode: def __init__(self, data=0, next_node=None): self.data = data self.next = next_node def search_list(L, key): while L and L.data != key: L = L.next # if key was not present in the list, L will have become null return L def insert_after(node, new_node): ...
import csv def read_csv(): filename = "Task_Training_Data .csv" fields = [] rows = {} with open(filename, 'r') as csv_file: csv_reader = csv.reader(csv_file) fields = next(csv_reader) for row in csv_reader: # print("[Name,Email]:", row[:2]) ...
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ d = dict() u = set() _str = str.split(' ') if len(pattern) != len(_str): return False for i in range(len(pat...
def room(): #"rooms" are written as functions, so that we can send the user to a previously visited room, without copy-pasting the whold thing. trapped = True #makes the variable we will use to end our while loops while trapped: print 'You wake up in a strange room. There is a mirror, a table and a win...
from math import sin, cos, tan, atan, radians ''' /** * * Terceira parte: Cálculo de vf e vr * ? r = rr (Raio da roda traseira) * ? alpha = Inclinação do terreno com a horizontal, em graus * ? theta = Ângulo da força trativa P medido em relação à horizontal * ? y = Distância vertical do ponto onde se conecta o implemen...
# 容器序列: tuple, list, deque 可以放置任意类型的序列 # 扁平序列: str, bytes, bytearray, array.array 只能放置同一类型的数据 # 可变序列: list, deque, bytearray, array # 不可变序列: tuple, str, bytes mylist = [] mylist.append(1) mylist.append("a") import _collections_abc from collections import abc # + # 只能+list a = [1, 2] c = a + [3, 4] print(c) # += 可以是...
# gil global interpreter Lock 全局解释器锁 # Python中一个线程对应于c语言中的一个线程, #gil使得,同一时刻只有一个线程运行在一个cpu上执行字节码,无法将多个线程映射到多个cpu上执行 # gil 会根据执行的字节码行数以及时间片释放gil, gil在遇到io操作的时候主动释放 # import dis import threading # def add(a): # a = a +1 # return a # print(dis.dis(add)) total = 0 def add(): global total for i in range(10...
# Hint: # 1. While your solution must handle the case for Web(size=123, degree=5) in # the test script, you may want to use different size and degree settings # for faster tests and for better test coverage. import time from crawler import WebCrawler from web import Web size = 1000 degree = 10 web = Web(...
import zbar from PIL import Image import cv2 import purchase_parser def read_qrcode(capture): # Breaks down the video into frames ret, frame = capture.read() # Displays the current frame cv2.imshow('Current', frame) # Converts image to grayscale. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ...
WORD_RE = "[^\W\d_]+" ASCII_RE = "[\x00-\x7F]" from nltk.corpus import stopwords rx = re.compile(WORD_RE, re.UNICODE) filterre = re.compile(ASCII_RE, re.UNICODE) # extract tokens tokens = rx.findall(text) # filter by contains ascii characters contains_ascii = filter(lambda s: bool(filterre.search(s)), tokens) tokens ...
from core import Object class Sphere(Object): def __init__(self, pos, radius): super().__init__(pos) self.radius = radius self.max_offset = radius def __contains__(self, point): return (self.pos - point).magnitude() < self.radius def __str__(self): return f"Sphere ...
""" Contract exceptions are raised when either the input or output contract is violated by data that pipes in or out. """ class InputContractException(Exception): """ Exception raised when the input contract is broken. """ def __init__(self, errors, contracts): """ Initialize the exc...
from ludecomp.lu import LU def solve(A, b, pivoting='partial'): """ Solves the linear system of equations Ax = b where A is well-determined. Concretely, uses PLU decomposition of A followed by forward and back substitution to solve for x. Params ------ - A: a numpy array of shape...
# Computes the grade level comprehension for inputted text from cs50 import get_string def main(): # Get input text from user text = get_string("Text: ") # Calculate and print reading level L = (100.0 * get_letter_count(text)) / get_word_count(text) S = (100.0 * get_sentence_count(text...
# In[11]: ## Programming Question 3 print("YEAH G") import pandas as pd import numpy as np import matplotlib.pyplot as plt print("YEAH G") from sklearn import linear_model #from sklearn import datasets ## imports datasets from scikit-learn #data = datasets.load_boston() ## loads Boston dataset from dataset...
""" Created on Tue Oct 6 15:17:59 2020 @author: MussaYousef """ ## Q1 import csv # imports the csv module import sys # imports the sys module f = open('TB_burden_countries_2014-09-29.csv') # opens the csv file for row in csv.reader(f): rowCount += 1 print ('There are', rowCount , 'rows in this datas...
import numpy as np def relu(x): return np.maximum(0,x) """ import matplotlib.pyplot as plt from step_function import step_function from sigmoid import sigmoid x=np.arange(-5.0,5.0,0.1) plt.plot(x,step_function(x),x,sigmoid(x),x,relu(x)) plt.ylim(-0.1,1.1) plt.show() """
import pandas as pd def main(): # File Location of file imported from Fluentcards.com file_location = input("Where is the file B?" + " ") file_tsv = file_location #file_tsv = "/Users/glenfordnunez/Downloads/La Fiesta del Chivo (Spanish Edition)_basic_2_21_2021.tsv" df = pd.read_csv(file_tsv, sep='\t') def c...
''' Numbers with non-decreasing digits ''' N = int(input().strip()) i = N while i > 0: digits = list(str(i)) if digits == sorted(digits): print(i) break i -= 1 else: print(i)
("\tเลือกเมนูเพื่อทำรายการ") print("\t############################################") print("\t กด 1 เลือกเหมาจ่าย") print("\t กด 2 เลือกจ่ายเพื่ม") x=int(input(" ")) y=int(input("กรุณาเลือกระยะทาง : ")) if x==1: if y >= 25 : print("ค่าใช้จ่ายทั้งหมด 55 บาท") else : print("ค่าใช้จ่ายทั้งหมด 25 บา...
def run(self, N, M): # # Write your code below; return type and arguments should be according to the problem's requirements # x = "" for i in range(N, M+1): if (i % 3 == 0 and i % 5 == 0): x = x + "FizzBuzz," else: if (i % 3 == 0): x = x + "Fizz," else: if (i % 5 == 0): x = ...
# step 2-2. collection: list / tuple / dictionary /set # unknown concept # tuple: can't change item # set: unordered, distincted # minus index a = [1, 2, 3, 4, 5] print(a[-1], a[-2], a[-3]) print(a[0], a[1], a[2]) # slice # 끝번호는 포함되지 않는다 print(a[0:2]) print(a[0:3]) # merge / concat a = [1, 22, 333] b = [7, 8] prin...
l=[] for x in range(1,11): l.append(x*x) print(l) print("*"*50) a=[x*x for x in range(1,11)] print(a)
#定义一个列表 names=["niui","niuiss","niuiasas","nsiajsia"] print(names) #使用append加入一个数据到原来的列表的最后 names.append("shabi") print(names) #或者使用insert添加内容 names.insert(2,"FBI") print(names) #################上面的运行效果如下############################### # ['niui', 'niuiss', 'niuiasas', 'nsiajsia'] # ['niui', 'niuiss', 'niuiasas', ...
num=int(input("请输入1-7表示星期几")) if num==1: print("是星期一") elif num==2: print("是星期二") elif num==3: print("是星期三") elif num==4: print("是星期四") elif num==5: print("是星期五") elif num==6: print("是星期六") elif num==7: print("是星期日") else: print("你他妈的是傻逼吧,让你输入1-7,你输得啥玩意?")
import numpy as np import matplotlib.pyplot as plt X = np.array([0,1,2,3,4,5,6,7,8,9]) Y = np.array([1,3,2,5,7,8,8,9,10,12]) X_bar = np.mean(X) Y_bar = np.mean(Y) # Determination of beta1_hat num = sum((X-X_bar)*(Y-Y_bar).T) den = sum(pow((X-X_bar),2)) beta1_hat = num/den print(beta1_hat) # Determi...
A = [5, 10, 15, 20, 25] print(A) new_list = [A[0],A[-1]] print(new_list)
""" + - * / divide as float // divide to int % left from division divmod(a,b) - return // , % ** stepen math.sqrt() koren floor() Decimal() """ ''' print(divmod(15,4)) def sum_of_numbers(a): summa = 0 while a >0: a, x = divmod(a,10) summa+=x print(summa) return summ...
list1 = [7, 5, -8, 9, 6, 3, 10, 1] def bubbleSort(list1): for i in range(0, len(list1)-1): for j in range(0, len(list1)-1-i): if list1[j] > list1[j+1]: list1[j], list1[j+1] = list1[j+1], list1[j] return list1 print(bubbleSort(list1))
#!/bin/python3 import math import os import random import re import sys def processJumps(c, i, jump_count): possible_jumps = c[i:i+3] print(possible_jumps, len(possible_jumps), jump_count) if (len(possible_jumps) == 1): return jump_count elif (len(possible_jumps) == 2): jump_count += ...
# Create a login project # if the user has failed 3 times, program should say access denied # if the use is successful, the prompt should say ACCESS GRANTED import login_user user_1 = login_user.User("bingus", "Password1") user_2 = login_user.User("dingus", "Password2") users = [user_1, user_2] limit_attempts = 3 is...
# Exercise 10 tab = int(input("I want the multiplication table from the number: ")) print(f"Mutiplication table of: {tab} \n") for c in range(0, 10): c += 1 print(tab, "X", c, "=", tab * c)
# Exercise 13 price = float(input("How much does it cost? ")) new_price = price - (0.05 * price) print(f"The new price with 5% discount is {new_price}")
# Exercise 20 - Element Search ''' Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and another number. The function decides whether or not the given number is inside the list and returns (then prints) an appropriate boolean. Extras: Use binary ...
#String Lists ''' Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) ''' text = str(input("Please enter a word: ")) rev = text[::-1] print(rev) if text == rev: print(text, " is a palindrome!") else: print...
#Autor: Axl Brandon Rodrigues '''Calcula a área e quantos litros de tinta serão usados para pintar a parede''' while True: try: a = float(input('Digite a altura de uma parede em metros: ')) except ValueError: print('Digite apenas valores numéricos!') else: break while True...
#Autor: Axl Brandon Rodrigues '''Conversor de número decimal para Binário, Hexadecimal e Octadecimal''' from time import sleep import os def binario(x): opc = '' bina = bin(numInt) print(f'{x} == {bina} ') def hexadecimal(x): hexa = hex(numInt) print(f'{x} == {hexa} ') def octad...
#Autor: Axl Brandon Rodrigues '''Mostra se o ano digitado é bissexto ou não''' while True: try: ano = int(input('Digite um ano: ')) except: print('Digite apenas valores inteiros!') else: break if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0: print(f'{ano} é um an...
#Autor: Axl Brandon Rodrigues '''Programa simles que mostra se um número é par ou ímpar''' while True: try: n1 = int(input('Digite um número: ')) except: print('Digite apenas valores inteiros!') else: break if n1 % 2 == 0: print(f'{n1} é par!') else: print(f'{n1...
#Autor: Axl Brandon Rodrigues '''Sorteia um aluno qualquer de uma amostra de 4 alunos''' from random import choice a1 = str(input('Qual o nome do primeiro aluno? ')) a2 = str(input('Qual o nome do segundo aluno? ')) a3 = str(input('Qual o nome do terceiro aluno? ')) a4 = str(input('Qual o nome do quarto aluno? ...
#!/usr/bin/env python #coding: utf-8 """ 文件打包 """ import os,sys import zipfile class Zip: def __init__(self): pass """ 文件打包 """ def zip_dir(self,dirname, zipfilename): filelist = [] fulldirname = os.path.abspath(dirname) fullzipfilename = os.path.abspath(zipfilenam...
# Purpose: At Wars, to find the number of user mentions in tweets # Author: Mike import json import os mentionCount = 0 path = 'test/' alltweets = 0 rawtweets = 0 #checks tweet and sees if there is a user mentioned def yesMention(tweet): t = json.loads(tweet) if t['tweet']['userMentions']: return True def ...
"""Each ListNode holds a reference to its previous node as well as its next node in the List.""" class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next """Wrap the given value in a ListNode and insert it after this node....
import math import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import plot_confusion_matrix, \ classification_report, \ roc_auc_score def score_regressor(X_train, y_train, X_eval, y_eval, model): """Prints the training and evaluation sco...
class Square: def __init__(self, x=0,y=0,sidelength = 1.0): self.x, self.y, self.sidelength = x,y, sidelength def getCenter(self): return self.x,self.y def getSideLength(self): return self.sidelength def containPoint(self,px,py): cx, cy, sLen = self.x, self.y, self.sidelength if abs(cx - px...
# p.92 tuple01.py str = "파이썬 문자열" # 문자열은 튜플이다 print(str[0]) # list 처럼 동작함 print(str[-1]) #str[-1] = '렬' # list가 아님을 알 수 있음 card = 'red',4,'python',True # 튜플로 선언 print(card) print(card[1]) #card[0] = 'blue' print() # p.92 tuple02.py one = '하나' print(type(one)) one = "원" print(one) two = '둘' print(type(t...
from tkinter import * window = Tk() label1 = Label(window, text = "COOKBOOK~~Python을") label2 = Label(window, text = "열심히", font = ("궁서체",30), fg = "blue") label3 = Label(window, text = "공부 중입니다", bg = "magenta", width = 20, height = 5 , anchor = SE) label1.pack() label2.pack() label3.pack() window.ma...
#!/usr/bin/env python3 from random import shuffle, randrange #modelowanie elementów gry: drzwi, wyboru drzwi i metod: ukrywającej nagrodę za losowymi drzwiami, wyboru drzwi itd. class Door(object): def __init__(self,prize): self.prize =prize class Show(object): def __init__(self): self.picked = None self.rev...
# This script calculates the volume of a sphere and prints it to the screen from math import pi diameter= input("type the diameter of the sphere for which you want to calculate the volume: ") radius= float(diameter)/2 volume= (4.0/3)*(pi)*(radius**3) print ("Volume of a sphere: %s" %(volume))
# Time Complexity: O(n) # Space Complexity: O(n) # Approach: Initialize a result array with -1s. # Use a monotonic stack. # Iterate the array. # While the value of the top of the stack is lesser than the value at i, pop the stack and update the resut array at popped value index with warmer temperature. # Add ...
############################################################## ##Playing with Lists ############################################################## ##Creating a list got_chars = ['Jon Snow', 'Khal Drogo', 'Jamie Lannister', 'Sansa Stark'] print(got_chars) ##Pulling data from lists print("My favorite G...
# 6.00 Problem Set 9 # # Name: # Collaborators: # Time: from string import * class Shape(object): def area(self): raise AttributeException("Subclasses should override this method.") class Square(Shape): def __init__(self, h): """ h: length of side of the square """ sel...
## this is at the top of every turtle file from turtle import * speed(0) shape("turtle") """ ### then first step is things like drawing a square forward(100) right(90) forward(100) right(90) forward(100) right(90) forward(100) right(90) clear() ### then drawing a square through a for loop for count in range(4): ...
# TCP Server # Anders Nelsson BTH # Exempel från kursbok from socket import * serverPort = 12000 # create TCP welcoming socket serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('',serverPort)) # server starts listening for incoming TCP requests serverSocket.listen(1) print ('The TCP server is ready to ...
# -*- coding: cp1252 -*- import random number = random.randint(0,1) if number == 0: print("Tails!") else: print("Heads!")
keepgoing = True while keepgoing: userwrote = input("Write something: ") if userwrote == "quit": keepgoing = False print("Bye bye!") else: print(userwrote)
def getlength(testme): if len(testme) < 42: return 0 else: return 1 result = getlength("ohgodwhydoesthisstringhavetobesolongicanteverrememberthis") if result == True: print("This string is long enough.") else: print("This string is too short.")
import sqlite3 from sqlite3 import Error class Database(): def __init__(self): self.conn = sqlite3.connect("score.db") self.user_name="" self.high_score=0 self.query = "" self.c= self.conn.cursor() def open(self): self.conn = sqlite3.connect("score...
""" This is a program for a chat bot...... 1. the bot will start with a greeting nd sk for name odf the person 2 bot will greet and welcome the person 3.bor will ask what a person want to do it will offer a choice of thing based upon what the bot is designed for 4.it will respond to users input approximately """ impor...