text
stringlengths
37
1.41M
#Двмерный массив ''' def show_matrix(matrix): for row in matrix: # запускает цикл каждый раз и у нас получается каждая строка for x in row: # выводит строку print(x, end=" ") print() m = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] show_matrix(m) # print(m) # print(m[0]) # print(m[0][1]) ''' ...
import random def init_matrix(matrix, min_n, max_n): # заполняем случаными числами матрицу for i in range(len(matrix)): # проходим по след строке (запоняем) for j in range(len(matrix[0])): # проходим по строке (запоняем) matrix[i][j] = ran...
# printing pattern for pyramid # # # # # # # # # # # # # # # a = 6 for i in range(1, a): print(a*" " + "# "*i) a -= 1
import random class Creature: def __init__(self, creature_name, lvl): """ Constructor method. Class fields are defined here, it is discourage to do this outside the __init__ function. :param creature_name: :param lvl: """ self.name = creature_name s...
""" Author: Andrew Siu (andrewjsiu@gmail.com) ------------------------------------------------- Detecting Large Purchases within a Social Network ------------------------------------------------- This program detects a significantly large purchase compared to previous purchase...
class Node : def __init__(self, idx, data = 0) : # Constructor """ id : Integer (1, 2, 3, ...) """ self.id = idx self.data = data self.connectedTo = dict() def addNeighbour(self, neighbour , weight = 0) : """ neighbour : Node Object weig...
#!usr/bin/python import sys def reducer(): current_word=None current_year=None current_occurs=0 current_pages=0 for line in sys.stdin: word,year,occurs,pages=line.split('\t') if word==current_word and year==current_year: current_occurs +=int(occurs) current_...
"""Simple functions to encode and decode an input string with an input password. """ import random random_map = {} q = random.randint(1,32) def maplist(): """Create a dictionary whose values and keys are all range from 32 to 127. Values have shift right for some positions, which is generated random...
def encode(input, password): encoded_input = '' for i in range(max(len(input),len(password))): idxa = i % len(input) idxb = i % len(password) encoded_input += chr((ord(input[idxa]) + ord(password[idxb])) % 256) return encoded_input def decode(encoded_input, password): decoded_i...
""" Assignment 1 by Yue Han Create January 27, 2013 My algorithm is very simple. It is a mirror reverse of the unicode. """ def encode(input, password): """ Takes two strings and transforms them into a third, encoded string """ encodeword = input + password encodelist = list (encodeword) for i in range...
#Alireza Louni def encode(user, password): encoded = [] for i in range(len(user)): index_password= password[i % len(password)] # we need to obtain remainder (%) since "password" and "user" might have different letter long. mixed = (ord(user[i]) + ord(index_password)) %...
def get_indices_of_item_weights(weights, length, limit): """ YOUR CODE HERE """ # dict to store total weight and which indices d = {} # store the index numbers for answer indices = [] # loop through list and add each weight to the list # along with the index number for i in ran...
#!/usr/bin/env python # coding: utf-8 print("This is a C' to F' converter.") temp_in_celsius = input("Please enter a temperature, in C\n--> ") temp_in_fahrenheit = float(temp_in_celsius) *9/5 + 32 print("The temperature in Fahrenheit is: {:.2f}".format(temp_in_fahrenheit))
from sys import exit def_reason = "You died for unknown reason" def die(why = def_reason): """ Function for clean exit, printing the reason. Default reason is unknown.""" print why, "Game over!" exit(0) def def_input(prompt = '> '): return raw_input(prompt)
class BinaryTree: def __init__(self,objkey): self.key=objkey self.leftChild=None self.rightChild=None def insertLeft(self,newNode): if self.leftChild==None: self.leftChild=BinaryTree(newNode) else: temp=BinaryTree(newNode) temp.leftChil...
from pythonds.graphs import Graph from pythonds.basic import Queue def pathExists(start,end): vertexQueue=Queue() vertexQueue.enqueue(start) while (vertexQueue.size()>0): item=vertexQueue.dequeue() if item.getId()==end.getId(): print ("path exists") return True ...
# binary tree or not from pythonds.trees.binaryTree import BinaryTree prev=None def isBinarySearchTree(root): global prev if root: if not isBinarySearchTree(root.leftChild): return False if (prev and prev.key>root.key): return False prev=root if not isBina...
#!/usr/bin/python3 # run this script by: python3 -i build_pyramid_medium_v1.py # the -i stands for interactive # when you run the above command you will be greated by a python3 prompt ">>>" # type in make_pyramid(n); sustitute an odd, not even, number for n # this number will be the amount of stars on the bottom row o...
a = input() b = input() a = int(a) b = int(b) if a > 0 and b > 0: print('1') elif a < 0 and b > 0: print('2') elif a < 0 and b < 0: print('3') else: print('4')
''' Created on 27-Sep-2012 @author: Arvind Krishnaa Jagannathan @author: Ramitha Chitloor ''' from core.game.model.Pawn import Pawn class Player(object): ''' Defines the class player which will have 1. The list of pawns belonging to the player 2. The name of the player 3. Path array indicating ...
''' Created on 27-Sep-2012 @author: Arvind Krishnaa Jagannathan @author: Ramitha Chitloor ''' class Pawn(object): ''' Class to define the attributes and properties of a pawn 1. Name of the pawn in the format (PlayerName, i) 2. The cumulative dice value 3. Position the pawn is on (x,y) ''' ...
#!/usr/bin/python # Write a procedure, shift, which takes as its input a lowercase letter, # a-z and returns the next letter in the alphabet after it, with 'a' # following 'z'. def shift(letter): result = chr(ord(letter)+1) if result > 'z': return 'a' return result print shift('a') #>>> b print shift('...
# -*- coding: utf-8 -*- """ Created on Wed Jun 9 14:37:06 2021 @author: wooihaw """ # Challenge 3 alist = ['Python', 'Java', 'Perl', 'PHP', 'JavaScript', 'C++', 'C#', 'Ruby', 'R'] # Method 1 - Using for loop blist = [] for i in alist: if i[0].upper()=='P': blist.append(i) print(f'{blist=}')...
# -*- coding: utf-8 -*- """ Created on Wed Jun 9 14:47:23 2021 @author: wooihaw """ # Challenge 4 s1 = set(range(1, 101)) # number from 1 to 100 s2 = set(range(5, 101, 5)) # numbers divisible by 5 s3 = set(range(7, 101, 7)) # number divisible by 7 s = s1 - (s2 | s3) # numbers that are not divisible by 5...
def printm(A,n): i=0 while i<n: j=0 while j<n: print(A[i][j], end=" ") j+=1 i+=1 print() def copym(A,B,n): i=0 while i<n: j=0 B.append([]) while j<n: B[i].append(A[i][j]) ...
from turtle import Turtle, Screen import random def assign_colors(list_of_turtles): for i in list_of_turtles: color = random.choice(colors) i.color(color) colors.remove(color) return list_of_turtles def assign_position(list_of_turtles): y = -120 for i in list_of_turtles: ...
def bmi_check(bmi): if bmi <=18.5: print("Your bmi is " + str(round(bmi, 2)) + ", which means you're underweight.") elif bmi > 18.5 and bmi <= 25: print("Your bmi is " + str(round(bmi, 2)) + ", which means have normal weight.") elif bmi > 25 and bmi <= 30: print("Your bmi is " + str(...
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine coffee_machine = CoffeeMaker() menushka = Menu() money = MoneyMachine() def machine_in_operation(): off = False while not off: options = menushka.get_items() user_input = input(f"What ...
################################# # IML_T3 # ################################# # # File Name: main.py # # Course: 252-0220-00L Introduction to Machine Learning # # Authors: Adrian Esser (aesser@student.ethz.ch) # Abdelrahman-Shalaby (shalabya@student.ethz) import pan...
# Import the GPIO library import RPi.GPIO as IO # Define motor pin on Raspberry Pi motor_pin = 12 # Set the mode as IO IO.setmode(IO.BOARD) IO.setup(motor_pin, IO.OUT) # Set PWM frequency pwm = IO.PWM(motor_pin, 100) # Define the function that reverses the PWM value for a human readable format. def true_pwm (num):...
#HYERICA 19년 1학기 컴퓨팅적 사고 기말고사 예상문제(학생제공용) #1번 문제 <점수 입력 후 성적 출력하기> print("점수를 입력하세요:") score = int(input()) if score>=90: print("A") elif score>=80: print("B") elif score>=70: print("C") elif score>=60: print("D") else: print("F")
x = int(input("Enter the 1st number: ")) y = int(input("Enter the 2nd number: ")) temvariable = x x = y y = temvariable print('The value of x after swapping: {}', x) print('The value of y after swapping: {}', y)
from random import randrange number=randrange(1,1000) secret=int(raw_input("We are going to play higher and lower, guess a number from 1 to 1000.\n>")) while(secret!=number): if(secret<number): print("Guess Higher") secret=int(raw_input("Enter another number.\n>")) elif(secret>number): print("Guess Lower") s...
# coding=utf-8 # author='HopePower' # time='2020/8/27 23:17' # 列表推导支持多重循环 matrix = [[1, 2, 3], [4, 5, 5], [7, 8, 9]] flat = [x for row in matrix for x in row] print flat squared = [[x**2 for x in row] for row in matrix] print squared # 超过两个表达式的列表推导是很难理解的,应该尽量避免
import pygame import piece as p #definition of the class responsible for the board and all behaviour of pieces inside it class table: def __init__(self): #creator of the class table self.pieceEliminated = False self.comboPossible = False #the two variables above are used to indicate characteristics of one p...
"""Calculate the Hamming difference between two DNA strands.""" def hamming(strand1, strand2): count = 0 if len(strand1) != len(strand2): raise ArgumentError("The lists are different lengths") if strand1 == "" or strand2 == "": raise Arugument("The strings are empty.") return sum([co...
# Decorator that registers processors to Detectors def register_proc(*classes): """ A simple decorator that attaches the registered functions to the appropriate classes """ def decorated(f): for cls in classes: if hasattr(cls, 'processors'): cls.processors.append(f) el...
# Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: # 0 <= a, b, c, d < n # a, b, c, and d are distinct. # nums[a] + nums[b] + nums[c] + nums[d] == target # You may return the answer in any order. # Example 1: # Input: nums = [1,0,-1,0,-...
''' Author: Michele Alladio es: An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. For example: 9 is an Armstrong number, because 9 = 9^1 = 9 10 is not an Armstrong number, because 10 != 1^2 + 0^2 = 1 153 is an Armstrong number, because: 153 = ...
''' Author: Michele Alladio es: A Pythagorean triplet is a set of three natural numbers, {a, b, c}, for which, a**2 + b**2 = c**2 and such that, a < b < c For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2. Given an input integer N, find all Pythagorean triplets for which a + b + c = N. For example, with ...
''' In this exercise, let's try to solve a classic problem. Bob is a thief. After months of careful planning, he finally manages to crack the security systems of a high-class apartment. In front of him are many items, each with a value (v) and weight (w). Bob, of course, wants to maximize the total value he can ...
''' Author: Michele Alladio es: Correctly determine the fewest number of coins to be given to a customer such that the sum of the coins' value would equal the correct amount of change. For example An input of 15 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) or [5, 10] An input of 40 w...
import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model house_price = [245,312,279,308,199,219,405,324,319,255] size = [1400,1600,1700,1875,1100,1550,2350,2450,1425,1700] size2 = np.array(size).reshape((-1,1)) regr = linear_model.LinearRegression() regr.fit(size2,house_price) print("Coeff...
''' #Code : Removing node from Circular Linked List: Condition : 1) Deleting head node 2) delete any other node ''' # Code class Node: def __init__(self,data=None,next=None): self.data = data self.next = next class Circularlinkedlist: def __init__(self): self.head = None ...
import time print("How many digits that you want to calculate?") print("2 Digits (Example: 2 + 2)") print("3 Digits (Example: 2 + 2 + 2)") print("4 Digits (Example: 2 + 2 + 2 + 2)") digits = input("Digits: ") if digits == "2": print("What calculation do you want?") print("addition") print("subt...
import time def sleeptime(hour,min,sec): return hour*3600 + min*60 + sec; second = sleeptime(0,0,2); for i in range(5): time.sleep(second); print(123)
"""Dataframe used as input by many estimator checks.""" from typing import Tuple import pandas as pd from sklearn.datasets import make_classification def test_df( categorical: bool = False, datetime: bool = False ) -> Tuple[pd.DataFrame, pd.Series]: """ Creates a dataframe that contains only numerical f...
"""HTTP Requests with Python ================= Using urllib: ================== import urllib urlhandler = urllib.urlopen('http://www.py4inf.com/code/romeo.txt') for line in urlhandler: print line.strip() ====================================================== """ import socket def make_socket(): """Crea...
"""distplot, kdeplot, rugplot, jointplot, pairplot""" import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy import stats from scipy.integrate import trapz sns.set() x = np.random.normal(size=100) mean, cov = [0, 1], [(1, .5), (.5, 1)] data = np.random.mult...
first_name = "Prashanth" last_name = "S" str1 = [] for i in range(1, len(first_name) + 1): str1.append(first_name[-i]) str1.append(" ") for i in range(1, len(last_name) + 1): str1.append(last_name[-i]) print("".join(str1))
# Your code here def finder(files, queries): """ YOUR CODE HERE """ # Your code here # Loop through list of file paths and create dictionary where each key is # the file (last entry in the path) and each value a list of file path(s) path_dict = {} for path in files: file = p...
#!/usr/bin/env python3 # -*-encoding: utf-8-*- import re def valid_mail(mail: str) -> bool: """ validation mail name using regex """ success = False pattern = re.compile(r'[\w.]+@([\w-]+\.)+[\w-]{2,4}') matched = pattern.match(mail) # None if isn't matched if matched is not None: ...
""" This module checks if board is correct and ready for game. """ def check_rows(board): """ Returns False if there are two identical numbers in row and True otherwise >>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\ " 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"]) ...
from math import atan, fabs from time import sleep def f(x): return atan(x) k = 0 a = -3 b = 3 funa = f(a) funb = f(b) if (funa*funb>0.0): print("Funkcijas atan(x) dotaja intervala [%s, %s] saknju nav" %(a,b)) sleep(1); exit() else: print("Funkcijas atan(x) dotaja intervala sakne(s) ir!") deltax...
class Queue(object): def __init__(self): self.q = list() def is_empty(self): return self.q == [] def size(self): return len(self.q) def add_to_queue(self, data): if self.is_empty(): self.q.append(data) elif self.size() == 1: temp = self...
import os import csv #path to collect data csvpath = os.path.join("./Resources/budget_data.csv") # assigning variables... netProfit = 0 monthProfit = 0 counter = 0 previous = 0 change = 0 # .. and lists changesList = [] months = [] # read file data w csv module with open(csvpath, newline='') as csvfile: csvread...
from selenium import webdriver from selenium.webdriver.common.keys import Keys #to use select in dropdown from selenium.webdriver.support.ui import Select import time driver=webdriver.Chrome(executable_path="C:\Program Files (x86)\chromedriver_win32\chromedriver.exe") driver.maximize_window() driver.get(...
""" UNIT 2: Logic Puzzle You will write code to solve the following logic puzzle: 1. The person who arrived on Wednesday bought the laptop. 2. The programmer is not Wilkes. OK 3. Of the programmer and the person who bought the droid, one is Wilkes and the other is Hamming. 4. The writer is not Minsky. OK 5. Neith...
# -*- coding: utf-8 -*- # Print List of Country Host of FIFA World Cup on Century 21 world_cup_21th = { '2002': ['South Korea', 'Japan'], '2006': 'Germany', '2010': 'South Africa', '2014': 'Brazil', '2018': 'Russia', } def find_country(year): if year in world_cup_21th: val = ...
def main(): b = int(input("How many degrees fahrenheit today? ")) sum = 0 print("temperature today in celsius is",(b-32)*5/9) main()
import urllib from BeautifulSoup import * #url = raw_input('Enter - ') #url = 'http://python-data.dr-chuck.net/comments_42.html' url = 'http://python-data.dr-chuck.net/comments_260258.html' html = urllib.urlopen(url).read() soup = BeautifulSoup(html) sumTotal = [] # Retrieve all of the span tags tags = soup('span') ...
from nltk.corpus import wordnet import itertools as IT list1 = input("set the first sentences: ").split() list2 = input("set the second sentences: ").split() def f(word1, word2): wordFromList1 = wordnet.synsets(word1)[0] wordFromList2 = wordnet.synsets(word2)[0] s = wordFromList1.wup_similarity(wordFromList...
from util import Queue from graph import Graph def earliest_ancestor(ancestors, starting_node): graph = Graph() for pair in ancestors: graph.add_vertex(pair[0]) graph.add_vertex(pair[1]) graph.add_edge(pair[1], pair[0]) q = Queue() q.enqueue([starting_node]) max_path_length ...
# The problem is: # Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. # Example 1: # Input: "Hello" # Output: "hello" # Example 2: # Input: "here" # Output: "here" # Example 3: # Input: "LOVELY" # Output: "lovely" # My code beats 100% of oth...
# Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. # To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. # To invert an image means that each 0 is replaced by...
# 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。 # n<=39 # -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n == 0: return 0 elif n == 1: return 1 else: p1 = 0 p2 = 1 for ...
# Given an n-ary tree, return the preorder traversal of its nodes' values. # The 1st solution: """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def preorder(self, root): """ :ty...
# PRIMEIRO: SELECTION SORT """ Algoritmo de classificação de seleção simples. O algoritmo divide a entrada em duas partes: a sublista de itens já classificado, que é construído da esquerda para a direita na frente (esquerda) da lista, e a sublista de itens restantes a serem classificados que oc...
import random import copy import time N = 2 class Cell: def __init__(self, pos): # A cell initially can have N*N possible answers self.possibleAnswers = list(range(1, N*N+1)) # The answer is initially None self.ans = None # the position of ca cell is a tuple of three integ...
import math # ------------------------------------------------------------- # --------------------- DATA FUNCTIONS ------------------------ # ------------------------------------------------------------- SOLVEDSET = set(range(1,10)) ROWS,COLS,BOXS = 0,1,2 whatRowColOrBox = [lambda cell: whatRow(cell),\ lambda ce...
h = 100 l = 0 g = (h+l)//2 print('Please think of a number between 0 and 100') print('Is your secret number ' + str(g) + '?') x = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.') while not x == 'c': if x != 'h' and x!= 'l': ...
from game import Game from player import BlackjackDealer class Blackjack(Game): def __init__(self): Game.__init__(self) self.name = 'Blackjack' self.dealer = BlackjackDealer(self) self.winner = [] self.init_deck() def deal(self): ''' deals 2 cards to every playe...
def enque(data): s1.append(data) def deque(): if len(s1) == 0: print("queue is empty") return while len(s1) > 0: s2.append(s1.pop()) d = s2.pop() while len(s2) > 0: s1.append(s2.pop()) return d def length(): return len(s1) s1 = [] s2 = [] for i in range(...
numero1 = int(input("Digite o primeiro numero: ")) numero2 = int(input("Digite o segundo numero: ")) if numero1 > numero2: print("Maior número = " + str(numero1)) if numero2 > numero1: print("Maior número = " + str(numero2)) if numero1 == numero2: print("Numeros identicos ")
def compare(num1, num2): if num1 > num2: return f"{num1} is greater than {num2}" elif num1 < num2: return f"{num1} is less than {num2}" else: return f"{num1} is the same as {num2}"
def square_sum(nr): return (nr*(nr+1)*(2*nr +1))/6 def sum_square(nr): return ((nr*(nr +1))/2)**2 print(square_sum(100)-sum_square(100))
# coding:utf-8 def get_train(): # 输入训练样本的特征以及目标值,分别存储在变量X_train与y_train之中。 X_train = [[6], [8], [10], [14], [18]] y_train = [[7], [9], [13], [17.5], [18]] return X_train, y_train # 导入numpy并且重命名为np。 import numpy as np def get_tezt_xx(): # 在x轴上从0至25均匀采样100个数据点。 xx = np.linspace(0, 26, 100) ...
# -*- coding: utf-8 -*- # Python 3.8.6 numberOfStudents = int(input("Enter the number of students enrolled in " "this course: ")) print() if numberOfStudents > 0: listOfNames = [] marksObtained = [] for x in range(numberOfStudents): print("Enter the name of stu...
# -*- coding: utf-8 -*- # Python 3.8.6 n = 0 while n not in [1,3,5,7,9]: n = int(input("Enter the order of the desired magic square (1/3/5/7/9): ")) print() # To add zeroes to every position. magicSquare = [[0 for x in range(n)] for y in range(n)] number = 1 i = int(n/2); j = n-1 while number < (n*n)+1: ...
# -*- coding: utf-8 -*- # Python 3.8.6 a = int(input("Enter the integer value for which you want to know the " "multiplication table: ")) for x in range(1,10): print(a, "x", x, " = ", a*x, sep = "")
# -*- coding: utf-8 -*- # Python 3.8.6 n = int(input()) num = 1 for i in range (1, n+1): for j in range (1, i+1): print(num*num, end = " ") num = num+1 print()
# -*- coding: utf-8 -*- # Python 3.8.6 import turtle turtle.bgcolor("black") myTurtle = turtle.Turtle(); myTurtle.setpos(-250,250); myTurtle.color("white") distanceToMoveWhenCalled = 25 rows = 20; columns = 22; rowCounterForSpiral = rows; columnCounterForSpiral = columns while rowCounterForSpiral > 0 and columnCoun...
# -*- coding: utf-8 -*- # Python 3.8.6 import speech_recognition as sr SAMPLE_AUDIO = ("sample.wav") r = sr.Recognizer() with sr.AudioFile(SAMPLE_AUDIO) as sourceFile: audio = r.record(sourceFile) try: print("The audio file says that", r.recognize_google(audio)) except sr.UnknownValueError: print("Goog...
# -*- coding: utf-8 -*- # Python 3.8.6 sum = 1 for x in range(2,10): sum = sum+x print("The sum of the first", x, "positive integers is", sum) # /* Trivia - 07.py # # * for x in range(unsignedInt1, unsignedInt2+1, positiveInt) assigns a new # value to x every time, beginning with unsignedInt1 and end...
## Will need to test this file ## In addition will need to add sanity checks and type checks class SrtFileCreator(): """ Constructs an SRT FILE. File name needed upon declaration of object """ def __init__(self, srt_file_name): self.subtitle_count = 0 self.srt_file_name = srt_file_name self.srt_file_contents = ...
#!/usr/bin/python3 """ print bs4 object run executable ./printSoup.py """ if __name__ == "__main__": from bs4 import BeautifulSoup as soupy myfile = open('python.html') soup = soupy(myfile, "lxml") print("BeautifulSoup Object: {}\na: {}\nstrong: {}".format (type(soup), soup.find_all('a'), s...
import argparse from geo_utils import calculate_distance STANFORD_LATITUDE = STANFORD_LONGITUDE = def calculate_distance_from_stanford(ref_longitude, ref_latitude): """ Arguments: `records` is a list of dictionaries with `latitude` and `longitude` keypairs `ref_longitude` is a float represent...
""" Abstract base class for all Interfaces. :Author: Maded Batara III :Version: v20181126 """ from engine import ViewEvents class Interface: """A view for the three-four-three game engine. """ def __init__(self): """ Initializes an Interface. When subclassing Interface, a...
""" Controller class for the threefourthree game. :Author: Maded Batara III :Version: v20181126 """ from engine import Game, ControllerEvents class Controller: def __init__(self, interface): """ Initializes a new Controller. """ self.current_game = None self.interf...
#Lists X=[] Y=[] input('Enter list of X: ') input('Enter list of Y: ') #Defining function def fizzbuzz(X,Y) if ((len(X)+len(Y))%3)==0: print('Fizz') elif ((len(X)+len(Y))%5)==0: print('Buzz') elif ((len(X)+len(Y))%((3 and 5)or (len(X)+len(Y))): print('fizzbuzz') else: prin...
class Link: empty = () def __init__(self, value, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.value = value self.rest = rest def __getitem__(self, i): if i == 0: return self.value else: return self.rest[i - 1] de...
from math import sqrt from math import ceil # Exercise 1. Implement the algorithm covered in lectures (and not any other algorithm) that determines if an integer n is prime. Your function should return True, if n is prime, and False otherwise. Your algorithm has to be effective for n ~ 1,000,000,000,000. A descriptio...
userId = 0 amountAtHand = 50000 accountNumber = 0 pin = 0 name = '' mainArray = [] accountNotPresent = False isLoggedIn = False loggedInUser = {} def registration(): global name name = input('Input your name') print('name has been saved') numberAndPin() def numberAndPin(): global accountNumber, pin, amountAtHan...
#!/usr/bin/env python3 """ Creating a Workbook object with OpenPyXL Adding, deleting and renaming sheets Saving the workbook to disk """ from openpyxl import Workbook def main(): #Creating the Workbook object wb = Workbook() # Create s new sheets ws = wb.create_sheet("A sheet", 0) #...
#crear un codigo que calcule las soluciones de la ecuacion cuadratica de # ax^2 + bx + c = 0 #para resolver se usa: # x1 = (-b + math.sqrt(bˆ2 - 4ac)) / 2a # x2 = (-b - sqrt(bˆ2 - 4ac)) / 2a # sqrt es raiz cuadrada # 2 ** 2 es para hacer potencia import math a = float(input('Ingrese el valor de "a" ...
''' TAREA1 Estudiante: Veronica Morera Crear un archivo llamado tarea_1.py Escribir un código en Python que imprima en pantalla lo siguiente: * 3.1415926 ** 3.141592 *** 3.14159 **** 3.1415 ***** 3.141 ****** 3.14 usando el operador % para definir la cantidad de digitos decimales de PI y la cantidad de asteriscos. '...
''' Crear líneas de código en Python que calcule el promedio de los valores contenidos en una lista. Ejemplo mis_valores = [5, 6, 10, 13, 3, 4] Pueden usar cualquier estrategia pero que sea simple. Considere si se tiene una lista que contiene las alturas de grupos de personas todos = [ [177,145,167,190,140,150,180...
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np # In[4]: my_list = [-17, 0, 4, 5, 9] my_array_from_list = np.array(my_list) my_array_from_list # In[5]: my_array_from_list * 10 # In[6]: my_array_from_list + 1 # In[ ]: #SLICING ARRAY # In[15]: my_vector = np.array([-17, -4, 0, 2, ...
''' 1- crear una tupla de mango, uvas, manzana, pera ''' #mis_frutas = ('mango', 'uvas', 'manzana', 'pera') #print(mis_frutas) #----------------------------------------------------------------- #2- agregar piña a la tupla de frutas mis_frutas = ('mango', 'uvas', 'manzana', 'pera') + ('piña', ) #print(mis_frutas...
def solution() : N = int(input()) result = 0 for i in range(int(N/2), N) : #print("i : ", i) temp = i sum_temp = i while True : sum_temp += temp % 10 if int(temp / 10) == 0 : break temp = int(temp / 10) if sum_temp ...