text
stringlengths
37
1.41M
import pygame import math import random from helper_code import scale class Pong: GAME_WIDTH = 500 GAME_HEIGHT = 500 FPS = 120 PLAYER_WIDTH = 10 PLAYER_HEIGHT = 40 PLAYER_VEL = 4 MAX_BOUNCE_ANGLE = 1 # ~60 degrees BALL_SIZE = 10 BALL_SPEED = 3 def __init__(self, win): ...
import pygame from space_invaders.projectile import Projectile # from living_entity import LivingEntity class Player: WIDTH = 30 HEIGHT = 30 VELOCITY = 3 LIVES = 3 COLOR = (63, 68, 16) DELAY_BETWEEN_SHOTS = 40 PROJ_VELOCITY = 4 def __init__(self, pos_x, pos_y): """ Players are...
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): #n 횟수 s 배열 height = 0 heightrecord = [] valleycount = 0 for i in range(len(s)): if s[i] == "U": height += 1 else: he...
import itertools import random #set up the deck def getDeck(): deck=list(itertools.product(range(3),range(3),range(3),range(3),[False])); idx=['col','shape','fill','num','dealt']; deck=[dict(zip(idx,x)) for x in deck]; return deck def deal(deck): not_dealt=[x for x in range(len(deck)) if not(deck[x]['dealt'])];...
"""Vanessa wants: to be more adventurous by going to more activities about Music,festivals, art, animals, food, languages, sunsets, photography """ import json import urllib2 def take_in_keyword(): # takes in user's interest via raw_input # return string pass def take_in_date_user_wants_to_go_out(): ...
class MovieInfo(object): def __init__(self, director, release_year, title, actor_1, actor_2, location): self.director= director self.release_year = release_year self.title = title self.actor_1 = actor_1 self.actor_2 = actor_2 self.location = location
print "Welcome to the survey!" name = raw_input("What is your name? ") color = raw_input("What is your favorite color? ") hobby = raw_input("What is your favorite hobby? ") movie = raw_input("What is your favorite movie? ") pets = raw_input("Do you prefer dogs or cats? ") siblings = raw_input("How many siblings do you ...
from json_class import JsonClass from dungeonsheets.item import Item class Shield(Item): """A shield that can be worn on one hand.""" id = "" name = "Shield" cost = "10 gp" base_armor_class = 2 type = "shield" json_attributes = Item.json_attributes + ( "base_armor_class", ) ...
'''age = 10 if age >= 18: print("可以去看电影了!") else: print("还未成年") ''' i = 0 while i < 3: score = int(input("请输入本次考试分数:")) if score <= 100 and score >90: print("优秀") elif score <= 90 and score > 80: print("良好") elif score <= 80 and score >=60: print("及格") ...
''' 登陆系统: 业务: 输入用户名和密码 从db.txt文件中匹配是否存在该用户以及 密码是否正确,若正确则登陆成功! 否则弹出友好提示信息!(用户名或密码错误!) ''' #1.将所有数据行提取,存储到字典里(字典:缓冲区,便于快速的修改) db = {} #开始读取db.txt文件 f = open("db.txt","r+",encoding="utf-8") data = f.readlines() #["张三:zhangsan","李思:lisi"] for i in data: line = i.spl...
''' 方法:函数 好处:一本万利,一次书写,处处使用。 def 【方法名】(参数列表): 方法体 [return] 方法名: 多个单词组成,第二个单词开始,首字母就要大写。 totalStudentNumber : 驼峰式命名法 参数列表: 1.单值传输 2.*args:元组:能不定数量的接受参数 3.**kwargs:字典 4.注意:3个参数列表的位置是禁止调换的。 ''' #就用方法来打印1-100以内的数据,(方法的递归调用) '''i = 1 def ...
#计算机 '''class Calculator: def __init__(self,a,b): self.a = a self.b = b def add(self): # 两数相加 return self.a + self.b def sub(self): # 两数相减 return self.a - self.b def mul(self): # 两数相乘 return self.a * self.b def dev(self): # 两数相除 r...
def find_person(dict_users, strU): if strU in dict_users: return dict_users[strU] else: return 'Not Found' if __name__ == "__main__": names = ['xiaoyun','xiaohong','xiaoteng','xiaoyi','xiaoyang'] QQ = ['88888','5555555','11111','12341234','1212121'] dict_users = dict(zip(names, Q...
#game_class_version.py import random print("Rock, Paper, Scissors, Shoot!") # CAPTURE INPUTS user_choice = input("Please choose one of the following options: 'rock', 'paper', or 'scissors': ") print("-----------") print("USER CHOICE: ",user_choice) # VALIDATE INPUTS options = ["rock", "paper", "scissors"] if us...
Total_amount = float(input("Enter total amount")) tip_percantage_amount = float(input("Enter the tip percentage amount")) tip_amount= (tip_percantage_amount/100) * Total_amount print(tip_amount)
TEXT = 'We choose to go to the Moon. We choose to go to the Moon in this decade and do the other things. Not because they are easy, but because they are hard. Because that goal will serve to organize and measure the best of our energies and skills. Because that challenge is one that we are willing to accept. One we are...
print''' ''' # defines the function name and its arguments, then what it does def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" ...
year = int(input()) result = 1 if year%400 != 0: if year%4 == 0: if year%100 == 0: result=0 else: result=0 print(result) ''' #짧은 코드 if x%4==0 and (x%100!=0 or x%400==0): print(1) else: print(0) '''
#-*- coding: utf-8 -*- #python3 a = input().split() #python3는 input() print(float(a[0]) / float(a[1])) #나눗셈 결과. 소수점까지 출력 print(int(a[0]) // int(a[1])) # 나눗셈 몫 ''' python3에서는 input() 함수로 사용자로 부터 입력을 받는다. 입력받은 값을 split( ) 함수를 이용해 space를 구분자로 하여 a 배열의 각 인덱스에 값을 저장한다. 첫번째 입력값 a[0]을 float 형으로 변환하고, 두번째 입력값 a[1]을 float 형으로...
#-*- coding:utf-8 -*- ''' 각 테스트 케이스마다 "Case #x: "를 출력한 다음, A+B를 출력 print에 바로 출력하려고 하면 띄어쓰기 출력형식이 맞지 않아서, 문자열로 결합 후 출력 output print format python3에서 %operator을 지원하지만 권장하지 않음 str.format 함수 사용 ''' import sys n = int(sys.stdin.readline().rstrip()) for i in range(1,n+1): x,y = map(int, sys.stdin.readline().rstrip().s...
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f: f = open("dictionary.txt","r") print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password #NOTE - You will have to use .strip() to strip whitesp...
''' CHECK if the string is palindrome eg = "civic" , "Level" ''' #!/usr/bin/python from argparse import ArgumentParser class palindrome(): def is_palindrome(self, s1): list1=list(s1) list1.reverse() s2=''.join(list1) if s1==s2: return True else: return Fa...
flower = "lily" def print_flower(): global flower # overrides the global variable flower = "hibiscus" print(f"Inside the function the flower is {flower}") print_flower() print(f"Outside the function the flower is {flower}")
for n in range(10): # 0 to 9 inclusive print(",,", n) for n in range(3, 10): # 3 to 9 inclusive print("}}", n) for n in range(2, 10, 3): # 2 5 8 increase in 3s from 2 to 9 inclusive print("qq", n) colors = ["blue", "red", "yellow", "orange"] for n in range(len(colors)): print(n, colors[n]...
num = int(input("Give me a number: ")) if num % 2 == 0: print("The number is even") elif num % 2 == 1: print("the number is odd") if num % 4 == 0: print("the number is even and divisible by 4") divisor = int(input("Give me a second number: ")) if num % divisor == 0: print("Divisor divides evenl...
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] numbers = [] for number in a: if number < 5: numbers.append(number) print(numbers) maximum = int(input("Give me a number: ")) print("Your number is " + str(maximum)) a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] numbers = [] for number in a: if number < maximum: ...
# Basic setup for Exercise 43's adventure game. # Generating all my room setups first, # then hacking on the engine and mapping.... from sys import exit from random import randint import inspect class MainHub(object): # Eventually I'd like the codeword to be randomly selected; not there yet def room_setup(self): ...
# you can optimize your code a bit this way # it's syntactic sugar, really age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input ("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
my_name = "Zed A. Shaw" my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' my_height_cm = my_height * 2.54 my_weight_kg = my_weight * .4536 # that's avoirdupois, thx print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height...
# ord() => ASCII olarak değeri verme chr() içerisinde ki değere göre karakter üretiyor #metin = input("şifrelenecek metni giriniz") metin = "Python" sifre = "" for k in metin: print(ord(k)) # ASCII kodlarını verir decimal olarak print(k, "=>", chr(ord(k) + 5)) sifre = sifre + chr(ord(k) + 5) print(sifre...
#!/usr/bin/env python from random import randint from time import sleep import unicornhat as unicorn print("""Snow Draws random white pixels to look like a snowstorm. If you're using a Unicorn HAT and only half the screen lights up, edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below. """) unicor...
#################################################################################### ################ program which compute pi from the first 20 ######################## ################### terms of the Madhava series ######################## #################################################################...
class Student: school_name = "Springifeld Elementary" id = 1 def __init__(self, name, lastname): self.name = name self.lastname = lastname self.id = 1 def __str__(self): return "Student" def get_name_capitalized(self): return self.name.capitalize()
import numpy as np np.random.seed(0) # Training data set X = [[1, 2, 3, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]] class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.1 * np.random.randn(n_inputs, n_neurons) # Creating random weight per neuron self.b...
# -*- coding: utf-8 -*- """ Created on Sun Mar 1 13:25:41 2020 @author: Apa """ import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation #Initialize parameters ====================== Nlayers = 5 # not counting the input layer & the output layer LayerSize = 50 input_size...
from abc import ABC from typing import List from main.components.button import Button class Keyboard(ABC): """Клавиатура для вьюхи.""" def __init__(self, *buttons: Button) -> None: self.buttons: List[Button] = sorted(buttons, reverse=True) def append(self, button: Button) -> None: """До...
import sqlite3 from sqlite3 import Error def create_connection(db_file): try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) print("Returned None!@") return None def create_table(conn, create_table_sql): """ create a table from the create_tabl...
import numpy as np import pylab as pl from sklearn import datasets from sklearn.tree import DecisionTreeRegressor from sklearn import cross_validation, metrics, grid_search def load_data(): boston = datasets.load_boston() return boston def explore_city_data(city_data): """Calculate the Boston housing sta...
#!/usr/bin/env python ''' SVM and KNearest digit recognition. Sample loads a dataset of handwritten digits from 'digits.png'. Then it trains a SVM and KNearest classifiers on it and evaluates their accuracy. Following preprocessing is applied to the dataset: - Moment-based image deskew (see deskew()) - Digit image...
#Data for the pokemon game import time import random as r #import pygame as py #Pokemon Class class Pokemon(): """Performs the tasks involving the player's information and the first pokemonin the player list""" def __init__(self,playerName,playerList): self.playerName = playerName ...
primeiro = int(input('Primeiro numero: ')) segundo = int(input('Segundo numero : ')) terceiro = int(input('Terceiro numero: ')) # Achando o menor número menor = primeiro if (segundo < menor): menor = segundo if (terceiro < menor): menor = terceiro print('Menor: ', menor)
from Analysis import Evaluation class SentimentLexicon(Evaluation): def __init__(self): """ read in lexicon database and store in self.lexicon """ # if multiple entries take last entry by default self.lexicon=dict([[l.split()[2].split("=")[1],l.split()] for l in open("data/s...
# Name: Kennedy Anukam # Date: 2/29/20 # Class: CS 457 # Purpose: Handle insert query import os start_directory = os.getcwd() def insert_table(command): """ function is used to insert to a table(file) from the in use database Parameters: command (string): Input of the quer...
#!/usr/bin/python3 """ test user model """ import unittest from models.base_model import BaseModel from models.user import User class TestUser(unittest.TestCase): """ test user model""" @classmethod def setUp(cls): """steup class """ cls.user = User() cls.user.first_name = "toor" ...
#author: Pedro Goecking #!-*- coding: utf8 -*- pesca = input("Pesca (kg): ") if calendar.isleap(ano) == True: print 'É ano bissexto.' else: print 'Não é ano bissexto'
import matplotlib.pyplot as plt import numpy as np # Generating simple data t = np.linspace(0,4*np.math.pi,64) y = np.sin(t) z = np.cos(t) w = np.tan(t) # first, starting a figure plt.figure(figsize=[6,6]) # first subplot plt.subplot(221) plt.plot(t, y, 'b-') plt.title('Sine function') plt.ylabel('sin(t)') plt.xlabe...
def depunct(inText, punctChars=',.?!;:/'): outText = inText for iChar in punctChars: outText = outText.replace(iChar,'') return outText sampleText = '''This is a multi-line text. This includes multiple sentences on multiple lines. Some lines may be short. However, other lines may be longer, contain...
age = 19 hand = 'left' if (age<20) & (hand=='right'): print('Meeting all the requirements.') else: if age<20: print('Age requirement is met') else: print('None of the requirements is met') # With if...elif...else statement age = 19 hand = 'left' if (age<20) & (hand=='right'): print...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA # loadin the data pTraitData = pd.read_csv('personality0.txt', sep=' ') featureNames = pTraitData.columns # list of features # K-means clustering with 3 clusters nClus = 3...
weight = float(input('Please enter your weight (pounds): ')) height = float(input('Please enter your height (inches): ')) if (weight<=300) and (height<=78): print('Requirements met!') elif weight<=300: print('Weight requirement met!') elif height<=78: print('Height requirement met!') else: print('Neithe...
import matplotlib.pyplot as plt import numpy as np # Generating simple data t = np.linspace(0,4*np.math.pi,64) y = np.sin(t) # plot with title and axis labels plt.plot(t, y, 'b-') plt.title('Sine function') plt.ylabel('sin(t)') plt.xlabel('Angle t (radian)') plt.show() # The range of the axes are controlled now plt...
age = 23 hand = 'right' # evaluating the age requirement if age>=18: print('The age requirement is met') # evaluating the handedness requirement if hand=='right': print('The handedness requirement is met')
from math import * from Settings import * def distance(x1, y1, x2, y2): return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) class point: def __init__(self, x, y): self.x = x self.y = y # rotates point around another point def rotate(self, degrees, center): ...
#!/usr/bin/python import sys # Version using system arguments #for word in sys.argv[1:]: # print (word[::-1] == word) # Words to test words = [ "Oxo", "OXO", "123454321", "ROTATOR", "12345 54321" ] # Tests each word for word in words: print (word[::-1] == word)
# -*- coding: utf-8 -*- """ Created on Tue Feb 27 16:24:48 2018 @author: Max Marder """ import random as rand import math def bucket(n, i_range): # count number of succeses count = 0 for i in range(i_range): # frequerncy list of size n freq = [0] * n for j in range(n): ...
while True: num1 = input("Ingrese Un Numero:") num2 = input("Ingrese Otro Numero:") res = float(num1) + float(num2) print("La Suma Es:", res) print("!Gracias!")
i = 0 while i < 5: print('it\'s less than 5') i += 1 else: print('and now it\'s 5') # Print this message when the condition is no longer True for i in range(1, 5): if i == 3: break print(i) else: print("for loop is done") print("Outside the for loop")
def contains_even_number(lst): for i in lst: if i % 2 == 0: print(f"List {lst} contains an even number.") break else: print(f"List {lst} does not contain an even number.") contains_even_number([1, 9, 8]) contains_even_number([1, 3, 5])
number = 9 print(type(number)) # Print type of variable "number" float_number = 9.0 print(type(float_number)) # Print type of variable "float_number" print(float_number) # Print its value converted_float_number = int(float_number) print(type(converted_float_number)) # Print type of variable "converted_flo...
hello_world = "Hello, World!" for character in hello_world: # Print each character from hello_world print(character) length = 0 # Initialize length variable for character in hello_world: length += 1 # Add 1 to the length on each iteration to count the characters print(len(hello_world) == length)...
import unittest try: from str_and_repr import Cat class TestCase(unittest.TestCase): def test_hasattr_repr(self): cat = Cat('sphynx', 'Kitty') actual_repr = repr(cat) self.assertFalse('Cat object at' in actual_repr, msg='Method __repr__() is not defined for class C...
def multiply_by(a, b=2, c=1): return a * b + c print(multiply_by(3, 47, 0)) # Call function using custom values for all parameters print(multiply_by(3, 47)) # Call function using default value for c parameter print(multiply_by(3, c=47)) # Call function using default value for b parameter print(multiply_by(3)) ...
class City: all_cities = [] def __init__(self, name, population, country): self.name = name self.population = population self.country = country self.add_city() def add_city(self): self.all_cities.append(self.name) if __name__ == '__main__': malaga = City('Mala...
texto = "String" numero = 1 nulo = None booleano = True or False lista = ["a", "b", "c"] dicionario = { 'chave_1': 'valor_1', 'chave_2': 'valor_2' } print texto print numero print nulo print booleano print lista print dicionario for i in range(10): print 'ola'
txt = "hello,a." #1 x= txt.capitalize() print (x) txt = "hello,b" #2 x = txt.casefold() print(x) x = txt.center(20) #3 print(x) x = txt.count("python") #4 print(x) txt = "My name is Harsimran" #5 x = txt.encode() print() x = txt.endswith(".") #6 print(x...
# DAS E Exam 15.04.2021 # Function def counter(file, letter): count = 0 for line in file: #lower to catch all line.lower() for char in line: if char == letter: count += 1 return count # Open file file = open("RandomText.txt", "r") print(counter(file,"p"...
# # rick_dict = { # # 'first name':'Rick', # # 'last name':'Sanchez' # # } # # print("The last name of rick is:", rick_dict['last name']) # # # my_list = [ 1,2,3,"rick", 5] # # # # obj=" " # # i=0 # # # # while obj != "rick": # # obj= my_list[i] # # print(obj) # # i+=1 # # if obj=="rick": # # ...
try: month = str(input("Введите месяц (словом): ")) num = int(input("Введите число (числом): ")) except: print("Невозможно обработать данные! Пожалуйста, введите данные, удовлетворяющие условиям!") else: if month == "март": if (num >= 21) and (num <= 31): print("Овен") elif (...
print("Введите четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки, " "потом для второй клетки: ", sep="\n") try: x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) except: print("Невозможно обработать данные! Пожалуйста, введите ...
#!/usr/bin/env python3 import sys input = " ".join(sys.argv[1:]) evaluated = eval(input) decStr = evaluated hexStr = hex(evaluated) binStr = bin(evaluated) print(decStr, hexStr, binStr, sep="\n", end="")
from random import choice from random import randint def rand_timesheet(): content = [] for _ in range(randint(1, 10)): line = [] time = 0 for _ in range(randint(1, 3)): a = rand_time(time, time + 3) b = rand_time(time + 4, time + 7) lin...
passport_list = [] valid_passports = 0 with open('input.txt') as f: passport_list = f.read().split('\n\n') def check_valid(s): rf = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] parts = s.split() data = [] for part in parts: p = part.split(':') data.append(p) for i in rf:...
# Using The Formula to Calculate Fibonacci Numbers # Fn = {[(√5 + 1)/2] ^ n} / √5 # Reference: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html # Time Complexity: O(1) import math def solution(n): phi = (math.sqrt(5) + 1) / 2 fibonacci = math.pow(phi, n) / math.sqrt(5) ...
##################################################### ########## Advent of Code 2019 Day 01 ############## ##################################################### import math total_fuel = 0 file = open('C:\\Users\\ryan.jackson\\Desktop\\input.txt', 'r') for module in file.readlines(): total_fuel += math.floor(int(mod...
# an Anylist is one of, # - None # - Pair (value, Anylist) class Pair: def __init__(self, first, rest): self.first = first self.rest = rest def __eq__(self, other): return ((type(other) == Pair) and self.first == other.first and self.rest == other.rest ...
#!/usr/bin/env python # coding=utf-8 cars = 100 space_in_car = 4.0 drivers = 30 passenger = 90 cars_not_driven = cars - drivers cars_driver = drivers carpool_capacity = cars_driver * space_in_car average_passengers_per_car = passenger / cars_driver print ("There are",cars,"cars available") print ("There are only ",d...
# from turtle import* # color("red") # begin_fill() # for i in range (4): # forward(20) # left(90) # end_fill() # mainloop() # print (*range(1,21)) # print (*range (0,20,2)) # print(*range(100,1,-1)) # for i in range(1,21): # print(i) for i in range (1,10): for j in range(1,10): if i*j >9: ...
from turtle import* forward (5) backward(2) left (90) forward (2) circle (50) penup forward (20) pendown circle(20) mainloop() # add at the end print ('aaa') print("hi",'3')
# Borno Kendley # bornokendley@gmail.com # instagram: @kendleyone import random print("Welcome to Rock-Paper-Scissors game\n") print("Possibility: Rock-Paper-Scissors") userScore = 0 computerScore = 0 Possibility = ["Rock", "Paper", "Scissor"] def Play(): global userScore global computerScore if use...
# assigning variables time and day time = '2:00a.m' day = 'saturday' #using the string.format method tocall thevariables print("It is {} on a {}.".format(time,day))
#!/usr/bin/env python3 ## ## EPITECH PROJECT, 2018 ## Sans titre(Espace de travail) ## File description: ## data ## """ Data class hold datas """ class Data: """Class that holds different data""" def __init__(self): self.avg = { 'crypto': -1, 'forex': -1, 'stock...
import random as r # module import time as t guesstimes = 0 while True: number = r.randint(0, 100) time1 = int(t.time()) while True: guess = int(input("Enter a number between 0 and 100: ")) if guess == number: print("You guessed right!") guesstimes += 1 break elif guess > number: ...
#!/usr/bin/python length=5 breadth=2 area=length*breadth print 'Areais',area print 'Perimeter is',2*(length+breadth)
import re def eval_plus(x): while m := re.search("\d+ \+ \d+", x): x = x.replace(m.group(), str(eval(m.group())), 1) return x def eval_all(x): while m := re.search("\d+ [\+\-\*\/] \d+", x): x = x.replace(m.group(), str(eval(m.group())), 1) return x def eval_expr(x, evaluate): ...
# Chapter 4 Homework 4-7 odd_numbers = list(range(3, 30, 3)) for odd_number in odd_numbers: print(odd_number)
# Chapter 3 Homework 3-4 names = [ "Hezz", "Eli", "Jay"] message = f" {names[0]}, you are invited to dinner today at 6:00." print(message) message = f" {names[1]}, you are invited to dinner today at 6:00." print(message) message = f" {names[2]}, you are invited to dinner today at 6:00." print(message)
# Chapter 4 Homework 4-1 pizzas = [ "pepperoni pizza", "cheese pizza", "garlic pizza"] for pizza in pizzas: print(f"I like {pizza.title()}") print("I love Pizza")
# Chapter 2 homework 2-4 name = "jackson the gamer" print(name.upper()) print(name.lower()) print(name.title())
# Chapter 5 Homework 5-4 alien_color = ["green", "yellow", "red"] if "green" in alien_color: print("\nYou get 5 points") else: "red" in alien_color print("\nYou get 10 points") print("*****************************************") if "yellow" in alien_color: print("you get 15 points") if "blue" in alien_color: ...
""" Functions for preprocessing the data, before classification """ from numpy import bincount, array, min, zeros, nonzero, where, sum from settings import NCLASSES def obtain_class_weights(true_classes, weight_calc = "inverted"): """ Given the true classes of some samples, gives a vector of sample weights. The ...
on# This file generates the BinarySearch pattern and puts it in the ../Patterns folder. import math import Helper # 100, 0 --> 50 # 100, 1 --> 25, 50, 75 # 100, 2 --> 12, 25, 37, 50, 62, 75, 87 def binary_search_points(length, depth): return binary_search_aux(floor(length / 2), floor(length / 4), def binary...
#need to make it so it returns the whole file, not just the line, into a list. #creating function to read file, split it at the end of a line, and close file def f(): try: fin = open('CustomerList.txt') contents = fin.read() lines = contents.split('\n') fin.close() ...
#construtor and destructor are optional. #The constructor is typically to set up the varibales. class Partyanimal: x = 0 name = '' #constructor with addition parameters z def __init__(self,z): self.name = z print('I am constructed', self.name) # called when object created #method de...
''' Task You are given a string . Your task is to print all possible size replacement combinations of the string in lexicographic sorted order. Input Format A single line containing the string and integer value separated by a space. Constraints The string contains only UPPERCASE characters. Output Format Pri...
''' https://www.hackerrank.com/challenges/countingsort4/problem ''' import math import os import random import re import sys def countSort(arr): first_half = arr[:len(arr)//2] first_half_val = set([b for a,b in first_half]) result = ['' for x in range(100)] for i, item in enumerate(arr):...
''' https://www.hackerrank.com/challenges/picking-numbers/problem ''' import math import os import random import re import sys def pickingNumbers(a): kl = [] j = [] a.sort() for val in a: if len(j)==0: j.append(val) continue elif abs(min(j)-va...
''' https://www.hackerrank.com/challenges/s10-interquartile-range/problem ''' # Enter your code here. Read input from STDIN. Print output to STDOUT _ = int(input()) v1 = list(map(int, input().split())) v2 = list(map(int, input().split())) vals = [] for it, v in enumerate(v1): vals.extend([v]*v2[it]) vals ...
''' https://www.hackerrank.com/challenges/designer-pdf-viewer/problem ''' import math import os import random import re import sys import string alph = string.ascii_lowercase dicty = dict(zip(alph, range(26))) # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): k = [] for va...
''' You are given a set and number of other sets. These number of sets have to perform some specific mutation operations on set . Your task is to execute those operations and print the sum of elements from set . Input Format The first line contains the number of elements in set . The second line contains the spac...
''' https://www.hackerrank.com/challenges/repeated-string/problem ''' import math import os import random import re import sys def repeatedString(s, n): length = len(s) if n<=length: return s[:n].count('a') elif n%length==0: return s.count('a')*(n//len(s)) else: f...