text
stringlengths
37
1.41M
# Дан словарь. Добавить каждому ключу число равное длине этого ключа # решение №1 dictionary = {'test': 'test_value', 'europe': 'eur', 'dollar': 'usd', 'ruble': 'rub'} print(dictionary) for key in list(dictionary.keys()): # проходим циклом по списку ключей dictionary[f'{key}{len(key)}'] = dictionary.pop(key) prin...
"""Создать класс Car. Атрибуты: марка, модель, год выпуска, скорость(по умолчанию 0). Методы: увеличить скорости(скорость + 5), уменьшение скорости(скорость - 5), стоп(сброс скорости на 0), отображение скорости, разворот(изменение знака скорости). Все атрибуты приватные.""" class Car: def __init__(self, brand, ...
""" Дана целочисленная квадратная матрица. Найти в каждой строке наи- больший элемент и поменять его местами с элементом главной диагонали.""" import random n = 5 # размер матрицы m = [[random.randint(1, 10) for i in range(n)] for i in range(n)] for row in m: print(row) max = 0 diagonal = 0 index_max_number = 0 f...
""" Создать lambda функцию, которая принимает на вход неопределенное количество именных аргументов и выводит словарь с ключами удвоенной длины. {‘abc’: 5} -> {‘abcabc’: 5} """ double = lambda **kwargs: {k * 2: v for k, v in kwargs.items()} print(double(hello=5, goodbye=7, howareyou=9))
#! /usr/bin/python import sys import math import time def foo(x): return math.log1p(x) num1 = input("Enter first number: \n") num2 = input("Enter second number: \n") print "Adding ",num1," and ",num2," equals: ",num1+num2,"\n" time.sleep(1) print "Subtracting ",num1," and ",num2," equals: ",num1-num2,"\n" time...
class Writer: def __init__(self, file): self.__file = file def write(self, persons): fout = open(self.__file, 'a+', encoding='utf-8') for person in persons: fout.write(str(person) + '\n') fout.close
__author__ = 'liuhuiping' #PI def GetPI(index = 3): return round(355/113,index) if __name__ =="__main__": print('date strunct test') print("list's method example" ) a = [665.3,443,45,23,665.3] print(a.count(333),a.count(665.3),a.count('x')) a.insert(2,-1) a.append(333) print(a) p...
""" Parses a text file with config variables to a dictionary """ def read_config_file(filename, delimiter='='): # Open file with open(filename, 'r') as f: lines = f.readlines() output = {} # Iterate through file for l, line in enumerate(lines): if line[0] == '#' ...
# -*- coding: utf-8 from __future__ import unicode_literals import random from components.card import Card class Deck(object): # How many cards to print before a line break happens. linebreak_index = 5 # Map the suit to a textual representation. #suits = {'heart': '\u2665', # 'diamond...
#all work and no play makes Jack a dull boy w1="all" #w2="work" w3="and" w4="no" w5="play" w6="makes" w7="Jack" w8="a" w9="dull" w10="boy" s=" " #print(w1+w2+w3+w4+w5+w6+w7+w8 + w9 + s+w10) print(w1,w2,w3,w4,w5,w6,w7,w8,w9,w10) # hey I got this error please help #Traceback (most recent call last): # File "C:\Users...
apostas =[] nomes =[] import random num = 0 def menu () : print ("==========================================") print ("Opções: ") print ("1 - Adicionar aposta") print ("2 - Listar apostas") print ("3 - Sortear um número") print ("4 - Apresentar o ganhador") print ("5 - Sair") def addAposta(): apos...
numeros = [10,20,30,40,50] nomes = ["marcos", "jose", "julia"] for numero in numeros : print (numero) for nome in nomes: print (nome) ######################### numeros = [10,20,30,40,50] soma = 0 for numero in numeros : soma = soma + numero print (soma) ####################### numeros = [10,20,30,4...
from fighters.classes import Fighter from typing import List import time class Combat: def __init__(self, final_boss: Fighter, fighters: List[Fighter]): self.final_boss = final_boss self.fighters = fighters @property def fighters_still_alive(self): return all([ fighte...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np # In[9]: def flipBit(s, prob): assert s in ["0", "1"] assert prob in [0,1] if prob==1: return '1' if s=='0' else '0' return s def applyIndividualBounds(x, lower = -1, upper = 1): #x (float) x = max(x,lower) x =...
import unittest import Judge import Board class JudgeTest(unittest.TestCase): def setUp(self): self.winners = [['X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' '] ,[' ', ' ', ' ', 'X', 'X', 'X', ' ', ' ', ' '] ,[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'X', 'X'] ...
import unittest from Mars import * # Goal for these tests is to make sure that if the user input is valid, the Mars Landing Area object is created successfully class mars_tests(unittest.TestCase): def test_create_mars_landing_area_coordinate_input(self): landing_area = create_mars_landing_area(5, 5) ...
import urllib2 import json #import os word = raw_input("Enter word to search ") print("Word: "+ word) url = 'http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=' + word + '&pretty=true' #url stores the json formatted output from Glosbe result = json.load(urllib2.urlopen(url)) #json representati...
import csv import os #file_to_load = os.path.join("Election_Analysis", "election_results.csv") #with open(file_to_load) as election_data: #print(election_data) file_to_save = os.path.join("analysis", "election.analysis.txt") open(file_to_save, "w") with open(file_to_save, "w") as txt_file: #outfi...
import numpy as np def example(x): return np.sum(x**2) def example_grad(x): return 2*x def foo(x): result = 1 λ = 4 # this is here to make sure you're using Python 3 for x_i in x: result += x_i**λ return result def foo_grad(x): return 4*x**3 def bar(x): return np.prod(x) d...
# Heaviside step function numbers = [-4,-3.5,-3,-2.5,-2,-1.5,-1,-0.5,0,0.5,1,1.5,2,2.5,3,3.5,4] for x in numbers: def heaviside(x): """Heaviside step function""" theta = None if x < 0: theta = 0. elif x == 0: theta = 0.5 else: return theta theta =...
#def greet(): # print('hello world') # greet() def area(radius): return 3.142 * radius * radius def vol(area, length): print(area * length) l = int(input('enter a length:')) r = int(input('enter a radius: ')) areacalc = area(r) vol(areacalc, l)
a = int(input()) b = int(input()) print(a//b) print(a%b) print("({0}, {1})".format(a//b, a%b))
#Binary Tree is : # - One node is marked as Root node # - Every node other than the root is associated with one parent node # - Each node can have an arbiatry number of child node # tree # ---- # j < -- root # / \ # f k # / \ \ # a h ...
#Mo dau ve Tuple #duoc gioi han boi cap ngoac () #cac phan tu cua tuple duoc ngan cach boi dau , #tuple co kha nang chu moi gia tri #toc do truy xuat cua tuple nhanh hon list #dung luong chiem trong bo nho nho hon list #bao ve du lieu cua ban se khong thay doi #co the dung lam key cua dictionary tup = (1,1,2,5,6,'Kt...
''' 1. Pick an element, called a pivot, from the original list 2. Rearrange the list so that: - All elements less than pivot come before the pivot - All elements greater or equal to pivot com after pivot 3. Here, pivot is in the right position in the final sorted list(it is fixed) 4. Recursively sort the su...
#Heap Sort import timeit def Heapify(a, i, n): #array to be heapified is a[i....n] L = 2 * i #Left child R = 2 * i + 1 #Right child max = i if L < n and a[L] > a[i]: max = L if R < n and a[R] > a[max]: max = R if max != i: a[i], a[max] = a[max], a[i] Heapi...
import random # 电脑随机出拳 computer = random.randint(1, 3) user = int(input('请出拳:1/拳头,2/剪刀,3/布')) if computer == 1: computer = '拳头' elif computer == 2: computer = '剪刀' else: computer = '布' if user == 1: user = '拳头' elif user == 2: user = '剪刀' else: user = '布' print('电脑出的是{},沙雕余鹏出的是{}'.format(com...
def get_left(i): return 2*i def get_right(i): return 2*i+1 def max_heapify(a, i, n): largest = i left = get_left(i) right = get_right(i) if left<=n and a[left]>a[largest]: largest = left if right<=n and a[right]>a[largest]: largest = right if largest!=i: a[largest], a[i]= a[i], a[largest] max_heapify(...
print("APP") a = input("enter a Number : ") print(float(a)*5)
import sys # Edge class class Edge: def __init__(self, destination, weight=1): self.destination = destination self.weight = weight #Vertex class class Vertex: def __init__(self,value='vertex', color="white", parent=None): self.value = value self.edges = [] self.color = c...
#221 def print_reverse(string): print(string[::-1]) print_reverse("python") #222 def print_score(list_): sum = 0 for i in list_: sum += i print(sum / len(list_)) print_score([1, 2, 3]) #223 def print_even(list_): for i in list_: if i % 2 == 0: print(i) print_even([1,...
#101 #true 또는 flase의 데이터 타입은 bool이다. #102 print(3 == 5) #103 print(3 < 5) #104 x = 4 print(1 < x < 5) #105 print((3 == 3) and (4 != 3)) #106 print(3 >= 4) # 부등호 모양이 틀릴 경우 오류 발생 #107 if 4 < 3: print("Hello World") #108 if 4 < 3: print("Hello World.") else: print("Hi, there.") #109 if True: print(...
# coding: utf-8 # In[2]: from matplotlib import pyplot as plt import numpy as np import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ See full source and exam...
16.1 class Time(object): """Represents the time of day. attributes: hour, minute, second """ def print_time(t): print '%.2d' : '%.2d' : '%.2d' (t.hour, t.minute, t.second) def is_after(t1, t2) if t1.hour 17.6 class Point(x,y): def __init__(self, x=0, y=0,): self.x = x...
#!/usr/bin/env python # -*- mode: python; coding: utf-8; -*- import re import sys from dictionaries import * ############################################################ # Parser Class # Encapsulates access to the input code. Reads an assembly language command, # parses it, and provides convenient access to the comm...
from time import clock tiempo_inicial = clock() def heap(arr, n, i): mgrande = i # Inicializamos l = 2 * i + 1 # Izquierda = 2*i + 1 r = 2 * i + 2 # Derecha = 2*i + 2 # si es el mas grande if l < n and arr[i] < arr[l]: mgrande = l # Si hijo derecho es más grande que la má...
print("Olá, seja bem vindo!") # Exibe mensagem de boas vindas nome = input("Digite seu nome: ") # Recebe dado do usuario print( 'Olá ', nome, ", seja bem vindo!", sep="" ) # Exibe o nome do usuário # Descobrindo o tipo da variável nome type( nome ) # str é string # Caixa alta de string nome_maisculo = nome.upper() pr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 5 00:14:40 2018 @author: shawon uva : 10340 - All in All #===================================================== """ def main(): while True: try: substring,string = map(str,input().split()) n,m=len(s...
s="django"; print(s[0]); print(s[5]); print(s[:4]); print(s[1:4]); print(s[4:]); print(s[::-1]); l=[3,7,[1,4,"hello"]]; l[2][2]="goodbye"; print(l); d1={"simple_key":"hello"}; d2={"k1":{"k2":"hello"}}; d3={"k1":[{"nest_key":["this is deep",["hello"]]}]}; print(d1["simple_key"]); print(d2["k1"]["k2"]); print(d3["k1"...
#problem 1 arraycheck1=[1,1,2,3,1] arraycheck2=[1,1,2,4,1] arraycheck3=[1,1,2,1,2,3] def arrayCheck(nums): for i in range(len(nums)-2): if nums[i]==1 and nums[i+2]==2 and nums[i+2]==3: return True return False #Problem 2 def stringBits(str): result="" for i in range(len(mystring...
# card game from random import shuffle #two useful variables for creating cards. SUITE="H D S C".split() RANKS="2 3 4 5 6 7 8 9 10 J Q K A".split() # mycards=[(s,r) for s SUITE for r in RANKS] same as below # # mycards=[] # for r in RANKS: # for s in SUITE: # mycards.append((s,r)) class Deck: """ ...
import cv2 as cv import numpy as np def roi(cfg, height, width): """ Creates the rectangular region of interest Args: cfg: {obj} -- representing specified config-parameters in config.py / myconfig.py height: {int} -- height of rectangle width: {int} -- width of rectangle ...
import csv import os from tkinter.filedialog import askopenfilename #get input from user fileToOpen = 'C:\\...\\YoloRecord.csv' #askopenfilename() def csvToList(csvFile): csvList = [] with open(csvFile) as csvfile: fileReader = csv.reader(csvfile) for row in fileReader: ...
import numpy as np a = np.array([[30,17,15],[19,90,16],[69,53,21]]) print 'Our array is:' print a print '\n' print 'Applying sort() function:' print np.sort(a) print '\n' print np.sort(a,axis=1) print np.sort(a,axis=0) # Order parameter in sort function dt = np.dtype([('name', 'S10'),('age', int)]) a = ...
import numpy as np a = np.array([[1,2,3],[3,4,5],[5,6,7]]) print 'First array:' print a print '\n' b = np.array([[5,6,7],[7,8,9],[10,11,12]]) print 'Second array:' print b print '\n' # both the arrays are of same dimensions print 'Joining the two arrays along axis 0:' print np.concatenate((a,b)) print ...
import numpy as np a = np.array([1,2,3,4]) print 'Our array is:' print a print '\n' print 'Applying average() function:' print np.average(a) print '\n' # this is same as mean when weight is not specified wts = np.array([4,3,2,1]) print 'Applying average() function again:' print np.average(a,weights = ...
import random import os my_dict = { "What is the base-2 number system called" : "binary", "What is the number system that uses the characters 0-F called" : "hexadecimal", "What is the 7-bit text encoding standard called" : "ascii", "What is the 16-bit te...
import heapq as hq num=[25, 35, 22, 85, 14, 65, 75, 22, 58] print('Original list : ',str(num)) largest=hq.nlargest(3,num) print("\nThree largest numbers are : ",largest)
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} def isKey(x): if x in d: print('Key is present in dictionary') else: print('Key is not present in dictionary') x=int(input('Enter the numbers to check : ')) print(isKey(x))
import heapq as hq def heapsort(i): li=[] for value in i: hq.heappush(li,value) return [hq.heappop(li) for i in range(len(li))] print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))
def Email(F_name,L_name,email): print(' {} {}, you are sucessfully done our registration work with your Email id : {} '.format(F_name,L_name,email)) F_name=input('Enter first name : ') L_name=input('Enter last name : ') email=input('Enter the email : ') Email(F_name,L_name,email)
from collections import deque from queue import LifoQueue stack1=LifoQueue(maxsize=2) stack=deque() stack=[] stack.append('a') stack.append('b') print(stack) stack.append(1) stack.append(2) stack.append(3) stack.pop() print(stack) print("Size ",stack1.qsize()) stack1.put('a') stack1.put('b') print("Full : ",stack1.ful...
class Student: def __init__(self,name,age): self.name=name self.age=age def myFunct(self): print("Hello my name is " + self.name) p1=Student('Priyanshu Singh',19) p1.age=19 print(p1.age) p1.myFunct()
n=int(input("Enter the number to find fact : ")) factorial=1 if n<0: print("Input is wrong") elif n==0: print("Factorial is 1") else: for i in range(1,n+1): factorial=factorial*i print("factorial is " + str(factorial))
from array import * def dupli(n): n_set=set() n_dupli=-1 for i in range(len(n)): if n[i] in n_set: return n[i] else: n_set.add(n[i]) return n_dupli n=array('i',[1,3,5,4,32,65,53,243,3]) print(dupli(n))
# Importing Modules import random import sys # A Function to ask if the player would like to play again def playAgain(): answer = input("Would you like to play again? Yes/No ") answer = answer.lower() if answer == 'yes' or answer == 'y': game() if answer == 'no' or answer == 'n': print('Thank you for p...
# 给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。 # # 你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。 # # 请你计算并返回达到楼梯顶部的最低花费。 # from typing import List class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) dp = [0] * (n+2) dp[0] = 0 dp[1] = 0...
a=[1,5,7,8,9,5,88,7,4,5,82,3,5,1,2,3,5] a.sort() y=a[-1] for x in range(len(a)-2,-1,-1): if y==a[x]: a.remove(a[x]) else: y=a[x] print(a)
from create_acc import * os.chdir(os.path.dirname(os.path.abspath(__file__))) db = sqlite3.connect("data.db") cr = db.cursor() def commit(): db.commit() db.close() def create(): global create os.system('clear') print("-"*50) print( ''' Warning !! If you entered an...
#!/usr/bin/python #Python program to discover print function ''' print syntax: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) ''' #print without any parameters print() #Print a static message print( "Welcome to discover python3 print function" ) #Print value stored in variable string1 = "This i...
""" CPLab_14.1: Box ----------- This is the object class for lab 14.1. It should create a Box object. """ class Box: """Constructor""" def __init__(self, wrd=""): self.word = wrd """Modifier""" def setWord(self, wrd): self.word = wrd def getWord(self): return self.wor...
__author__ = 'Surya' class GetSs: def __init__(self, chk): self.check = chk self.count = 0 def setCheck(self, chk): self.check = chk self.count = 0 def countSs(self): for i in range(0, len(self.check)): if self.check[i] == "s": self.count...
""" Lab 22.2 List Count --------- In this lab, you will write a program that counts the number of instances of an input number in an array. for example, the array [3, 5, 3, 4] contains 2 instances of the number 3. """ from ListCount import * def main(): nums = [7, 7, 1, 7, 8, 7, 4, 3, 7, 9, 8] val = 7 ...
"""================================================================ * Lab_13.3 * * Lab Goal : * ----------- * This lab was designed to teach you more about objects and * the String class. * * Lab Description : * ----------------- * One person is going to marry another person ...
""" * APLab_14.4: Factorial *------------ * This is the object class for lab 14.4. It * should create a Factorial object. """ class Factorial: """Constructor""" def __init__(self, num): self.number = num self.Factorial = 1 """Modifier""" def setNum(self, num): self.number ...
import math class Circle: def __init__(self, r=0): self.radius = r self.pi = math.pi def setValues(self, r1=0): self.r = r1 def calcCircle(self): self.circle = self.pi * self.radius**2 def getCircle(self): return self.circle
""" Lab 23.2 List Fun House -------- In this lab, you will write a program takes an array and... - prints the sum of values from @ start to @ stop - counts the number of times val occurs in the list - returns a copy of the list with all occurrences of val removed """ from ListFunHouse import * def main(): o...
""" CPLab_15.3: Vowel Counter ----------- This is the object class for the VowelCounter lab. """ class VowelCounter: """Constructor""" def __init__(self, wrd): self.word = wrd self.found = 0 self.vowels = "aeiouAEIOU" """Modifier""" def setWord(self, wrd): self...
from Circle import* """ Declare your class and main() method """ def main(): r = int(input("What is the radius: ")) newUser = Circle(r) newUser.calcCircle() area = 22/7 * r print("Your circle is ", newUser.getCircle()) """ take user input for the radius of a circle""" """ Create a new object of th...
""" ================================================================ Lab_24.2 Sorry Game --------- In this lab, you will be writing a program that emulates the classic came "Sorry". You will move 5 pieces around a track that is 18 spaces long against a second player. The program simulates a dice roll to move...
"""Question 5: Missing a letter...""" from Five import * word = input("Please enter a word: ") down = Down(word) down.turnDown() print(down)
""" Ex_03 In this exercise, you will create a shopping list for a party. You will list at least 4 items that you need and print the results. """ class ShoppingList: def __init__(self, i1, i2, i3, i4): self.item1 = i1 self.item2 = i2 self.item3 = i3 self.item4 = i4 def getitem1(...
"""Question 3: Division by Zero error..""" class FactorCounter: def __init__(self, num): self.number = num self.count = 0 def setNum(self, num): self.number = num self.count = 0 def countFactors(self): for i in range(1, self.number): if self.number % i =...
""" * APLab_15.2: Greatest Common Denominator * ----------- * In this lab, you will create a program that takes two input * numbers, and finds their greatest common denominator. Your * finished program should take two input numbers, and print the * gcd of the two inputs. """ from GCD import* from GCD import* ...
"""======================================================================================== * EX_01: if-else statements * * Objectives: The purpose of this lab is for you to demonstrate you have learned to use * if-else statements to compare numerical data. You will be creating a * ...
srepair = "0000fixed!" print(srepair) print(srepair.strip("0")) sides = " <--I would love to touch the sides--> " #original: nothing removed print("|" + sides + "|") #removes leading whitespace.... print("|" + sides.lstrip() + "|") #removes trailning whitespace... print("|" + sides.rstrip() + "|") ...
import torch import torch.nn as nn import io import torch.nn.functional as F from torchvision import transforms from PIL import Image from pathlib import Path path = Path('app/pretrained.pt') #Define the shape/architecture of the model since pre-trained model can be further worked upon, or an test image can be used to...
#Create a function that shows the incomplete word/phrase that includes the letter(s) that have been guessed correctly #Do an double if in the else #mixed case letter: not str.islower() and not str.isupper() name = "Dod" if "X" in name: print('Yes') else: print("no")
A = int(input("Enter the principal amount : ")) B = int(input("Enter the number of years : ")) C = int(input("Enter the rate of interest : ")) SI = (A * B * C)/100. print("Simple interest : {}". format(SI))
#!/usr/bin/env python import argparse def main(): # parse CLI args parser = argparse.ArgumentParser(description="Computes profit/loss of a PokerStars HomeGame.") parser.add_argument("-b", "--buy-in", type=float, default=5, help="buy in (€)") parser.add_argument("players", metavar="PLAYER BALANCE", n...
''' Using while loop , if else , for, break Divisible by 3 - Fizz Divisible by 5 - Buzz Divisible by 3 and 5 - Fizz Buzz Prime number - Prime ''' count=1 while(count<=100): if(count%3==0 and count%5==0): print(count ,"-","Fizz Buzz") elif(count==1 or count==2 or count==3 or count==5): print(count ,"-","Prime")...
class Node: # Initialize the class def __init__(self, position: (), parent: ()): self.position = position self.parent = parent self.g = 0 # Distance to start node self.h = 0 # Distance to goal node self.f = 0 # Total cost # Compare nodes def __eq__(self, other...
#Задача 4. Вариант 5. #Напишите программу, которая выводит имя "Жан Батист Поклен", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. #Dzhariashvili D. G. #15.04.2016 real_name = "Фредерик Аустерлиц" imaginary_name =...
# PONG Gone Wild # Date: Aug 30, 2018 # By: Kavan Lam ###################################################################################################################### # The following is an independent game project. The game is called 'PONG Gone Wild' and is a twist to the classic # # arcade game, 'PONG'...
import prompt tries_count = 3 def flow_game(get_quiz, case): print("Welcome to the Brain Games!") print(case, end="\n\n") user_name = prompt.string("May I have your name? ") print("Hello, {}!".format(user_name)) for i in range(tries_count): question, correct_answer = get_quiz() pr...
# name="fngksjlxmzadkkdkf" # print(name[0]) #数组第一位 # print(len(name)) #数组长度 # print(name[2:5]) #数组第三位到第五位 # my_List=["你好",2018,2019,2020,"许桐","许桐"] # print(my_List[0]) #第一位 # my_List.append("大哥") #将对象追加到列表末尾 # print(my_List) # print(my_List.count("许桐"))#返回值出现的次数,许桐出现两次 # help(my_List) # mylist=[1,2,3,4,5] # ...
import sqlite3 def main(): with sqlite3.connect("Database.db") as db: cursor=db.cursor() sql="""create table User (UserName text, Password text, FirstName text, LastName text, Email text, StartFavourite...
# -*- coding: utf-8 -*- """ Created on Fri Jan 15 15:30:06 2021 @author: sangliping """ num = input('请输入一个数字:') if int(num)<10: print(num) if 3: #整数作为条件表达式 print('ok') a = [] #列表作为表达式 空列表为False if a: print('空列表 False') s = 'False' #非空字符串 if s: print('非空字符串') c = 9 if 3<...
import _thread import time # 为线程定义一个函数 def print_time(threadName,delay): count = 0 while count < 3: time.sleep(delay) count += 1 print(threadName,time.ctime()) _thread.start_new_thread(print_time,('Thread-1',1)) _thread.start_new_thread(print_time,('Thread-2',2)) #time.sleep(5) print('...
# -*- coding: utf-8 -*- """ Created on Thu Dec 3 08:44:58 2020 @author: sangliping """ import numpy as np x = np.arange(8) print(x) #[0 1 2 3 4 5 6 7] print(np.append(x,8)) #是在副本上添加 [0 1 2 3 4 5 6 7 8] print(np.append(x,[9,10])) #[ 0 1 2 3 4 5 6 7 9 10] print(np.insert(x,1,8)) #[0 8 1 2 3 4 5 6 7] x[3]...
# -*- coding: utf-8 -*- """ Created on Tue Dec 1 23:14:02 2020 @author: sanglp """ print(60 in [70,60,50,80]) print('abc' in 'abcwqwe') print([3] in [[3],[4],[5]]) print('3' in map(str,range(5))) print(5 in range(5))
# -*- coding: utf-8 -*- """ Created on Fri Jan 15 14:06:22 2021 @author: sangliping """ r1 = {'name':'高小一','age':18,'salary':30000,'city':'北京'} r2 = {'name':'高小二','age':19,'salary':10000,'city':'上海'} r3 = {'name':'高小五','age':20,'salary':10000,'city':'深圳'} tb = [r1,r2,r3] print(tb) # 获得第二行人的薪资 print(tb[1].get('salary'...
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Float, or_, and_ from sqlalchemy.orm import sessionmaker import requests """ACCESSING A TABLE""" engine = create_engine('sqlite:///homework_sql.db', echo=True) Base = declarative...
''' Moataz Khallaf A.K.A Hackerman main 2/20/2019 ''' ###___imports___### import csv, time, random ###___vars/arrays/dicts___### #useless and overcomplicated. I'm just too proud to take it out DvM = { #Disney vs Marvel .... "D" : 1, "M" : 2 } char = 1 ###___Subs___### ###input def menu(): ...
import tensorflow as tf # step 1: pre-process the data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("mnist", one_hot=True) X_train = mnist.train.images y_train = mnist.train.labels X_test = mnist.test.images y_test = mnist.test.labels x = tf.placeholder(tf.float32, ...
## time clock ## # In/Out Low Value In/Out High Value Rounded Value Hours # :0 :7 :00 0.00 # :8 :22 :15 0.25 # :23 :37 :30 0.50 # :38 :53 :45 0.75 # :54 :59 :60 1.00 def main(): week=[] workweek=["Monday","Tuesday","Wendsday","Thursday","Friday"] #get all the hours for the week and ...
# This is my first program print ("Hello World") myName = input("What is your name?\n") print ("Your name is " + myName) print("Hello World again!")
""" Sets are unordered collection os unique elementss Meaning there can only be onr representative of the same object Lets see some examples """ myset=set() myset.add(1) print (myset) myset.add(2) print (myset) myset.add(2) print (myset) mylist=[1,1,1,1,1,3,3,3,3,3,4,4,4,34,3,3,3,3,22,...
print ('hello') print (len('hello')) mystring="hello World" print (mystring[0]) print (mystring[5]) print (mystring[-5]) print (mystring[9]) print (mystring[2:]) print (mystring[:]) print (mystring[:3]) print (mystring[1:3]) print (mystring[::]) print (mystring[::2]) print (mystring...
some_value="100" print (some_value.isdigit()) def user_choice(): choice="WRONG" while choice.isdigit()==False: choice=input("Please enter a number(0-10): ") if choice.isdigit() == False: print ("Sorry that is not a digit") print (int(choice)) user_choice() ...