text
stringlengths
37
1.41M
# Write a Python program to create Fibonacci series upto n using Lambda. from functools import reduce def fibonacci(count): sequence = (0, 1) for _ in range(2, count): sequence += (reduce(lambda a, b: a + b, sequence[-2:]), ) return sequence print(fibonacci(7))
# Write a Python program to get a list, sorted in increasing order by the last # element in each tuple from a given list of non-empty tuples. # Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] # Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] def last(x): return x[-1] def out20(lis): return ...
# Write a Python program to iterate over dictionaries using for loops. def out35(dic): for key, value in dic.items(): print(f'{key}: {value}') out35({0: 10, 1: 20, 2: 30})
# Write a Python program to check whether a given string is number or not using Lambda. def f18(string): return string.isnumeric() print(f18("123")) print(f18("123abc")) print(f18('abc123')) print(f18("9812345678"))
# Write a Python program to sum all the items in a list from functools import reduce def out16(func, lis): return func + lis print(reduce(out16, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# Write a Python script to add a key to a dictionary. # Sample Dictionary : {0: 10, 1: 20} # Expected Result : {0: 10, 1: 20, 2: 30} sample = {0: 10, 1: 20} def out28(key, value): sample[key] = value return sample print(out28(2, 30))
# Write a Python program to get a single string from two given strings, separated # by a space and swap the first two characters of each string. # Sample String : 'abc', 'xyz' # Expected Result : 'xyc abz' def out4(lis): first_two_letter1 = lis[0][:2] first_two_letter2 = lis[1][:2] char1 = first_two_lette...
import csv import plotly.figure_factory as ff import pandas as pd import statistics df = pd.read_csv("StudentsPerformance.csv") performance = df['reading score'].tolist() mean = statistics.mean(performance) median = statistics.median(performance) mode = statistics.mode(performance) std_deviation = statis...
import random """Functions""" #Creates up to 6 rooms def room_creation(): for amount in range(random.randint(1,6)): rooms.append(room()) n = 0 for some in rooms: rooms[n].treasure_chance() rooms[n].healing_chance() rooms[n].monster_chance() #Just to make sure room cre...
""" Physics 18L - Experiment 4 - Day 2 Christian Lee Professor: N. Whitehorn TA: Teresa Le Lab Date: Thursday, Oct 24, 2019 UCLA Physics Department Required libraries: matplotlib, numpy, scipy Projectile motion in 2D """ #Settings for 2D Projectile Motion #Number of particles num_particles = 5 #Gravitational Ac...
import random, sys def common_member_set(lista1, lista2): a_set = set(lista1) b_set = set(lista2) if (a_set & b_set): return sorted(list(a_set & b_set)) else: return [] def remove_list_duplicates(lista): cleanlist = [] [cleanlist.append(x) for x in lista if x not in clea...
def format(number): upper = number // (1<<64) lower = number % (1<<64) print(""+hex(upper)+","+hex(lower)+",") for q in range(-342,0): power5 = 5 ** -q z = 0 while( (1<<z) < power5) : z += 1 if(q >= -27): b = z + 127 c = 2 ** b // power5 + 1 format(c) els...
#импорт pygame и random import pygame as pg import random as rnd #Кадры в секунду FPS = 60 #Цвета WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 225, 0) BLUE = (0, 0, 225) BLACK = (0,0,0) #идентификация окна программы pg.init() screen = pg.display.set_mode((140, 140)) clock = pg.time.Clock() ...
from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("Test") # setMaster(local) - we are doing tasks on a single machine sc = SparkContext(conf = conf) # read data from text file and split each line into words words = sc.textFile("../TXT/input_for_word_count.txt").flatMap(lambda...
# Module is create to take a 3 row matrix, and return a parametric curve for the shot # Row 0 should be x-positions, row 2 should be y-positions, row 3 should be approximate z-positions # The z-positions are expected to not be perfectly parabolic, but the x and y coords should be on some y=mx + b line import numpy as ...
''' Write a program to find the sum of the given elements of the list. (Hint: Use reduce method.) Example:Input:list = [1, 2, 3, 4, 5, 6, 7, 8, 9]''' from functools import reduce lst = [1,2,3,4,5,6,7,8,9] res = reduce(lambda a,b:a+b,lst) print(res)
'''Write a program to accept an input string from the user and determine the vowels in the string and calculate the number of vowels. ''' name = input("enter name") lst = ['a','i','o','u','e','A','E','I','O','U'] c = list(filter(lambda x: x in lst,name)) print(c)
data = "raj,sneha,sandy,Anu" print(list(map(lambda x: x.capitalize(),data.split(",")))) x = list(map(lambda x:x.capitalize(),data.split(","))) print(list(filter(lambda x:x.startswith("A"),x)))
max=6 for i in range(1,max+1): for j in range(max,i-1,-1): print(" ",end="") for k in range(1,i+1): print(k,end="") for l in range (k-1,0,-1): print(l,end="") print()
tnum = num = int(input("enter the number")) sum = 0 while num >9 : sum = (num%10+num//10) num = sum print(num)
from vending_machint.data import Drink flag = True balance = 0 drinks = { Drink('可樂',20), Drink('雪碧',20), Drink('茶裏王',20), Drink('原萃',25), Drink('純粹喝',25), Drink('水',20) } def desposit(): """ 儲值功能 :return: nothing """ global balance value = eval(input("儲值金額:")) while...
pos = -1 def search(list,n): l = 0 u = len(list)-1 while l <= u: mid = (l+u)//2 if list[mid] == n: globals()['pos'] = mid return True else: if list[mid] < n: l = mid+1 else: u = mid-1 return False ...
#Print the word with more than one occurrence from the given String Program def wordOccur(s): counter=[] st="" answer=[] res=list(set(s)) for i in res: count=0 for j in range(0,len(s)): if i==s[j]: count=count+1 counter.append(count) for i in range(0,len(counter)): if counter[i]>1: ...
# Check if a Mth fibonacci number divides Nth fibonacci number m=int(input("Enter Mth fibonacci no: ")) n=int(input("Enter Nth fibonacci no: ")) a=1 b=1 arr=[] arr.append(a) arr.append(b) for i in range(2,n): c=a+b arr.append(c) a=b b=c print(arr) ele1=arr[m-1] ele2=arr[n-1] if ele2%ele1==0: p...
import sys def isPalindrome(str): for i in range(0, len(str)/2): if str[i] != str[len(str)-i-1]: return False return True def main(): user_input = raw_input("Enter a string to see if it's a palindrome: ") print(isPalindrome(user_input)) if __name__ == "__main__": main...
import numpy as np class SingleAxisTrajectory: """A trajectory along one axis. This is used to construct the optimal trajectory in one axis, planning in the jerk to achieve position, velocity, and/or acceleration final conditions. The trajectory is initialised with a position, velocity and ac...
""" Given an array a of n integers and a number, d , perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. """ import math import os import random import re import sys # Complete the rotLeft function below. def rotLeft(a, d): shift = a[d:] + a[:...
""" Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed. countingValleys has the following parameter(s): n: the number of steps Gary takes s: a string describing his path """ import math import os import random import re import sys ...
import sys # Se determina opcion 1 para que el ciclo pueda ser ejecutado opcion = 1 # Se declara una funcion por cada opcion posible # En este caso es determinar si un numero es mayor o menor que 0 def mayorcero(): numero = int(input('Ingrese un numero: ')) if numero > 0: print(f'{numero} es mayor que 0...
# Programa que simule un tablero de ajedrez con estas caracteristicas f = int(input('Ingrese numero de filas: ')) c = int(input('Ingrese numero de columnas: ')) ajedrez = [[0 for j in range(c)]for i in range(f)] if f == 8 and c == 8: for i in range(0, f, 1): for j in range(0, c, 1): if i == 0: ...
# Matrices en python f = 0 c = 0 valor = 0 suma = 0 contador = 0 # Declarar la matriz f = int(input('Ingrese numero de filas de la matriz: ')) c = int(input('Ingrese numero de columnas de la matriz: ')) matriz1 = [[0 for j in range(c)] for i in range(f)] # Llenar la matriz con datos elegidos for i in range(0, f, ...
# Programa que imprime numeros de 5 a 1 for i in range(5, 0, -1): print(i)
# Robert Higgins G00364712 # 12th Feb 2018 # Euler Project Problem 5: Smallest multiple of numbers from 1 - 20 prod = 1 num = 1 while num <= 20: if prod % num != 0: prod = num*prod num +=1 print("LCM of all numbers from 1 - 20, inclusive, is:", prod)
# Robert Higgins G00364712 # 12th Feb 2018 # Euler Project Problem 2: Even Fibonacci Numbers fibNo1 = 0 fibNoLast = 1 fibNoCurr = fibNo1 + fibNoLast sumTotal = 0 while (fibNoCurr < 4000000): if (fibNoCurr % 2 == 0): sumTotal += fibNoCurr fibNo1 = fibNoLast fibNoLast = fibNoCurr fib...
""" Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. """ """ 解题思路: 建立一个新的对应关系,增加小数字的一些组合 Note:只需要一个小数字在左边即可 举例说明: 9:"IX" 因为如果是8的话是三个小数字在右边 此时变为VIII """ class Solution(object): def intToRoman(self, num): """ :type num:...
''' You are to calculate the diagonal disproportion of a square matrix. The diagonal disproportion of a square matrix is the sum of the elements of its main diagonal minus the sum of the elements of its collateral diagonal. The main and collateral diagonals of a square matrix are shown in figures 1 and 2 respectiv...
import sqlite3 import hashlib def initializeTables(): #create the user table in user.db if the table does not already exist conn = sqlite3.connect("databases/users.db") c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS users (username text, password text) ''') conn.commit() ...
from array import * def main(): num = float(input("Ingrese un valor en centimetros: ")) print("El valor en pulgadas es: ", round(num/2.54, 4)) if __name__ == "__main__": main()
from array import * def main(): num1 = int(input("Ingrese el primer numero entero: ")) num2 = int(input("Ingrese el segundo numero entero: ")) num3 = int(input("Ingrese el tercer numero entero: ")) # Valida si los tres numeros son iguales if num1==num2 and num1==num3: for x in range(3): ...
# The purpose of this script is to generate a random # DNA sequence of length n, n is an int argument from sys import argv as argument from random import * """Script requires int as argument""" numToBase = {'0':'A','1':'T','2':'C','3':'G'} if(len(argument) != 2): print("Error in argument length; int is required...
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_deriv(x): return sigmoid(x) * (1 - sigmoid(x)) class neural_network: # Layer nodes describes the shape of the neural network (how many nodes in each layer) # lr is the learning rate, used to scale the amount the weights/bia...
#coding: utf-8 #Gabriel Dantas Santos de Azevêdo #Matrícula: 118210140 #Problema: Caixa Preta (descartando leituras) controle = True contp = 0 contc = 0 conta = 0 while True: dados = raw_input().split() peso = int(dados[0]) combust = int(dados[1]) altitude = int(dados[2]) for i in range(len(dados)): if peso...
#coding: utf-8 #Gabriel Dnatas Santos de Azevêdo #Matrícula: 118210140 #Problema: Unnamed conjunto_de_conjuntos = [] conjunto = [] entrada = "" contador = 0 elementos = 0 while entrada != "fim": entrada = raw_input() if entrada == "fim": break elif int(entrada) >= 0: conjunto.append(entrada) elif int(entrada)...
#coding: utf-8 #Gabriel Dantas Santos de Azevêdo #Matrícula: 118210140 #Problema: Controle de Qualidade peso_cong = float(raw_input()) peso_dps = float(raw_input()) peso_ag = peso_cong - peso_dps perc_ag = peso_ag * 100.0 / peso_cong if perc_ag >= 5 and perc_ag < 10: print '%.1f%% do peso do produto é de água congel...
a = 3 b = 5 a=4 #print(a*b-b) city = "P a r i s" #print(3*len(city)) # 3*len(city) # len([1,2,5,6,9]) def fenelon_longueur(toto): o = 0 for letter in toto: o = o + 1 print(o) #print(fenelon_longueur('Ba+---^???!rcelone')) #print(fenelon_longueur('r')* 5 ) #print(type(78.9), type('pi')) # def che...
items_count = int(input("Введите количество элементов списка ")) my_list = [] i = 0 number = 0 while i < items_count: my_list.append(input("Введите следующее значение списка ")) i += 1 for elem in range(int(len(my_list) / 2)): my_list[number], my_list[number + 1] = my_list[number + 1], my_list[number] ...
import random import turtle l = open("wordfile.txt").read().splitlines() x = l[random.randint(0, len(l)-1)] h = list(x) w = ["_", "_", "_", "_", "_", "_", "_"] errorattempts = 8 prevguessleft = 8 attempts = 0 t = turtle.Turtle() t.pensize(10) t.pencolor("black") t.fd(200) t.bk(100) t.lt(90) t.fd(400) t.rt(90) t.fd(100)...
import math figure = str(input()) if figure == "треугольник": a = float(input()) b = float(input()) c = float(input()) p = (a + b + c)/2 s = math.sqrt(p*(p-a)*(p-b)*(p-c)) print(s) elif figure == "прямоугольник": a = float(input()) b = float(input()) s = a * b print(s) elif figu...
"""Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation. """ def what_century(year): century = int(year) // 100 + 1 century = str(century) if year[-3:] == "000" or year[-2:] == "00": if year[1::-3] == "3": return str(i...
# index(원소) : 리스트 내 특정한 원소의 인덱스를 찾기 list1 = ['나동빈', '강종구', '박진경', '박지훈'] print(list1.index('박진경')) #print(list.index('이태일')) #reverse() : 리스트의 원소를 뒤집기/그 함수를 불러오자 마자 자동으로 해당 변수의 값이 바로 뒤집혀짐 # 슬라이싱 기법 : 슬라이싱으로 변경된 list를 기존의 리스트에 다시 담아줘야 변경된 결과가 출력됨 list1 = [1,2,3] list1.reverse() print(list1) list1 = list1[::-1] print(l...
password = 'a123456' i = 0 while i < 3: userpw = input('pls enter password') if password == userpw : print('login success') break else : i = i + 1 if 3 - i > 0: print('login fail , pls retry again') print('remain', 3 - i, 'times') #elif 3 - i == 0: #print('login fail , no more chance')
def get_prime(nth): prime = [2, 3] n = prime[-1] + 2 while len(prime) < nth: isPrime = True for x in prime: if n % x == 0: isPrime = False break if isPrime: prime.append(n) n += 2 return prime def get_pri...
questions = ["name", "quest", "favourite colour"] answers = ["lancelot", "the holy grail", "blue"] for q, a in (zip(reversed(questions), reversed(answers))): print(f"what is your {q}? It is {a}.")
import sys class Node: def __init__(self, data): self.dataVal = data self.nextVal = None # Class representing a queue.The front stores the front node and rear stores the last node of Linked List class Queue: def __init__(self): self.front = None self.rear = None def isEmpt...
from collections import defaultdict import timeit import sys try: #Read all words from txt file words_file = open("words.txt","r") lines = words_file.readlines() words_file.close() #Initializing variable and data structures dictL={} sortedWordDict={} croppedDict={} anagramDict={} ...
#!usr/bin/env python from Queue import PriorityQueue class State(object): """docstring for State""" def __init__(self, value, parent, start = 0, goal = 0): self.children = [] self.parent = parent self.value = value self.dist = 0 if parent: s...
#!/usr/bin/env python3 # This code was designed to learn how to handle a Sentiment Analysis with TextBlob library. # libs from textblob import TextBlob # returns the sentiment of text def analyze(obj): sentiment = obj.sentiment.polarity # print(sentiment) if sentiment == 0: print('Neutral') elif sentimen...
#!/usr/bin/python from passlib.hash import sha512_crypt import getpass import re import sys print("***** Chose your password wisely. It should be longer than 7 character, contain atleast a capital letter, a small letter and a number *****") print( "Please enter your password") raw_password = getpass.getpass() print("...
"""Implementation of a StringBuilder""" class StringBuilder(): """Builds a string""" def __init__(self, delimiter: str = '') -> None: self.delimiter = delimiter self.charlist = [] def append(self, word: str) -> None: self.charlist += list(word) def to_string(self) -> str: ...
""" Assignment # 4 - ATM Alan Petrie This program asks the user for their PIN number. """ import random def main(): """ Main function: Evaluates if a user entered PIN is correct """ pin = 1234 counter = 0 max_tries = 3 #Get PIN from user while True: try: user_pin...
def somme(nb1, nb2): return nb1 + nb2 def moyenne(nb1, nb2): return somme(nb1, nb2) / 2 note1 = 10 note2 = 30 moyenne = moyenne(note1, note2) print("Note 1 : ", note1) print("Note 2 : ", note2) print("La moyenne est de", moyenne) def mean(nb1, nb2, nb3): return (nb1 + nb2 + nb3) / 3 print(mean(1,2,3)...
from User import User users = [] #Messages Format successMsg = 'AWESOME YOU HAVE ALREADY IN OUR APP' minorErorMsg = 'OPPS, YOU ARE MINOR' errorMsg = 'Password or user incorret' welcomeMsg='<<<<Welcome to our login form made with python>>>>' option1Msg = '1- Create a User from Scratch' option2Msg = '2- Login using JWT'...
class Parrafo(): def __init__(self): self.lineas = [] def agregar_lineas(self, nombre): entry = input("\nIngrese parrafo. Para terminar ingresesolamente '.': \n") while entry != ".": self.lineas.append(entry) entry = input("") self.lineas = '...
#!/usr/bin/env python3 import random import sys min = 1 max = 20 number = 0 part1 = 0 part2 = 0 while True: upordown = random.randint(0,1) if upordown == 1: result = random.randint(1,max) part1 = random.randint(1,result) part2 = result - part1 else: part1 = random.randin...
from tkinter import * class Calc(Frame): def __init__(self, master=None): Frame.__init__(self,master) self.grid() self.criaComponet() def criaComponet(self): self.entrada = Entry(self.master, width=34, bd =3 ) self.entrada.grid(row=1, column=0) boto...
import unittest from pprint import pprint from src.RandomGenerator.RandomGenerator import RandomGenerator class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.random = RandomGenerator() # Assigning start and end range of numbers to perform random function. self.start = 1 ...
from src.Calculator.Addition import addition from src.Calculator.Division import division def calculate_mean(data): try: total_sum = 0.0 for num in data: total_sum = addition(total_sum, num) return division(len(data), total_sum) # division will perform total_sum / len(data) ...
''' #author: cristianlepore ''' class Animal(object): def __init__(self, age, name = None): self.age = age self.name = name def get_age(self): return self.age def get_name(self): return self.name def set_age(self, newAge): self.age = newAge def set_name(self,...
''' @author: cristianlepore ''' def factorial(x): ''' input: a number output: the factorial of x ''' if x == 1: return 1 else: return x * factorial(x-1) x = 4 print(factorial(x))
''' @author: cristianlepore ''' count = 0 strToFind = "bob" s = "azcbobobegghakl" while(strToFind in s): s = s[s.find(strToFind) + 1 : -1] count += 1 print(count)
''' @author: cristianlepore ''' def applyToEach(L, f): ''' input: a list and a function output: A list after having applied the function f to each element of the list ''' for i in range(len(L)): L[i] = f(L[i]) return L def mult(a): ''' input: one numbers output: one number....
def oddTuples(aTup): ''' input: a tuple. output: a new tuple containing only the odd element of the input tuple ''' # Start code here # Definition of the new tuple myTuple = () # Loop for i in range(len(aTup)): if i % 2 == 0: myTuple += (aTup[i],) # Retu...
def mult(a, b): ''' input: two numbers output: a recursion of a times b ''' if b == 1: return a else: return a + mult(a, b-1) a = 10 b = 5 print(mult(a, b))
# 1: Создайте функцию, принимающую на вход имя, возраст и город проживания человека. Функция должна возвращать строку # вида «Василий, 21 год(а), проживает в городе Москва» def anketa(name, age, sity): info = f'{name.title()}, {age} год(а), проживает в городе {sity.title()}' return info print(anketa(...
# code_report Solution # https://youtu.be/yMxoRT381yQ # from https://docs.python.org/3/library/bisect.html import bisect def find_lt(a, x): 'Find rightmost value less than x' i = bisect.bisect_left(a, x) if i: return a[i-1] raise ValueError def find_le(a, x): 'Find rightmost value le...
import time start_time = time.time() def count(name): for i in range(1, 50001): print(name, " : ",i) num_list = ['p1','p2','p3','p4'] for num in num_list: count(num) print("---%s seconds ---" % (time.time() - start_time))
print("Введите элементы списка в строку:") num = input() nums = num.split() nums = list(map(int, nums)) n = len(nums) print('nums =', nums) def is_monotonic(nums): i = 1 counter = 0 for i in range(1,n): if min(nums) == nums[0]: if nums[i] >= nums[i-1]: continu...
#Bài 4. Nhập họ tên, tách họ tên thành 2 phần họ và tên riêng name = str(input('Nhập họ tên: ')) list_name = [] # Thêm các chữ trong họ tên vào một mảng for word in name.split(): if word.isalpha(): list_name.append(word) # Tên sẽ là chữ có vị trí cuối cùng trong mảng vừa tạo print('Họ: ', end = '') for i...
# Bài 53. Viết chương trình nhập một ma trận số nguyên có kích thước MxN. In ra: # Tổng các phần tử của ma trận # Số các phần tử dương, phần tử âm, phần tử 0 của ma trận # Phần tử lớn nhất, nhỏ nhất của ma trận # Các phần tử trên đường chéo chính của ma trận (M = N) # Tổng các phần tử trên đường chéo chính của ma trận ...
from gpio import GPIO import time #GPIO.setmode(GPIO.BCM) #GPIO.setup(26,GPIO.OUT) #GPIO.setup(19,GPIO.OUT) #GPIO.setup(13,GPIO.OUT) #GPIO.setup(6,GPIO.OUT) #GPIO.setup(5,GPIO.OUT) #GPIO.setup(11,GPIO.OUT) #GPIO.setup(9,GPIO.OUT) #GPIO.setup(10,GPIO.OUT) #D=[26, 19, 13, 6, 5, 11, 9, 10] D=[0, 1, 2, 3, 4, 5, 6, 7] ...
import math def isPalindrome(val): if ( len(val) == 1 or len(val) == 0): return 1 elif ( val[:1] == val[len(val)-1:]): return isPalindrome(val[1:len(val)-1]) else: return 0 lrg=0 for i in range(100,999): for j in range(100,999): prod = i * j string = str(prod) if (isPalindrome(string)):...
def initializeDict(pat_dict): # Initialize the value to 0 for each key for key in pat_dict.keys(): pat_dict[key] = 0 return pat_dict def initializeList(lst): # Initialize the list to empty for i in range(len(lst)): lst.pop() return lst def leastSubstring(pattern, article)...
def mergeStringSet(set_list, merge_set_list): used_set = list() set_1 = set_list[0] used_set.append(0) j = 1 while j < len(set_list): count = 0 for char in set_list[j]: if char in set_1: count += 1 if count > 0: for char in set_list...
def StringContain(long_str, short_str): # In order to sort it, transfer string to list long_str_list = list(long_str) short_str_list = list(short_str) # Sort list long_str_list.sort() short_str_list.sort() # print(long_str_list, short_str_list) # Polling character from short string to...
import sys from _collections import deque class Deque(): def __init__(self): self.deque = deque() def push_front(self, num): self.deque.appendleft(num) def push_back(self, num): self.deque.append(num) def pop_front(self): if self.size() == 0: return -1 ...
# 1. 1000보다 작은 음이 아닌 정수 10개를 입력 받는다. # 2. 입력된 값이 1000보다 작은 음이 아닌 정수가 아닐 경우 다시 입력 받도록 한다. # 3. list 하나를 만들고 입력 받은 수에 42로 나눈 나머지 값을 리스트에 저장한다. # 4. list를 set 집합으로 바꾸어서 중복된 값을 제거한다. # 5. set의 길이를 출력한다. list = [] for i in range(10): while(True): num = int(input()) if (0<= num < 1000): brea...
month = input ('Which month? ') valid = True febMonth = False if month == 'january' or month == 'march' or month == 'may' or month == 'july' or month == 'august' or month == 'october' or month == 'december': days = '31' elif month == 'april' or month == 'june' or month == 'september' or month == 'november': da...
''' Dominic Rochon DNA program COMP1405A - Fall2020 ID: 101195449 I have all the needed functions in here... A+ pls :D ''' def pair (strand): ''' Program checks the inputted letters and assigns matching pair a,A,t,T,c,C,g,G are the valid inputs, A goes with T, and C goes with G lowercase letters are autom...
import helper import datetime def count_vowels(word: str): vowels = 0 for i in word: if helper.vowel_check(i): vowels += 1 return vowels def number_of_hits(target, word): count = 0 findPos = 0 while not findPos == -1: findPos = word.find(target) if not ...
# To extract the youtube trailer link of a movie import urllib3 from bs4 import BeautifulSoup import re from mechanize import Browser import json import requests from bs4 import BeautifulSoup from requests import get import pandas as pd from urllib.parse import urlparse import httplib2 import urllib.request import sql...
s = "Deeam is a wonderful girl " ss = "is" f = s.find(ss)+len(ss) print(f)
class Foo(object): def __init__(self, func): super(Foo, self).__init__() self._func = func def __call__(self): print('class decorator') self._func() # 类装饰器 @ Foo def bar(): print('I am bar') bar()
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情'] print('------删除之前------') for tempName in movieName: print(tempName) movieName.pop() print('------删除之后------') for tempName in movieName: print(tempName)
import random # 定义一个列表用来保存3个办公室 offices = [[],[],[]] # 定义一个列表用来存储8位老师的名字 names = ['A','B','C','D','E','F','G','H'] i = 0 for name in names: index = random.randint(0,2) offices[index].append(name) i = 1 for tempNames in offices: print('办公室%d的人数为:%d'%(i,len(tempNames))) i+=1 for name in tempNames: ...
import random playerInput=input("请输入(0剪刀、1石头、2布:)") player = int(playerInput) computer = random.randint(0, 2) if (player == 0 and computer == 2) or (player == 1 and computer == 0)\ or (player == 2 and computer == 1): print("电脑出的拳头是%s,恭喜,你赢了!"%computer) elif(player == 0 and computer == 0) or (player == 1 an...
# 批量在文件名前加前缀 import os funFlag = 1 # 1表示添加标志 2表示删除标志 folderName = './' # 获取指定路径的所有文件名字 dirList = os.listdir(folderName) # 遍历输出所有文件名字 for name in dirList: print(name) if funFlag == 1: newName = '[黑马程序员]-' + name elif funFlag == 2: num = len('[黑马程序员]-') newName = name[num:] print(...
import time # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
age=30 print("------if判断开始------") if age>=18: print("------我已经成年了-----") print("------if判断结束------")
# 定义类 class Demo: data1 = 100 # 定义为属性data2赋值的方法 def set(self, num): self.data2 = num # 重载方法 def __repr__(self): # 返回自定义的字符串 return 'data1 = %s; data2 = %s'%(self.data1, self.data2) # 创建实例对象 demo = Demo() # 调用方法给属性赋值,并创建属性 demo.set(200) # 调用__repr__方法进行转换 print(demo) print(str...
# 定义类 class Car: # 移动 def move(self): print("车在奔跑...") # 鸣笛 def toot(self): print("车在鸣笛...嘟嘟...") # 创建一个对象,并用变量BMW保存它的引用 BMW = Car() # 添加表示颜色的属性 BMW.color = "黑色" # 调用方法 BMW.move() BMW.toot() # 访问属性 print(BMW.color)