text
stringlengths
37
1.41M
https://edabit.com/challenge/gr4ihixfTaoEmZiin Add the Index Given a list of numbers, create a function which returns the list but with each element's index in the list added to itself. This means you add 0 to the number at index 0, add 1 to the number at index 1, etc... Examples add_indexes([0, 0, 0, 0, 0]) ➞ [0, 1,...
ERROR: type should be string, got "https://edabit.com/challenge/BfSj2nBc33aCQrbSg\n\nTruncatable Primes\nA left-truncatable prime is a prime number that contains no 0 digits and, when the first digit is successively removed, the result is always prime.\n\nA right-truncatable prime is a prime number that contains no 0 digits and, when the last digit is successively removed, the result is always prime.\n\nCreate a function that takes an integer as an argument and:\n\nIf the integer is only a left-truncatable prime, return \"left\".\nIf the integer is only a right-truncatable prime, return \"right\".\nIf the integer is both, return \"both\".\nOtherwise, return False.\nExamples\ntruncatable(9137) ➞ \"left\"\n# Because 9137, 137, 37 and 7 are all prime.\n\ntruncatable(5939) ➞ \"right\"\n# Because 5939, 593, 59 and 5 are all prime.\n\ntruncatable(317) ➞ \"both\"\n# Because 317, 17 and 7 are all prime and 317, 31 and 3 are all prime.\n\ntruncatable(5) ➞ \"both\"\n# The trivial case of single-digit primes is treated as truncatable from both directions.\n\ntruncatable(139) ➞ False\n# 1 and 9 are non-prime, so 139 cannot be truncatable from either direction.\n\ntruncatable(103) ➞ False\n# Because it contains a 0 digit (even though 103 and 3 are primes).\nNotes\nThe input integers will not exceed 10^6.\n\n\n\nB=131\nA=str(B)\nleft, right, contrl=[], [], ''\ndef prime(num):\n K=sum([1 for j in range(2,int(num**(1/2))+1) if num%j==0])\n if K==0: return True\n else: return False\nif '0' in A: print('False')\nelse:\n for i in range(len(str(A))):\n if prime(int(A[0:i+1]))==False or int(A[0:i+1])==1: break\n else:\n contrl+='right'\n for i in range(1,len(str(A))+1):\n if prime(int(A[-i:]))==False or int(A[-i:])==1: break\n else:\n contrl+='left'\n print('both'*(len(contrl)>5) or 'False'*(len(contrl)==0) or 'left'*(len(contrl)==4) or 'right'*(len(contrl)==5))\n\n\n\n\nimport math\ndef is_prime(num):\n if num >= 2:\n i=2\n while i <= math.sqrt(num):\n if num % i == 0:\n return False\n i += 1\n else:\n return True\n else:\n return False\ndef truncatable(num):\n right= sum([ 1 for i in range(1,len(str(num))+1) if is_prime(int(str(num)[:i])) ])==len(str(num))\n left= sum([ 1 for i in range(len(str(num))) if is_prime(int(str(num)[i:])) ])==len(str(num))\n if \"0\" in str(num):\n return False\n else:\n return \"both\"*left*right or \"right\"*right or \"left\"*left or False\ntruncatable(62383)\n\n\n\n\n\ndef isprime(n):\n # return all([n%i==0 for i in range(2,n//2)])\n return not any([n%i==0 for i in range(2,n//2)])\ndef l_truncatable(n):\n n=str(n)\n return all([isprime(int(n[i:])) for i in range(len(n)) ] )\ndef r_truncatable(n):\n n=str(n)\n return all([isprime(int(n[:i])) for i in range(len(n),0,-1) ] )\nn = 317\nprint(l_truncatable(n)r_truncatable(n)\"Both\" or l_truncatable(n)'Left' or r_truncatable(n)\"Right\" )\n\n\n\ndef prime(x):\n return x > 1 and not any (x%i==0 for i in range (2,x))\n\ndef left(x):\n return all(prime(int(x[i:])) for i in range (len(x)))\n\ndef right(x):\n return all(prime(int(x[:i+1])) for i in range (len(x)))\n\ndef truncatable(n):\n n = str(n)\n if \"0\" in n:\n return False\n if left(n) and right(n):\n return \"both\"\n if left(n):\n return \"left\"\n if right(n):\n return \"right\"\n else:\n return False\n\n\n\n"
#verilen sayının faktöriyelini hesaplama... def factorial(n): return n*factorial(n-1) if n>1 else 1 def factorial(Z): total = 1 for i in range(1, Z+1): total *= i return total def factorial(Z): if Z == 0: return 1 elif Z == 1: return 1 elif Z > 1: return Z * factorial(Z-1) else: retur...
https://edabit.com/challenge/6vSZmN66xhMRDX8YT Advanced List Sort Create a function that takes a list of numbers or strings and returns a list with the items from the original list stored into sublists. Items of the same value should be in the same sublist. Examples advanced_sort([2, 1, 2, 1]) ➞ [[2, 2], [1, 1]] adv...
https://edabit.com/challenge/riF3RkrcKpBp3sKCX Capital Split Create a function which adds spaces before every capital in a word. Uncapitalize the whole string afterwards. Examples cap_space("helloWorld") ➞ "hello world" cap_space("iLoveMyTeapot") ➞ "i love my teapot" cap_space("stayIndoors") ➞ "stay indoors" Notes ...
# Написати скрипт, який з двох введених чисел визначить, яке з них більше, а яке менше. a = input("Enter number:") b = input("Enter number:") if a > b: print("a>b is", a > b) elif a < b: print("a<b is", a < b) elif a == b: print("a=b is not", a == b) # Написати скрипт, який перевірить чи введене число парн...
import tkinter import random # 1 - Crate a window window = tkinter.Tk() # 2 - Set size window.geometry("700x500") # 3 - Create a frame frame = tkinter.Frame() # Set the tile frame.master.title("CREATE BY @SOMPHORS") def doOnClick_1(event): canvas.move("click", 0, 20) def doOnClick_2(event): ...
def buscar_funciones(arch_python): """[Autor: Javier Acho] [Ayuda: Devuelve una secuencia con los nombres de las funciones que se definen en el archivo que recibe. El archivo debe estar abierto en modo lectura.] """ nombres_funciones = [] for linea in arch_python: if lin...
import csv from PartA import* def creat_portfolio(data): # Creat a list which contains 100 company code, in order to ensure whether the user input the correct . company_code = [] for items in data[:101]: company_code.append(items['code']) portfolio_list = [] while True: ...
def encode_name(name): """ encode_name encodes special characters to be xml-compatible entities """ if name is None: return name return name.replace("&", "&amp;") def encode_identity(name): import re pattern = re.compile('[^a-zA-Z]+') return re.sub(pattern, '', name) def r...
# -*- coding: utf-8 -*- """ Created on Sat Sep 17 13:05:17 2016 @author: efron """ """ Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern e...
# -*- coding: utf-8 -*- """ Created on Mon Aug 22 13:19:43 2016 @author: efron """ from lazyproperty import LazyProperty from math import sqrt from itertools import chain class Vector: ''' example class to play around with python magic''' def __init__(self, *args): self._items = tuple(x for x in chain...
# -*- coding: utf-8 -*- """ what is the 10,001st prime? """ def get_primes_under(n): with open('primes.txt') as text: for line in text: prime, _ = line.split('\n') prime = int(prime) if prime < n: yield prime else: break
# -*- coding: utf-8 -*- """ Created on Tue Sep 13 08:13:30 2016 @author: efron """ """ If we are presented with the first k terms of a sequence it is impossible to say with certainty the value of the next term, as there are infinitely many polynomial functions that can model the sequence. As an example, let us cons...
# euler 061: ''' Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae: Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... Square P4,n=n2 1, 4, 9, 16, 25, ... Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... ...
# -*- coding: utf-8 -*- """ Created on Sun Aug 28 10:09:55 2016 @author: efron """ from typing import Callable, List def triangular(n: int) -> int: return (n*n+1)//2 def square(n: int) -> int: return n**2 def pentagonal(n: int) -> int: return (n*(3*n-1))//2 def hexagonal(n: int) -> int: ...
import sys filename = raw_input("What filename are you looking for? ") if len(sys.argv) < 2: print "Please enter a directory to search." sys.exit() directory_to_search = sys.argv[1] import os if not os.access(directory_to_search, os.F_OK): print "Not a valid directory." sys.exit() print "Searching inside " + ...
import re from cryptography.fernet import Fernet def encryption(text): try: key = Fernet.generate_key() fernet = Fernet(key) print(text) enctext = fernet.encrypt(text.encode()) print(enctext) dectext = fernet.decrypt(enctext).decode() print(dectext) exc...
"""Ranks for poker game.""" # pylint: disable=C0301 from typing import List from gym_poker.envs.poker.card import Card class Ranks: """ Define Ranks in poker and find a winners. """ @staticmethod def get_winners(cards_dummy: List[List[Card]]): """ >>> ranks = Ranks() >>> d...
#https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/ #Distance Calculation and Nearest Neighbor Calulation sourced from website above # Example of getting neighbors for an instance from geopy.distance import geodesic from math import sqrt import pandas as pd from i...
# Nome do restaurante, note e distância dados = input( "Deseja colocar restaurantes manualmente(M) ou ver um exemplo (E)? ").lower() def orderByNota(nota): return nota[1] def orderByDistancia(distancia): return distancia[2] if(dados == "e"): restaurantes = [["O Mineiro", 4.2, 1.7], ["Amor aos Ped...
# day_09.py """ A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters. You sit for a while and record part of the stream (your puzzle input). ...
# day_24.py """ The CPU itself is a large, black building surrounded by a bottomless pit. Enormous metal tubes extend outward from the side of the building at regular intervals and descend down into the void. There's no way to cross, but you need to get inside. No way, of course, other than building a bridge out of t...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务4: 电话公司希望辨认出可能正在用于进行【电话推销】的电话号码。 找出所有可能的电话推销员: 这样的电话总是向其他人【拨出电话】, 但从来...
#coding:utf-8 # List集合 L = ['sxn', 'hys', 'lcx'] print L # 动态语言,List元素类型可以不同 L = ['sxn', 21, 'hys', True] print L print L[0] print L[1] print L[2] print L[3] # 下标负的对应集合的倒数第几个 print L[-1] print L[-2] print L[-3] print L[-4] # 添加新元素 L = ['A', 'B', 'C'] L.append('D') # 在集合末尾添加 print L L.insert(1, 'X') # 在指定索引位置添加 print ...
#coding:utf-8 # 迭代 for..in.. # for循环迭代数列 1-100 并打印出7的倍数 for i in range(1, 101)[6::7]: print i # 迭代永远是取出元素本身,而非元素的索引 # 想在 for 循环中拿到索引,使用enumerate()函数 # 索引迭代也不是真的按索引访问,而是由 enumerate() 函数 # 自动把每个元素变成 (index, element)这样的tuple, # 再迭代,就同时获得了索引和元素本身 L = ['A', 'B', 'C', 'D'] for index, name in enumerate(L): print index, ...
#coding:utf-8 # 1 ~ 10 print range(1, 11) # 列表生成式 # 写列表生成式时,把要生成的元素如x * x 放到前面, # 后面跟 for 循环,就可以把list创建出来 # 1 * 1 ~ 10 * 10 print [x * x for x in range(1, 11)] # [1x2, 3x4, 5x6, 7x8, ..., 99x100] print [x * (x + 1) for x in range(1, 100, 2)] # 复杂的表达式 # HTML表格 d = { u'桑笑楠': 21, u'胡云裳': 22, u'吕超贤': 23 } tds = ['<tr...
""" python极为灵活的参数处理机制 调用函数时使用*和**展开可迭代对象,映射到单个参数(*其实是元组拆包,而**可以理解为字典拆包,虽然没有这种说法),*和**在使用时只能有一次 def func(arg1, arg2=None, *args, arg=None, **kwargs): pass arg1: 传统的定位参数 (potitional argument) args2 : 关键字参数(keyword argument),调用函数时提供的实参可以是不指明关键字的 *args : 未指定名称的参数(连续的)会被它捕获,存入元组 arg : 仅限关键字参数,调用函数时提供的实参必须是指明关键字,须放在前面有*的参数后面...
#coding:utf-8 # 格式化(较详细内容见书 P46) # 格式化操作符 %, 右操作数可以是任意东西 format = 'Hello, %s! What\'s your %s?' s = ('hys', 'age') print format % s format = '%.3f' # 对于其他数据类型类似 import math print format % math.pi print '%.3f' % math.pi # 模板字符串 $ from string import Template s = Template('Hello $name!') print s.substitute(name = 'hys')...
#coding:utf-8 print 45678 + 0x12fd2 print "Learn Python in imooc" print 100 < 99 print 0xff == 255 print 'hello, python' # 字符串单引号和双引号均可,中文注释Line1不能少 print '100 + 200 = ', 100 + 200 # python是动态语言,变量类型不固定 a = 1 print a a = 'sxn' print a a = u'桑笑楠' # 要输出中文字符串,必须在字符串前面加上u print a print '\"I\'m sxn\", he says.' # 转义字符 # ...
''' # Problem 2 ### Even Fibonacci numbers 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 fou...
# !/Python ###多线程筛选 def sort_list(listname='share_list', price=18, day=10): a = len(globals()[listname]) sort_price_list(listname, price) sort_ma_list(listname, day) b = len(globals()[listname]) print('过滤掉%s支股票,还剩%s支股票' % (a-b, b)) # 筛选价格 def sort_price(share_code, target_price=18): #print('检...
# Turtle Race import turtle import random screen = turtle.Screen() screen.setup(height=400, width=500) user_input = screen.textinput(title="Make your bet.", prompt="Which turtle will win race? Enter colour: ") turtle_colour = ["red", "yellow", "green", "blue", "coral", "orange", "cyan"] turtle_y_posotion = [-100, -...
def update_pwd(new): _file = None try: file = 'password.txt' _file = open(file, 'w', encoding='utf-8') _file.write(new) # except FileExistsError or FileNotFoundError as e: except: # print(e) pass finally: if _file: _file.close() def get_pwd(...
# def number_statistics(L, R): # _str = "" # for i in range(L, R+1): # _join = str(i) # _str = "{}{}".format(_str, _join) # lst = list(_str) # times = 0 # while '2' in lst: # lst.pop(lst.index('2')) # times += 1 # return times # # # print(number_statistics(int...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode ...
""" // Question: 3 /* * Let's call an array A a mountain if the following properties hold: A.length * >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... * A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is * definitely a mountain, return any i such that A...
"""// Question: 8 /* * Remove Duplicates from Sorted Array Given a sorted array nums, remove the * duplicates in-place such that each element appear only once and return the * new length. Do not allocate extra space for another array, you must do this * by modifying the input array in-place with...
"""// Question: 10 /* * Check if there are duplicates in k distance * * There is a string and we have to figure out if there are duplicates in K * distance. Input: string: "ABCADEB", K = 3 Output : false * * Input: string: "ABACDEB", K = 3 Output : true * */ public Intege...
""" # Definition for a Node. class Node(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random """ class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ copyMa...
''' File: feature_normalizer_new.py update history: 05/09(jz): change function 'normalize' and 'multiclass_normalize' by return X[:,2:] -------------------------------------------------------------------- This code is a part of the final project for course Machine Learning and Computational Statis...
import random mitu_tahab= input("Sisesta mitu tahab: ") mitu_tahab= int(mitu_tahab) ounte_jaak= 14 for i in range(0, mitu_tahab): yhele= random.randint(1, 2) ounte_jaak= ounte_jaak - yhele print(yhele) print("jargi jai" + str(ounte_jaak))
class Node(): def __init__(self, data, leftChild=None, rightChild=None): self.data = data self.leftChild = None self.rightChild = None class BST(): def __init__(self): self.root = None self.traversalList = [] def insert(self, data): new_node =...
#In this program, we are reversing the array #-------------------------------------------- #we are asking input from the user for the array arr = input("please input the array of numbers:- ") #in range len(arr)-1 is start index and -1 is end index and -1 is the step count #this way it decreases by -1 and returns the ...
# st = "code" # print(st[:3]*3) s = [10,2,2,3,3] s1 = [10,2,2,3,3] # s1 = s print(id(s1),id(s)) print(s1 is s) print(s1 == s)
class Lit: TF = { True : "T", False : "F"} to_bool = { True: True, False: False, "True": True, "False": False, "T" : True, "F" : False, "t" : True, "f" : False } def __init__(self, variable, bool=None): #simulate a second constructor Lit(i) that takes a positive/negative i, as if from cnf ...
# EM.py - Simple implementation of Expectation-Maximization algorithm # # You can do with this code whatever you want. The main purpose is help # people learning about this. Also, there is no warranty of any kind. # # Juan Miguel Valverde Martinez # http://laid.delanover.com import numpy as np import matplotlib.pyplot...
# -*- coding: utf-8 -*- from unittest import TestCase from datextractor import number_parsing """ Output of the parser is an array of tuples [match, value, (start, end)] """ class NumberParsingTestCases(TestCase): def test_captured_patterns(self): input_text = 'I have 2 kids' parser = number_parsing(inp...
def formar(num): if isinstance (num,int): return formar_aux(num) else : return "Error de valadacion" def formar_aux(num): if num == 0: return [] elif num%10%2==0: return ([num%10] + formar_aux(num//10)) else : return formar_aux(num//10)
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None def append(self, data): if self.head is None: new_node = Node(data) new_nod...
for x in "hello": print(x) if "h" in "hello"" print ("h is in hello") else: print ("h is not in hello")
#! usr/bin/env/ Python3 # board.py # coded by Saito-Saito-Saito # last edited: 25 September 2020 # explained on https://Saito-Saito-Saito.github.io/2048 from config import * import copy import random local_logger = logger_setup(__name__, level=INFO) class Board: def insert(self, *, logger=None): logg...
Learn more or give us feedback from dealer import Dealer dealer1 = Dealer() def menu(): dealerChoice = input(f''' (1). Shuffle (2). Deal the Cards (3). Re-deal the Dealt Cards Enter Choice: ''') if(dealerChoice == '1'): dealer1.shuffle() ...
""" Authors: James Lawson and Beth Ann Townsend Project 5 File name: eightQueens.py This is a program that finds a solution to the "Eight Queens" logic problem so that all queens on the chessboard are safe from attacks from one another. The program, upon calculating a solution, prints the outcome. """ def main(): i...
""" Example script to locate a specific URL from website. In this case we could try to use the found URL to download the zip file for the Wikipedia Detox corpus, but for brevity sake this shows a skeleton of how to use BeautifulSoup + requests to outline such a process. """ import requests from bs4 import BeautifulSou...
def filter(s): """ Converts CamelCase to underscore_case >>> filter("AnExample") 'an_example' >>> filter("RSAAuthentication") 'rsa_authentication' >>> filter("RhostsRSAAuthentication") 'rhosts_rsa_authentication' >>> filter("X11Forwarding") 'x11_forwarding' >>> filter("TestE...
#coding: utf-8 ''' Pandigital multiples Problem 38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by...
from main import db # Importing the db from main class User(db.Model): # This is the the User class that inherits from db.Model __tablename__ = "users" # This explicitally names th...
#!/usr/bin/env python3 inp = input() listNum = [] checkList=['0','1','2','3','4','5','6','7','8','9'] for i in inp: if i not in listNum: listNum.append(i) listNum.sort() notFound = [] print(listNum) for j in checkList: if j not in listNum: notFound.append(j) if len(notFound) == 0: print ("No missing digits")...
#!/usr/bin/env python3 def factorial( x ): if x == 0: return 1 result = x for i in range( x-1, 0, -1 ): result *= i return result def f( k, x ): # print( 'f( k = {}, x = {} )'.format( k, x ) ) numerator = ((-1)**k)*(x**(2*k)) denominator = factorial(2*k) # print( 'numerator = {}, denominator = {}'.format( ...
#!/usr/bin/env python3 s = input() num1Bits = s.count( '1' ) if num1Bits % 2 == 0: print( '{}{}'.format( s, 0 ) ) else: print( '{}{}'.format( s, 1 ) )
#!/usr/bin/env python3 inputStr = input() map1Str = input() map2Str = input() outputStr = '' for i in inputStr: match = False for mapCharIndex, mapChar in enumerate( map1Str ): if i == mapChar: outputStr += map2Str[mapCharIndex] match = True break for mapCharIndex, mapChar in enumerate( map2Str ):...
def grid_line(): i=1 while i<=3: print('+','---',sep='',end="") i+=1 print("+") def draw_bar(): j=1 while j<=3: print('| ',sep='',end="") j+=1 print("|") def draw_bar_loop(): i=1 while i<=4: draw_bar() i+=1 grid_line() draw_bar_loop() grid_line() draw_bar_loop() grid_line()
# Given Two Arrays, write a function to compute their intersection # Each element in the result must be unique # The result can be in any order class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: myList = [] left = 0 left2 = 0 nums1.sort() ...
class Solution: ''' leader permutations and combinations ''' def numIdenticalPairs(self, nums: List[int]) -> int: comb = combinations(nums, 2) count = 0 for i, j in comb: ''' looping through the the pairs i created ''' if i == j and i <= j: ''' i...
class Solution: def isPowerOfThree(self, n: int) -> bool: def divider(k): if k == 1: return True if k % 3 != 0: return False if k < 3: return False ...
# coding: utf-8 # ## Exploring and Visualizing the Number of Out-of-School Children Around the World Using Python # # ### Table of Contents # # * Getting Started with Data Scientist Workbench # # * CO2 emissions by Country by Year # # * Get the Data # # * Import the data using Pandas # # * Dataframe character...
# -*- coding: utf-8 -*- """ Created on Wed Sep 2 19:18:08 2020 This is the data structure of the graph @author: Administrator """ import numpy as np class graph: def __init__(self, num=0): self.num = num self.adj = np.zeros((num,num)) def set_edge(self,v,w,value): self...
from grabInput import * import pickle bodies = [] #Prompts the user if they want to add any bodies, then update everything to the getBodies.txt file def additionAndGeneration(): global bodies for i in range(len(bodies)): print(str(i) + ": " + str(bodies[i][0]) + " ") #Promp the user for the question and then store...
#-*-coding: utf-8-*- #Punto 3 A) def pos_ori(): print (u"Ingrese la posición en el eje 'X' de KAREL:") px= int(input()) print (u"Ingrese la posición en el eje 'Y' de KAREL:") py= int(input()) print (u"Ingrese la orientación de KAREL:") o= raw_input() print u"Las cordenadas iniciales de KAREL...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, Form from wtforms.validators import DataRequired, Email, EqualTo, Length, Optional class SignupForm(FlaskForm): """User Signup Form.""" full_name = StringField('full_name', validators=[DataRequired()]) use...
import random # a function to create a list where range is the largest number in the list def list_range(r): #int(range) list = [] r=pp for i in range(r): list.append(i) if i != r-1: continue return list # a function that will do the main task to randomis...
#Ordered Immutable datatype mystring = 'Hello world, Tim, Bob, Steve' ''' print (mystring.strip()) print (mystring.upper()) print (mystring.lower()) print (mystring.startswith('World')) print (mystring.endswith('d')) print (mystring.count('o')) print (mystring.find('o')) print (mystring.find('ll')) pri...
from pylab import plot,show from numpy import pi # Defining the differential equation def accel(x, t): a = -x return a # Entering initial values v = 1 x = 1 dt = pi / 20 # Creating lists to plot future points xpoints = [] ypoints = [] # Computationally solving the differential equation for...
from tkinter import * from tkinter import messagebox class Window: def __init__(self, width, height, x, y, title, resizable=(False, False), icon=None): self.root = Tk() self.root.geometry(f'{width}x{height}+{x}+{y}') self.root.title(title) self.root.resizable(resizable[0], resizabl...
a = input('') b = a.find('f') c = a.rfind('f') if b == -1: print() elif b == c: print(c) else: print(b, c)
a = 0 while int(input()) != 0: a += 1 print(a)
#!/usr/bin/python2 import sys def youLose(): print "Try again ;-)" sys.exit(1) try: p = input("Please enter password : ") except: youLose() with open("/etc/passwd") as f: passwd = f.readline().strip() try: if (p == int(passwd)): print "Well done ! You can validate...
import random from collections import OrderedDict def shuffle_vocabulary(d): keys = list(d.keys()) random.shuffle(keys) return OrderedDict([(k, d[k]) for k in keys]) def translate_test(vocabulary): correct_words = 0 incorrect_words = 0 vocabulary = shuffle_vocabulary(vocabulary) for wo...
seleccion = int(input("Enter a number: ")) if seleccion == 1: print("Thank you.") elif seleccion == 2: print("Well done.") elif seleccion == 3: print("Correct.") else: print("Error")
import random def pick_num(): num1 = int(input("Introduce low limit: ")) num2 = int(input("Introduce high limit: ")) comp_num = random.randint(num1, num2) return comp_num def first_guess(): print("I am thinking of a number...") guess = int(input("Make a guess: ")) return guess def comparator(comp_num, guess)...
name = str(input("Enter your name: ")) num = int(input("Enter a number: ")) for z in range(0, num): for i in name: print(i)
age = int(input("What is your age?")) if age < 10: print("Too low.") elif age >=10 and age <= 20: print("Correct.") else: print("Too high.")
total = 0 while total <= 50: add = int(input("Enter a number: ")) total = total + add print("The total is", total)
set_list = {} for i in range(4): name = str(input("Insert name: ")) age = int(input("Insert age: ")) size = int(input("Insert shoe size: ")) set_list[name] = {"Age":age, "Shoe size": size} print() ask = str(input("Introduce a name: ")) print(set_list[ask])
sports_list = ["Baseball","Basketball"] added_sport = str(input("introduce your sport: ")) sports_list.append(added_sport) sports_list.sort() print(sports_list)
file = open("Names.txt", "a") file.write("\n" + str(input("Add a name to the list: "))) file.close() file = open("Names.txt", "r") print(file.read())
#Color Guess game import random print("There are 5 colors:\n\nblue\nyellow\nred\norange\npurple\n") color = random.choice(["blue","yellow","red","orange","purple"]) guessed = False second = False while guessed == False: guess = str(input("Guess which i like the most...\n")) if guess == color: ...
seq = str(input("Introduce una secuencia de numeros: ")) inicio = int(input("Intruduce la posicion inicial: ")) final = int(input("Intruduce la posicion final: ")) print(seq[inicio:final])
import sqlite3 conn = sqlite3.connect("Bookshop.db") c = conn.cursor() c.execute("""SELECT * FROM Authors""") lista = c.fetchall() print ("Authors and birthplaces\n") for index, i in enumerate(lista, start=1): print(index, i[0] + ' - ' + i[1]) authorToSearch = input("\nEnter an author: ") c.execute("""SELECT * ...
import turtle # turtle.shape("arrow") # Tres cuadrados seguidos turtle.color("black", "yellow") turtle.begin_fill() for i in range(0, 4): turtle.forward(50) turtle.left(90) turtle.end_fill() turtle.penup() turtle.forward(75) turtle.pendown() turtle.color("black", "blue") turtle.begin_fill...
"""A module that implements a realization of simple http server.""" import os import socket import sys import io import mimetypes class MyServer(): """Simple http requests handler.""" def __init__(self): self.main_dir = os.getcwd() print("main_dir:", self.main_dir) def send_an...
#!/usr/bin/env python # coding: utf-8 # In[1]: # Import pandas library import pandas as pd # Read the online file by the URL provides above, and assign it to variable "df" other_path = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/coursera/project/kc_house_data_NaN.csv"...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ 题目描述:求1~n之内的素数。 程序分析:判断素数的方法,原始的是用除了1和自身外的 其他数去除那个数,如果都不能除尽,就是,否则 就不是。 一个简化的方法就是没必要用2~n-1去除,只需要 用2~sqrt(n)去除就可以。 一个更加简化的方法是用2~sqrt(n)范围内的素数 去除 一个更加更加简化的方法是用 “埃拉托色尼(Eratosthenes)筛法”,他是古希腊的著 名数学家。他采取...
""" 题目描述:将一个列表的数据复制到另一个列表中。 程序分析:使用列表[:] """ #原始列表 l = [x for x in range(10)] #print('初始列表为:', end = '') print('初始列表为:', l) #并没有真正复制,知识增加了一个指向列表的标识符 #l_copy1 = l #l[0] = 3,会同时改变l[0]和l_copy1[0] #print(l) l_copy2 = l[:] #l_copy2[1] = 100 print('第一种方式复制后的列表为:', l_copy2) l_copy3 = list(l) #l_copy3[2] = 200 print('第三种方式复...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- ############################ #File Name: example048.py #Author: kernellmd #Created Time: 2018-05-22 19:10:39 ############################ """ 题目描述:使用lambda表达式来创建匿名函数。 """ #原始程序 MAXIMUM = lambda x,y: (x > y) * x + (x < y) * y MINIMUM = lambda x,y: (x > y) * y + (x <...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- ############################ #File Name: example079.py #Author: kernellmd #Created Time: 2018-05-23 12:38:27 ############################ """ 题目描述:字符串排序 """ if __name__ == '__main__': str1 = input('input string:') str2 = input('input string:') str3 = input('inpu...
#!/usr/bin/env python3.6 #-*- coding: utf-8 -*- """ 题目描述:有5个人坐在一起,问第五个人多少岁?他说比 第4个人大两岁。问第4个人岁数,他说比第3个人大两岁。 问第3个人,又说比第2人大两岁。问第2个人,说比 第一个人大两岁。最后问第1个人,他说是10岁。请 问第五个人多大? 程序分析:利用递归的方法,递归分为递推与回归两个阶 段。要想知道第五个人岁数,需知道第四人的岁数, 依次类推,推到第一人(10岁),再往回推。 """ #改进1 #将递归函数的返回改变为单一出口 def age...
class Student: id_generator = 1 def __init__(self, name, age, gpa): self.student_id = Student.id_generator self.name = name self._age = age # _age attribute is non-public self.gpa = gpa Student.id_generator += 1 def __repr__(self): print("") return f"<Student(\nID: {self.studen...
class Movie: # auto-increment id value id_generator = 1 def __init__(self, title, rating): self.id = Movie.id_generator self.title = title self.rating = rating # Unique id for newly created movie instances Movie.id_generator += 1 def __repr__(self): print("\n") return f"<ID: {sel...