text
stringlengths
37
1.41M
from cs50 import get_int def main(): while True: credit_number = get_int("Your credit number: ") if credit_number > 0: break if credit_number > 5100000000000000 and credit_number < 5600000000000000: if func(credit_number, 8) == 0: print("MASTERCARD") el...
""" 各种算法的公用数据结构 """ import random from numpy import array class Sample: def __init__(self, _feature=None, _target=None): self.feature = _feature self.target = _target class SampleSet: """ 保存所有训练数据的集合,只接受list类型的feature """ def __init__(self, features=None, targets=None): ...
x = int(input("How many candies do you want")) av = 10 i =0 while i <= x: if(i > av): break; print("candies ",1) i += 1 print("Out Of Stock") print("Bye")
# general Function def add(x,y): return x + y result = add(3,4) print(result) # lambda Function result1 = lambda a,b: a+b # single line functions print(result1(2,5))
# Script for Python3.* by Stephen Curtis - 12 Dec 2016 from tkinter import * from tkinter import ttk from datetime import datetime from datetime import timedelta expected = "" def calc(): now = datetime.now() wdlt = e.get() cdlt = (int(wdlt) / 5) * 7 due = now + timedelta(days=cdlt...
hours = { '1': '13', '2': '14', '3': '15', '4': '16', '5': '17', '6': '18', '7': '19', '8': '20', '9': '21', '10': '22', '11': '23', '12': '00' } string = input().split(':') if string[0] != '12': if 'PM' in string[1]: string[0] = hours[string[0]] print...
noises = input().split() for noise in noises: if noise == 'Grr': print('Lion', end=' ') elif noise == 'Rawr': print('Tiger', end=' ') elif noise == 'Ssss': print('Snake', end=' ') else: print('Bird', end=' ')
############################################################################################################ # # This is a very old interface I made when I just started out in python. It has been rewritten # for my thesis and edited for the kinect Pong game I did during my internship # # It allows easy usage of i...
#given an array of integers find the missing number in the array def missingnumber(arr): num = 0 n = sorted(arr) for i in range(0, len(arr)-1): n = arr[i]+1 == arr[i+1] if n == False: return arr[i]+1 arr = [1,2,3,5,6,7,8,9] result = missingnumber(arr) print(result)
#this equation seems to work for any array filled with a set of consecutive numbers ( each integer only appears once ) nums = [1,2,3,4,5,6,7,8,9,10] n = len(nums) print('Sum of array ', n*(n+1)//2)
#Write a function to find the longest common prefix string amongst an array of strings. #If there is no common prefix, return an empty string "". class Solution: def longestCommonPrefix(self, strs): x = '' dict = {} l = [] for s in strs: if s not in dict: ...
#Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. #For example, two is written as II in Roman numeral, just two one's added together. #Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. #exceptions: #I can be placed bef...
#!/usr/bin/env python # encoding: utf-8 """ @version: 1.0 @author: lizhifeng @license: no @contact: lizhifeng2009@126.com @site: @software: PyCharm Community Edition @file: command.py.py @time: 15/12/22 下午1:27 """ class Brucer: def makeMutton(self): print "cook mutton" def makeChicken(self): ...
#!/usr/bin/env python # encoding: utf-8 """ @version: 1.0 @author: lizhifeng @license: no @contact: lizhifeng2009@126.com @site: @software: PyCharm Community Edition @file: bridge.py.py @time: 15/12/22 下午3:20 """ class Machine: def action(self): pass class Computer(Machine): def action(self): ...
name_list = ["张三", "李四", "王五", "李四"] # len (length 长度) 函数可以统计列表中元素的总数 list_len = len(name_list) print("列表中包含%d个元素" % list_len) # count 方法可以统计列表中某一个数据出现的次数 str_count = name_list.count("李四") print("\"李四\"出现的次数是%d次" % str_count)
# Tuple 元组与列表类似,不同之处在于元组的元素不能修改 info_tuple = ("zhangsan", 18, 1.75, 18) print(type(info_tuple)) print("名字是 %s" % info_tuple[0]) single_tuple = (5,) print(type(single_tuple)) # 取值和取索引 print(info_tuple[1]) print(info_tuple.index(1.75)) # 统计计数 print(info_tuple.count(18)) print(len(info_tuple)) # 循环遍历 for info in in...
# post请求(携带了参数) # 响应数据是一组json数据 import requests import json if __name__ == '__main__': # 1.指定url post_url = "https://fanyi.baidu.com/sug" # 2.UA伪装:将对应的User-Agent伪装到一个字典中 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280....
for num in [1, 2, 3]: print(num) if num == 2: break else: # 当for循环完全执行完后,才会执行else部分 # 当循环因break退出,else部分不会执行 print("这里会执行吗") print("循环结束")
# 1.判断空白字符 space_str = " \t\n\r" print(space_str.isspace()) # 2. 判断字符串中是否只包含数字 # >1 都不能判断小数 # >2 isdecimal 判断全角数字 # isdigit 可判断全角数字、①、\u00b2 # isnumeric 可判断全角数字、汉字数字 num_str = "1" print(num_str) print(num_str.isdecimal()) # True print(num_str.isdigit()) # True print(num_str.isnumeric()) # True nu...
# By Python para zumbi - Profº Fernando Masanori # 5) Solicite o preço de uma mercadoria e o percentual de desconto. # Exiba o valor do desconto e o preço a pagar. preco = float(input("Digite o preço da mercadoria:\n")) desconto = float(input("Digite o percentual de desconto:\n")) preco_final = preco - (preco * desco...
import readData # Sets the size of the square features. DIM = 3 # Method for getting features where each feature is the number of pixels in # each square of size DIM x DIM. Contains additional loops for if the size of # the image is not divisible by the DIM. Used for face classification def getFeatures(data, width, h...
#LZW encoder #Name: Mounika Rayana #Student ID: 801168148 #importing the required libraries import sys import struct from struct import * input_file = sys.argv[1] #taking the input file from the command line file1 = open(input_file,"r") #opening the file input_string = f...
# Easy Collection # Array # Language : Python3 # Question: https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/ # Remove duplicates from sorted array # Statement: Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length....
import random coin=int(random.randint(25,100)) print("coin=",coin) o=int(input("How many players will play?:")) z=coin while True: if o==2: if z==coin: x=int(input("player1:")) if(x<coin and x>0): coin=coin-x print("coin=",coin) ...
class student: def __init__(self,first_name,last_name,age): self.name = first_name +" " +last_name self.age = age s1 = student("sanjay","dangwal",19) print(s1.name)
def func(input_list,**kwargs): if kwargs.get("reverse_str"): return [name[::-1].title() for name in input_list] else: return [name.title() for name in input_list] #return [name[::-1] for name in input_list] string=['sanjay','vijay'] print(func(string)) print(func(string,reverse_str=True))
def even_num(n): for i in range(n+1): if(i%2==0): yield i for i in even_num(10): print(i)
with open("file_ex.txt","r") as fr: with open("file_result.txt","w") as fw: for line in fr.readlines(): name,salary = line.split(",") fw.write(f"{name}'s salary is {salary}")
def multiply(num,*args): num_list=list(args) for i in range(len(num_list)): num_list[i]=num_list[i]*num return tuple(num_list) print(multiply(4,2,4,5,1,3))
def reverse(l): reverse_list =[] for i in range(len(l)): reverse_list.append(l.pop()) #print(l) return reverse_list name = input("enter a list : ").split(",") #print(name) for j in reverse(name): print(j, end =",")
square = [] for i in range(1,11): square.append(i**2) print(square) square2 = [i**2 for i in range(1,11)] print(square2) negative = [] for i in range(1,11): negative.append(-i) print(negative) negative2 = [-i for i in range(1,11)] print(negative2) names = ["sanjay","deepak","riya"] first_latter = [] for name...
char_name = " Akshay " print(char_name+" is a good boy") uName =input("Your Name Please: ") uName2=input("Your last Name Please:") print(uName +" "+ uName2) from student import student student1=Student("Jim","Bus",3.8,True)
from tkinter import * from tkinter import messagebox def qualification(): amount = entryamount.get() try: amount = int(amount) if amount > 5000: messagebox.showinfo("STATUS FEEDBACK","Congratulation. You Qualify to go to Malaysia") else: messagebox.showinfo("STA...
#!/usr/bin/ env python3 """ Python script to handle the clients side.""" import socket import os import time from sys import exc_info, platform def format_file_size(size): """ Formatted size of the file on Bytes, KB, MB or GB. :param size: the size of the file in Bytes. :return: Formatted ...
#Universidad del Valle #Curso: Tecnologías Geomáticas #Docente: Ing. Carlos Quiroga #Hecho por: #Jose Miguel Vera Saavedra y Vanessa Hernandez Bedoya import serial #se importa la libreria serial import time #Se importa la libreria time import pandas as pd #Se importa la libreria pandas ser = serial.Serial("COM3",9600...
''' Write a Python program that converts miles to kilometers. Specifically, the program should: 1.)Asks the user to enter the number of miles 2.)Convert the number of miles to kilometers and store it in a variable named kilo 3.)Print the message “Your value expressed in kilometers is: “ followed by the value kilo ''' ...
#Mulitiplication Table a=int(input('Enter a number: ')) for i in range(1, 11): print('{}*{}={}' .format(a,i,a*i)) print('********************')
#triangle #1 for i in range(0,10): for j in range(0,i+1): print('* ', end='') print(end='\n') #2 for i in range(0,10): print('* '*i) #3 n=11 for i in range(0,11): for j in range(0,n): print(end=' ') n=n-1 for k in range(0,i): print(end='* ') print(end='\n...
from collections import Counter def get_group_count(group): group_count = 0 letter_counts = Counter(group) for letter in letter_counts: if letter_counts[letter] == group_len: group_count += 1 return group_count with open('input.txt') as inp: group = [] groups_anyone = [] ...
running_sum = 0 sums = [] with open('input.txt', 'r') as _file: for line in _file: if line == "\n": sums.append(running_sum) running_sum = 0 else: running_sum += int(line) sums.append(running_sum) # part 1 print(max(sums)) # part 2 print(sum(sorted(sums, reverse...
from tkinter import * from tkinter import ttk root = Tk() notebook = ttk.Notebook(root) notebook.pack() # pack is geometry manager frame1 = ttk.Frame(notebook) frame2 = ttk.Frame(notebook) notebook.add(frame1, text='tab1') notebook.add(frame2, text='tab2') # when call the tab method, it will add tab on the right ttk...
from tkinter import * root = Tk() canvas = Canvas(root) canvas.pack() canvas.config(width=640, height=480) line = canvas.create_line(160, 360, 480, 120, fill='blue', width=5) # starting x, y. ending x, y pixels canvas.itemconfigure(line, fill='green') # change the item 'line' in canvas print(canvas.coords(line)) # ge...
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f: f = open("dictionary.txt","r") print("Can your password survive a dictionary attack?") my_list = [] for line in f: my_list.append(line.strip()) #Take input from the keyboard, storing in the variable test...
# Now we step into randomness """ |_|_|_|_|_ |_|_|_|_|_ |_|_|_|_|_ | starting point If we consider the above figure, we can see the grid and a starting point. let us consider the starting point as home. Now given a number of blocks, we must be able to list some random walks which if taken the distance will be less t...
# Here we will learn about two functions """ sort() and sorted() sort() : changes the existing list cannot be used on a tuple as tuple is immutable sorted(): creates a new list out of a tuple or a list or a string what ever may be the input, the output is list """ list1 = ["orange","apple","berry","green a...
# To read/ write data into csv.. # lets try without csv module. path ="NewGoogle Stock Market Data.csv" file = open(path) data = [line for line in file] print(data[0]) print(data[1]) line = data[1] print(type(line[0])) # here every value is in the form of a string print(line[0]) # still not comma seperated # lets ...
# functions """THIS IS A DOC STRING... MAINLY USED FOR DOCUMENTATION""" def Area(): print("area") Area() # Can have aruguments and return types import math def volume(r): return (4/3 * math.pi* pow(r,3)) print(volume(3)) # we can have any number of arguments. While calling we must # make sure that we pas...
def is_prime (n): count = 0 for i in range (1, n+1): if n%i==0: count += 1 if count == 2: return True return False n = int (input()) print(is_prime(n))
#Import Libraries import os #Gives Python access to Linux commands import time #Proves time related commands import RPi.GPIO as GPIO #Gives Python access to the GPIO pins GPIO.setmode(GPIO.BCM) #Set the GPIO pin naming mode GPIO.setwarnings(False) #Supress warnings #Set pin 25 as an i...
from PIL import Image from gcbmanimation.util.tempfile import TempFileManager Image.MAX_IMAGE_PIXELS = None class Frame: ''' Represents a presentation-format image that can be included in an animation. A frame usually applies to a particular year and points to an image file on disk. Arguments: 'ye...
#!-*- coding:utf-8 -*- shoping = [ ('苹果手机',6400), ('笔记本电脑',8600), ('手表',3000), ('机票',5000), ('汽车',9990), ('书',400) ] shoping1 = [] #存放已买商品 salary = input("输入你的工资>:") if salary.isdigit():#判断是不是整数 salary = int(salary) while True: for index,item in enumerate(shopin...
""" Fama-French-Three-Factor-Model Implementation ---------------------------------------------------------------------------------------------------------------- Here is the workflow of the model realization in this file: 1) Get data (ticker pool, S&P500, risk free rate, close price, market cap and book-to-market ...
''' This is an example of fitting noisy data. This program will produce accurate restricted polynomial fitting for the data inputted. A plot of the fit and data will be produced as well. The main limitation of this algorithm is that it does not work for data distributions with significant gaps on the x axis betwe...
""" Class Basics class Ajith: x=10 a1=Ajith() print(a1.x) """ """ Class with Self class Ajith: name="ajith" def __init__(self, name, age): self.name=name self.age=age Ak=Ajith("kumar",32) print(Ak.name) """
# La PEP 572 introduce le Assignment Expression # Le Assignment Expressions sono indentificate dall'operatore Walrus (Tricheco) Operator := class AssignmentExpression: pass if __name__ == "__main__": def somma(a, b): return a+b # if x = somma(3,5) > 6 -> senza operatore Walrus andrebbe in errore ...
''' BinaryTree structure is copied from https://github.com/heineman/python-algorithms ''' class BinaryNode: def __init__(self, value): self.value = value self.left = None self.right = None def add(self, val): if val <= self.value: self.left = self.addToSubTree(self.l...
# -*- coding: utf-8 -*- import re def word_count(sentence): counted_words = dict() clean_sentence = re.sub(r'[^а-яА-ЯA-Za-z0-9]', ' ', sentence) words = clean_sentence.lower().split() for word in words: counted_words[word.decode('utf-8', errors='ignore')] = words.count(word) return count...
NORTH, EAST, SOUTH, WEST = 0, 1, 2, 3 X_MOVES = [0, 1, 0, -1] Y_MOVES = [1, 0, -1, 0] class Robot(): def __init__(self, bearing=NORTH, x_cor=0, y_cor=0): self.bearing = bearing self.x_cor = x_cor self.y_cor = y_cor self.movements = { 'A': self.advance, 'R': ...
# Given a string of brackets, determine if the string is balanced from stack import Stack def is_balanced(code_string): opening_brackets = ["{","[","(","<"] closing_brackets = ["}","]",")",">"] bracket_matches ={"}":"{","]":"[",")":"(",">":"<"} s = Stack() brackets_extracted = [] for letter ...
import threading import time import random # Custom thread object class custThread(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.name = name def run(self): getTime(self.name) print("Thread ",self.name," Execution Ends ") def getTime(name...
for i in [0,1,2,3,4,5]: print(i**2) for i in range(6): # createsan iterator over that range producing it one at a time print(i**2) print("\n\n Looping over list : The right way :") colors = ['red','blue','green','yellow'] for i in range(len(colors)): # don't do this print(colors[i]) for color ...
class Stack: def __init__(self): self.stack = [] def push(self,val): self.stack.append(val) def pop(self): if self.isempty(): return None else: self.stack.pop() def print_stack(self): print(self.stack) def size(self): retur...
import random string = "a quick brown fox jumps over the lazy dog" string = list(string) jumbled = "" print(string) for letter in range(0,len(string)-1): jumbled += string.pop(random.randint(0,len(string)-1)) print(string) print(jumbled)
print("\nWith list comprehension") my_nums = [ x*x for x in [1,2,3,4,5]] print(my_nums) print("\nWith GENERATORS - replace square brackets with parentheses") my_nums = ( x*x for x in [1,2,3,4,5] ) print(my_nums) # use generator only once , below 2nd print wont work after 1st runs for num in my_nums: pr...
#! /usr/bin/env python3 # load required modules from Bio import SeqIO import argparse # create an ArgumentParser object ('parser') that will hold all the info necessary to parse the command line parser = argparse.ArgumentParser(description="This script filters out user-specified sequence(s) from a FASTA file") # use...
''' Question 2.1 Skeleton Code Here you should implement and evaluate the k-NN classifier. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt import math from collections import Counter from sklearn.model_selection import KFold class KNearestNeigh...
#Nursima Donuk and William Lu import random sentence = 'Yesterday, <PERSON> and I went to the park. On our way to the <ADJECTIVE> park, <PERSON> and I saw a <ADJECTIVE> <NOUN> on a <NOUN> .' PERSON = ['my professor', 'Sam', 'my friend', 'Alex', 'my dog', 'my mother'] ADJECTIVE =['pink', 'big', 'fast', 'gross', 'flat']...
def countApplesAndOranges(s,t,a,b,apples,oranges): new_apples = [] new_oranges = [] for positiona in apples: new_pa = a + positiona new_apples.append(new_pa) for positiono in oranges: new_po = b + positiono new_oranges.append(new_po) apple_count = 0 orange_count ...
""" This code solves for Question 2 """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import lognorm # read the data print("##################### Loading the raw data... #######################") green_data = pd.read_csv("green_tripdata_2015-09.csv") print('Green Taxi data ...
def load_map(add): f = open(add, "r") line=[] for x in f: line.append(x) return (line) # pacman_map = load_map("map/level1.amap") # for line in pacman_map: # print (line) def simplify_map(array): new_array= [] for i in array: l_sym=['═', '║', '╔', '╗', '╚', '╝'] for...
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy as np import matplotlib.pyplot as plt #1. 데이터 x = np.array([1,2,3,4,5,6,7,8,9,10]) y = np.array([1,2,3,4,5,6,7,8,9,10]) x_train = x[:7] y_train = y[:7] x_test = x[7:] y_test = y[7:] [print(i) for i in x_train] print...
def get_county_data(file_name, num_rows=None): """ Retrieves a single data-file from the King County Assessors webstie. Retrieves the single data-file from the King County Assessors webstie defined by file_name using the Pandas read_csv() function Args: file_name: The name of the file t...
#Lesson 1 #Creating and instantiating classes and instances of those classes. #Example of a class in Python. class Employee: # This is the constructor method __init__ which initializes all attributes of a object. def __init__(self, first, last, pay): self.first = first self.last = last ...
def pythag_trip(): r = 'y' while r != 'n': try: s1 = int(input("Enter a side: ")) s2 = int(input("Enter a side: ")) s3 = int(input("Enter a side: ")) l = [s1, s2, s3] max_l = max(l) #print(s1**2 + s2**2) == (max_l**2) if...
def largest_Palindrome(): l1 = [] l2 = [] l3 = [] l4 = [] l1 = [x for x in range(100, 1000)] l2 = l1 for x in l1: for y in l2: l3.append(x*y) for x in l3: if str(x)[::-1] == str(x): l4.append(x) return max(l4) x = largest_Palindro...
story = '''_______! he said ________ as he jumped into his convertible ______ and drove off with his ___________ wife.''' print(story) values = {'noun':'','verb':'','adjective':''} values['noun'] = input("\nEnter a noun (Person, Place or Thing): ") values['verb'] = input("\nEnter a verb (action): ") values['ad...
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> def square(x): return x * x >>> def my_map(func, arg_list): result =[] for i in arg_list: result.append(func(i)) return result >>> square...
def ninety_nine_bottles(): lst = [x for x in range(0,100)] lst.reverse() for x in lst: while x > 1: print(str(x) + " bottles of beer on the wall " + str(x) + " bottles of beer, take one down pass it around, " + str(x-1) + " bottles of beer on the wall!") print("\n") ...
from urllib.request import urlopen from urllib.parse import urljoin from bs4 import BeautifulSoup # $ pip install beautifulsoup4 url = input('Enter - ') for _ in range(18): # repeat 18 times soup = BeautifulSoup(urlopen(url)) a = soup.find_all('a', href=True) # all <a href> links if len(a) < 3: # ...
''' fully credit to anthonywritescode''' ''' day19_x is n unefficient way to do this question''' import itertools import collections import re def day19_1(): with open('/Users/xinyue/Downloads/day19_1.txt','r') as file: input_file = file.read().split('\n\n') rules_dic = {} for i in input_file[0]....
import random class Weapon: def __init__(self): self.weapon_name = '' self.weapon_attack_power = 0 self.weapon_name_randomized() self.attack_power() def weapon_name_randomized (self): weapon_names = ["axe", "sword", "polearm", "naginata", "Throwing star", "Spear", "Dagg...
# 819. Most common word """ Given a string paragraph and a string array of the banned words banned, r eturn the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique. The words in paragraph are case-insensitive and the answer should be ret...
# 알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오. # 길이가 짧은 것부터 # 길이가 같으면 사전 순으로b import sys sys.stdin =open('1181_input.txt','r') N = int(input()) words = [] for _ in range(N): words.append(input()) words = list(set(words)) # 길이 순 정렬 / 2순위 : 사전 순 정렬 words = sorted(words,key= lambda x : [len(x),x]) ...
# Given the root of a binary tree, return its maximum depth. # # A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # 깊이를 측정하는데에는 여러 방법이 있지만 먼저 BFS를 이용해서 풀어보겠다. from collections import deque # Definition for a binary tree node. class TreeNod...
class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: res=[] table={} a=["Table"] for i in orders: if i[2] not in a: a.append(i[2]) if i[0] not in table: table
# Lesson10, Task3 # import own module import numerical_methods as num # set initial data a = 0 b = 1 def f(_x): return (3*(1 + _x**(4/3)))**(-1) # calculate and print results integral = num.trapeze(f, a, b, 6) print("I = {} for n = 6".format(integral)) print ()
# LEsson6, Task4 # import own module import matrix_operations as m_op # import numpy module import numpy as np # set initial data B = [] x0 = [] for i in range(20): B.append([]) x0.append([1]) for j in range(20): if i == j: B[i].append(round(0.025 * (i+1),3)) elif j == i...
#Lesson10, Task1 # change own method for particular task def trapeze(_f, _v, _p, _m = 2000, _eps = 0.0001): """Finds numerically definite integral of function in the interval [_a, _b] with precision _eps and returns the value of the integral""" """By default amount of nodes is 20""" # variable for the...
#program to find a meter conversion #Get input from user A=int(input("")) def conversion(A): B=A*1000 return B def conversion2(A): C=A*100000 return C B=conversion(A) C=conversion2(A) print(B) print(C)
#program to remove repeated string S=input().split() X=input() i=S.count(X) if(i>0): c=S.index(X) S.pop(c) print(*S,end='') else: print(*S,end='')
#Program for converting celsius to farenheit #Get input from user A=float(input("")) #convert it into fahrenheit farh=(A*9/5)+32 #display the output B=round(farh,2) print(B)
#program to find multiple of 3 N=int(input("")) l=[] for i in range(1,4): l.append(i*N) print(*l,end='')
#Program to find factorial of a given number #Get input from user N=int(input("")) #Initialize the value fact=1 #Check the number is positive def facto(): fact=1 if(N>0): for i in range(1,N+1): fact=fact*i return fact elif(N==0): return 0 facto() print(facto())
#password verification import hashlib user="Durga" password="Durga23" word=hashlib.sha256(password.encode()).hexdigest() for i in range(1,6): user1=input("Enter username") password1=input("Enter password: ") pass1=hashlib.sha256(password1.encode()).hexdigest() if(user==user1): if(pass1==word): ...
#Program to print first and third character of string #Get input from user s=input() #print two letter of string print(s[0],end="") print(s[2])
# coding=utf-8 # 使用时先导入 import calendar # calendar:获取一年是日历字符串 # 参数 # w = 每个日期之间的间隔字符数 # l = 每周所占用的行数 # c = 每月之间 的间隔数 cal = calendar.calendar(2020) print(cal) cal = calendar.calendar(2020, l=0, c=5) print(cal) # isleap: 判断是否是闰年 isLeap = calendar.isleap(2020) print(isLeap) # leapdays: 获取指定年份之间的闰年的个数 print(calendar....
# coding=utf-8 def printFunc(): print("*" * 100) return None # 函数名可以当变量使用 def sayHello(name): print("{0} 你好, 来一份牛排吗?".format(name)) sayHello("月月") # 函数名当变量使用直接 yueyue = sayHello yueyue("yueyue") # 自己组装类 示例 1 class A(): pass def say(self): print("Saying......") class B(): def say(self): ...
# coding=utf-8 # 死锁案例 import threading import time lock_1 = threading.Lock() lock_2 = threading.Lock() # 先申请的锁后释放 原则 def func_1(): print("func_1 starting.....") lock_1.acquire() print("func_1, 申请了 lock1.......") time.sleep(2) print("func_1等待 lock2..........") lock_2.acquire() print("func_1...
from random import randrange guessed_letters = [] def choose_word(): with open('words.txt', 'r') as words_list: num_lines = sum(1 for line in words_list) random_line = randrange(1,num_lines) words = open('words.txt') lines = words.readlines() word = lines[random_line] return word[0:-1] def initialize_...
#Q.1- Name and handle the exception occured in the following program: #a=3 #if a<4: # a=a/(a-3) # print(a) # try: # a=3 # if a<4: # a=a/(a-3) # print(a) # except Exception: # print("Hello") # Q.2- Name and handle the exception occurred in the following program: # l=[1,2,3] # print(l[3]) # try: # l=[1,2,...