text
stringlengths
37
1.41M
# Courtsey : https://www.geeksforgeeks.org/python-design-patterns/?ref=lbp """ In the Classic implementation of the Singleton Design Pattern, 1. we simply use the staticmethod for creating the getInstance method which has the ability to return the shared resource. 2. We also make use of so called Virtual private co...
S = input("Insira o conjunto S, separado por espaço: ") setS = [] for x in S.split(): if x not in setS: setS.append(x) powerset = [[]] for x in setS: powerset.extend([subset + [x] for subset in powerset]) for sub in powerset: print(sub)
#!/usr/bin/env python import turtle import random import math def draw_stuff(): window = turtle.Screen() window.bgcolor("white") brad = turtle.Turtle() brad.shape("turtle") brad.color("black") brad.speed(20) for i in range(0,180): brad.right(i) #first box for i in range(0,4): brad.forward(100) ...
''' Returneaza true daca n este prim si false daca nu. ''' def is_prime(n): # codul vostru aici ePrim=1 if n==1 or n==0: return False for i in range(2,n//2+1): if n%i==0: ePrim = 0 return False if ePrim: return True ''' Returneaza produsul numerelor din lista lst. ''' def get_prod...
# DATATYPES LESSON # Python Data Types from Basic to Advanced # 1. Booleans # 2. Numbers # 3. Strings # 4. Bytes # 5. Lists # 6. Tuples # 7. Sets # 8. Dictionaries # 1. Booleans condition = False if condition == True: print("You can continue with the prpgram.") else: print("The program will end here.") # skip ...
# TIME COMPLEXITY: O(N + Log N) # SPACE COMPLEXITY: O(N) class TopVotedCandidate(object): def __init__(self, persons, times): """ :type persons: List[int] :type times: List[int] """ self.times = times self.persons = persons # Map to keep track of the leader a...
''' name = input('Enter:') print(name) apple=input ('Enter:') x=int( apple) - 10 print(x) ''' ''' str1 = "Hello" str2 = "there" bob = str1 + str2 print(bob) str3 = '123' str3 = str3 + 1 x = int(str3) + 1 print (x) ''' ''' fruit = 'banana' letter = fruit[1] print(letter) x=3 w = fruit[x-1] print(w) ''' ''' Name = 'La...
# 题目:画图,学用circle画圆形。 from tkinter import * canvas = Canvas(width=400, height=500, bg='yellow') canvas.pack(expand=YES, fill=BOTH) k = 1 j = 1 for i in range(0,26): canvas.create_oval(210 - k,210 - k,210 + k,210 + k, width=0.5) k += j j += 0.5 mainloop() ''' import tkinter as tk class Application(tk.Fr...
# 题目:对10个数进行排序。 list1=[53,7,35,69,74,2,58,19,52,38] list=[24,3,5,75,26,47,75,45,26,1,5,7,345,65,43] n=len(list) for i in range(n-1): for j in range(n-1-i): if list[j]>list[j+1]: list[j],list[j+1]=list[j+1],list[j] print(list)
# 题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。 a=input('请输入一串数字,用空格隔开:') alist=a.strip().split(' ') l=len(alist) blist=[] for i in alist: blist.append(int(i)) mi=min(blist) ma=max(blist) for i in range(l): if blist[i]==mi: x=i if blist[i]==ma: y=i blist[-1],blist[x]=blist[x],blist[-1] blist[0],...
# 题目:输出一个随机数。 import random import string print(random.uniform(10,20)) # 生成一个指定范围内的随机符点数 print(random.random()) # 返回随机生成的一个实数,它在[0,1)范围内。 print(random.randint(10,20)) # 用于生成一个指定范围内的整数 print(random.randrange(10,20,3)) # 从指定范围内,按指定基数递增的集合中 获取一个随机数。 # 如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]...
#题目:一个整数,它加上100和加上268后都是一个完全平方数,请问该数是多少? import math for i in range(2000): x=i+100 y=i+268 if (x==int(math.sqrt(x))*int(math.sqrt(x))) and (y==int(math.sqrt(y))*int(math.sqrt(y))): print('x的平方根是 is ', math.sqrt(x)) print('y的平方根',math.sqrt(y)) print('this number are:',i)
# 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 def fb(n,m): list=[m,m+1] for i in range(n): list.append(list[-1]+list[-2]) return list a=fb(18,1) b=fb(18,2) c=zip(a,b) list=[] for i,j in c: list.append(j/i) print(i,j) print(sum(list)) # ------------------------- a = 2.0 b = 1.0 s ...
# 题目:按逗号分隔列表 from collections import Iterable a=[1,2,3,4,5] b=[] for i in a: b.append(str(i)) # join只能连接迭代对象,所以需要将数字转换为字符 s=','.join(b) print(s) l=(str(n) for n in a) # l是生成器; s1=','.join(l) # Python使用生成器对延迟操作提供了支持。所谓延迟操作,是指在需要的时候才产生结果,而不是立即产生结果。 print(s1) print(isinstance(l,Iterable)) # 判断l是否迭代
# python3 from itertools import combinations def merge(array1, array2): arr_out = [] left_offset = 0 right_offset = 0 inv = 0 for _ in range(0, len(array1) + len(array2)): if left_offset == len(array1): for each in array2[right_offset:]: arr_out.append(each) ...
# Image Classification with Convolutional Neural Network # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # Initialising the CNN classifier = ...
#zahlenraten.py #Sicht vom Benutzer import random max = 200 min = 1 gewonnen = False zufallszahl = random.randint(min,max) entscheidung = input ("Willst du ein Spiel spielen? ja oder nein") if(entscheidung == "nein"): print("Schade") else: print("Auf gehts") print("Bitte rate eine zahl zwischen ...
# Affichage de la liste des nombre premiers d'un intervalle de valeurs print(''' Exercice 2 ''') # Python3 program to find the prime # numbers between a given interval if __name__ == '__main__': # Declare the variables a, b, i, j, flag = 0, 0, 0, 0, 0 # Ask user to enter lower value of in...
__author__ = 'Rajkumar Pillai' """ file: Countdown.py Description:This program generates an expression which when evaluated is equal to the target value using random restart algorithm """ import random from collections import defaultdict # list of 100 1 digit number randomNumbers = [5, 1, 7, 8, 5, 5, 6, 7...
from graphics import * def draw_square(sqX, sqY, sqSize, color, window): square = Rectangle(Point(sqX, sqY), Point(sqX + sqSize, sqY + sqSize)) square.setFill(color) square.draw(window) userInput = True while userInput: try: user = input("""Do you want the program to generate your checkerboar...
# Ajax是一项用于网站开发的重要技术。 可以在不刷新网页的情况下,与服务端交互。 # 百度翻译我们输入文字之后就会发起Ajax请求 # 对每个字符发起Ajax请求(post请求) # post请求携带了数据 # 响应的数据时json数据 import requests import json if __name__ == '__main__': # 指定url post_url = 'https://fanyi.baidu.com/sug' # ua伪装 headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win...
""" File: bank.py defines the bank class """ from savingsaccount import SavingsAccount import pickle class Bank(object): def __init__(self, fileName = None): """Creates a new dictionary to hold the accounts. If a filename is provided, loads the accounts from a file of pickled accounts.""" ...
""" 题目来源: 牛客网 @See https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423 剑指offer 题4 题目描述 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 思路: 1. replace(' ', '%20') 2. 一个空间复杂度为O(n)算法,且不占用额外空间,主要针对C语言进行优化: 已知空格替换为'%20',每替换一次原字符串长度+2。如果从头扫到位,发现一次...
""" 题目来源: LeetCode @See https://leetcode-cn.com/contest/weekly-contest-160/problems/find-positive-integer-solution-for-a-given-equation/ 题目序号 5238 周赛60 题目描述: 给出一个函数 f(x, y) 和一个目标结果 z,请你计算方程 f(x,y) == z 所有可能的正整数 数对 x 和 y。 给定函数是严格单调的,也就是说: f(x, y) < f(x + 1, y) f(x, y) < f(x, y + 1)...
import unittest from leetcode.dynamicProgramming import 最大子序和53 as tT class MyTestCase(unittest.TestCase): def test_case1(self): s = tT.Solution() self.assertEqual(6, s.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) def test_case2(self): s = tT.Solution() self.assertEqual(-1, s...
""" 题目来源: 牛客网 @See https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337 剑指offer 面试题17 题目描述: 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 思路: 考虑两种情况: ①: 允许使用额外的空间 ②: 不允许使用额外的空间 要注意的是代码的健壮性,及传入的两个链表存在空链表的样例。 样例输入: [1, 3, 5, 7, 9] [2, 4, 6, 8, 10] 样例输出: [...
""" 题目来源: LeetCode @See https://leetcode-cn.com/problems/maximum-subarray/ 题目序号 53 题目描述: 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 思路: DP(见下) 或者 分治法,时间复杂度理论上分别为 O(n) 和 O(nlogn) 1. DP: 若之前子序列的和值大于0 说明对nums[i]有增益 则子序列加入nums[i] 若之前子序列的和值小于0 显然应该丢弃这个序列,重新从nums[i]计数 2. 分治法: @See...
import unittest from newcoder.sort_search import 旋转数组的最小数字 as tT class TestCase(unittest.TestCase): def test_empty_input(self): s = tT.Solution() self.assertEqual(0, s.minNumberInRotateArray([])) def test_order_input(self): s = tT.Solution() self.assertEqual(1, s.minNumberInRo...
""" 题目来源: LeetCode @See https://leetcode-cn.com/problems/add-two-numbers/ 题目序号 2 题目描述: 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 思路: 注意代码的鲁棒性即可,要防止 5 + 5 这种只算到 5 而忘了进位的情况 样例输入: 输入:(2 -> 4 -> 3) + ...
import unittest from newcoder.linklist import 用两个栈实现队列 as tT class TestCase(unittest.TestCase): def test_queue(self): q = tT.Solution() q.append_tail(1) q.append_tail(2) assert q.delete_head() == 1 assert q.delete_head() == 2 def test_complex_queue(self): q = t...
#Realizar un programa en python que devuelva el promedio de 3 números enteros. print("Ingrese los numeros de los cuales quiere sacar el promedio: ") a=int(input()) b=int(input()) c=int(input()) promedio=a+b+c promedio=promedio/3 if promedio<6: print("El promedio es menor a 6") elif promedio>6: print("...
#!/usr/bin/python # -*- coding: utf-8 -*- """ 使用多线程,支持多个Client ip:num 作为编号 """ import socket #socket模块 import commands #执行系统命令模块 import threading HOST = '127.0.0.1' # 127.0.0.1 PORT = 50007 #端口 listNum = 50 #支持最多线程数 timeOut = 500 #进程超时时间 def Client_threads(conn,addr): try: while True: #表示可持续接收Client if ...
def build(dictionary): root = [{}, []] for word in dictionary: node = root for character in word: try: node = node[0][character] except KeyError: node[0][character] = [{}, []] node = node[0][character] node[1] = dict...
import collections def doc(s): if hasattr(s, '__call__'): s = s.__doc__ def f(g): g.__doc__ = s return g return f def _set(arr, i, item): arr[i] = item item[2] = i def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" item[2] = l...
print('hello world') print('hello', 'world', "man") print('hello', 'world', 'woman') print(100+200+300) print('100+200+300 =', 100+200+300) a = -100 if a >= 0: print(a) else: print(-a) # name = input() name = input('please input your name:') print('hello', name)
# # @lc app=leetcode.cn id=112 lang=python3 # # [112] 路径总和 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: ...
#!/usr/bin/env python3 # imports go here import itertools import pandas as pd import plotly.plotly as py from plotly.graph_objs import * # # Free Coding session for 2015-05-25 # Written by Matt Warren # years = list(range(2015, 2045)) YEARS_TO_SIMULATE = 30 INFLATION_RATE = 0.03 INTEREST_RATE = 0.04 KWH_PRICE = 0...
#!/usr/bin/env python3 # imports go here import datetime # # Free Coding session for 2015-02-28 # Written by Matt Warren # year = datetime.date.today().year if __name__ == '__main__': if year % 4 == 0: print("this is leap year") else: print("%d not a leap year" % year)
#!/usr/bin/env python3 # imports go here # # Free Coding session for 2015-04-28 # Written by Matt Warren # WHO_WHAT_WHEN = [] def add_task(who, what, when): WHO_WHAT_WHEN.append({'who': who, 'what': what, 'when': when}) def print_tasks(): print("{:^30}|{:^30}|{:^30}".format("WHO", "WHAT", "WHEN")) for...
#!/usr/bin/env python # imports go here import random # # Free Coding session for 2014-11-19 # Written by Matt Warren # target = random.randint(0, 10) guess = 0 while target != guess: guess = int(input('Guess a number 1-10:')) print "Got it!"
""" list overlap """ a=[1,2,3,4,5,6,7,8,9,10] b=[1,3,5,7,9] c=[] for i in a and b: if i in a and b: c.append(i) print(c)
#!/usr/bin/env python # coding: utf-8 # In[2]: """"Question: Pig Latin You are given a piece of English text on a single line. Write a program that translates the text to Pig Latin. English is translated to Pig Latin by taking the first letter of every word, moving it to the end of the word, and adding “ay.” Assumpt...
import collections class Solution(object): def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ if n == 0: return len(tasks) tasks_counter = collections.Counter(tasks) most_common = tasks_counter.most_c...
class Solution: def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ #when it starts decreasing, it is at its peak goingUp = False for i in range(0, len(nums)-1): if nums[i] < nums[i+1]: goingUp = True ...
# Author:UserA # 队列示例 py文件命名的时候千万不能使用queue这种关键字 ''' class queue.Queue(maxsize=0) #先入先出 class queue.LifoQueue(maxsize=0) #last in fisrt out 后进先出 class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列 ''' import queue # q = queue.Queue() q2 = queue.LifoQueue() q3 = queue.PriorityQueue() # q.put(1) # q.put(2) # q.put(3) ...
# Author:UserA # 字符串相关常用函数 str = "my name is UserA" print(str.capitalize()) # 整个字符串第一个字母大写,并不是指每个单词。 print(str.count("a")) # 统计a出现次数,区分大小写。 print(str.find("name")) # 找到name首次出现的位置。 str2 = "my name is {name}" print(str2.format(name='zhangsan')) print("2str_33".isidentifier()) # 判断是不是一个合法的变量名 print('+'.join(['1', '2'...
# Author:UserA # 多继承:Python是支持多继承的。 # class Person: # 经典类 class Person(object): # 新式类 def __init__(self, name, age): self.name = name self.age = age def eat(self): print("%s eat......" % self.name) def sleep(self): print("%s sleep......" % self.name) def talk(self): ...
# Author:UserA # 线程示例一 import threading import time def sayhi(num): # 定义每个线程要运行的函数 print("running on number:%s" % num) time.sleep(2) t1 = threading.Thread(target=sayhi, args=("t1",)) # 生成一个线程实例,args第二个参数没有也必须使用逗号分开。 t2 = threading.Thread(target=sayhi, args=(2,)) # 生成另一个线程实例 t1.start() # 启动线程 t2.start() ...
# 1. Import and test 3 of the functions from your functions exercise file. # Your functions exercise are not currently in a file with a # name that can be easily imported. Copy your functions exercise # file and name the copy functions_exercises.py. # Import each function in a different way: # import the module an...
import unittest import sort class TestSort(unittest.TestCase): # Test Insertion Sort def test_insertion_sort(self): # 断言空列表直接返回 self.assertEqual(sort.insertion_sort([]), []) # 断言单元素列表直接返回 self.assertEqual(sort.insertion_sort([1]), [1]) # 断言2元素列表 self.assertEqual(sort.insertion_sort([2, 1]), [1, 2]) # ...
# This project practices merging of tables in Pandas to build a page # visits funnel for a fictional t-shirt company import codecademylib import pandas as pd visits = pd.read_csv('visits.csv', parse_dates=[1]) cart = pd.read_csv('cart.csv', parse_dates=[1]) checkout = pd.read_c...
def durchlauf(satz1,satz2): ausgabe = "" while len(satz1) < len(satz2): satz1 += " " for i in range(len(satz1)): ausgabe = satz1[i] + " " + satz2[i] print(ausgabe) while input().upper() != "X": eingabe1 = input("Bitte schreiben \n:") eingabe2 = input("Schreibe noch etwas ...
s = [] for _ in range(int(input())): t = input() if t == "pwd": if s: print("/" + "/".join(s) + "/") else: print("/") else: path = t[3:] if path.startswith("/"): s = [] path = path.split("/")[1:] else: path =...
thislist = ["apple", "banana", "orange"] print(thislist) # indexing #0 , 1 , 2 print(thislist[-1]) # range of indexing : [start : end] print(thislist[:2]) print(thislist[1:]) # check a list element # ['apple','banana','orange','apple'] if "apple" in thislist: print('Apple is inside the list') else: print('...
#preorder traversal ## as a external function that takes a binary tree as input def preorder(tree): if tree: print(tree.getRootVal()) preorder(tree.getLeftChild()) preorder(tree.getRightChild()) ## as a method in tree class def preorder2(self): print(self.key) if self.leftChild: ...
# Obtained from: https://github.com/geodav-tech/decode-google-maps-polyline # This function is free of any dependencies. def decode_polyline(polyline_str): '''Pass a Google Maps encoded polyline string; returns list of lat/lon pairs''' index, lat, lng = 0, 0, 0 coordinates = [] changes = {'latitude': 0...
#!python3 # Code Challenge 02 - Word Values Part II - a simple game # http://pybit.es/codechallenge02.html from data import DICTIONARY, LETTER_SCORES, POUCH import string from itertools import permutations import random NUM_LETTERS = 7 # re-use from challenge 01 def calc_word_value(w): """Calc a given word value...
from data import DICTIONARY, LETTER_SCORES import string def load_words(): """Load dictionary into a list and return list""" l = [] with open(DICTIONARY, "rt") as f: l=[line.rstrip('\n') for line in f] return l def calc_word_value(w): """Calculate the value of the word entered into functio...
from .basic import dot, transpose def pivot_matrix(A): """ Find the pivot matrix of A :param A: n * n matrix :return: """ n = len(A) res = [[float(i == j) for i in range(n)] for j in range(n)] for j in range(n): max_value = float('-inf') max_row = None for i in ...
def paraboloid(x,y): return (x+10)**2+(y-20)**2 # path ID is defined relative to the current position # thres is the number we want to reach below def gradient(x,y,thres, fun, step=2,pathID =0): z = fun(x,y); if z<thres: return (x,y); # id=1 go up elif (pathID !=3) & (fun(x,y+step)<z): return gra...
#lists rainbow = ['red','orange','yellow','green','blue','indigp','violet','red'] object1 = [1,2,3,4,5] object2 = [6,7,8,9,10] #main program print(rainbow[1:4]) print(rainbow[2:]) print(rainbow[0::2]) print(len(rainbow)) print('red' in rainbow) print(rainbow.count('red')) print(rainbow.index('red')) objec...
# Matt Alpert's Version BOARDS_PATH = './sudoku_boards.txt' # path to board data def board_generator(path=BOARDS_PATH): with open(path, 'r') as f: # first line should always just label first board f.readline() board = [] # stores board in list of list form for line in f: ...
# Importamos el modulo random mediante la instruccion import import random # Creo una variable de tipo float y le asigno un valor numero1 = float(10.5) # Creo una funcion en la cual declaro una variable de tipo float # que adquirira un valor aleatorio entre 1 y 10 y al final se sumaran y me mostrara el resultado a...
# -*- coding: utf-8 -*- """ Created on Mon May 11 17:11:06 2020 @author: Hossein """ from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: new_list = [] for i in nums: new_list.append(i*2) new_list=new_list.sort() return n...
""" Phone number formatter Formats phone numbers into the standard format. This is strictly for mobile phones mainly in Uganda. Copyright (C) 2011 <David Okwii> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Softwar...
''' import turtle window = turtle.Screen() window.setup( 800, 600 ) window.title( 'RG' ) t = turtle.Turtle() # t.hideturtle() t.pencolor('blue') t.speed(3) # "R" import math t.lt(90) t.fd(100) t.rt(90) t.circle(-30 ,180) t.lt(130) t.fd(math.sqrt(40 *40 + 30 *30)) # "G" t.penup() t.goto(90 ,...
#Дано два лінійних масиву однакової розмірності. Скласти третій масив з #добутку елементів перших двох масивів, що стоять на місцях з однаковим індексом. #Павлюк Владислав import numpy as np#импортируем библиотеку нампи import random while True: b=np.zeros(5,dtype=int)#инициализируем масив нулями,и присваиваем тип...
#Знайти суму додатніх елементів лінійного масиву цілих чисел. #Розмірність масиву - 10. Заповнення масиву здійснити з клавіатури. #Павлюк Владислав import numpy as np#импортируем библиотеку нампи while True: b=np.zeros(5,dtype=int)#инициализируем масив нулями,и присваиваем типу данных тип данных инт suma=0 ...
#Знайти добуток всіх елементів масиву дійсних чисел, менших заданого #числа. Розмірність масиву - 10. Заповнення масиву здійснити випадковими числами #від 50 до 100. #Павлюк Владислав import numpy as np#импортируем библиотеку нампи import random while True: x=int(input('Введите число для сравнения:')) b=np.zero...
#Заданий масив А (1:20). Знайти добуток всіх його ненульових елементів. #Павлюк Владислав import numpy as np#импортируем библиотеку нампи import random while True: b=np.zeros(20,dtype=int)#инициализируем масив нулями,и присваиваем типу данных тип данных инт for i in range(20):#проходимся по елементам масива ...
#Підрахувати кількість елементів одновимірного масиву, для яких #виконується нерівність i*i<ai<i! #Павлюк Владислав #Змінній t привласнити значення істина, якщо максимальний елемент #одновимірного масиву єдиний і не перевищує наперед заданого числа а. #Павлюк Владислав import numpy as np#импортируем библиотеку нампи im...
#Знайти добуток елементів лінійного масиву цілих чисел, які кратні 5. #Розмірність масиву - 10. Заповнення масиву здійснити випадковими числами від 10 до #100. #Павлюк Владислав import numpy as np#импортируем библиотеку нампи import random while True: b=np.zeros(10,dtype=int)#инициализируем масив нулями,и присваеив...
log_file = open("um-server-01.txt") ## OPENING THE FILE ## def sales_reports(log_file): ##CALLS THE FUNCTION for line in log_file: ##A FOR LOOP THAT GOES THROUGH EACH LINE IN THE FILE line = line.rstrip() ##STRIPS UNNECESSARY SPACE BETWEEN VALUES day = line[0:3]## I BELIEVE THIS TELLS THE CONSOLE ...
# flag = True # while flag: # print("狼的诱惑") # print("我们不一样") # print("月亮之上") # print("庐州月") # print("人间") # flag = False # flag = True # while flag: # print("狼的诱惑") # print("我们不一样") # flag = False # print("月亮之上") # print("庐州月") # print("人间") # while True: # print(...
#!/usr/bin/python # '!a' (apply ascii()), '!s' (apply str()) and '!r' ( apply repr()) can be # used to convert the value before it is formatted print("\nExample program 1 - Using format() convert the values\n") import math print('The value of PI is aproximately {}.'.format(math.pi)) print('The value of PI i...
class Robot: def __init__(self, name): self.name = name def SayHello(self): print("Hello, I'm " + self.name) def SetName(self, name): self.name = name print(self.name) self.name = "I am in love with Python" print(self.name) if __n...
#!/usr/bin/python # import re module import re print("find all : ", re.findall(r'\bf[a-z]*','which foot or hand fell fastest')) print("sub string: ", re.sub(r'(\b[a-z]+) \1',r'\1','cat in the hat')) print("replace: ", 'tea for too'.replace('too','two')) # import math module import math print("Cos of...
#!/usr/bin/env python # Operator Overloading class Marks: def __init__(self,marks,subject): print("Inside constructor ( __init__) ") self.marks = marks self.subject = subject def __str__(self): print("Inside constructor ( __str__) ") return 'Total marks %d o...
#!/usr/bin/python # Dictionaries in python dict = {'Subject':'Physics','Year':2014,'Marks':88} # to print complete dictionary print("Complete dict : ", dict ) # If we attempt to access a data item a key # which is not part of the dictionary, we get an error # to print the values in the dictionary print("d...
#catching multiple exceptions at once try: a = float(input('First number, please: ')) b = float(input('Second number: ')) print('Your result is ', a/b) except (ZeroDivisionError, ValueError, TypeError) as e: print("Error :", e) else: print("No exception found")
import re m = re.match('(\w\w\w)-(\d\d\d)', 'abc-123') print(m.group()) # entire match print(m.groups()) print(m.group(1)) # subgroup 1 print(m.group(2)) # subgroup 2 print(m.groups()) # all subgroups m = re.match('ab', ...
#number of lines of a file filePath = "demo.txt" lineCount = len(open(filePath, 'r').readlines()) print("File %s has %d lines." % (filePath,lineCount))
#!/usr/bin/python print("\nExample program: \n") #Creating a compressed file import lzma data = b"Welcome to Python" with lzma.open("example.xz", "w") as file: file.write(data) file.close() # reading in a compressed file with lzma.open("example.xz") as file: filecontent = file.read() prin...
from __future__ import division import numpy as np from sklearn import cross_validation from sklearn import linear_model from sklearn import datasets from sklearn import metrics ''' Compute linear regression coefficients using gradient descent ''' # --------------------------------------------------------------------...
pizzas = [ 'Neapolitan Pizza', 'Chicago Pizza', 'New York-Style Pizza', 'Sicilian Pizza' ] for pizza in pizzas: print(f"I like {pizza}.") print("I really love pizza!") animals = ['dog', 'cat', 'bird'] for animal in animals: print(f"A {animal} would make a great pet.") print("Any of the a...
rivers = { 'Sepik River': 'New Guinea', 'Mississippi River': 'the United States', 'Volga River': 'Europe', 'Zambezi': 'Africa', 'Mekong River': 'Tibetan Plateau', 'Ganges': 'India', 'Danube': 'Europe', 'Yangtze River': 'China', 'Nile': 'East Africa', 'Amazon River': 'Peru' } [pr...
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] print("My favorite foods are:") print(my_foods) print("\nMy friend favorite foods are:") print(friend_foods) my_foods.append('ice cream') print(my_foods) print(friend_foods) another_friend_foods = my_foods print(another_friend_foods) another_fr...
number = int(input("Please input a number: ")) if number % 10 == 0: print(f"{number} is multiples of ten.") else: print(f"{number} is not multiples of ten.")
import unittest from programy.nlp.stopwords import StopWords class StopWordsTests(unittest.TestCase): def test_remove(self): stopwords = StopWords(language="english") self.assertIsNotNone(stopwords) self.assertIsNotNone(stopwords._words) self.assertEqual([""], stopwords.remove(["...
import random print(""" \t猜数字游戏 系统随机生成一个小于20的数 猜猜这个数是多少 友情提示:你有10次机会 """) num = random.randint(0,20) time = 10 while time >0: time -= 1 try: gnum = int(input("\n输入一个你想到的数:")) except ValueError: print(f'\n请确认你输入的是数字,你还有{time}次机会') continue if gnum == num: ...
import random from functools import reduce def condition(ls): """returns False if two consecutive list-elements start with the same letter, else True""" return reduce(lambda x,y: False if x is False or x[0]==y[0] else y, ls) != False def generate_lists2(num_elems): l1 = list(["A" + str(i) for i in range(n...
# welcome to the first workshop, which trains use of the os module ################################################################################ # imagine you found a nice dataset you need to analyse, but instead of consisting # of a single file or a set of conveniently named files sitting together in a # directo...
from collections import Counter import itertools import random def hits_and_misses(guess_seq, true_seq): """ computes the match score of the guessed sequence p, given the true sequence q. :param guess_seq: a string containing guessed sequence guessed :param true_seq: the target sequence :return: th...
class sjf: def __init__(self, name, arrival, burst,priority, waiting, turnround, q, ready): self.name = name self.arrival = arrival self.burst = burst self.waiting = waiting self.turnround = turnround self.priority = priority self.q = q self...
from math import * #Lançamento vertical simples g = -9.8 #aceleração da gravidade y = 10 #h initial vy = 0 #velocidade em y, pois v em x é constante dt = 2 #tempo de queda while y >= 0: y = y + (vy * dt) # S = So + Vt vy = vy + (g*dt) # V = Vo + at print(y,vy) ...
import statistics ages = [13, 15, 16, 16, 19, 20, 20, 21, 22, 22, 25, 25, 25, 25, 30, 33, 33, 35, 35, 35, 35, 36, 40, 45, 46, 52, 70] # 3.7(a) ages_min = 13 ages_max = 70 ages_ans1 = (35 - ages_min) / (ages_max - ages_min) * (1 - 0) + 0 print('%.2f' % ages_ans1) # 3.7(b) ages_mean = statistics.mean(ages) ages_standar...
import random import math # function to generate random primes 'p' & 'q' and calculate 'N' and 'PhiN' def primeNum(): # An empty list to store the prime numbers to be generated primeArray = [] for i in range(1, 65535): # checking for prime numbers in the range between 2 and the square root of the ...
from tkinter import * root = Tk() #Frame is a rectangular area that contain other topFrame = Frame(root) topFrame.pack(side = BOTTOM) bottomFrame = Frame(root) bottomFrame.pack() b1 = Button(topFrame,text = 'Button 1',fg = 'red') b2 = Button(topFrame,text = 'Button 2',fg = 'blue') b3 = Button(topFrame,text = 'Button ...
"""Perceptron model.""" import numpy as np from tqdm import tqdm class Perceptron: def __init__(self, n_class: int, lr: float, epochs: int): """Initialize a new classifier. Parameters: n_class: the number of classes lr: the learning rate epochs: the number of e...
def sublista(): l = [] sublista = [] for i in range(6): l.append(int(input("insira um valor a lista: "))) print(l) x = int(input("x: ")) y = int(input("y: ")) for j in range(x+1, y): for k in l: if k == j: sublista.append(k) print(f"Os elemento...