text
stringlengths
37
1.41M
#leetcode #question - 9. Palindrome Number #level=easy x=-121 revs=0 org_num=x while x>0: remainder=x%10 revs=(revs*10)+remainder x=x//10 if org_num==revs: print("true") else: print("false")
# Reverse Words # Complete the function that accepts a string parameter, and reverses each word in the string. # All spaces in the string should be retained. def reverse_words(text): word = [] for i in text.split(): word.append(i[::-1]) word = ' '.join(word) return word # return ...
# Binary Search Algorithm # Create a random list of numbers between 0 and 100 with a difference of 2 between each number. # Ask the user for a number between 0 and 100 to check whether their number is in the list. # The programme should work like this. # The programme will half the list of numbers and see whether t...
import sys import cs50 def shift_low(letter, key): return chr(((ord(letter) + key - ord('a')) % 26) + ord('a')) def shift_up(letter, key): return chr(((ord(letter) + key - ord('A')) % 26) + ord('A')) def do_cipher(letter, key): if not letter.isalpha(): return letter ...
class Line: def __init__(self, coor1, coor2): self.coor1 = coor1 self.coor2 = coor2 pass def distance(self): x1, y1 = self.coor1 x2, y2 = self.coor2 return ((x2 - x1)**2 + (y2 - y1)**2)**0.5 def slope(self): x1, y1 = self.coor1 x2, y2 = self...
import numpy as np import matplotlib.pyplot as plt # Create some training samples in which np.dot(X.T, X) is a singular matrix X = np.array([ [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1], [1, 0, 1], [1, 0, 1] ]) Y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) # Attemp...
# Gaussian (a.k.a. normal) distribution import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm # Probability Density Function (PDF) r = np.random.randn(1000) p = norm.pdf(r) plt.scatter(r,p) plt.title("Probability Density Function (PDF)") plt.xlabel("r") plt.ylabel("p") plt.show() # Log Proba...
from tkinter import * from time import sleep # region "Variables" HEIGHT = 600 WIDTH = 800 window = Tk() window.title("Test Environment") c = Canvas(window, width=WIDTH, height=HEIGHT) c.pack() # endregion class Sprite: def __init__(self, colour, x1, y1, x2, y2): self.colour = colour self.x1 = x1 ...
num = (int(input('Digite um número: ')), int(input('Digite um numero: ')), int(input('Digite um numero: ')), int(input('Digite um numero: ')) ) print(f'O valor 9 apareceu {num.count(9)} vezes') print(f'O valor 3 apareceu na {num.index(3)+1}ª posicao') print('Os valores pares digitados foram:...
primeira = input("Informe a primeira string: ") segunda = input("Informe a segunda string: ") terceira = "" for letra in primeira: if letra not in segunda and letra not in terceira: terceira = terceira + letra for letra in segunda: if letra not in primeira and letra not in terceira: terceira +=...
import random as ra import math simulations = 10 area = [] for i in range(simulations): points = 0 for j in range(10000): x = ra.random() y = ra.random() if (x-0.5)**2 + (y-0.5)**2 <= 0.25: points += 1 area.append(points/10000) print("The area is {}".format(sum(area)/s...
# a library class # to display book # to lend book # to add book # return book # dictionary # a main function and run an infinite while loop asking # users for their input import time class library: DICT = {"Anatomy", "Biophysics", "BotanyCell", "biology", "Ecology", "Evolutionary biology", "Genetic...
my_dict = {"name": "matt", "cash": 5.45} print "claves\n-------" for key in my_dict.keys(): print key print "\nvalores\n-------" for value in my_dict.values(): print value
import random import unittest from decimal import Decimal from fractions import Fraction import quickselect as statistics class NumericTestCase(unittest.TestCase): """Unit test class for numeric work. This subclasses TestCase. In addition to the standard method ``TestCase.assertAlmostEqual``, ``assert...
class LazyProperty: def __init__(self, method): self.method = method self.method_name = method.__name__ print('b', self.method) # print(f"function overriden: {self.fget}") # print(f"function's name: {self.func_name}") # self : LazyProperty object # obj : Test object ...
def check_palindrome(name): name = name.upper() if name[0:] == name[: : -1]: return True else: return False print(check_palindrome('Kajak')) print(check_palindrome('Radar')) print(check_palindrome('Dupa')) print(check_palindrome('Lupul'))
# Elisabeth Finkel # December 2017 # Credits for idea to http://www.physics.cornell.edu/~myers/teaching/ComputationalMethods/ComputerExercises/ # import random import string def read_file_into_word_list(filename): inputFile = open(filename, 'r').read() translator = str.maketrans(string.punctuation, ' '*len(st...
def getHeight(totalCoins): height = 0 while(totalCoins > height): height += 1 totalCoins = totalCoins - height return height with open('C:/Users/David/Desktop/python/beginner/tricoinInput.txt') as f: total = f.readline() for x in range(int(total)): case = f.readline() ...
# Determine if the given character is a digit or not. # Example # For symbol = '0', the output should be # isDigit(symbol) = true; # For symbol = '-', the output should be # isDigit(symbol) = false. def isDigit(symbol): return symbol.isdigit() # Given a string, return its encoding defined as follows: # First, t...
# Consider integer numbers from 0 to n - 1 written down along the # circle in such a way that the distance between any two neighbouring # numbers is equal (note that 0 and n - 1 are neighbouring, too). # Given n and firstNumber, find the number which is written in the # radially opposite position to firstNumber. #...
from datetime import datetime from datetime import timedelta def fallback(time): time = time.split(':') hour, minute, am_pm = time[0], time[1][:2], time[1][2:] time = f'2018-11-2 {hour}:{minute} {am_pm}'.format( hour=hour, minute=minute, am_pm=am_pm) time = datetime.strptime(time, '%Y-%m-%d %I...
# Given two lists lst1 and lst2, your task is to return a list formed by the elements # of lst1 followed by the elements of lst2. # Note: this is a bugfix task, which means that the function is # already implemented but there is a bug in one of its lines. Your task is to find and fix it. # Example # For lst1 = [2,...
# In order to stop the Mad Coder evil genius you need # to decipher the encrypted message he sent to his minions. # The message contains several numbers that, when typed # into a supercomputer, will launch a missile into the # sky blocking out the sun, and making all the people on Earth grumpy and sad. # You figured o...
# -*- coding: utf-8 -*- """ A program to determine alpha and theta angles form by a given inclined plan. Such plan is define by three coordinates {x,y,z} """ import sympy as sp # Define referential system N = sp.vector.CoordSys3D('N') # Create three coordinates that define the inclined plan x1, y1, z1 =...
# FIND THE LARGEST AND SMALLET NUMBER FROM THE GIVEN LIST """ list=[1,5,90,85,45,67,32] print("Smallest number in the list is:", min(list)) print("Largest number in the list is: ",max(list)) """ #Python program to find smallest # number in a list # creating empty list list1 = [] # asking number of elements to put ...
""" Define a function that can accept two strings as input and print the string with the maximum length in the console. If two strings have the same length, then the function should print both the strings line by line. """ string1=input("Enter the first string: ") string2=input("Enter the second string: ") for i in s...
""" Write a function called showNumbers that takes a parameter called limit. It should print all the numbers between 0 and limit with a label to identify the even and odd numbers. Sample input: show Numbers(3) (where limit=3) Expected output: 0 EVEN 1 ODD 2 EVEN 3 ODD """ def showNumbers(limit): print("Limit is :"...
""" Create a list of given structure and get the Access list as provided below: x=[100,200,300,400,500,[1,2,3,4,5,[10,20,30,40,50],6,7,8,9],600,700,800] Access list: [1, 2, 3, 4]Access list: [600, 700] Access list: [100, 300, 500, 600, 800] Access list: [[800, 700, 600, [1, 2, 3, 4, 5, [10, 20, 30, 40, 50], 6, 7, 8, 9]...
""" Write a program in Python to perform the following operator based task: Ask user to choose the following option first: If User Enter 1 - Addition If User Enter 2 - Subtraction If User Enter 3 - Division If User Enter 4 - Multiplication If User Enter 5 - Average Ask user to enter two numbers and keep those numbers i...
""" Write a program in Python to iterate through the string “hello my name is abcde” and print the string which is having an even length. """ def printWords(s): # split the string s = s.split(' ') # iterate in words of string for word in s: # if length ...
""" Write a Person class with an instance variable “age” and a constructor that takes an integer as a parameter. The constructor must assign the integer value to the age variable after confirming the argument passed is not negative; if a negative argument is passed then the constructor should set age to 0 and print “Ag...
'''Fast translate once all string literals''' import os import re if 'myDict' not in globals(): myDict = {} def translateFile(fileName, resultFile): with open(fileName) as f: content = f.read() strLiterals = re.findall(r'''(['"])(.*?)\1''', content) for _,literal in strLiterals: translation = askTran...
#!/usr/bin/env python3 import math import sys from typing import List from typing import Tuple base_chance: int = 70 def print_separator() -> None: print(f'{"-" * 70}') def int_input(msg: str) -> int: return int(input(msg).replace(',', '')) def input_option(msg: str, options: str) -> str: while Tr...
#Calvin Field #4/26/15 #This is the same game as the quick_game.py, but using pygame, and not PIL import random from Tkinter import * import pygame from livewires import games, color import math #Creating screen window games.init(screen_width = 700, screen_height = 650, fps = 50) #Make the class for creating the play...
f = open("yesterday",'r') DATA = f.read() num_of_yesterday = DATA.count('yesterday') num_of_Yesterday = DATA.count('Yesterday') Sum_of_yesterday = num_of_Yesterday + num_of_yesterday print("Number of A Word 'Yesterday' is " , Sum_of_yesterday)
import math num = [] n = input("Please enter Any Number: ") while True: for j in range(len(n)): x = 0 a = n[x] a = int(a) for i in range(a): print("*",end="") x = x+1 print("") if len(n) < x: break
user1 = input("시급은 얼마입니까?") hourly_wage = int(user1) user2 = input("몇 시간 일했습니까?") time = int(user2) total_wage = hourly_wage * time fmt = """시급 {0}원으로 {1}시간 일했으므로 수당은 {2}원입니다.""" desc = fmt.format(hourly_wage, time, total_wage) print(desc)
import re x=True while x: passw = input("entr password") if len(passw)<8 or len(passw)>15: print("INVALID PASSWORD") print("length of the password not less than 8 or not greater than 15 characters") elif not re.search("[a-z]",passw): print("INVALID PASSWORD") print("...
# https://codeforces.com/problemset/problem/59/A word = input() u, l = 0, 0 for char in word: if char >= 'A' and char <= 'Z': u += 1 elif char >= 'a' and char <= 'z': l += 1 if u > l: print(word.upper()) else: print(word.lower())
# https://codeforces.com/problemset/problem/456/A n = int(input()) laptops = [tuple(map(int, input().split())) for _ in range(n)] laptops = sorted(laptops, key=lambda x: x[1], reverse=True) laptops = sorted(laptops, key=lambda x: x[0]) for i in range(n-1): if laptops[i][0] < laptops[i+1][0] and laptops[i][1] > l...
# https://codeforces.com/problemset/problem/472/A num = int(input()) if num % 4 == 0: print(num // 2, num // 2) elif (num - 9) % 2 == 0: print(9, num - 9) else: print(4, num - 4)
# https://codeforces.com/problemset/problem/4/C n = int(input()) db = {} for i in range(n): name = input() if name not in db: print('OK') db[name] = 1 else: print(f"{name}{db[name]}") db[name] += 1
# https://codeforces.com/problemset/problem/1144/A def is_diverse(s: str) -> bool: arr = sorted(char for char in s) if (ord(arr[-1]) - ord(arr[0]) + 1 == len(s)) and (len(set(arr)) == len(s)): return True else: return False def main(): t = int(input()) cases = [input() for _ in ran...
# https://codeforces.com/problemset/problem/1517/A def get_largest_2050(x): if len(str(x)) <=4 or int(f"2050{'0' * (len(str(x)) - 4)}") <= x: return int(f"2050{'0' * (len(str(x)) - 4)}") else: return int(f"2050{'0' * (len(str(x)) - 5)}") def main(): t = int(input()) cases = [int(input(...
# https://codeforces.com/problemset/problem/431/A a, b, c, d = map(int, input().split()) table = {'1': a, '2': b, '3': c, '4': d} print(sum(table[char] for char in input()))
"""program to print a pattern""" max=4 for i in range(1,max+1): for j in range(max,i,-1): print(" ",end="") for k in range(1,i+1): print(k,end="") for l in range(k-1,0,-1): print(l,end="") print()
"""10. Write a program to count the number of unique words and the number of occurrences of each of those words from the question provided below. Input: "How much wood would a woodchuck chuck if the woodchuck could chuck wood?" Output: Number of unique words: x abcd: p times efgh: q times rstu: t times""" data="How mu...
''' CS50: Introduction to Computer Science (course by Harvard University, taken via edX.org) PSet6: Credit (for "more comfortable") @author: Andrey Tymofeiuk Important: This code is placed at GitHub to track my progress in programming and to show my way of thinking. Also I will be happy if someb...
# Напишите программу, которая умеет шифровать и расшифровывать шифр # подстановки. Программа принимает на вход две строки одинаковой длины, на # первой строке записаны символы исходного алфавита, на второй строке — # символы конечного алфавита, после чего идёт строка, которую нужно # зашифровать переданным ключом, и е...
# Напишите программу, которая подключает модуль math и, используя значение # числа pi из этого модуля, находит для переданного ей на стандартный ввод # радиуса круга периметр этого круга и выводит его на стандартный вывод. import math n = float(input()) print(math.pi * n * 2)
# Напишите программу, которая принимает на вход список чисел в одной # строке и выводит на экран в одну строку значения, которые повторяются в # нём более одного раза. # Для решения задачи может пригодиться метод sort списка. # Выводимые числа не должны повторяться, порядок их вывода может быть # произвольным. a = ...
# Напишите простой калькулятор, который считывает с пользовательского # ввода три строки: первое число, второе число и операцию, после чего # применяет операцию к введённым числам ("первое число" "операция" "второе # число") и выводит результат на экран. # Поддерживаемые операции: +, -, /, *, mod, pow, div, где # mod...
import turtle daniel = turtle.Turtle() wn = turtle.Screen() def drawEyes(turtle,color,size,x,y): turtle.penup() turtle.color(color) #Sets the color for the turtle turtle.fillcolor(color) #Sets the color for the eyes turtle.goto(x,y) #Turtle moves to specified location turtle.begin_fill() #Tu...
import numpy as np import matplotlib import matplotlib.pyplot as plt import math #1. Simulate continuous random variables with selected distributions ############################### #P(1.1) a = 2.0, b = 5.0 --------------------------------------------------------------------------- #Generate the values of the R...
#This program will simulate drawing a card from a deck until King of Hearts is drawn #Program will then draw a line graph showing draws it took to get King of Hearts per game import turtle import random MIN = 1 MAX = 4 MAX_2 = 13 #The drawCard function draws until a King of Hearts is obtained def drawCard...
import math import turtle x1 = int(input("Enter the first x-coordinate: ")) y1 = int(input("Enter the first y-coordinate: ")) x2 = int(input("Enter the second x-coordinate: ")) y2 = int(input("Enter the second y-coordinate: ")) x3 = int(input("Enter the third x-coordinate: ")) y3 = int(input("Enter the third y-c...
import turtle wn = turtle.Screen() wn.bgcolor("lightblue") daniel = turtle.Turtle() daniel.color("green") daniel.shape("turtle") print(list(range(5, 60, 2))) daniel.up() for size in range(5, 60, 2): daniel.stamp() daniel.forward(size) daniel.right(24) wn.exitonclick()
import turtle def drawBar(t, height): """ Get turtle t to draw one bar, of height. """ t.begin_fill() # start filling this shape t.left(90) # turn left 90 degree t.forward(height) # move forward for a distance = height t.write(str(height)) # write height t...
#! /usr/bin/env python '''dna_to_aa: convert DNA sequence to amino acids; mostly from: http://www.petercollingridge.co.uk/book/export/html/474''' # Currently cuts off one aa of negative strand data with 3rd codon info import sys #import ipdb __version__ = '0.1' __author__ = '@speach' BASES = ['t', 'c', 'a'...
"""This module contains utils used through the rest of the code files. Functions ---------- check_directory: checks if a directory exists, creates it if not. """ import sys import os def check_directory(path: str) -> str: """Checks if a path exists in filesystem and whether it is a dir or not. If it...
'''A set of functions to evaluate the performance of a prediction, given the predicted output and the expected one Scoring indices: - (binary) MCC - (binary) sensitivity - (binary) positive predictive value - (multi) three-class accuracy all the confusion matrix-related indices are implemented as methods of the class ...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
#!/usr/bin/python def GetNumberLenght(n): return len(str(n)) n=0 counter=0 while(n<50): n+=1 lenght=0 i=0 while(lenght<=n): i+=1 lenght=GetNumberLenght(i**n) if lenght==n: counter+=1 print counter
#/usr/bin/python import sys n=int(sys.argv[1]) def getpathlenght(posx,posy): global patharray if posx==0 or posy==0: patharray[posx][posy]=1 #There is only one path to these if patharray[posx][posy]=='': patharray[posx][posy]=getpathlenght(posx-1,posy)+getpathlenght(posx,posy-1) #...
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import time factorirallist=[1] def factorial(n): global factorirallist if n==1 or n==0: return 1 summe=1 if len(factorirallist)>n: return factorirallist[n] for i in range(1,n+1): if len(factorirallist)>...
def loadmatrix(): file=open('matrix.txt') matrix=file.read() matrix=matrix.split('\n')[:-1] for i in range(len(matrix)): matrix[i]=matrix[i].split(',') for j in range(len(matrix[i])): matrix[i][j]=int(matrix[i][j]) return matrix def findShortestpath(x,y): global matr...
#!/usr/bin/python import sys def isPythagoreanTrip(a,b,c): if a**2+b**2==c**2: return True return False for c in xrange(1,1001): for b in xrange(1,c): if c+b>1000: break for a in xrange(1,b): if a+b+c==1000: if isPythagoreanTrip(a,b,c): ...
#!/usr/bin/python def Factorial(n): if n==0: return 1 if n==1: return 1 if n==2: return 2 if n==3: return 6 if n==4: return 24 if n==5: return 120 if n==6: return 720 if n==7: return 5040 if n==8: return 40320 ...
# Adam Smith # Projecteuler.net problem #6 # The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 # The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbe...
def f1(x): return (x + 1, str(x) + "+1") def f2(x): return (x + 2, str(x) + "+2") def f3(x): return (x + 3, str(x) + "+3") def unit(x): return (x, "Ops:") def bind(t, f): res = f(t[0]) return (res[0], t[1] + res[1] + ";") x = int(input("정수 입력 : ")) print( bind(bind(bind(unit(x), f1), f2), f3) )
from Matrix import Matrix from Vector import Vector class Rotate(): def __init__(self): self.Matrix = Matrix() self.Vector = Vector() def getRotatedPoint(self, _ox,_oy, _x, _y, _angle): _x1 = _x - _ox; _y1 = _y - _oy; ...
#!/usr/bin/env python # coding: utf-8 # # Hierarchical Clustering Lab # In this notebook, we will be using sklearn to conduct hierarchical clustering on the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris) which contains 4 dimensions/attributes and 150 samples. Each sample is labeled as one of the three ty...
#!/usr/bin/env python # coding: utf-8 # ### Feature Scaling - Solution # # With any distance based machine learning model (regularized regression methods, neural networks, and now kmeans), you will want to scale your data. # # If you have some features that are on completely different scales, this can greatly impa...
from typing import * R32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345" def r10_to_r32(num: int): if 0 <= num <= 31: return R32[num] raise Exception("Number out of range") def r32_to_r10(ch: str): if len(ch) == 1 and ch in R32: num = R32.find(ch) return num raise Exception("string ne...
def draw_stars(arr): for val in arr: string = '' for i in range (0,val): string += '*' print string draw_stars([4,6,1,3,5,7,25]) print '' def draw_stars2(arr): for val in arr: string = '' if type(val) == str: for i in range (0,len(val)): string += val[0].lower() else: for i in range (0,va...
#FIND AND REPLACE str = "It's thanksgiving day. It's my birthday,too!" for i in range (0,len(str)): if str[i:i+3] == 'day': print str[0:i] + 'month' + str[i+3:len(str)] break #MIN AND MAX x = [2,54,-2,7,12,98] min = x[0] max = x[0] for i in x: if i < min: min = i if i > max: max = i print 'Max:',max,'Min...
def insertionSort(arr): for n in range (0, len(arr)): # Go through each element in list # min = arr[n] for i in range (n, 0, -1): # Takes current number and compares it to the one before it, if arr[i] < arr[i-1]: # If current number is less, then swap it. Go backwards in the array until no longer less tha...
class Other(object): def override(self): print "OTHER override()" def implicit(self): print "OTHER implicit()" def altered(self): print "OTHER altered()" # notice how the Child class does not inherit from the Other class # however there may be some cases where we want to use some att...
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print self.price print self.max_speed print self.miles return self def ride(self): print 'Riding...' self.miles += 10 return self def reverse(self): ...
class DNode(object): def __init__(self, value): self.prev = None self.value = value self.next = None class DList(object): def __init__(self): self.head = None self.tail = None def printAllValues(self): node = self.head while node: print node.value node = node.next def addNode(self, value): ...
class Hospital(object): def __init__(self, name, capacity): self.patients = [] self.name = name self.capacity = capacity def admit(self, patient): if len(self.patients) < self.capacity: self.patients.append(patient) self.patients[len(self.patients)-1].bedNumber = self.patients[len(self.patients)-2].bed...
#!/usr/bin/python # -*- coding: UTF-8 -*- #print("hex1 ^ hex2 = %x")%(hex) #hex1 ^ hex2 = 746865206b696420646f6e277420706c6179 #异或 def myxor (string1 , string2): l1 = toHex(string1) l2 = toHex(string2) l3 = [] for x in range(0, len(l1)): l3.append(hex(int(l1[x], 16) ^ int(l2[x],1...
# Write a script election.py that will simulate an election between two candidates, A and B. One # of the candidates wins the overall election by a majority based on the outcomes of three regional # elections. (In other words, a candidate wins the overall election by winning at least # # two regional elections.) Candid...
# Define a function, enrollment_stats(), that takes as an input a list of lists where each # individual list contains three elements: (a) the name of a university, (b) the total number of # # enrolled students, and (c) the annual tuition fees. # This function should return two lists: the first containing all of the stu...
# This script should use a while loop to iterate through the dictionary and # grab # a random state and capital, assigning each to a variable. The user is then # asked what the capital of the randomly picked state is. The loop continues # forever, asking the user what the capital is, unless the user either answers # c...
# not following rigid straight line sequence of execution # getting conditional execution ability # loops when he know condition or number of repetetions involved #indentatio is important #if m%n !=0: # (m,n) = (n,m%n) #0 in condition is treated as false like wise "",[] is also false # loops y=1 z=0 for i in [1,2,3...
class BSTNode(object): def __init__(self, x): self.data = x self.left = None self.right = None #in-order traversal and global variable to count smallest K #Time complexity: O(n) #Space complexity: O(1) counter = 0 def kthSmallest(root, k): global counter if(not root): return None left = kthSmallest(root.left...
"""A matrix e.g. [[1,2,3], is defined as a list of lists where the inner lists represent the rows. [4,5,6]] e.g. the first element in every row translate to the first column """ def is_matrix(matrix): for i in range(1, len(matrix)): if len(matrix[i-1]) != len(matrix[i]): rais...
import simpy from collections import namedtuple import collections import random """ different classes/colleges that can only accept 50 students per course minimum grade to get in is 85, if the grade is lower, they have to leave and are added to failed_applications if the course is full, they are added to overflow_ap...
''' Created on 1 May 2019 @author: enerve ''' def has_won(B, coin, x, y): ''' Checks if 'coin' has won the game by playing at x,y ''' if _count(B, coin, x, y, 0, 1) >= 4: return True if _count(B, coin, x, y, 1, 0) >= 4: return True if _count(B, coin, x, y, 1, 1) >= 4: retu...
import socket import sys def main(): #passamoso af_inet onde utliza do ip #3soc_stream onde usamos o tcp #passamoso protocolo que fara a conexão com o server 0 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) except socket.error as e: print("Conexão falhou!") pr...
#Pedimos um numero ao usuario! a = int(input("Informe um numero:\n")) #Colocamos uma variavel inicializada com 0 para ser contador! div = 0 #faremos um laço for para verificar se é primo ou não! for x in range(1, a+1): resto = a % x if resto == 0: div +=1 if div == 2: print(f"numero {a} é primo!")...
#Criando um aclasse calculadora! class calculador: #Usando o metodo init def __init__(self): pass def soma(self , a, b): return a+b def sub(self, a, b): return a-b def mult(self, a, b): return a*b def div(self, a, b): return a/b calculador = calculado...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Exercise 4: Tuples @author: user01 """ #%% Creating tuples t=(1,); print(t[-1]); b=tuple([x for x in range(100,201)]); print(b[0],b[-1]); #%% Use tuples on a loop mylist=[23,"hi",2.4e-10] for (count,item) in enumerate(mylist): print(count,item) for a ...
import math class Point: """ Point class for representing and manipulating x,y coordinates. """ def __init__(self, initX, initY): """ Create a new point at the given coordinates. """ self.x = initX self.y = initY def getX(self): return self.x def getY(sel...
import multiprocessing import time from random import randint def countUp(): i = 0 while i <= 3: print('Up:\t{}'.format(i)) time.sleep(randint(1, 3)) # sleep 1, 2 or 3 seconds i += 1 def countDown(): i = 3 while i >= 0: print('Down:\t{}'.format(i)) time.sleep(ra...
# def nextMove(n,r,c,grid): for i in range(n): for j in range(n): if grid[i][j] == 'p': if i == r: if j < c: return 'LEFT' else: return 'RIGHT' if j == c: ...
#!/bin/python3 import os import sys from functools import reduce # # Complete the connectingTowns function below. # def connectingTowns(n, routes): # # Write your code here. # return reduce(lambda x,y : x * y, routes) % 1234567 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w'...
#!/bin/python3 import os import sys # # Complete the strangeGrid function below. # def strangeGrid(r, c): # # Write your code here. # if r % 2 == 0: return (r - 2) * 5 + 2 * c - 1 else: return (r - 1) * 5 + 2 * (c - 1) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_...
#!/bin/python3 import math import os import random import re import sys # Complete the matrixRotation function below. def matrixRotation(matrix, r, m, n): cycle = min(m,n) // 2 for i in range(cycle): lst = [] for j0 in range(i, m-i): lst.append(matrix[j0][i]) for j1 in rang...