text
stringlengths
37
1.41M
#development release def is_prime(number): ''' Check whether the input number is a prime number using Fermat's Little Theorem Please advise... ''' success = 0 for i in range(1,number): print((i^(number-1)) % number) if (((i^(number-1)) % number) == 1): success += 1 #return chance if number is prime ...
import random import turtle wordList = ['python','programming','university','computer','ganis'] word = list(wordList[random.randint(0,len(wordList) - 1)]) displayWord = list('-' * len(word)) guesses = 6 count = 0 answers = 0 lettersUsed = [] wordFound = False def initialize(): turtle.left(180) turtle.forwar...
n = int(input('Ingrese un numero entre 1 y 12: ')) if n >0 and n<13: for x in range(1,13): print(f'{n} X {x}: {n*x}') else: print(f'Numero fuera de rango\n{n} no esta entre 1 y 12')
class Node: def __init__(self,data): self.left=None self.right=None self.data=data def inorder(temp): if (not temp): return inorder(temp.left) print(temp.key,end = " ") inorder(temp.right) def insert(temp, key): if not temp: root= Node(key) return queue=[] queue.append(temp) ...
# -*- coding: utf-8 -*- """ Created on Fri May 29 10:10:52 2020 @author: tanck """ for ix in range(10): square = ix**2 print(f"Square of {ix:2} is {square:2}") print("All done and out of the loop; ix is ",ix)
def initMatrix(height, width, initValue): """Initialized a matrix of given size with given values""" field = [] for y in xrange(height): field.append([]) for x in xrange(width): field[y].append(initValue) return field def redrawField(field): """Dumps the current game field state as psaudographics to the con...
for rabbit in range(1+35): for chicken in range(1+35): if rabbit + chicken == 35 and rabbit*4+chicken*2==94: print 'Chicken:%s,Rabbit:%s' %(chicken,rabbit)
# -*- coding: utf-8 -*- from __future__ import unicode_literals def HouseGuest(Goal): i = 0 house = [] Goal = int(Goal) while i < Goal: print "welcome to our house guest: Mr.%r" % (i) house.append(i) print "Now the house have people :", for x in house: print "Mr.%s"%(x), if len(house)-1 == ...
from collections import deque import time from generate_maze import mazeGenerate maxFringe=0 nodesNum=0 pts=[] def matrix2graph(matrix): # printMap(matrix) height = len(matrix) width = len(matrix[0]) if height else 0 graph = {(i, j): [] for j in range(width) for i in range(height) if matrix[i][j] == 1...
import math def load_input(): with open("input6.txt") as f: return f.readlines() lines = load_input() def parse(line): idx = line.index(")") parent = line[:idx] child = line[idx + 1:].strip() return (parent, child) to_parent = dict() nodes = set() for line in lines: pair = parse(line) to_parent[p...
import random max_num = int(input("Welcome to guess the number.\nPlease enter the maximum number I can think of:")) secret_number = random.randint(1, max_num) guess_count = 0 error_count = 0 correct_guess = 0 print("I've thought of a number between 1 and {}".format(max_num)) # print(secret_number) def guess_calc(s...
# With a given integral number n, write a program to generate a dictionary # that contains (i, i*i) such that is an integral number between 1 and n # (both included). and then the program should print the dictionary. # Suppose the following input is supplied to the program: 8 # Then, the output should be: {1: 1, 2: 4,...
import pygame from Collider import Collider from Resources import colors class Box(Collider): def __init__(self, x_pos, y_pos, width, height, fill_color=colors.BLACK, border_color=colors.BLACK, border_thickness=0): self._x_pos = x_pos self._y_pos = y_pos self._width = width self._...
class MiniMax: """ class containing implementation of MiniMax Alogrithm """ def optimal_move(self, board): """ returns the optimal move for the computer Args: board (List): 3*3 2D matrix storing selected coordinate for x or o Returns: List: coor...
# -*- coding: utf-8 -*- """ Created on Thu Aug 11 18:51:10 2016 @author: Alexander """ """This program takes in a binary number as a string and returns the equivalent quartenary and its location in the unit square""" import turtle import random def spacefillingfunction(L): M = (int(max(L))) #guess ...
#8. Write a function, is_prime, that takes an integer and returns True # If the number is prime and False if the number is not prime. def is_prime(num): for numbers in range(2,num-1): if num%(numbers)==0: return False else: return True print(is_prime(11))
#1.Create a variable, paragraph, that has the following content: # "Python is a great language!", said Fred. "I don't ever rememberhaving this much fun before." class Pytalk: def __init__(self,name): self.name=name def python_talk(self): print(''' "Python is a great language!", said {}."I...
import csv as csv import numpy as np csv_file_object = csv.reader(open('test.csv', 'rb')) #Load in the csv file header = csv_file_object.next() #Skip the fist line as it is a header data=[] #Creat a variable called 'data' for row in csv_file_object: #Skip through each row in the csv file data.append(row) #adding...
str0 = '((((((((((((((2, 3)))))))))))))' str1 = '((((((((((((((2, 3)))))))))))})' str2 = '(([{(((((((((((2, 3)))))))))))))' str3 = '{(((((((((((((2, 3))))))))))))}' def bal(my_string): chars = ["{","}","[","]"] lst = list(my_string) lst = filter(lambda x: x not in chars, lst) counter_brackets_one = ...
print ("How old are you?"), age = input() print ("How tall are you?"), height = input() print ("How much do you weigh?"), weight = input() print ("So, you're '{0}' old, '{1}' tall and '{2}' heavy.".format(age, height, weight))
# Using Google text-to-speech(gtts) from gtts import gTTS import os # en=english language myobj = gTTS(text=input("Enter Text for Text to Speech : "), lang='en') # saving the speech as a mp3 file. myobj.save("name.mp3") os.system("mgp321 name.mp3")
class Node(): def __init__(self, value): self.value = value self.next = None self.prev = None class LinkedList(): def __init__(self): self.head = None self.tail = None self.length = 0 def get_size(self): return self.length def is_empty(self): if self.g...
z=[2,1,4,3,7] x=9 def sum(): for i in range(0,len(z)): for j in range(0,len(z)): if z[i]+z[j]==x: print(i,j) sum()
import os import random import time class TicTacToe: def __init__(self): self.new_game = True self.turn = 'X' self.theBoard = {'1': ' ','2': ' ','3': ' ','4': ' ','5': ' ','6': ' ','7': ' ','8': ' ','9': ' '} self.players = [] self.game_over = False def play_again(self)...
import time #Imports a module to add a pause #Figuring out how users might respond answer_A = ["A", "a"] answer_B = ["B", "b"] answer_C = ["C", "c"] yes = ["Y", "y", "yes"] no = ["N", "n", "no"] #Grabbing objects sword = 0 flower = 0 required = ("\nUse only A, B, or C\n") #Cutting down on duplication ...
string= input("sisestage string. ") string.strip() a = len(string) b = float(len(string) / 2) if a>= 7 and (a%2) !=0: print (string[int(b-1.5):int(b+1.5)]) print("true") else: print("false")
def is_majority(items: list) -> bool: t,f=0,0 for n in items: if n: t+=1 else: f+=1 return t>f if __name__ == '__main__': print("Example:") print(is_majority([True, True, False, True, False])) # These "asserts" are used for self-checking and not for an auto-testing...
import math #FUNCION def binario(x): temp = x A= [] B=[] modulo = 0 cociente = 0 while x != 0: # mientras el número de entrada sea diferente de cero # paso 1: dividimos entre 2 modulo = x % 2 cociente = x // 2 A.append(modulo) # guardamos el módulo calculado ...
from player import Player; class Team: def __init__(self, number_of_players, name): self.number_of_players = number_of_players; self.name = name; self.players = []; def addPlayer(self, name): if(len(self.players) < self.number_of_players): self.players.append(Play...
string = "ThIsisCoNfUsInG" substring = 'is' count = 0 for i in range (0, len(string)): temp = string[i:i+len(substring)] if temp == substring: count += 1 print(count)
#!/usr/bin/env python import sys def perror(s): sys.stderr.write(s+'\n') def label(i): if i==0: return 'inicio' else: return 'A'+str(i-1) cities=['Gary', 'Fort_Wayne', 'Evansville', 'Terre_Haute', 'South_Bend'] def label_city(i): return cities[i] class Graph: def __init__(self, V): self.V = ...
# CMSC389O Spring 2020 # HW3: Searching & Sorting -- Implement Natural Logarithm # Description: # Implement the ln() function, but don't use the library log functions or integration functions. # Other library functions are fine # Solutions should be within 1e-6 of the actual value (i.e. |student_ln(x) - ln(x)| < 1e-6)...
import webbrowser import ssl from webbrowser import Chrome count = 0 url = input("enter your desired url: ") tries = 3 while True: times = input("How many times would you like to open the url: ") try: times = int(times) break except ValueError: print("You didnt enter a number you...
t = float(input('Digite a temperatura em graus célcius: ')) f = 9 * (t / 5) + 32 print('{}ºC são {}ºF'.format(t, f))
#Faça um programa que leia um número inteiro e mostre na tela #seu sucessor e seu antecessor #====================================================== n = int(input('Digite um número: ')) print('O numéro escolhido é {} e seu sucessor é {} e seu antecessor é {}'.format(n,n-1,n+1))
#Crie um programa que leia um número real qualquer e mostre sua parte inteira. from math import trunc n = float(input('Digite um número com virgula para que o programa mostre sua parte inteira: ')) print('A parte inteira do número é {}'.format(trunc(n)))
"""Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com SANTO""" nome = input('Digite o nome de sua cidade: ').strip() print('Sua cidade começa com o nome Santo? ') pnome = nome.split() print('Santo' in pnome[0])
def main(): positionsRed = [ ['','','','','','',''], ['','','','','','',''], ['red','','','','','',''], ['','red','','','','',''], ['','','red','','','',''], ['','','','red','','','']] positionsBlue = [ ['','','','','','blue',''], ['','','','','blu...
import sys def up_from_leaf_to_root_with_calculating_childs_num(arr, num): abs_num = abs(num) parent = arr[abs_num][0] if parent == 0: # 루트 노드 return my_child_num = arr[abs_num][3]+arr[abs_num][4]+1 if parent < 0: # 부모 노드가 오른쪽에 있을 때 arr[abs(parent)][3] = my_child_num else: ...
class Node: """ A node that consists of a trie. """ def __init__(self, key, count=0, data=None): self.key = key self.count = count self.children = {} class Trie: def __init__(self): self.head = Node(None) """ 트라이에 문자열을 삽입합니다. """ def insert(...
from math import log2 n = int(input()) k = int(log2(n / 3)) stage = [[' '] * n * 2 for _ in range(n)] def change_for_star(y, x): stage[y-2][x+2] = '*' stage[y-1][x+1] = stage[y-1][x+3] = '*' stage[y][x] = stage[y][x+1] = stage[y][x+2] = stage[y][x+3] = stage[y][x+4] = '*' def tri(y, x, count): if cou...
class Node: def __init__(self, item): self.item = item self.count = 0 self.next = [] def insert(node, ch): if not node.next: node.next.append(Node(ch)) for i in node.next: if i.item == ch: return i node.next.append(Node(ch)) return node.next[-1] ...
class Account(): _money = 0 def deposit(self, value): convertido = 0 try: convertido = float(value) except: raise ValueError("Valor deve ser numerico") if (convertido < 0 ): raise ValueError("Valor deve ser positivo") self....
#!/usr/bin/python3 # encoding: utf-8 ''' FileSort -- Sorts files based on their EXIF data or file date. FileSort is a Python program to sort files based on their EXIF or file date. It defines classes_and_methods @author: Alexander Hanl (Aalmann) @copyright: 2018. All rights reserved. @license: MIT @deffie...
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def main(x,y): # Use try except to catch specific error instead of the system printing # out whole list of tracebacks try: x = int(x) y = int(y) z = x/y except ValueError: print("I caught a ValueError") ...
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ s = 'This is a long string with a bunch of words in it.' print(s) # split a string l = s.split() print(l) # split by a specific character print(s.split("i")) # join a list into string s2 = ":".join(l) print(s2)
#!/usr/bin/python # -*- coding: utf-8 -*- ''' true_subset_zero.py Implementing the true subset puzzle. @author: Luis Martin Gil @contact: martingil.luis@gmail.com @website: www.luismartingil.com @github: https://github.com/luismartingil ''' import unittest MIN_RANGE = -65000 MAX_RANGE = 65000 class itemNotRange(E...
#Accepting the string s=input("Enter the word ") #Using dict.get() r={} for keys in s: r[keys]=r.get(keys,0)+1 #printing the result print("No. of characters in "+s+" is : \n"+str(r))
def longest_seq(nums): numSet = set(nums) res = 0 for n in nums: if n+1 in numSet: currLen = 0 while n+currLen in numSet: currLen += 1 res = max(res, currLen) return res print(longest_seq([100,4,200,2,3,1]))
#!/usr/bin/python """ Demonstration of Graph functionality. """ from sys import argv from graph import Graph, Node def main(): graph = Graph() # Instantiate your graph graph.add_vertex(1) graph.add_vertex(2) graph.add_vertex(3) graph.add_vertex(4) graph.add_vertex(5) graph.add_vertex(6...
#find a 3x3 non singular matrix import numpy as np # initialize array A and Identity matrix B= np.array([[2, 0, -1],[0, 2, -1],[-1, 0, 1]]) I= np.identity(3) A= 3*I - B print(A)
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ # Note: try to reduce running time for some extreme cases (long input) class Solution(object): """ solution that are not optimized def twoSum(self, numbers, target): if (len(numbers) < 2): return None for ...
import math def quadratic(a,b,c): if not isinstance(a and b and c,(int,float)): raise TypeError('bad operand type') drt=b*b-4*a*c if drt<0: print("该方程无解") return None,None else: x=(-b+math.sqrt(b*b-4*a*c))/2*a y=(-b-math.sqrt(b*b-4*a*c))/2*a return x,y x1,x2=quadratic (2,2,2) print(x1,x2) def produc...
class Student(): name = "dana" age = 18 def say(self): self.name = "aaaa" self.age = 200 print("My name is {0}".format(self.name)) print("My age is {0}".format(self.age)) def sayAgain(s): print("My name is {0}".format(s.name)) print("My age is {0}".format(s.age)) yueyue = Student() yueyue.say() yueyue...
# -*- coding: utf-8 -*- ''' Created on 2019年9月4日 @author: Administrator ''' from tkinter import * import math class MainPage(object): def __init__(self, master=None): self.root = master #定义内部变量root self.root.geometry('%dx%d' % (300, 250)) #设置窗口大小 self.year = IntVar() self.date =...
#!/usr/bin/env python from __future__ import print_function import random import sys import os def addnos(fnum, lnum): """ function to add 2 numbers together """ sumnos = fnum + lnum return(sumnos) def main(args): help(addnos) #print("add 2 nos together-->", addnos(5,7)) stringnos = a...
#!/usr/bin/env python import numpy as np import sys def read_unstructured_data(): """ Read unstructured data, ie. mixed data types """ # # Assign the filename: file # filename = "C:\\Users\mdjuk\\repos\\q_python_scripts\\titanic.csv" data = np.genfromtxt(filename, delimiter=',', names...
#!/bin/env python ''' from __future__ import print_function from datetime import datetime import os import sys import types def main(args): pass if __name__ == '__main__': print ('Start of XXXX.py at.....', format(str(datetime.now()))) main(sys.argv[1:]) print ('End of XXXX.py at.....', format(str(datetime.n...
#!/usr/bin/env python from __future__ import print_function import random import sys import os class Bird: """ A base class to define bird properties """ count = 0 def __init__(self, chat): self.sound = chat Bird.count += 1 def talk(self): return(self.sound) ...
from __future__ import print_function # need this to allow print function to work with () from datetime import datetime import os import sys import types def main(args): A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) A1 = range(10) A2 = sorted([i for i in A1 if i in A0]) A3 = sorted([A0[s] for s in A0]) A4 =...
#!/usr/bin/env python from __future__ import print_function import os, sys def dataline (): """ this will load data as expected """ emp_str_1 = '"1","0","3","male","22.0","1","0","A/5 21171","7.25","","S"' (PassengerId,Survived,Pclass,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked) = emp_str_1.sp...
''' Obtaining user input.....Page 20-21 the line below was initially 6 lines, and then selecting all lines, then Ctrl+Shift+L, Del at end of first line will automatically join all of the lines together days = ["1","2","3","4","5","6"] ''' import sys def main(args): try: print('Start of input.py.....\n') user...
#!/bin/env python from __future__ import print_function import sys ''' sys.argv is a list of arguments. So when you execute your script without any arguments this list which you're accessing index 1 of is empty and accessing an index of an empty list will raise an IndexError. With your second block of code you're ...
''' Obtaining user input.....Page 20-21 the line below was initially 6 lines, and then selecting all lines, then Ctrl+Shift+L, Del at end of first line will automatically join all of the lines together days = ["1","2","3","4","5","6"] ----------------------------------------------------------------------------------...
import sys ''' CTRL-S to save the file CTRL-B to build the file, ie to run it ''' def main(args): print("Start of script") # define 2 varables a = 8 b = 2 # display th result of adding the variable values print 'Addition\t', a, "+", b, "=", a + b # display the result of subtraction th variable values pr...
# python -m unittest anagrams_test.py import unittest from assignment2 import Node, BinaryTree, Solution class TestSolution(unittest.TestCase): def setUp(self): # replace this with function construct_binary_tree_from_list self.binary_tree1 = Node(1) self.binary_tree1.left = Node(2) ...
print "Hello" peremen1=0 peremen2=0 spisok1 = [] def spisok(): while len(spisok1) in range(15): s=input("Enter number ") spisok1.append(s) return spisok1 spisok() while peremen2 == 0: if spisok1[peremen1] == 0: print " Index is " , spisok1.index(spisok1[peremen1]) peremen2=1 ...
print "Hello" spisok1 = [] peremen1=0 def spisok(): while len(spisok1) in range(15): s=input("Enter number ") spisok1.append(s) return spisok1 spisok() minimum=spisok1[0] while peremen1 != 15: if minimum > spisok1[peremen1]: minimum=peremen1 peremen1=peremen1+1 elif minim...
class Fib(object): def __init__(self): self.prev=0 self.curr=1 def __next__(self): value = self.curr self.curr+=self.prev self.prev=value yield value def func(n): for i in range(n): yield i**2 print(func(5))
r= input("doner le rayon de cercle") m=int(r) surf = 3.14 * (m**2) perim = 3.14 * 2 *m print("la surface du cercle est :",surf ,"et le perimetre est :",perim)
#exo11calcul a=input("veuillez saisir la valeur de a") a=int(a) op=input("taper 1 pour l'addition , 2 pour la soustraction , 3 pour la multiplication et 4 pour la division " ) op=int(op) b=input("veuillez saisir la valeut de b") b=int(b) if (op ==1): print (a+b) if (op ==2): print(a-b) if (op==3): print(a*b)...
#exo25suitenom for i in range (1,11): print(i*[i]) #-----commmit------- a=int(input("veuillez saisir un entier a")) div = a//2 if (a == 2 or a==3): print (a, "est un nombre premier") div = 0 for i in range (4 , div+1): div = div + a % i if (div != 0): print(a , " est pas premier") if (div...
# NLP Program to identify dollar amount in the txt file, it will output the dollar amount included in the txt file # @Author: Yulong He 2020.02.07 # Possible format for identification: # $500 million/billion/trillion # $6.57 # 1 dollar and 7 cents # 5 cent/cents # one/two/three hundred/hundreds/million/billion... dolla...
import re, math class Sci: split = 'e' sci_format = r'([+-]*\d+\.\d+)e([+-]*\d+)' __num = 0.0 __exp = 0 def __init__(self, sci, int_size=1, float_size=3): if isinstance(sci, int) or isinstance(sci, float): if sci == math.inf: # If incoming Int or Float is too large ...
password = input("Enter a new password: ") result = [] if len(password) > 8: result.append(True) else: result.append(False) digit = False for i in password: if i.isdigit(): digit = True result.append(digit) uppercase = False for i in password: if i.isupper(): uppercase = True resu...
from modules.parsers import parse, convert feet_inches = input("Enter feet and inches: ") parsed_feet = parse(feet_inches)['feet'] parsed_inches = parse(feet_inches)['inches'] result = convert(parsed_feet, parsed_inches) if result < 1: print("Kid is too small.") else: print("Kid can use the slide.")
import csv with open("../files/weather.csv", 'r') as file: data = list(csv.reader(file)) city = input("Enter a city: ") for row in data: if row[0] == city: print(f"Temparature of {row[0]} is {row[1]}")
password = input("Enter a new password: ") result = {} # define a dictionary if len(password) > 8: result["length"] = True # equivalent of result.append(True) for lists else: result["length"] = False digit = False for i in password: if i.isdigit(): digit = True result["digits"] = digit ...
password_prompt = "Enter password: " password = input(password_prompt) while password != "pass123": print("Incorrect password!") password = input(password_prompt) print("Password is correct!")
def parse(feet_inches): parts = feet_inches.split(" ") feet = float(parts[0]) inches = float(parts[1]) return {"feet": feet, "inches": inches} def convert(feet, inches): meters = feet * 0.3048 + inches * 0.0254 return meters feet_inches = input("Enter feet and inches: ") parsed_feet = parse...
import json """ json.load(f): Load JSON data from file (or file-like object) json.loads(s): Load JSON data from a string json.dump(j, f): Write JSON object to a file (or file-like object) json.dumps(j): Output JSON object as string """ # json_file = open("./test.json", "r") # movie = json.load(json_...
vowel = ['A','E','I','O','U','a','e','i','o','u'] isVowel = input("Enter a character between a and z (or A and Z):") if isVowel in vowel: print(isVowel,'is a vowel: True') else: print(isVowel,'is a vowel: False')
inStock = [[],[],[],[],[],[],[],[],[],[]] gamma = [11,13,15,17] delta = [3,5,2,6,10,9,7,11,1,8] from copy import deepcopy def setZero(): alpha = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] beta = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] print('Alpha after initialization:\n',alpha) return (alpha,beta) al...
import argparse parser = argparse.ArgumentParser(description='Please input the company name') parser.add_argument('--company', help='give the company name for permutation') args = parser.parse_args() company_name = args.company def read_subdomain_list(): lines = [] with open("subdomains-top1mil-110000.txt", "...
def merge(arr, l, m, r): n1 = m - l + 1 n2 = r - m # create temp arrays L = [0] * n1 R = [0] * n2 # Copy data to temp arrays L[] and R[] for i in range(n1): L[i] = arr[l + i] for j in range(n2): R[j] = arr[m + 1 + j] # Merge the temp arrays bac...
from collections import namedtuple Car = namedtuple('Car', ['miles', 'color']) car1 = Car(miles=100, color='red') print(car1) car1.miles = 200 # can't set attribute
from collections import deque class MyQueue(object): def __init__(self): self.nodes = deque() # self.head = None def peek(self): # print the head data print(self.nodes[0]) def pop(self): self.nodes.popleft() def put(self, value): if value: ...
"""Snake, classic arcade game with different modifications Sebastin Joya Maximiliano Carrasco Gabriel Dichi 30/10/2020 """ import random from turtle import * from random import randrange from freegames import square, vector speed=int(input('Please Write a number from 0 to 100 to chosee speed (while closer to the num...
# Find the first 10 digits of the sum of the following 100 50-digit numbers: # (see numbers here: https://projecteuler.net/problem=13) # Answer: 5537376230 # Answer (the finalSum): 5537376230390876637302048746832985971773659831892672 # Here I wanted to build something robust - the site gives us uniformity but here we...
def solution(enter, leave): answer = [] room = [] answer = [0] * (len(enter)+1) i=0 while leave: if leave[0] in room: room.remove(leave[0]) leave.pop(0) # print("if") else: # print("else") for j in room: ...
''' Run the application.Then open a browser and type in the URL http://127.0.0.1:5000/ , you will receive the string HELLO as a response, this confirms that your application is successfully running. The website will also display your HELLO [your name] when you type it in URL(http://127.0.0.1:5000/name) ''' from flask...
#!/usr/bin/python3 '''Reddit query using recursion''' import requests def recurse(subreddit, hot_list=[], after=''): ''' Queries the Reddit API and returns a list containing the titles of all hot articles for a given subreddit. If no results are found for the given subreddit, the function returns None...
from Player import * import random class Board(): def __init__(self,player1,player2,initsit=None): if initsit==None: self.players=[player1,player2] p1Building=[[Building(1,player1),4],[Building(2,player1),3],[Building(3,player1),2],[Building(4,player1),1]] p2Building=[[Building(1,player2),4],[Building(2,pl...
driving = input ('請問你有沒有開過車?') if driving != '有' and driving != '沒有': print('只能輸入 有/沒有 ') raise SystemExit age = int(input('請問你的年齡?')) if driving == '有': if age >= 18: print('你通過測驗了') else: print('奇怪,你怎麼會開過車') elif driving == '沒有': if age >= 18: print('你可以考駕照了') else: print('再幾年就可以去考了')
#create dummy variables, these are helper functions import pandas as pd def cleanGender(x): """ This is a helper funciton that will help cleanup the gender variable. """ if x in ['female', 'mostly_female']: return 'female' if x in ['male', 'mostly_male']: return 'male' if x in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # PC## - Graffiti # Howard, Bandoni # 1/24/20 # # This code draws Graffiti Spelling HI #========================== # -*- coding: utf-8 -*- from turtle import * #fetches turtle commands money = Screen() #create one canvas for all of your turtles. money.screensize(400,6...
while(True): my_string = raw_input("Enter string to remove dups(Blank to terminate): ") if (my_string == ""): break;
# contains the sorting algorithms for the playlist searches # 50 most popular def get_fifty(d): songs = sorted(d, key=d.get) top_songs = [] i = 0 # add length methods for dictionaries shorter than 50 while(i < 50): top_songs.append(songs[i]) i += 1 return top_songs
""" Alexander Hay HW2 - Machine Learning Learning aim: Motion model Learning algorithm: Neural Network Dataset: DS1 + Training Data: (t, v, w) - odometry (x, y, theta) - groundtruth + Test Data: (t, v, w) - odometry Part A 1. build training set 2. code learning algorithm """ import numpy as np...
""" Alexander Hay A* Algorithm Part A: 1. Build grid cell of 1x1m, ranges x:[-2,5], y:[-6,6]. * Mark cells with landmarks 2. Implement A* Algorithm 3. Use algorithm to plan paths between the following sets of start/goal positions: A: S=[0.5,-1.5], G=[0.5,1.5] B: S=[4.5,3.5], G=[4.5-,1.5] C: S=[-0.5...