text
stringlengths
37
1.41M
from BTNode import BTNode class BST: __slots__ = 'root', 'size' def __init__(self): self.root = None self.size = 0 def __insert(self, val, node): if val < node.val: if node.left is None: node.left = BTNode(val) else: self._...
''' balances.py This program creates a balance puzzle from an input file, solves any missing weights, and draws the balance puzzle using the turtle. ''' __author__ = 'Bikash Roy - br8376', 'Tanay Bhardwaj' import turtle import sys class Beam: __slots__ = 'name', 'left', 'right', 'distance', 'branch', 'pixel', '...
# Program to check if a number is prime or not num = 29 # To take input from the user #num = int(input("Enter a number: ")) # define a flag variable flag = False # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2, num): if (num % i) == 0: # if factor is f...
v = lambda m: all(len(m[0]) == len(x) for x in m[1:]) def f(a, b): r = [] for i in range(2): if not v([a, b][i]): raise ValueError('Matriz #%d não é válida.' % i) if len(a[0]) != len(b): raise ValueError('Não é possível obter o produto.') for x in a: tm = ...
file = input("Enter file name:") import re fh = open(file) sum = 0 for line in fh: y = re.findall("[0-9]+",line) if y == []: continue #print(y) for n in y: #print(n) n = int(n) sum = sum + n #print(sum) print(sum)
import time import math start_time = time.time() def is_prime(n): """ Check if given number is a prime or not Parameter: ------------ n: integer Return: ---------- True if n is a prime number False otherwise """ # Raise errors: if n is None: ret...
def lowercase(): print("The input given in lowercase is :"); print(str_input.lower()); def uppercase(): print("The input in uppercasev is :"); print(str_input.upper()); str_input=str(input("Enter the string to convert to upper and lower cases :")); lowercase(); uppercase();
class rectangle: lenght=0; width=0; def area(self): length=int(input("Enter the length of the rectange: ")); width=int(input("Enter the width of the rectangle: ")); a=length*width; print("The area of the rectangle is: ",a); return; rect1=rectangle(); rectang...
"""Cut Circles script. Cuts circles on frames based on three different mouse clicks. Images already processed are moved to another folder. Usage: python cutCircles.py <image/video> <source_folder> Manual: When started on a folder with several images, the program will open the first one and wait for t...
# 6.00x Problem Set 3 # # Successive Approximation: Newton's Method # # Problem 1: Polynomials def evaluatePoly(poly, x): ''' Computes the value of a polynomial function at given value x. Returns that value as a float. poly: list of numbers, length > 0 x: number returns: float ''' # ...
class Vector: def __init__(self, vec1): self.vec1=vec1 def shape_of(self): return (len(self.vec1), ) def __eq__(self, other): return self.vec1 == other.vec1 def __add__(self, other): # if shape_of(self.vec1) != shape_of(self.vec1): # raise ShapeExceptio...
""" File name: RotationEvaluator.py Author: Matthew Allen Date: 7/12/20 Description: This file implements an evaluator which is used to evaluate a rotation in the simulation and report the DPT produced by that rotation. """ from Environment import CombatSimulator from Environment.Game import Enemy,...
# Name: Maria Halvarsson # Date: 2021-04-11 # Course code: DD100N7 # This program represents a robot that takes care of your pets. The robot can feed and play with the pets. # Each pet has a name, species, hunger and play need. The hunger and play need is an integer value # that is between 0 and 10 where 10 is the hun...
""" Builds and trains a neural network that uses policy gradients to learn to play Tic-Tac-Toe. The input to the network is a vector with a number for each space on the board. If the space has one of the networks pieces then the input vector has the value 1. -1 for the opponents space and 0 for no piece. The output o...
def star_string(num): if num < 0: raise ValueError() if num == 0: return '*' else: return '*'*(2**num - 2**(num-1)) + star_string(num-1)
def remove_odd_digits(num): neg = 1 if num < 0: neg = -1 num = abs(num) lastdigit = int(num%10) if lastdigit == 0: if num >10: return (remove_odd_digits(int(num//10))*10) * neg else: return 0 elif lastdigit % 2 != 0: return (remove_odd_...
# -*- coding: utf-8 -*- """ Created on Fri May 1 20:58:56 2020 @author: Raúl """ MAX = "white" MIN = "black" class Piece: isKing = False isBlack = None #constructor for the piece class, indicating the color of the piece #initially all the pieces are not kings def __init__(se...
""" Programmer: Collin Michael Fields Date: 11/1/2018 Purpose: Calculate the value of E out to a certain decimal place. (Currently only works to the 48th decimal place. """ import math from decimal import * #Setting the precision to a value that will not cause it to error out. getcontext().prec = 999 print("Welcom...
#Programmer: Collin M. Fields #Date: 03/19/2019 #Purpose: Fibonacci Sequence #Displays only the value at that point in the sequence. def fibonacciSequence(n): if(n == 1): return 1 elif(n == 0): return 0 else: return fibonacciSequence(n-2) + fibonacciSequence(n-1) #Shows entire Fibonacci sequence up to and ...
import pygame class button(): def __init__(self,color,x,y,width,height,text = ''): self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text def draw(self,win,outline = None): if outline: pygame.draw...
# -*- coding: utf-8 -*- """ Created on Thu Sep 26 11:03:02 2019 @author: parju """ class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def put(self, item): self.items.insert(0,item) def get(self): return self....
import pygame import sys pygame.init() screen_width = 1200 screen_height = 900 screen = pygame.display.set_mode((screen_width, screen_height)) WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) GREEN = (54,89,74) GREY = (50,50,50) YELLOW = (255, 255,0) square_size = (screen_height - 100) / 8 board_grid = [["em...
my_str = 'MaDam' my_str = my_str.casefold() rev_str = reversed(my_str) if list(my_str) == list(rev_str): print("Palindrome.") else: print("Not Palindrome.")
#Write a program to take input from user using following approach and return the datatype of all variable: #raw_input() x = raw_input("What is you name?") print x print type(x) x = raw_input("Enter the age") print x print type(x) #raw_input with type conversion x = int(raw_input("Enter the age")) print x print type(...
# Write a program to print the list of numbers which has a cube # of odd numbers in the range of 1,50. x=range(1,51) print x for i in range(len(x)): x[i]=x[i]**3 res= filter(lambda x:x%2 > 0, x) print res
# -*- coding: utf-8 -*- # 2015-2016 Complementos de Programacao # Grupo 3 # 43134 Luís Filipe Leal Campos # 48392 Mariana Vieira De Almeida Nave from Service import Service from Driver import Driver from Vehicle import Vehicle class DetailedService(Service): """A DetailedService. Similar to Service but with mor...
#Meredith Hu #Project Euler - Multiples of 3 and 5 #2017-6-20 def mults(): s = 0 threes=0 while threes <999: threes+=3 s+=threes fives=0 while fives<995: fives+=5 if fives%3==0: fives+=5 s+=fives return s print mults()
import sqlite3 datahandle=sqlite3.connect('EmailCount.sqlite') cur=datahandle.cursor() cur.execute('DROP TABLE IF EXISTS Counts') cur.execute("CREATE TABLE COUNTS ( email VARCHAR(128), count INTEGER)") filename=input("ENTER THE FILE NAME- ") if(len(filename)<1): filename='mbox-short.txt' filehandle=op...
from xml.dom import minidom xmldoc = minidom.parse("kml.kml") # this line read whole xml document kml.kml ( kml is after ?xml tag name) kml = xmldoc.getElementsByTagName("kml")[0] # retuns the list of all tags matched with kml tag name, 0 is to get the first element document = kml.getElementsByTagName("Docum...
import random as rand import string class AdoptionCenter: """ The AdoptionCenter class stores the important information that a client would need to know about, such as the different numbers of species stored, the location, and the name. It also has a method to adopt a pet. """ def __init__(se...
# EdX MITx.6.00.1x - Week 6 # Lecture 11 Problem 6 """For this exercise, you will be coding your very first class, a Queue class. Queues are a fundamental computer science data structure. A queue is basically like a line at Disneyland - you can add elements to a queue, and they maintain a specific order. When you wa...
val1, val2, val3 = input().split() distancia = float(val1) record = float(val2) tiempo = float(val3) if distancia > 0 and record > 0 and tiempo > 0: valMedio = (distancia*0.001)/(tiempo/3600) rPromedio = record + (record *(25/100)) if valMedio > record and valMedio < rPromedio: print("NUEVO ...
""""Thread synchronisation with queue""" from threading import Thread from queue import Queue import time import random class Producer(Thread): def __init__(self, queue): Thread.__init__(self) self.queue = queue def run(self): for i in range(5): item = random.randint(0, ...
example = [1, ["another", "list"], ("a", "tuple")] example mylist = ["element 1", 2, 3.14] mylist mylist[0] = "yet element 1" print(mylist[0]) mylist[-1] = 3.15 print (mylist[-1]) mydict = {"Key 1": "value 1", 2: 3, "pi": 3.14} print(mydict) mydict["pi"] = 3.15 print(mydict["pi"]) mytuple = (1, 2, 3) print(mytuple) myf...
import time import os from random import randint from threading import Thread class MyThreadClass (Thread): def __init__(self, name, duration): Thread.__init__(self) self.name = name self.duration = duration def run(self): print ("---> " + self.name + \ " running, belonging t...
import multiprocessing import random import time class producer(multiprocessing.Process): def __init__(self, queue): multiprocessing.Process.__init__(self) self.queue = queue def run(self) : for i in range(10): item = random.randint(0, 256) self.queue.put(item) ...
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import math NUMBERS = range(0, 2) def cpu_heavy(x): count = 0 for i in range(x ** 2): count += i ** 2 def threading_example(fn=cpu_heavy, chunksize=100): """Threaded version: 8 threads.""" items = [] # Melhores prát...
def coro(): i = 0 while i < 2: item = yield i += 1 print(item) c = coro() next(c) try: c.send("abc") c.send("abc 2") c.send("abc") # aqui dá erro! c.send("abc") except StopIteration as si: print("ahhh mlq") import asyncio async def async_function(): pr...
## https://www.hackerearth.com/practice/notes/number-theory-1/ def SieveofEratosthenes(n): for i in range(2,n+1): if(prime[i]==0): prime[i]=1 tmp=i*2 while(tmp<=n): prime[tmp]=-1 tmp+=i def countNoOfPrimes(n): count=0 for i in ran...
def LetterChanges(str): length=len(str) str=str.lower() i=0 while i < length: str[i]=ChangeLetter(str[i]) i=i+1 return str def ChangeLetter(char): if char.isalpha(): char=chr(ord(char)+1) char=VowelChange(char) return char else: return char def VowelChange(char): if isVowel(char): char=char.upp...
while True: compras = float(input('Valor total das compras? ')) money = float(input('Valor Recebido: ')) troco = money - compras cinq = troco // 50 resto50 = troco - (cinq * 50) vint = resto50 // 20 resto20 = troco - ((cinq * 50)+(vint * 20)) dez = resto20 // 10 resto10 = tr...
# class_pupils = input('Введите имена учеников через запятую:\n') class_pupils = 'Полина ,Антон, Арсений , Евгений, Алексей, Тимур' correct_result = ['Полина', 'Антон', 'Арсений', 'Евгений', 'Алексей', 'Тимур'] # print('Ученики класса:', class_pupils) _result = class_pupils.split(',') result = [] for item in _result...
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() distance = 0x7fffffff result = 0 size = len(nums) for i in range(size - 2): start = i +...
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ self.solve(board) def solve(self, board): candidates = [str(x) for x in range(1,10)] for...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.maxium ...
# -*- coding: utf-8 -*- # Basic random, dictionary # Various loops # import namun masih pakai alias import numpy.random as nr import matplotlib.pyplot as mp # inisialisasi list 10 elemen data=[0]*30 print(data) # Generate random values print("Generate random values") for i in range(len(data)): data[i] = nr.randi...
l = [] n = int(input("enter the number of elements:")) for i in range(0,n): temp = input("enter the string:") l.append(temp) for i in range(0,len(l)): if len(l[i])==4: print(l[i])
from PIL import Image import PIL import Tkinter import sys #python grayscale.py nombredetuimagen.jpg imagen = sys.argv[1] def grayscale(image): newima=Image.open(image).convert('RGB') pix=newima.load() w,h = newima.size for i in range(w): for j in range(h): r,g,b = pix[i,j] newPixel = (r + g + b) / 3 ...
x = 0 y = 0 robot_name ='' command = '' direction = 0 single_arg_command = ['off','help','right','left'] multi_arg_command = ['forward','back','sprint'] def is_num(number): try: number = int(number) except: return False if int(number) == 0: return True elif int(number): ...
# Leon Luong 69139013 Lab sec. 9 import math def frac_to_point(frac_x: float, frac_y: float) -> 'Point': "Returns a point using fractional coordinates." return Point(frac_x, frac_y) def pixel_to_point(pixel_x: float, pixel_y: float, width: float, height: float) -> 'Point': "Returns a poi...
#!/usr/bin/env python tot = 0 with open('input') as file: for char in file.read(): if char == '(': tot += 1 elif char == ')': tot -= 1 print tot
#!/usr/bin/env python3 '''\ Python script to rename files or directories in a specified directory/folder ''' import os import re def print_error_message(message): '''Prints error message to the terminal/console message: Message to be printed ''' CRED = '\33[1m\33[31m' CEND = '\033[0m' print(...
from Queen import Queen import math import timeit # def testQueens(n, i): ###################################### # Deprecated Original Testing Method # ###################################### ################################################################################################################## ...
# Author: Manujinda Wathugala # Cracking the Coding Interview # Chapter 1 - Arrays and Strings # 1.3 - URLify # O(n) def URLify(str, str_len): # Count the number of spaces spaces = 0 for idx in range(str_len): if str[idx] == ' ': spaces += 1 last_idx = str_len + 2 * spaces - 1 ...
import requests from shapely.geometry import Point def geocode(q: str) -> Point: """ Geocodes an address from a query :param q: String containing an address to geocode :return: shapely Point object """ url = "https://loc.geopunt.be/v4/Location" params = { "q": q } res = req...
import tkinter as tk from datetime import datetime from .documentReader import Doc import os # class untuk menambahkan Catatan Baru / Membuat windows baru untuk membuat Noted baru class newNoted(): def Create(self,namaMhs,nimMhs,semester,matakuliah,prodi,kelas): # function untuk save buuton def Sa...
import random game_data = {1:'scissor', 2:'rock', 3: 'paper'} win_cnt = 0 #ㅇㅣ긴 횟수 while(win_cnt<2): print("input your number") user = int(input()) comp = random.randint(1,3) print(game_data[user],game_data[comp]) if user == 1: comp = comp % 3 if comp == 1: user = user % 3 ...
it = input().split() print(it) for i in it[0]: if it[0].index(i) != 0: print(":", end="") print(i, end="")
'''Basic Characters for splitting/removing in strings''' NEWLINE = '\n' TAB = '\t' CARRIAGE_RETURN = '\r' SPACE = ' ' EMPTY = '' '''Being Part #1''' ''' Takes in a string representation of a matrix like such: 5 9 2 8 9 4 7 3 3 8 6 5 and computes the checksum (different of the max and min of each row, summed together...
# Exercise 25: Even More Practice # 06/11/17 # This exercise is a little different, you're going to import it into python and # run the functions yourself. # This tokenizies the string you first create. def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return...
# Exercise 23: Read Some Code # 06/11/17 # The goal isn't to get you to understand code, but to teach you the following 3 skills. # 1 Finding Python source code for things you need. # 2 Reading through the code and looking for files. # 3 Trying to understand code you find. # Here's what you do: # 1 Go to bitbucket.or...
input_a = input("Please give age ") age = int(input_a) if age >= 18: print("You can vote for the failure") if age < 18: print('get outta hear let us mess up your future')
#define parent class Animal, containing a few methods hello(), sleep() and run() class Animal: def __init__(self, name, age): self.age=age self.name=name def hello(self): print("Hello! my name is "+ self.name+ ", age is "+self.age) def sleep(self): print(self.na...
import math class Area(): def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length*self.width class Square(Area): def __init__(self, side): self.side = side def square_area(self): return self.side**2 class ...
import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer #load data filename = "dickens_94_tale_of_two_cities.txt" file = open(filename, 'rt') text = file.read() file.close() ############################ # preprocessing #########################...
#Exercise 3.3 try: x = float(input("Enter a score between 0.0 and 1.0: ")) if x >= 0.0 and x <= 1.0: pass else: print("Error: Number must be a value between 0.0 and 1.0.") quit() except: print("Error: Must enter a number.") quit() if x >= 0.9: print('A') elif x >= 0.8: ...
#!/usr/bin/env python '''https://en.wikipedia.org/wiki/SKI_combinator_calculus via chapter 3 of hindley,seldin''' import re from typing import List atom = str term = List[atom] name = r'[a-z]+' assigned = r'[A-Z]' def ap(x: atom, y: atom) -> atom: return x + y def I(xs: term) -> term: fst = xs.pop(0) rst = ...
import sys number = [] for i in range(5): temp = input('Enter number between 1 and 30 : ') num = int(temp) if num < 1 or num > 30: print('You typed wrong range number!') sys.exit(-1) number.append(num) star = '*' for c in number: print(star * c)
def adjacentElementsProduct(inputArray): high = inputArray[0]*inputArray[1] for x in range(len(inputArray)-1): temp = inputArray[x]*inputArray[x+1] if (temp>high): high = temp return high
from itertools import combinations def crazyball(players, k): return list(combinations(sorted(players), k)) players = ["Ninja", "Warrior", "Trainee", "Newbie"] k = 3 print (crazyball(players,k)) # [["Newbie","Ninja","Trainee"], # ["Newbie","Ninja","Warrior"], # ["Newbie","Trainee","Warrior"],...
def longestWord(text): maior = "" tamanho = 0 text = removeSymbols(text) for x in text.split(" "): if (len(x) > tamanho): maior = x tamanho = len(maior) return maior def removeSymbols(text): for char in ",![]": text = text.replace(char, ...
with open("input.txt") as f: foods = f.read().split("\n") food_map = dict() all_ingredients = [] for food in foods: ingredients, allergens = food.split(" (contains ") allergens = allergens[:-1] allergens = allergens.split(", ") ingredients = ingredients.split(" ") for ingredient in ingredients...
with open("input.txt") as f: foods = f.read().split("\n") food_map = dict() all_ingredients = [] for food in foods: ingredients, allergens = food.split(" (contains ") allergens = allergens[:-1] allergens = allergens.split(", ") ingredients = ingredients.split(" ") for ingredient in ingredients...
import pandas as pd df = pd.read_csv('test_non_numeric.csv') cols = ['name', 'ticket', 'cabin'] df.info() df = df.drop(cols, axis=1) dummies = [] cols = ['pclass', 'sex', 'embarked'] for col in cols: dummies.append(pd.get_dummies(df[col])) titanic_dummies = pd.concat(dummies, axis=1) df = pd.concat((df,titanic_dum...
# Libraries used import random import time def quickSortRandomPivot(arr_list): quickSortHelperRandomPivot(arr_list,0,len(arr_list)-1) def quickSortHelperRandomPivot(arr_list,first,last): if first < last: splitpoint = partitionRandomPivot(arr_list,first,last) quickSortHelperRandomPivot(arr_list,first,spl...
#!/usr/bin/env/ python3 # -*- coding: utf-8 -*- for i in range(1, 41): if (i % 3 == 0) or ('3' in str(i)): i = '(' + str(i) + ')' print(i, end=' ') print()
'''Simple 1 deck Blackjack game with just hit/stand/double down. no Splitting or Insurance. Features: . Dynamic hand values (aces can be either 1 or 11) . Actual deck tracking, meaning the deck does not shuffle between hands and the cards dealt are removed from it. Deck will shuffle when there are no more cards...
#Ryan Kaplan import random, Villager as v class Town: # Initializes the town def __init__(self, name): self.day_count = 1 self.name = name self.villagers = self.init_villagers() self.chickens = 0 self.roosters = 0 self.wood = 300 self.st...
import pandas as pd import numpy as np # Set up perceptron algorithm to model randomised target functions. track performance in the form of the number of # iterations for the model to converge on the target function, and the likelihood of mis-classifying a random point in # the target space. # Specify desired trainin...
#!python3 from Restriccion import Restriccion from Aleatorio import Aleatorio class Poblador: ceros = [] restricciones = [] #Lista de restricciones aleatorios = [] #Lista de aleatorios zExpresion = "" #Expresion algebraica de la funcion objetivo constantes = [] #Lista de constantes z = 0.0 #Valor de Z def __in...
# -*- coding: utf-8 -*- """ Created on Sun Aug 22 16:37:28 2021 @author: Natasha Camargo """ def fibonacci(n): if n < 0: return "It's Negative" if n == 1: return 1 if n == 0: return 0 if n >=2: return fibonacci(n-1) + fibonacci(n-2)
from fractions import Fraction TOLERANCE=1e-8 class puiseux(object): """ Class to represent (truncated) Puiseux series. """ def __init__(self,poly,checkReduced=False): """ 2x^(2/3)-3x^(4/7) would be input as [[2,(2,3)],[-3,(1,7)]] and represented internally as {Fraction(1...
from sympy import poly,pprint from sympy.abc import x,y from puiseuxPoly import puiseux from mypoly import mypoly from expandParallel import solutionList from fractions import Fraction as fr import sys """ A convenience class that uses Sympy to allow easier command line input. Asks user for a polynomial and for the num...
#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2020/4/12 21:00 #@Author: Kevin.Liu #@File : linearRegression.py from sklearn.linear_model import LinearRegression from sklearn import datasets from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import numpy as np X = np.linspac...
#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2020/4/17 10:31 #@Author: Kevin.Liu #@File : mian_numpy_vector.py import numpy as np if __name__ == '__main__': print(np.__version__) # np.array 基础 list = [1, 2, 3] list[0] = 'Linear Algebra' print(list) vec = np.array([...
import sys def is_integer(nb): try: int(nb) return True except: return False def printbits(base_10): compare = 2 ** 31 k = [] while compare > 0: if base_10 & compare: k.append('1') elif compare <= base_10: k.append('0') compare >>= 1 print(''.join(k)) def scrub_input(argv): if len(argv) > 2:...
#insertion sort algorithm ''' Application -- small array/list -- algorithm sorts elements in place Time Complexity: O(n*2) Auxiliary Space: O(1) ''' def sort(listinput): ''' Sorting logic: insert the element in proper position i loop from 1st element to last of List pointer j traversed from i-1...
# def my_first_function(): # print "mona" # def my_first_function(name): # print "Hello {}!".format(name) # print "Your name?" # name = raw_input() # my_first_function(name) # print range (10) # print range (2,11) # print range (2,11,2) def sum(): num1=1 num2=2 total=num1+num2 prin...
#print (''.join([i.lower() if i.isupper() else i.upper() for i in input()])) def swap_case(s): for i in s: if (i>='A' and i<='Z'): print(i.lower(),end="") if (i>='a' and i<='z'): print(i.upper(),end="") else: print(i,end="") return if __name__ == ...
def sum (): a = int(input("Enter: ")) b = int(input("Enter: ")) c = a+b print(c)
class Node(object): def __init__(self, val): self.val = val self.next = None def get(self): return self.val def get_next(self): return self.next def set_next(self, val): self.next = val class LinkedList(object): def __init__(self, head=No...
# Caeser Cipher Encryptor from string import ascii_lowercase as alphabet test = "xyz" #1 Make Cipher Dict #2 Loop over letters #2.1 lookup position in cipher #2.2 get letter from ascii_lowercase string #build string and return def caeserCipherEncryptor(string, key): keys = [(idx + key) % 26 for idx i...
from player import Player import random class Ai(Player): def __init__(self, name): super().__init__() self.name = name self.miss = 0 self.hit = 0 self.row = 0 self.column = 0 self.choice = 0 self.choice_list = [1,2,3,4,5] def place_ships(self): ...
# -*- coding: utf-8 -*- """ Created on Tue May 15 12:29:20 2018 @author: JITESH """ d=input() def fix_teen(y): if y>=13 and y<=19 and y is not 15 and 16: y=0 return y else: return y x=map(fix_teen,d.values()) print d def sum(a,b): return a+b print "Sum=",reduce(sum,x)
ch=input() if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): print("Vowel") elif ((ch>='a') and (ch<='z')): print("Consonant") else : print("invalid")
import board import digitalio import time print('running stepper') #connect LED light led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT # Connect step and direction pins step_pin = digitalio.DigitalInOut(board.D27) step_pin.direction = digitalio.Direction.OUTPUT dir_pin = digitalio.Di...
print [x for x in range(2, 100) if not x % 2] print range(2, 100, 2) #prints even number 2 to 100
import csv column = [] with open('hotels.csv', 'rt') as f: reader = csv.DictReader(f) for row in reader: column.append(row) # print(column) print('What is the state:') state = input() print('Cost or Rating:') column_for_operation = input() print('Operation:') operation = input() data_having_state...
# Guide to the sorted Function in Python # using sorted() method #sorted() allows u to store that new value in a new variable that stores that list and keeps original list stored sale_prices = [ 100, 83, 220, 40, 100, 400, 10, 1, 3 ] sorted_list = sorted(sale_prices, reverse=Tru...
# Guide to Slices in Python Tuples post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published') print(post[:2]) # returns => tuple ('Python basics', 'Intro to guide to py') -> grab first 2 elements print(post[1::2]) # => starts at second element and skips 'some cool content' and returns...