text
stringlengths
37
1.41M
# # @lc app=leetcode id=674 lang=python3 # # [674] Longest Continuous Increasing Subsequence # # @lc code=start class Solution: # def findLengthOfLCIS(self, nums: List[int]) -> int: # """ Strategy 1: Dynamic Programming # Runtime: O(n) # Space:O(n) # Args: # nums (List[...
from typing import List class Solution: def formatRange(self, num1: int, num2: int): if num1 == num2: return str(num1) return str(num1) + "->" + str(num2) def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: """Strategy 1: Liner Scan ...
# # @lc app=leetcode id=103 lang=python3 # # [103] Binary Tree Zigzag Level Order Traversal # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collection...
# # @lc app=leetcode id=98 lang=python3 # # [98] Validate Binary Search Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import math class Solution: ...
# # @lc app=leetcode id=415 lang=python3 # # [415] Add Strings # # @lc code=start class Solution: def addStrings(self, num1: str, num2: str) -> str: """Strategy 1: Linear Scan Args: num1 (str): number 1 in string num2 (str): number 2 in string Returns: ...
# # @lc app=leetcode id=350 lang=python3 # # [350] Intersection of Two Arrays II # from collections import Counter from typing import List # @lc code=start class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: """ Strategey 1: Counter Runtime: O(n + m), where n is ...
# # @lc app=leetcode id=10 lang=python3 # # [10] Regular Expression Matching # # @lc code=start from abc import abstractmethod class Solution: def isMatch(self, s: str, p: str) -> bool: """ Strategy 1: Dynamic Programming Runtime: O(n * m), where n is the length of s and m is the length of p ...
# # @lc app=leetcode id=69 lang=python3 # # [69] Sqrt(x) # from math import e, log # @lc code=start class Solution: # def mySqrt(self, x: int) -> int: # """ Startegey 1: Pocket Calculator # Runtime: O(1) # Space: O(1) # Args: # x (int): the number x # Returns...
""" 797. All Paths From Source to Target For a node: add node to path if node is target, add to path to result visit all neightbors remove node from path return result: Time : 2^N """ class Solution(object): def allPathsSourceTarget(self, graph): """ :type graph: List[List...
""" Brute Force TLE: 1. At each day check if curr day is in range of last bought ticket 2. If oppurtunity to buy, try all 3 options """ class Solution(object): def mincostTickets(self, days, costs): """ :type days: List[int] :type costs: List[int] :rtype: int """ ...
""" 939. Minimum Area Rectangle 1. for a point r1,c1 and r2,c2 check if point r1,c2 and r2,c1 exist 2. if it does, find the area 3. if area less than prev value, update the area value to be returned. Runtime: O(N^2) space : O(N) """ from collections import Counter class Solution(object): def minAreaRect(self,...
# 2.2 Write a program that uses input to prompt a user for their name and then welcomes them. # Note that input will pop up a dialog box. Enter Sarah in the pop-up box when you are prompted # so your output will match the desired output. # The code below almost works name = input("Enter your name") print("Hello", name...
# Preberemo input # Splitamo po vrsticah # Gremo vrstico po vrstico # ! Izvedi naslednji ukaz # Stroj mora vedeti: # - vrednost -> OK # - v kateri vrstici je -> OK # - vse vrstice, ki jih je ze izvedel # - Seznam ukazov -> OK class Ukaz: def __init__(self, tip_ukaza, stevilka): self.tip_ukaza...
# Sprasuj uporabnika po stevilkah in jih # dodajaj v seznam dokler ni 0 seznam_stevil = [] vpisano_stevilo = int(input("Vnesi stevilo")) stevilo_vpisanih = 1 while stevilo_vpisanih != 10 and vpisano_stevilo != 0: # Enako kot pri if stavku # zamaknemo stvari noter seznam_stevil.append(vpisano_stevilo) ...
# Funkcije # Izracunaj fakulteto stevila n n = 50 zmnozek_fakultete = 1 fakulteta = 1 for j in range(n): zmnozek_fakultete *= fakulteta fakulteta += 1 # V zmnozek_fakultete je skrit rezultat za n! # Tukaj pa izracunamo vsoto # Spiši na ta način še funkcijo ki sešteje števke # x%10 x// 10 def loop_pure (n)...
from random import randint import Player import Board class Chess(): def whatColor(self): return randint(0, 9) def newgame(self): m = Chess() print (""" "Welcome, please enter your names in order to start the game and press the enter key. """) player1, player2 = m.getPlayers() ...
x=int(15) flag = 0 for num in range (2,x + 1): for num1 in range (2,int(num/2)): if num%num1 == 0: flag = flag + 1 break if flag == 0: print(num,"is a prime number") flag=0
a=20 def sum(a): a=a+1 b=20 print(a) sum(a) print("a=",a)
# add, mul ,div ,sub def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b def main(): ch = int(input("press 1 for add \n 2 for sub \n 3 for mul \n 4 for div \n press 0 to exit \n")) while ch!=0: a = int(input("Enter num1 value: ")) ...
__author__ = 'tales.cpadua' class SnakeSegment(): def __init__(self, pos_x, pos_y): self.pos_x = pos_x self.pos_y = pos_y class Snake(): def __init__(self, display, block_size, pos_x=300, pos_y=300): self.color = (0, 155, 0) self.display = display self.block_size = bl...
#!usr/bin/python # -*- coding: utf-8 -*- import numpy as np class Perceptron(object): """Perceptron classifier. Parameters ------------ n_rate : float, Learning rate(between 0,0 and 1.0) n_iter : int, Passes over the training dataset. Attributes ------------ w_n : 1d-array, Weights a...
num = int(input('get the value:')) for i in range(2,num+1): count = 0 for j in range(2,i): if i%j != 0: count += 1 if count == i-2: print (i)
import os import imageio from PIL import Image images = [] size = (150, 150) for filename in os.listdir("images"): # only consider the extensions below when creating the gif if filename.endswith(".png") or filename.endswith( ".jpg") or filename.endswith(".jpeg") or filename.endswith( ...
import asyncio from time import time class Clock: """ Abstraction measuring elapsed time and waiting """ def now(self): """ Measure the current time, in seconds """ raise NotImplemented() async def sleep(self, n): """ Waits until the specified amount of time has elapsed """...
import re from solutionP1 import Queue, Stack def check_palindrom(text): # clean data text = str(text).lower() text = re.sub('[^a-z0-9]+', '', text) mid = len(text) // 2 is_even = True if len(text) % 2 != 0: is_even = False first_half = text[:mid] second_half = text[mid:] ...
def findNonDuplicate(A): # empty list if len(A) == 0: return None # no duplicate value if len(A) == 2 and A[0] == A[1]: return None # Recursive case if len(A) > 2: mid = len(A) // 2 if mid % 2 != 0: mid += 1 right = A[mid:] left =...
import numpy as np import matplotlib.pyplot as plt def generate_point(func, num_point): # func: the parameter of function # num_point: the number of points needing to generate # generate point of x randomly point_x = np.random.random((num_point, 1)) * 6 point_y = func(point_x) return point_x...
s = raw_input().strip() i = 0 target = 0 temp =0 default = "SOS" while i<len(s): for x in s[i:i+3]: if x!=default[temp]: target=target+1 temp=temp+1 else: temp=temp+1 temp=0 i=i+3 print target
def merge(array1, array2): ''' :param array1: sorted list :param array2: sorted list :return: list, merged from 2 arrays ''' res = [] pointer1 = 0 pointer2 = 0 while pointer1 < len(array1) and pointer2 < len(array2): if array1[pointer1] <= array2[pointer2]: ...
# Task 1 # speed = int(input('Enter speed: ')) # distance = int(input('Enter distance: ')) # time = distance / speed # print('Time for reaching place: ' + str(time)) # name = input('Enter your name: ') # age = input('Enter your age: ') # surname = input('Enter your surname: ') # print(f'Hello, Your surname is {surnam...
# DayOFBirth = int(input('Enter day of your birth: ')) # MonthOfBirth = int(input('Enter month of your birth: ')) # YearOfBirth = int(input('Enter year of your birth:')) # print(DayOFBirth+MonthOfBirth+YearOfBirth) # payment=int(input('Paymentfor courses: ')) # discount= int(input('Discount for best students: ')) # pr...
import random class QueueSimulation: def __init__(self,a,b,c,d): self.process_rate = a self.min_req_rate = b self.max_req_rate = c self.queue = [] self.queue_capacity = d def step(self, req): result = [] lost_count = 0 while len(se...
target = int(input("Enter target: ")) def reachTarget(target): # Handling negatives by symmetry target = abs(target) # Keep moving while sum is smaller of difference is odd sum = 0 step = 0 while (sum < target or (sum-target) % 2 != 0): step = step + 1 sum = sum + ...
from queue import Queue q = Queue(3) assert(q.is_empty()) assert(hasattr(q, "items")) assert(hasattr(q, "insert")) assert(hasattr(q, "remove")) assert(hasattr(q, "is_empty")) result = q.insert(5) assert(result == True) assert(not q.is_empty()) assert(q.__str__() == "5") result = q.insert(7) assert(res...
import numpy board = [] counter = 0 def win_check(player): # win horizontally player_win = 0 if board[0] == board[1] == board[2] == player or board[3] == board[4] == board[5] == player or board[6] == board[7] == board[8] == player: player_win += 1 # win vertically elif board[0] ==...
class Node: content = None Next = None def __init__(self): pass class LinkedList: def __init__(self): self.head = [] def push(self): pass def is_empty(self): if len(self.head) == 0: return True else: return...
string = input("Enter a string: ") shift = int(input("Enter Caesar shift: ")) char = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" enc = '' dec = '' def encrypt(str, n): global enc for i in str: if i in char: check = ord(i) + shift if check >= 97 and check ...
age = int(input("How old are you? ")) if (age < 16) or (age > 65): print("Enjoy your free time") else: print("Have a good day at work") x = "false" if x: print("x is true") x = input("Please enter some text: ") if x: print("You entered '{}".format(x)) else: print("You did not entered anything") ...
import Crypto.Random.random as rand import hashlib import string # Given a password and salt, compute their hash def hash_password(password, salt): cur = password + salt # Repeatedly hash the password, to make brute forcing more expensive for _ in range(10000): cur = hashlib.sha512(cur).hexdigest() # Done! re...
#!/usr/bin/python3.6 import numpy as np import sys import math import DecisionTree as dt def bootstrap(trees,depth,train,test,display = False): """Performs bootstrap aggregation with a decision tree learner for k-class classification""" #Build an array for indices/predictions for output indices = np.z...
#!/usr/bin/python # -*- coding: UTF-8 -*- for i in range(1,10): for j in range(11,20): print(i,j) if j == 15: break print i
#!/usr/bin/python # -*- coding: UTF-8 -*- # 随着随机次数的增加 # 平均值越来越趋向于5.5 # 也就是(1+10)/2 import random s1 = 0 s2 = 0 s3 = 0 s4 = 0 for i in range(1,10**1+1): p = random.choice(range(1,11)) # print('从1到9中取个随机值,第一次是:%d') % p s1 += p i1 = float(i) print('1到10之间,取10次随机值之和是:%d,平均值是:%f') % (s1,s1/i1) for j in range(1,10**3+1...
from quaternion import Quaternion as Q import sys if __name__ == '__main__': q = Q(1,2,3,4) r = Q(0,-2,1,-4) print("\nTest quaternions") print("q = " + str(q)) print("r = " + str(r)) print("\nQuaternion operations and functions") print("q+r = " + str(q+r)) print("q...
# SplinesGenerator.py # Author: Tinli Yarrington # Date: 3/22/15 # Dates edited: 3/23/15, 3/24/15, 3/25/15, 3/26/15 # Purpose: user inputs number of vertices and values of sides, and program generates bases splines for those graphs # Notes: # - change program so it can take more than three vertices # - conf...
# ************数据类型************ # 科学记数法 print(1.23e8) # 字符串:""或''本身只是一种表示,如果字符串中有',那就用""括起来。 print("I'm OK") # 既包含',又包含",用转义字符\ print('I\'m \"OK\"') # 用r''表示''里面的字符不允许转义 print(r'\\\t\\') # 用'''...'''格式表示多行内容 print('''line1 line2 line3''') # 布尔值 print(3 > 2) print(True and True) # 空值None # 变量: a = 123 print(a) a = '...
# map和reduce函数: # map:接收两个参数,一个函数,一个Iterable,map将传入的函数作用于每一个元素,并返回新的Iterable def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # 高阶函数 print(r) print(list(r)) print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) # 变为字符串 from functools import reduce def add(x, y): return x + y print(red...
# 排序算法: # python内置的函数:高级函数 print(sorted([12, -5, -62, 124, 65, 30])) # 接收一个key来实现自定义排序:按绝对值排序 print(sorted([12, -5, -62, 124, 65, 30], key=abs)) # 对字符串排序是对其ascii值来排序 # 反向排序,只需制定reverse为True就好: print(sorted([12, -5, -62, 124, 65, 30], reverse=True))
# TODO: 正割法: import matplotlib.pyplot as plt import numpy as np def getValue(x): return x ** 2 - 1.5 * x def paintf(): # TODO: 绘制x轴y轴 x = np.arange(-1, 4, 0.05) y1 = [0 * a for a in x] y = np.arange(-1, 4, 0.05) x1 = [0 * a for a in y] plt.plot(x, y1, '-', color='black') plt.plot(x...
# 函数: # help(abs) # 调用帮助文档查看abs函数 print(abs(100)) print(abs(-10)) print(max(1, 2, 3, 4)) # max函数直接接受任意多个参数,并返回最大的那个 # 类型转换 print(int('123')) print(str(123)) print(bool(1)) print(bool('')) # 定义函数: def my_abs(x): if not isinstance(x, (float, int)): # 修改的my_abs()函数--异常处理,instance<->示例 raise TypeError('b...
""" ---------------------------------------------------------------- Caren Groenhuijzen 01-07-2020 Eindopdracht gemaakt voor de leerlijn Python van NOVI Hogeschool ---------------------------------------------------------------- """ import socket as s import pickle as p """This client can connect to the server. It c...
class Tile(): """the class for tiles. self variables: mine: if its true it means the tile has a mine, if it has no mine its false visible: the tiles state, meaning if its revealed (1) or not (0) flagged: if the flagged nearby_mines: the amount of mines nearby functions: reveal:...
'''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. Hints:''' class inputString(object): def _init_(cow): cow.bull="" def getString(cow): cow.bull=raw_inp...
#Program to perform BFS and Print a spanning tree for a source #!/usr/bin/python class Queue: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): ...
io=input("") while(io): n=int(raw_input("enter the year: ")) if n%4==0: if n%400==0: print "its leap year" elif n%100==0: print "not leap year" else: print "its leap year" io=io-1
#Evaluating a postfix expression class stack: def __init__(self): self.items=[] self.t=-1 def push(self,item): self.t+=1 self.items.insert(self.t,item) def pop(self): self.t-=1 def size(self): return self.t def isempty(self): return self.items==[] def top(self): return self.items[self.t] st=stac...
#merge sort ---- one of the comparison sort # recursion def mergesort(liz): if len(liz) > 1: mid=len(liz)//2 liz1=liz[:mid] liz2=liz[mid:] mergesort(liz1) mergesort(liz2) i=0 j=0 k=0 while i < len(liz1) and j < len(liz2): if liz1[i] >= liz2[j]: liz[k]=liz1[i] k=k+1 i=i+1 else: ...
# 标准库(python 常用模块) # 输出格式 # reprlib 模块为大型的或深度嵌套的容器缩写显示提供了 :repr() 函数的一个定制版本 # pprint 模块,用于当输出超过一行的时候,pretty printer 添加断行和标识符,使得数据结构显示的更清晰 # textwrap 模块格式化文本段落以适应设定的屏宽 import pprint t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta','yellow'], 'blue']]] pprint.pprint(t, width=30) import te...
N = raw_input('N: ') if N=="1": print'A' elif N=="2": print'B' elif N=="3": print'C' elif N=="4": print'D' elif N=="5": print'E' else: print'eroor'
"""A recursive decent parser that returns a parse tree Takes rules as a list of tuples (name, rule) and a token list (a list of (token name, token value) pairs) and returns a parse tree of nodes (rule name, value1, value2, ...) where values may be (token, value) or a child node. Rule values are lists of strings (or ...
"""Implements an infinite set which contains all but a finite set of elements""" from partialorder import partial_ordering # partial_ordering decorator fills in __lt__ and __gt__ based on __le__ and __ge__ @partial_ordering class UniverseSet(object): """This class acts like a set in most ways. However, all operati...
"""A tool for working with iterators as though they are lists Sometimes you have a lazy iterator, which you want to use in some function that expects a list or tuple (or other indexable iterable). One solution is to convert the iterator to a list, but then you lose laziness. This LazyList wrapper takes an iterable (...
import os.path import pathlib from os import path def saveToFile(filePath, textToSave): # Check if current file path exists file = pathlib.Path(filePath) if file.exists(): print("File exists") else: print("File doesn't exist. Creating file") # Open the file and overwrite the curre...
#!/usr/bin/python3 from CS312Graph import * import time import itertools # --------------------- objects ---------------------------- class Node: id = None dist = None vertex = None def __init__(self, id, dist, vertex): self.id = id self.dist = dist self.vertex = vertex ...
#!/usr/bin/python2.7 # -*- coding: latin-1 -*- import sys #purpose of this exercice is to validate if that an input is made of only numbers #Of course there is a lot of better way to do that, but at this step, the studdents don't have # enough background to do it better. #the number to be filled by the user number ...
nome = input('Digite o seu nome: ') idade = int(input('Qual a sua idade: ')) idade_limite = 18 if idade >= idade_limite: print(f'{nome} pode solicitar empréstimo...') else: print(f'{nome} não pode solicitar o empréstimo...')
num1 = 0 num2 = 0 if not num1 != num2: print('Retorno 1') else: print('Retorno 2')
# -*- coding: utf-8 -*- def compositeWallSeries(resistanceList): """This function takes as input a list of resistances, each of which is a dictionary. It computes the series of the resistances token as input. """ R_series=0 resistancesResults = {} for resistance in resistanceList: A = re...
########################################################################################################################################## # Basically to understand the Class, Inheritance # # @lessons learned: # Python does NOT support method overloading... aka CompileTime Polymorphism... # https://ww...
# Monta a matriz com todos os valores inicialmente iguais a zero def montar_matriz(linhas, colunas): matriz = [] for i in range(linhas): linha = [] for j in range(colunas): linha.append(0) matriz.append(linha) return matriz # Monta o distanciamento def montar_distanciame...
#!/usr/bin/python # -*- coding=utf8 -*- """ # Author: wanghan # Created Time : 2017年03月27日 17:43:27 # File Name: 默认参数.py # Description: """ def power(x,n=2): s = 1 while n > 0: s = s*x n = n - 1 return s print(power(2))
#!/usr/bin/python """Implements k-fold cross-validiation and Ditterch's 5x2 cross-validiation method. """ import random def _buildFolds(inputData, k=10): """Return a list of folds. Each fold is a list of examples. The inputData must be list-like, meaning that it's type can be the built-in list or ...
################################################################################################## ########################### Variable Practice ######################################### ################################################################################################## #####################...
# 找出数组中的第一个重复数字,限制,n个数的数组,所有数字都在0~n内 # 思路:用一个指针i从前往后遍历,设指向的数字为m,直到找到第一个m与i不同的位置 # 将m交换到其下标位置处,若m与其下标位置数已经相同,则停止输出,否则循环 class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # 思路:遍历整个数组,下标i,值m,若i==m,判断下一个元素, # 否则将m放到与下标相同的位置上 ...
# 根据前序和中序遍历重构二叉树 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here # 思路:前序遍历的首个元素是根节点,在中序遍历中找到该节点,确定左右子树节点个数 # 这时又分别得到左右子树的前中...
# 求fib第n项 # 思路:生成一个39项的数字,从前往后遍历生成 # -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here l = [0 for i in range(n + 1)] l[0] = 0 if n > 0: l[1] = 1 i = 2 while i <= n: l[i] = l[i - 1] + l[i - 2] i = i + 1 ...
class AddEvenNum: def evenNumber(self): allEvenNumber=[] for x in range(10,20): # print(x) if x%2==0: allEvenNumber.append(x) # print(x) return allEvenNumber # if __name__=="__main__": # evenNumber()
class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print 'Sorry, minimum balance must be maintained.' ...
class BankAccount: def __init__(self): self.balance = 0 def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance ''' >>> a = BankAccount() >>> b = BankAccount() >>> a.deposit(100) 1...
#main.py from fraction import Fraction def H(n): h = Fraction(0, 1) for k in range(1, n + 1): h += Fraction(1, k) return h def T(n): t = Fraction(0, 1) k = 0 while(k <= n): t += Fraction(1, 2) ** k k += 1 return t def Z(n): z = Fraction(0, 1) ...
#!/usr/bin/python3 """ function that append a strig to a file """ def append_write(filename="", text=""): """ appending to a file """ with open(filename, mode='a', encoding="UTF8") as myfile: return myfile.write(text)
#!/usr/bin/python3 """ function that write a str to a file """ def write_file(filename="", text=""): """ writing to a file """ with open(filename, mode='w', encoding="UTF8") as myfile: return myfile.write(text)
################################################################################ # # blank_gen.py # A barebones D&D Monster Generator using statblock5e # Only the monster name is filled in, all other monster information must be # inserted into the code manually. # # Usage: python blank_gen.py [monster name] # If the...
# Homework: Your job is to make a custom calculator. # Your calculator should accept at least three values. # For example height, width, length # It should print a prompt that makes it clear what # is being calculated. # For example: # Enter height, width, and length to calculate the area of a cube # Height: 3 ...
#!/usr/bin/env python3 from csv_parser import CsvParser from decimal import Decimal class SalesReport: """ This class holds the data returned by your generate_sales_report() method. # Your SalesReport must also contain: # * The total sales associated with each product over the quarter. # * The a...
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import asyncio,threading,time @asyncio.coroutine def hello(): print("Hello world!") # 异步调用asyncio.sleep(1): x = asyncio.sleep(1) print('r=' + type(x)) r = yield from asyncio.sleep(1) print("Hello again!") @asyncio.coroutine def hello2(): ...
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- def square_gen(val): i = 0 val_from_send = None print("\nsquare_gen begin") while True: # 使用yield语句生成值,使用out_val接收send()方法发送的参数值 print("before yield val_from_send =", val_from_send,',i =',i) val_from_send = (yield val_from_send *...
''' 1. The list of non-negative integers that are [5,10,7,14,25,36] . Print the square of each number. eg for [1,2,3,4] the output would be 1 4 9 16 ''' def squaringNumbers(listofnumbers): for i in range(0,len(listofnumbers)): print(listofnumbers[i]**2) squaringNumbers([5,10,7,14,25,36])
''' 3. Write a function called raindrops that takes a number. - If the number is divisible by 3, it should return “Pling”. - If it is divisible by 5, it should return “Plang”. - If it is divisible by both 3 and 5, it should return “PlingPlang”. - If it is divisible by by 7, it should return "Plong" - If...
def sum(lista): suma = 0 for i in lista: suma += i return suma def multip(lista): multiplicacion = 1 for i in lista: multiplicacion *= i return multiplicacion n=int(input("cantidad numeros:")) lista=[] for i in range(0,n): lista.append(int(input("ingrese numero "+str(i+1)+"...
frase=int(input("Ingrese cantidad de palabras: ")) palabras=[] for i in range(0,frase): palabras.append(raw_input("Palabra "+str(i+1)+": ")) def mas_larga(lista): mayor=len(lista[0]) maslarga=lista[0] for palabra in lista: if mayor <= len(palabra): mayor=len(palabra) mas...
from abc import ABCMeta, abstractmethod class figure(): """parent class""" __metaclass__ = ABCMeta @abstractmethod def reckon(self): """return square"""
# name=input('我的名字:') # age=input('我的年龄:') # sex=input('我的性别:') # print('我的名字是:'+name, '\n我的年龄是:'+age,'\n我的性别是:'+sex) # mmm=''' # ----------------info of %s------------------ # name : %s # age : %s # job : %s # hobbie : %s # --------------------end----------------------- # ''' % ('曾阿牛', '曾阿牛 ', 100, '明教教主', '...
#!/usr/bin/env python3 ''' loopy test ''' #channel = int(input("What channel do you REALLY want?: ")) FAVS = [26, 52, 4, 498, 102] for channel in FAVS: if channel < 11: print("For Channel ", channel, " You need the basic package") elif channel < 41: print("For Channel ", channel, " You need th...
import math def ehPrimo(n): result = True size = int(math.sqrt(n)) for i in range(2,size): #print('{} dividido por {}'.format(n,i)) if n % i == 0: result = False break return result if __name__ == "__main__": n=991564654552145 ...
#program works!!! cards_chosen = ['king','4','3','8','3'] hit = 0 while True: print ('Here are your cards: ') def print_list(x):#dont really know how this works but it works just to make it print nicer print('\n'.join(x)) print_list(cards_chosen[0:2+hit]) values = {'2':2,'3':3,'4':4,'5':5...
#going to finish the dealer's hand #figure out how to print the list/cards not backwards #need to add this to the final combined part cards_chosen = ['king','4','2','7','3'] dealer_hit = 0 win_lose = 'lose' cards_chosen_values = [] sum_of_player = 20 values = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'ja...
#be able to give a user a initial amout of chips, ask for wager, print ('Hey there player, I\'ve started you off with 500$. Try and get as high as you can.) money = 500 bet = input('What\'s your wager? ') if bet <= money: #run blackjack game else: print ('I\'m sorry but I can\'t accept that value as a bet.) ...
from tkinter import * class Box: def __init__(self, size): self.size = size def in_horizontal_contact(self, x): return x <= 0 or x >= self.size def in_vertical_contact(self, y): return y <= 0 or y >= self.size def in_square_contact_x(self, x, y, gap): ...
"""Defines Data Models for Spellcheck Module.""" from spellcheckapp import db class SpellChecks(db.Model): """ SpellChecks Database Model. Defines SpellChecks fields. """ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), db.ForeignKey('users.username'), unique=...
# write a program to convert a users input from kgs to lbs and vice-versa kgs = int(input("Enter weight in kgs: ")) pounds = kgs/0.90 print("The weight in pounds is", round(kgs, 1)) pounds = int(input("Enter weight in Pounds: ")) kgs = pounds/0.90 print("The weight in kgs is", round(kgs, 1)) # find the total pri...