text
stringlengths
37
1.41M
#encoding:utf-8 # __author__ = 'donghao' # __time__ = 2019/4/10 16:46 mydict = {'name':'donghao','age':20} mydict2 = {'name':'donghao2','age':22,'school':'nyist'} # mydict.pop('name') # mydict.keys() # # mydict.items() # # mydict.values() #mydict.update(mydict2) print(mydict)
# encoding:utf-8 # __author__ = 'donghao' # __time__ = 2019/3/23 17:39 # 简单工厂模式(Simple Factory Pattern):是通过专门定义一个类来负责创建其他类的实例, # 被创建的实例通常都具有共同的父类 # 使用: # 1.不知道用户想要创建什么样的对象 # # 2.当你想要创建一个可扩展的关联在创建类与支持创建对象的类之间。 # 缺点: # 但是工厂的职责过重,而且当类型过多时不利于系统的扩展维护。 class Factory(object): def select_car_by_type(self, car_type): ...
n = 0 max = 0 a = int(input()) while a != 0: if a > max: max = a n = 1 elif a == max: n += 1 a = int(input()) print(n)
a = int(input()) b=a i = 0; while a!=0: a = int(input()) if a>b: i+=1 b=a print (i)
sum = 0 n = int(input()) for i in range (1, n+1): sum += i ** 3 print(sum)
from math import sin, acosh, pi #import a = int(input('Enter a: ')) #enter a and x x = int(input('Enter x: ')) G = 3 * (-3 * a ** 2 + 2 * a * x + 21 * x ** 2)/(35 * a ** 2 + 37 * a * x + 6 * x ** 2) #solutions of equation G F = 1 /(sin(20 * a ** 2 + 9 * a * x - 20 * x ** 2 - 1 * pi / 2)) #solutions of equation F Y ...
a = int(input()) b = int(input()) if a<b: for i in range(a, b+1,1): print(i) else: for i in range(a, b+1,-1): print(i)
import argparse class ArgumentParser(argparse.ArgumentParser): """ Argument parser class. Provide program description and define arguments """ def __init__(self): description = ('Organize your files by filtering duplicates and move them into another directory.' ' Also it...
import numpy as np class Position: """Entity position component""" # The length of the vessel position's history TRACE_LENGTH = 100 def __init__(self, lonlat=None): self._history = { 'lon': [], 'lat': [] } self._lonlat = lonlat if self._lonlat...
"""Utility functions for processors""" import math import random import numpy as np import numpy.linalg as la from utils.constants import KNOTS_TO_METERS_SEC, METERS_TO_COORDS, TARGET_REACHED_DELTA def lonlat_array_to_screen(proj, lonlat): """Projects a 2-dimensional array to the screen using the given projection...
''' Арифметические операции Напишите программу, в которой вычисляется сумма, разность и произведение двух целых чисел, введенных с клавиатуры. Формат входных данных На вход программе подаётся два целых числа, каждое на отдельной строке. Формат выходных данных Программа должна вывести сумму, разность и произведение вв...
''' Значение функции Напишите программу вычисления значения функции f(a, \, b) = 3(a + b)^3 + 275b^2 - 127a - 41f(a,b) =3(a+b) 3 +275b 2 − 127a−41 по введеным целым значениям aa и bb. Формат входных данных На вход программе подаётся два целых числа, каждое на отдельной строке. В первой строке — значение aa, во вто...
import matplotlib import numpy as np import matplotlib.pyplot as plt import random import math k = 0 num = 2 # define função teste def f(x): fx = 0 for k in range(num): fx += (x[k]**2) return fx # Ponto de inicio --> Determina o ponto de partida da procura def entrada_valor(num): """ ...
import random a = int(input('Digite um valor para a: ')) b = int(input('Digite um valor para b: ')) c = int(input('Digite um valor para c: ')) x = 0 x2 = 0 xmelhor = 0 cont = 0 y = a * (x ** 2) + b * x + c y2 = 0 ymelhor = a * (xmelhor ** 2) + b * x + c if b == c == 0: print('Valor de y = 0 para x = 0') while...
d,b=input().split() if(len(d)==len(b)): print("yes") else: print("no")
number=int(input()) v=0 m=1 while(number>0): print(m,end=' ') v,m=m,v+m number=number-1
h=int(input()) sum=0 for i in range(0,h+1): sum+=i print(sum)
import matplotlib.pyplot as plt import seaborn as sns # Transforms correlation values to colors (for heatmap) def value_to_color(val): n_colors = 256 # Use 256 colors for the diverging color palette palette = sns.diverging_palette(20, 220, n=n_colors) # Create the palette color_min, color_max = [-1, ...
# Python 2.7.12 Tic Tac Toe #Author K.Fujioka #The Game Board board = [0,1,2, 3,4,5, 6,7,8] def show(): print board[0],'|',board[1],'|',board[2] print '--------' print board[3],'|',board[4],'|',board[5] print '--------' print board[6],'|',board[7],'|',board[8] whi...
class PVSimulator: """ This class represents a PhotoVoltaic simulator, it gets an energy reading and outputs a mock photovoltaic energy. The mock is represented by simply an efficiency value that we pass to it, multiplied by the input energy. """ def __init__(self, efficiency): if efficienc...
# (08)*********************Ones and ones-like and ones-initializer in tensorflow******************* # -----if we want to creat tensor which all elements should be ones then we use ones function # ----Creat Tensor with every elements are one in Tensorflow 2.X # ----Syntax: tf.ones() # -----importing libraries import...
""" ========================================================================= Rubik's Cube Solver Program ========================================================================= A Python program to solve a 3x3x3 Rubik's Cubes. Draws the cube using MATPLOTLIB. Uses the Layer-by-Layer approach...
#Matriz transpuesta f=int(input('Digite el numero de filas y el numero de columnas: ')) #creamos una matriz vacia A=[] for i in range(f): A.append([0]*f) #leemos su contenido de teclado for i in range(f): for j in range(f): A[i][j]=int(input('Digite el contenido de %d y %d de la matriz A: '%(i+1,j+1)...
""" simluation of any number of teathered particles """ from pylab import * import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class particle(object): ke = 8.9875517873681764e9 def __init__(self, q...
from tkinter import * from tkinter import messagebox root=Tk() root.geometry("500x500") root.title("Tic Tac Toe Game") root.resizable(0,0) root.configure(background='Cadet Blue') PlayerX=IntVar() PlayerO=IntVar() PlayerX.set(0) PlayerO.set(0) buttons=StringVar() click=True def checker(buttons): ...
"""" Sum square difference Problem 6 Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. Answer: 25164150 Completed on Fri, 13 Jan 2017, 02:39 """ def main(): num_list = xrange(1,101) sum_squares = sum([i**2 for i in num_list]) square_sum = (s...
from AbstractBaseState import state class state_a(state): def __init__(self): super().__init__() self._name=1 @property def name(self): return self._name def Output(self,input): if(input==True): print("a1") else: print("a2") def setup(...
import argparse import itertools import sys # parser = argparse.ArgumentParser() # parser.add_argument("--first", help="""Find the "First Locked Position"Rotate dial to the left (towards 10) hard until the dial gets locked.Notice how the dial is locked into a small groove. If you're directly between two digits such a...
def count_substring(string, sub_string): # count variable to hold the sub string matches count = 0 length_string = len(string) length_sub_string = len(sub_string) if length_string>=length_sub_string: # Sample string's from hackerrank # string 1: ABCDCDC # sub-string 1: CDC ...
#!/usr/bin/env python3 """ Decode unicode input """ import fileinput import sys import unicodedata def format_char(char): name = unicodedata.name(char, "[name missing]") return f'U+{ord(char):0>4X}\t{name}' if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] in {'-h', '--help'}: print(...
nama = input("Inputkan Nama :") skor = float(input("Input Nilai Akhir : ")) variabel = 'Hallo', nama, '!Nilai anda setelah dikonversikan adalah' if skor >= 85: print(variabel,'A') elif skor >= 80: print(variabel,'A-') elif skor >= 75: print(variabel,'B+') elif skor >= 70: print(variabel,'B')...
# Numeric Functions x = '47' y = int(x) print(f'x is {type(x)}') print(f'x is {x}') print(f'y is {type(y)}') print(f'y is {y}') y = float(x) print(f'y is {type(y)}') print(f'y is {y}') x = -46 y = abs(x) print(f'y is {type(y)}') print(f'y is {y}') x = 46 y = divmod(x, 3) print(f'y is {type(y)}') print(f'y is {y}') ...
''' Given a binary tree of integers, return all the paths from the tree's root to its leaves as an array of strings. The strings should have the following format: "root->node1->node2->...->noden", representing the path from root to noden, where root is the value stored in the root and node1,node2,...,noden are the val...
""" Given a square matrix of positive integers a, your task is to sort the numbers in each of its diagonals parallel to the secondary diagonal. Each diagonal should contain the same set of numbers as before, but sorted in ascending order from the bottom-left to top-right. Example For a = [[1, 3, 9, 4], [9, 5, 7...
def buyAndSellStock(stock_price): max_profit_val, current_max_val = 0, 0 for price in reversed(stock_price): current_max_val = max(current_max_val, price) potential_profit = current_max_val - price max_profit_val = max(potential_profit, max_p...
import requests from bs4 import BeautifulSoup # Set the URL you want to webscrape from url = 'https://en.wikipedia.org/wiki/Deep_learning' # Connect to the URL response = requests.get(url) # Parse HTML and save to BeautifulSoup object¶ soup = BeautifulSoup(response.text, "html.parser") # printing page title in cons...
import numpy as np import time functionx = lambda x : np.cos(x) + x**3 def integral(a, b, tramos): h = (b - a) / tramos x = a suma = functionx(x) for i in range(0, tramos - 1, 1): x = x + h suma = suma + 2 * functionx(x) suma = suma + functionx(b) are...
""" TASK 0: What is the first record of texts and what is the last record of calls? Print messages: "First record of texts, <incoming number> texts <answering number> at time <time>" "Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds" """ import csv with open('tex...
import itertools n = input() length = int(len(n)) n = int(n) array = ['3','5','7'] tempPattern0 = [] tempPattern1 = [] allPattern = 0 if length == 3: for pair in itertools.permutations(array, 3): if (num := int(''.join(pair))) < n: tempPattern1.append(num) else: for pair in itertools.permu...
from util import Coordinates from util import getValue from agent import * import string class Board: """ Board class """ def __init__(self): self.N = 8; self.agents = [] self.agents.append(Larva(6, 3)) for i in range(0, 8, 2): self.agents.append(Bird(7, i)) ...
import math class Solution(object): def staircase(self, n): memo = [-1] * (n + 1) return self.staircase_helper(n, memo) def staircase_helper(self, n, memo): if n < 0: return 0 elif n == 0: return 1 elif memo[n] != -1: return memo[n] ...
n = int(input("Wpisz liczbe: ")) """ def siema (x): if x < 1: return "Ta liczba jest mniejsza od 1!" for i in range(2,x): if x%i == 0: return "To nie jest liczba pierwsza!" else: return "To liczba pierwsza!" print (siema(n)) """ asd = True if n < 1: print("T...
import math def l_p(n): for i in range(2,int(math.sqrt(n))+1): if n % i == 0: return "Liczba nie jest pierwsza" return "Liczba jest pierwsza" n = int(input("wczytaj n")) print(l_p(n)) ################################# BEZ FUNKCJI x = int(input("wczytaj x")) prime = True #wartość logiczn...
x = 6 # Liczba x u góry jest równa 6 x = "jakiś napis" """ Oooo tam góry jest jakis napis """ # typy logiczne x = False x = True #lista x = [1,2,3,"czesc", False] x = input("Wprowadź tekst\n") # wprowadzanie danych STRING # \n przejscie do następnej lini print(x) y = int(input("wprowadź liczbę")) print(y*y) text...
import random def sort(array): less = [] equal = [] greater = [] if len(array) > 1: rand = random.randint(0, len(array) - 1) pivot = array[rand] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) ...
# ------------------------------------------------------------------------------------------------- # # PRACTICE EXERSISES 1 - EXPRESSIONS # # Solve each of the practice exercises below. # # ------------------------------------------------------------------------------------------------- """ 1.1 There are 5280 fe...
# -*- coding: utf-8 -*- """ @file: easy.findNumberIn2DArray.py @date: 2020-10-06 11:23 AM @desc: 剑指 Offer 04. 二维数组中的查找 @url : https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/ """ # [ # [1, 4, 7, 11, 15], # [2, 5, 8, 12, 19], # [3, 6, 9, 16, 22], # [10, 13, 14, 17,...
# -*- coding: utf-8 -*- """ @file: easy.getIntersectionNode.py @date: 2020-09-27 1:31 PM @desc: 160. 相交链表 @url : https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next...
# -*- coding: utf-8 -*- """ @file: im.search.minArray.py @date: 2020-09-08 10:23 AM @desc: 剑指 Offer 11. 旋转数组的最小数字 @url : https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/ """ # 输入:[3,4,5,1,2] # 输出:1 from typing import List class Solution: def minArray(self, numbers: Lis...
# -*- coding: utf-8 -*- """ @file: im.heap.getLeastNumbers.py @date: 2020-09-08 10:23 AM @desc: 剑指 Offer 11. 旋转数组的最小数字 @url : https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/ """ # 输入:arr = [3,2,1], k = 2 # 输出:[1,2] 或者 [2,1] # # 输入:arr = [0,1,2,1], k = 1 # 输出:[0] import heap...
# -*- coding: utf-8 -*- """ @file: e.spiralOrder.py @date: 2020-09-07 4:19 PM @desc: 剑指 Offer 29. 顺时针打印矩阵 @url : https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/ """ # 输入:matrix = [ # [1,2,3,4], # [5,6,7,8], # [9,10,11,12] # ] # 输出:[ # 1,2,3,4, # 8,12,11,10, # ...
# -*- coding: utf-8 -*- """ @file: easy.twoSum.py @date: 2020-09-18 08:38 AM @desc: 两数之和 @url : https://leetcode-cn.com/problems/two-sum/ """ from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hash = {} for i, num in enumerate(nu...
# -*- coding: utf-8 -*- """ @file: easy.twoSum.py @date: 2020-09-30 08:38 AM @desc: 25. K 个一组翻转链表 @url : https://leetcode-cn.com/problems/reverse-nodes-in-k-group/ """ # 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 # # k 是一个正整数,它的值小于或等于链表的长度。 # # 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 # #   # # 示例: # # 给你这个链表:1->2->3...
# Home work # Write a Python program that counts occurrencies of a long text # and prints a table taking into account the order given by the counts # example: # Lexem | Count # # the | 34 # of | 25 # a | 15 # .... # rare | 1 # oxygen | 1
# -*- coding: utf-8 -*- """ Created on Tue May 5 17:07:27 2020 @author: ABC """ # Recurrent Neural Network # Part 1 - Data Preprocessing #1 Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #2 Importing the training set dataset_train = pd.read_csv("Google_Stock_Price...
a=int(input("Enter the number A:")) b=int(input("Enter the number B:")) c=int(input("Enter the number C:")) if (a>b & a>c): print("a is greatest") elif b>c: print("B is greatest") else: print("C is greatest")
import random a={1:'rock',2:'paper',3:'scissor'} while True : p=input("your choice rock/paper/scissor") c=a[random.randint(1,3)] print("you choose:",p,"computer choose",c) if(p==c): print("draw") elif(p==rock and c==paper): print("computer won")
#Programa que determina el promedio de dos números y #si este es o no mayor que 10 #Elaborado por: M.hijazi Fecha: 14-07-2021 #INICIO del programa #DECLARACÓN de variables #Var. de ENTRADA (aquellas cuyo valor se lee ¿Qué nos dan?) num1 = int num2 = int #Var. de SALIDA (aquellas cuyo valor se escribe ¿Qué nos piden?)...
import pygame from pygame.sprite import Sprite class Bullet(Sprite): ''' A class to manage bullets fired from LS. ''' def __init__(self, ai_settings, screen, soumao): ''' Create a bullet object at LS's current posistion. ''' super (Bullet, self). __init__() self.screen = screen # Create a bullet at (0,...
print("enter two numbers") a=int(input()) b=int(input()) c=(a+b)/2 print ("avg is",c) d1=a-c d2=b-c print("deviation:-") print("negative deviation-",d1) print("positive deviation-",d2)
print("tempratue converter") print("enter the temprature") f=float(input()) c=(5/9)*(f-32) print("temprature in celicius is:",c,"degrees")
""" hashset去除冗余 """ def removeDup(head): hashset = set() curNode = head.next preNode = head while curNode: if curNode.data in hashset: preNode.next = curNode.next else: hashset.add(curNode.data) preNode, curNode = curNode, curNode.next
""" 插入法逆序 """ def Reverse(head): ''' 将原链表分割成待插链表和插入链表 head->1->Null,2->3->4...7->Null 插入链表从头结点后的第二个结点开始, 插入链表头结点向待插链表Head节点后插入 ''' curNode = head.next.next # 插入链表中的头节点 head.next.next = None # 使原链表第一个节点成为待插链表尾节点 while curNode: # curNode->head.next nextNode, curNod...
"""Provides helper functions that clean, parse, and prepare text for making web requests.""" # pylint: disable=import-error # Standard Lib imports import string from typing import Optional # Project imports from .keywords import PYTHON_KEYWORDS from requests_html import HTMLSession, HTMLResponse, Element def remove...
##### FUNCTIONS ########## ###### def: Find closest pair in d ###### ###### Returns indices i and j taht are closest ###### Ignores entries that are non-positives def get_min_pair(d): mindist = 100000000 best_i = -1 best_j = -1 # looking through every cell for shortest distance (with exceptions) fo...
#!/usr/bin/python3 import cv2 import numpy import textwrap3 blank = numpy.zeros((900, 900, 3), dtype=numpy.uint8) blank[0:850, 0:850] = 255, 255, 255 cv2.imshow("Draw picture", blank) # draw a rectangle ''' The rectangle will be drawn on rook_image Two opposite vertices of the rectangle are defined by ( 0, 0) and ( w...
#Implement a function void reverse(char* str) in c or c++ which #reverses a null terminated string #Done in python to serve as an example of how one would do it in python def reverse(string): return string[::-1] def reverse2(string): string = list(string) reversed_string = [] for i in xrange(len(stri...
from BaseTreeImplementation import Node # Implement a function to check if a binary tree is a binary search tree temp = [] def is_binary_search_tree(root): in_order(root) for i in xrange(len(temp)): if i + 1 < len(temp): if temp[i] > temp[i + 1]: return False return Tr...
# Design a musical jukebox using object oriented design class CD(object): def __init__(self, cd_name=None, *songs): self.cd_name = cd_name self.songs = songs class CDPlayer(object): def __init__(self): self.max_number_of_cds = 10 self.cd_list = [] def add_cd(self, cd_nam...
for i in range (10): x=input("Задайте х:") x=int(x) y=input("Задайте у:") y=int(y) def f(x,y): return x**y print ("f(x,y)=x^y = ",f(x,y))
age=input("Сколько тебе лет?") age=int(age) if 55<age<65: print("Пора задуматься о пенсии!") elif 25< age <55: print("Тебе ещё рано думать о пенсии!") elif age>65: print("Хорошо поработали!Теперь можно и отдохнуть!") else: print("О пенсии точно думать рано!Лучше подумай об учебе!")
from cs50 import get_string s = get_string("name: ") initials = "" for c in s: if c.isupper(): initials += c print(initials)
from cs50 import get_string from student import Student students = [] dorms = [] for i in range(3): name = get_string("Name: ") dorm = get_string("Dorm: ") s = Student(name, dorm) students.append(s) for student in students: print(f"{student.name} lives in {student.dorm}")
def usuario_escolhe_jogada(n,m): pecas = int(input("Quantas peças você vai tirar? ")) if pecas > m or pecas <= 0 or pecas > n: while pecas > m or pecas <= 0 or pecas > n: print("Oops! Jogada inválida! Tente de novo.") pecas = int(input("Quantas peças você vai tirar? ")) ...
for x in range(1, 3): for y in range(1, 5): print('%d * %d = %d' % (x, y, x*y))
items = [] inventory = [] user = [] cart = [] #Utility function to check whether user exists or not def isUser(username): for i in user: flag = 0 if i[0] == username: flag = 1 return flag #Utility function to check whether item exists or not def isItem(category,br...
# https://www.hackerrank.com/challenges/akhil-and-gf/ # notice that 1..11 with n ones can be written as (10^n - 1) / 9 = a / 9 # taking the mod from this number (knowing that a divisible by 9 fully) # (10^n - 1) mod (9 * k). And after this because the number is divisible by 9, divide it by 9 def only_ones(n, k): a ...
# ========== Modular arithmetic ========== def modInv(a, mod): # calculate the modular inverse for 1 number def egcd(a, b): # extended Eucledian algorithm x, y, u, v = 0, 1, 1, 0 while a != 0: q, r = b / a, b % a m, n = x - u * q, y - v * q b, a, x...
# https://www.hackerrank.com/challenges/manasa-and-factorials # the main idea is to have a fast helper to calculate the number of zeros in the factorial # after this with the help of the binary search find the location of the the correct element def numberOfZerosInFactorial(n): k = 0 while n / 5: n /= 5...
# https://www.hackerrank.com/challenges/stars # for every possible 2 points check the sum of the weights above and below the the line # (not taking into the account these two points). Then also try different combinations with these # points it can be 2 points above the line, 2 points below the line, 1 point above, one ...
from itertools import permutations def is_prefix(arr): s = 0 for i in arr: s += i if s < 0: return False return True def is_sufix(arr): return is_prefix(arr[::-1]) def analyse(n): total = 0 arr = [-1] * n + [1] * (2 * n) for i in set(i for i in permutations(ar...
# https://www.hackerrank.com/challenges/building-a-list/ def f(start, arr, s): for i in xrange(s, len(arr)): print start + arr[i] f(start + arr[i], arr, i + 1) for i in xrange(input()): input() s = raw_input() s = ''.join(sorted(s)) f('', s, 0)
# https://www.hackerrank.com/contests/infinitum10/challenges/sherlock-and-moving-tiles # let's fix the first tile and move only the second with the speed v = |s1 - s2| # then the equation, which describes the motion, can be written as # t = 2^(1/2) * (l - q^(1/2)) / v def move(l, s1, s2, q): return 2**0.5 * (l - q...
# https://www.hackerrank.com/challenges/circle-city # basically checks the number of points on the circle with an integer coordinates. # instead of checking the whole circle it is suffice to check just one quarter for pp in xrange(input()): r, k = map(int, raw_input().split()) r_root, cnt = r**0.5, 0 if r_r...
# https://www.hackerrank.com/contests/infinitum11/challenges/prime-factorization-2 def getDivisorSieve(n): p, n_sqrt, sieve = 3, int(n**0.5) + 1, [0] * (n + 1) for i in range(2, n + 1, 2): sieve[i] = 2 while p <= n_sqrt: for i in xrange(p, n + 1, p): if not sieve[i]: ...
# -*- coding: utf-8 -*- """ Created on Tue Dec 10 16:26:42 2019 @author: Nathan """ from itertools import permutations, islice from math import factorial as f import numpy as np def brute(locs): """ Aruments: locs (atlas): an atlas type object Returns: (tuple): tsp path based on O(n!) bru...
total = 0 def sum(numone, numtwo): global total total = numone + numtwo print('inside function', total) return total sum(2, 3) # 5 print('outside function', total) # 5
def sum_of_min_and_max(lst): minimal = min(lst) maximal = max(lst) suma = minimal + maximal return suma print(sum_of_min_and_max([1,2,3,4,5,6,8,9])) print(sum_of_min_and_max([-10,5,10,100])) print(sum_of_min_and_max([1]))
class Node: def __init__(self, data): self.data = int(data) self.next = None class LinkedList: def __init__(self): self.head = None def asc_ordered_list(self, data): new_node = Node(data) if self.head is None: self.head = new_node return ...
import random hand=["Rock","Paper","Scissors"] #Función que devuelve el mensaje de victoria, derrota o empate. def result(P1,P2): win="YOU WIN!!" lose="YOU LOSE!!" draw="IT'S A DRAW" if(P1==P2): return(draw) if(P1=="Rock" and P2=="Scissors"): return(win) if(P1=="Paper" and P2=="Rock"): return(win) if(P1=="Scis...
#!/usr/bin/env python3 def partitions(s, n): "Generate all partitions of the given sequence" if n == 0: yield [ s ] elif len(s) == 0: yield [] elif len(s) == 1: yield [ s ] elif len(s) > 1: yield [ s ] for i in range(1,len(s)): for p in partitions(...
if __name__ == '__main__': # num = int(input("请输入个数:")) # i = 1 # while i <= num: # j = 1 # while j <= i: # print("*", end = " ") # j += 1 # print("\n") # i += 1 num = int(input("enter a num: ")) for i in range(1, num): ...
#!/usr/bin/env python # reducer.py # a reducer for the inverted index problem. # It gets a sorted collection of tuples (word, file-name) # and generates a list of tuples of the form # (word, [list of file-names]). from __future__ import print_function from operator import itemgetter import sys currentWord = None fil...
#!/usr/bin/env python # A basic mapper function/program that # takes whatever is passed on the input and # outputs tuples of all the words formatted # as (word, 1) from __future__ import print_function import sys # input comes from STDIN (standard input) for line in sys.stdin: # create tuples of all words in lin...
number = int(input("Number: ")) if number > 0: print("n is positive") elif number < 0: print("n is negative") else: print("n is Zero:))")
#Es gibt in Python zwei Arten von Schleifen while und for #Bei der While-Schleife werden die Befehle in der Schleife ausgefuehrt, #Solange die Bedingung wahr ist. #Durch die Einrueckung sagt man, welche Befehle zu der Schleife gehoeren #Hier das vorherige Beispiel, was jedoch endlos laeuft #Variablen initialisie...
#!/usr/bin/python3.9 # This script has completely customiseable operators and order of operations # It supports operators with any number of operands (e.g. factorial only has one operand) import re notOperator = "[^^\\*\\/\\+-]" # Regex matching all characters which are not operators orderOfOperations = [ {"reg...
import hello import main import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt from scipy import stats print("Hello World") ''' Alright so Read this before reading my code. This is actually more complicated than i thought it was. so we have three changes going on. for us t...
def powerSet(arr): l = 2 ** len(arr) for i in range(l): print generateSet(i, arr) def generateSet(i, arr): genSet = [] for x in range(len(arr)): if ( i >> x) % 2 == 1: genSet.append(arr[x]) return genSet powerSet(['a','b','c'])
# -*- coding: utf-8 -*- def Test(candidate): # return True if it is the password. subst = { ‘a’: [‘a’, ‘A’, ‘@’], ‘b’: []...} def crack(seed_word, subst): if len(seed_word) == 0: return None return testSubs(seed_word, 0 , subst) def testSubs(subs_word, index, subst): if index == len(subs_word): ...