text
stringlengths
37
1.41M
# Lucia Saura 17/02/2018 # Collaz Conjeture # https://en.wikipedia.org/wiki/Collatz_conjecture i = 17 while i > 1: if i % 2 == 0: print(i//2) i = i//2 else: print (i * 3 + 1) i = i * 3 + 1
'''Esta é uma tarefa de demonstração. Escreva uma função: def solution(A) que, dada uma matriz A de N números inteiros, retorna o menor número inteiro positivo (maior que 0) que não ocorre em A. Por exemplo, dado A = [1, 3, 6, 4, 1, 2], a função deve retornar 5. Dado A = [1, 2, 3], a função deve retornar 4. Dado...
#!/usr/bin/env python # From the Census Incorporated place CSV, create an optimized JS lookup that # will return a place based on the following procedure: # # 1. Choose a random number in the range of [0, Population of the US) # 2. Return the place that person would live in # # Output: # { # // Whoa. A _bunch_ of pe...
"""A camera library for projection.""" import json import numpy as np try: import google3 from google3.pyglib import gfile from cvx2 import latest as cv2 GOOGLE3 = True except: import cv2 GOOGLE3 = False class Camera(): """A simple camera class.""" def __init__(self, rvec...
class Company: def __init__(self): self.name = None self.country_code = None self.identifier = None self.address = None self.exists_since = None self.exists_until = None def __str__(self): return 'Company {self.name} ({self.country_code}, {self.identifier...
# Harker Russell #J Fausto # Steve Sharp def is_vowel(word): word_lenght = len(word) position = 0 while position < word_lenght: if(word[position] == 'A') or (word[position] == 'E') or(word[position] == 'I') or (word[position] == 'O') or (word[position] == 'U') or (word[position] == 'a') or (word[po...
from collections import namedtuple Chest = namedtuple("Chest", ["open", "contains"]) class Problem: def __init__(self, startkeys, chests) self.keys = startkeys[:] self.chests = chests[:] def clone(self): return Problem(self.keys, self.chests) def open_chest(self, index): s...
class Ken: def __init__(self, weights): self.weights = weights[:] self.weights.sort() def play(self, other_weight): """Implements Ken's optimal strategy, based on `other_weight` being played by Naomi. Returns weight which Ken will play.""" if other_weight > self...
import sys radius = input("enter radius") print(radius * radius * 3.14 )
def threeNumber(x,y,z): addition = x + y+ z print addition if x==y==z: print addition * addition * addition threeNumber(2,2,2)
#!usr/bin/python import re match = re.search(r'iii','piiiiiig') => found, match.group() == "iii" match = re.search(r'iii' , 'piiiiig') => not found, match == None
# -*- coding: utf-8 -*- # @Time : 2020/10/7 15:32 # @Author : Evan # @Email : evan@stu.haut.edu.cn # @File : train_regression_model.py # @Software: PyCharm # @Description: train a regression model import numpy as np from sklearn.linear_model import LinearRegression import data_preparation from sklearn.metrics ...
#!/usr/bin/env python3 # Write a program that computes the GC% of a DNA sequence # Format the output for 2 decimal places # Use all three formatting methods dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change gc = 0 for i in range(0, len(dna)): if dna[i] == 'G' or dna[i] == 'C': gc += 1 else: gc +=...
t = int(raw_input()) while t > 0: a = int(raw_input()) while a >= 10: suma = 0 while a != 0: b = a % 10 a = a / 10 suma = suma + b a = suma print a t= t -1
# Definir dos funciones que reciban una cantidad variable de argumentos: a) una función que # puede llegar a recibir hasta 30 números como parámetros y debe devuelva la suma total de # los mismos; b) otra función que reciba un número variable de parámetros nombrados (usar # **kwargs), e imprima dichos parámetros. De an...
# Dada una frase donde las palabras pueden estar repetidas e indistintamente en mayúsculas # y minúsculas, imprimir una lista con todas las palabras sin repetir y en letra minúscula. frase = """Si trabajás mucho CON computadoras, eventualmente encontrarás que te gustaría automatizar alguna tarea. Por ejemplo, podrías...
# Dada una lista de strings con el siguiente formato: # tam = ['im1 4,14', 'im2 13,15', 'im3 6,34', 'im4 410,134'] # Donde im1, im2, etc son los nombres de las imágenes y la parte de números representa el valor # de una coordenada (x, y). Se solicita que arme dos listas que contengan, nombre y luego una # tupla de las...
import math CONSt= 17.31 d1 = float( input("ingrese la distancia_1 (en metros)\n")) d2 = float(input("ingrese la distancia_2 (en metros)\n")) f = float(input("ingrese la frecuencia en Mhz \n")) R = 17.31 * math.sqrt( ((d1*d2)/(f*(d1+d2))) ) print("===="*30 ) print("el radio de fresnel es : {:.2f} mts".format(R) )...
# -*- encoding:utf-8 -*- # 循环 flag = True count = 1 ''' while flag: print(count) count = count + 1 if count > 100: flag = False while count <= 100: print(count) count = count + 1 ''' s = 'aksldfj' for i in s: print(i) s = 'fsadf苍井空fklsadf' if '苍井空' in s: print('非法字符')
# 无序列表 不会有重复的元素 set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6} print(set1 - set2) # 求差集 {1,2,3} print(set2 - set1) # {6} print(set1 & set2) # 求交集 {4,5} print(set1 | set2) # 求合集 {1,2,3,4,5} # 定义一个空集合 set3 = set() print(type(set3), len(set3)) # 'set' 0
# 装饰器进阶 # 复习 def wrapper(f): def inner(*args, **kwargs): print('被装饰的函数执行之前做的事') result = f(*args, **kwargs) print('被装饰的函数执行之后做的事') return result,1 # 这个才是func1的真正返回值 return inner @wrapper def func1(*args, **kwargs): print(args, kwargs) return 111 # 这个不是func1的返回值 result ...
# 函数 def greet_user(): '''简单的问候语''' print('hello python') greet_user() def greet(msg): print(msg) greet('hello python') # 位置实参 def describe_pet(animal_type, pet_name): '''显示宠物信息''' print('\nI have a ' + animal_type + '.') print('My ' + animal_type + '"s name is' + pet_name.title() + '.') descr...
# 只有内置方法里面有__iter__方法的数据类型才可以被for循环 list = [] print(list.__iter__()) # 查看list的所有方法 # print(dir([])) # 获取list1的迭代器 list1 = [1] list1.__iter__() # 得到迭代器, 迭代器才有__next__方法 print(list1.__iter__().__next__()) # 获取list1的下一个, 和JS的迭代器类似 # 只要含有__iter__方法的都是可迭代的 --可迭代协议 # 内部含有__next__ 和__iter__方法的就是迭代器 # example from collect...
# 类型判断 isinstance('1', str) # True isinstance('1', (int, str, float)) # True 如果是元祖中其中一种,返回True # 身份运算符 is # 关系运算符 == # isinstance # 最好使用isinstance , 可以判断子类的类型
# 类基础 # 创建和使用 #### 创建类 class Dog: '''一次模拟小狗的简单尝试''' def __init__(self, name, age): self.name = name self.age = age def sit(self): print(self.name.title() + 'is now sitting!') def roll_over(self): print(self.name.title() + ' rolled over!') #### 创建实例 my_dog = Dog('willie...
# -*- coding: utf-8 -*- """ Created on Sat May 14 20:58:35 2016 @author: Sofia """ from tkinter import* #Import necessary libraries from tkinter.ttk import* import math from tkinter import messagebox import numpy as np win1=Tk() #Create first window which takes user's input win1.title('GRAPHING...
def alphabet_position(letter): """Receives a letter (that is, a string with only one alphabetic character) and returns the 0-based numerical position of that letter within the alphabet. Example: a -> 0, A -> 0""" return ord(letter.upper()) - ord("A") def rotate_character(char, rot): """Receives a char...
#! -*- coding: utf-8 -*- # 创建一个Thread的实例,传给它一个函数 import threading from time import sleep, time loops = [4, 2] def loop(nloop, nsec, lock): print('start loop %s at: %s' % (nloop, time())) sleep(nsec) print('loop %s done at: %s' % (nloop, time())) # 每个线程都会被分配一个事先已经获得的锁,在 sleep()的时间到了之后就释放 相应的锁以通知主线程,这...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 单线程telnet import telnetlib import string import sys,os # 调用telnet,输出结果True/False+字符串 def check_port(ip,port): address = 'telnet ' + ip + ' '+ port try: tn = telnetlib.Telnet(ip, port, timeout=10) result = (True,address + ' ---Passed\n') exce...
import re #The following function calculate the normalized counts. def normalized_count(tWord,tFind): count = (tFind / tWord) * 100 return count #The following sets up variables and lists pronouns = ["I", "you", "he", "she", "it", "we", "they", "me", "him", "her", "us", "them"] modals = ["must", "sha...
#%% s=input('請輸入一句英文句子 ') s1=s.title() s2=s.capitalize() s3=s.upper() s4=s.swapcase() a=s1.split(' ') print(a[::-1]) print(s2) print(s3) print(s4) # s5=s.replace([0],'pig') # print(s5) #%% 全班學生 = set(['john','mary','tina','fiona','claire','eva','ben','bill','bert']) 英文及格 = set(['john','mary','fiona','...
import os import pandas as pd def csv_to_df(file_name, csv_data): ''' Salva um arquivo .csv e retorna um dataframe Params: file_name (str): nome do arquivo .csv csv_data (str): dados no farmato de csv Returns: (DataFrame): objeto DataFrame com ...
def divisors(): ''' this function prints all the divisors of a number :return: ''' num = int(input("enter a number")) list = [] for i in range(2,num): if(num % i == 0): list.append(i) print list if __name__ == '__main__': divisors()
# -*- coding: utf-8 -*- line = '+++++++++++++++++++++++++++++++++++++++' laptop = ['sony', 'ibm', 'hp', 'dell', 'apple'] print(len(laptop), laptop) print('I like %s thinkpad! :)' % laptop[1]) print('But I don\'t like %s xps :(' % laptop[-2]) print(line) laptop.append('compaq') # append one element to last position l...
box = ''' -------------- | example | -------------- ''' print(box) result = 1024*768 # \n\t are string, \n means a new line, \t means a table, \a is a beep sound print("1024 * 768 =\n\t", -result, '\n\a') # print a \, a new line, and a \ print('\\\n\\', '\n') # use r" to ignore \ print(r'\\\n\\') print() # \r mean...
# -*- coding: utf-8 -*- line = '#################' # %s字符 %f浮点数 %d整数 %x十六进制整数 print('Hello, %s' % 'world') print('Hello, %s is %s' % ('world', 'ok')) # 1000.99被%d取整, %.2f指定小数点位数 print('Hello %s, you have $%d and $%.2f bonus!' % ('Leo', 99.12345, 99.12845)) print(line) # the 5 below means %d starting from 5th (4 space...
class User: # here's what we have so far def __init__(self, name, email): self.name = name self.email = email def printUser(self): print(self.name) class BankAccount(User): def __init__ (self, name, email, acc_name='Checking'): User.__init__(self, name, email) ...
#import Python test framework import unittest #import libraries import math # our 'unit' # this is what we are running our test on def reverseList(revArray): loopCount = math.floor(len(revArray)/2) for i in range(loopCount): revArray[i], revArray[-1-i] = revArray[-1-i], revArray[i] return revArray...
i=1 while i<=1000: if 3%i==0: print("nav") if 7%i==0: print("gurukul") if 21%i==0: print("navgurukul") else: print(i) i=i+1
from enum import Enum class Suits(Enum): DIAMONDS = unichr(0x2666) HEARTS = unichr(0x2665) CLUBS = unichr(0x2663) SPADES = unichr(0x2660) class Card(object): def __init__(self, suit, number): self.suit = suit.value self.number = number self.val = self.get_...
import sys import pdb import argparse def main_two(args): pass def main_one(args): with open(args.filename) as file_open: data = file_open.readlines() count = 0 for row_w in data: row = [int(i) for i in row_w.split()] max_i = row[0] min_i = row[0] if not...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 19 21:20:41 2020 @author: katherinefilpolopez """ import re def transponMethod(seq, transSeq): n = len(transSeq) n = int(n/2) trans1 = transSeq[:n] trans2 = transSeq[n+1:] tracker = 0 for i in range(n-2): for j...
import sqlite3 class DB_class: conn = None cursor = None def __init__(self): self.conn = sqlite3.connect('test.db') self.cursor = self.conn.cursor() cmd = 'CREATE TABLE IF NOT EXISTS products (name TEXT, description TEXT)' self.cursor.execute(cmd) cmd = 'CREATE TAB...
card_rank = int(input()) if card_rank == 1: card_name = 'Ace' elif card_rank == 11: card_name = 'Jack' elif card_rank == 12: card_name = 'Queen' elif card_rank == 13: card_name = 'King' else: card_name = card_rank print('Drew a ' + str(card_name))
from deck import print_card, draw_card, print_header, draw_starting_hand, print_end_turn_status, print_end_game_status from deck_test_helper import get_print, mock_random import unittest from unittest.mock import patch class TestBlackjack(unittest.TestCase): """ Class for testing Blackjack. There are two helpe...
#server # TCP Server Code #host="127.0.0.1" # Set the server address to variable host host="127.168.2.75" # Set the server address to variable host port=4446 # Sets the variable port to 4444 from socket import * # Imports socket module s=socket(AF_INET, S...
memo = {0: 0, 1: 1} # base case def fib3(n): if n not in memo: memo[n] = fib3(n-1) + fib3(n-2) # memoization return memo[n] if __name__ == "__main__": print(fib3(20))
# python doe not require an else block at the end of an if-elif chain # sometimes an else block is useful # or sometime times it is clearer to use an additional elif statement that catches a specific condition of interest age = 24 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: # the e...
# every attribute in a class needs an initial value, even if that value is 0 or an empty string # in some cases, such as when setting a default value, it makes since to specify this initial in the ... # ... body of the init method # if you do this you do this for an attribute you don't have to include a parameter fo...
print("\t\t\t - PIZZA TOPPINGS -") pizza = "Please type your prefer pizza topping: " pizza += "\n\tType 'quit' to cancel program" while True: topping = input(pizza) if topping != "quit": print(" Adding " + topping) else: break print("\n\t\t\t - MOVIE TICKETS -") # create a...
# often you'll want to take one action when a conditional test passes and different one action in all other cases # an if-else allows you to define an action or set of actions that are executed when the conditional test fails # here is the same code from 4.12 but will a message for anyone who is not old enough to v...
# reverse() can be used to print a list in reverse order cars =["bmw", "audi", "toyota", "sabaru"] print(cars) cars.reverse() print(cars) # note reverse does not sort() the list instead just reverses it
# you can nest a dictionary inside another dictionary, but can get complicated quicky when doing so users = { "a-einstein" : { "first" : "albert", "last" : "einstein", "location" : "princeton", }, "m-curie" : { "first" : "marie", "last" :...
# an assumption made about every list so far is that it has at least one value in it # here we will check if the a list is empty before running a loop requested_toppings = [] # started with an empty list if requested_toppings: # if the list contains at least one item list turns up as true for x in requested...
# you may need to check for multiple conditions # for example if you want two conditions to be true to take an action # here is a code to check if both people are over 21 age_0 = 22 age_1 = 18 print((age_0 >=21) and (age_1 >=21)) # check whether both ages are equal to or over 21
# motorcycles = ["honda","yamaha","suzuki"] # print(motorcycles[3]) # one common error is asking for non-existant values. i.e. asking for a forth item when there are only 3 values motorcycles = ["honda","yamaha","suzuki"] print(motorcycles[-1]) # when the index is -1 it always returns the last item
# an if statement is an expression that can be evaluated as True or False and is ... # ... called a conditional test. if the if statement is True python executes the code ... # ...following the if statement. if the test evaluates to false python ignores the following ... # ... if statement # most conditional test...
# If the value's position you wan't to remove is unknown, the remove() fucntion can be use to remove using just the value motorcycles = ["honda","yamaha","suzuki","ducati"] print(motorcycles) motorcycles.remove("ducati") # remove() removes the value "dacati" without giving the position i.e motorcylces.pop(3) prin...
# when modeling something from the real world code, you may find that you are adding more detail to the class # you'll find that you have a growing list of attributes and that your files are becoming lengthy # in this situation you might recognise that part of one class can be written as a separate class # you can b...
# previously I have been working thorough all the elements in a list # a specific group in a list is called a slice # to make a slice you specify the index of the first and last elements you want to work with # similar to the range() function python stops one item before the second index you specify # for examp...
# sometimes people will ask for anything in their lists # below are two lists # the first is a list of available topping and second is a list the user has requested # each time each time request_toppings is checked against the list of available_toppings available_toppings = ["mushrooms", "olives", "green peppers"...
# dictionaries allow you to connect simple pieces of related information # in this lesson we will learn how to access information once its in a dictionary and how to modify that information # consider a game featuring aliens that can have different colours and point values # a dictionary stores that information ab...
# here is how to change the label type and graph thickness import matplotlib.pyplot as plt squares = [1, 4, 9, 16, 25] # set linewidth plt.plot(squares, linewidth = 5) # set title and label axes plt.title("Square Numbers", fontsize=24) # .title() to gives a title plt.xlabel("Value", fontsize =14) # .xlabel...
# a function can return any kind of value you need it to # including data structures like lists and dictionaries # for example the following function takes parts of a name and returns a dictionary representing a person def build_person(first_name, last_name, age=""): """Return a doctopmary of information abou...
class Restaurant(): """ About restaurants or whatever""" def __init__(self, restaurant_name, restaurant_type): self.restaurant_name = restaurant_name self.restaurant_type = restaurant_type self.number_served = 0 def open_restaurant(self): print(self.restaurant_na...
# Siraj Raval: Build a Neural Net in 4 Minutes # https://www.youtube.com/watch?v=h3l4qz76JhQ import numpy as np # Sigmoid, a function that will map any value to a value between zero and one # will be run at every neuron of our network when data hits it # useful for creating probabilities out of numbers def nonlin(x,d...
from Utility import * class BinarySearch: utility=Utility() print("enter the number of words for binary search : ") var_input = utility.input_int_data() if (var_input <= 0): print("please check the input : ") else: my_array=[None]*var_input print(" enter values ") fo...
from Utility import * class Annagram: utility=Utility() var_str_1=raw_input("please enter first string : ") var_str_2 = raw_input("please enter second string : ") var_result = utility.annagram(var_str_1,var_str_2) if(var_result): print("it is a annagram ") else: print("it is no...
from Utility import * class Gambler: utility = Utility() print("Please enter a number_of_times : ") number_of_times = utility.input_int_data() if number_of_times <= 0: print("check the input") else: loss = 0 wins = 0 x = 1 # for x in range(1, number_of_time...
from Node import * class LinkedList: def __init__(self): self.head=None def add(self,data): obj_node=Node(data) if(self.head == None): self.head=obj_node else: temp = self.head while(temp.next_node != None): temp = temp...
import math class Utility: def input_int_data(self): while True: try: var_input = int(input()) return var_input break except NameError: print("please enter a integer...try again") except NameError: ...
from Utility import * class WindChill: utility=Utility() print("please enter the temperature t (in Fahrenheit) below '50'") var_t = utility.input_int_data() print("please enter the wind speed v (in miles per hour) between '3' and '120'") var_v = utility.input_int_data() if ((var_t <= 50) and (v...
from Utility import * class DeckOfCards: def deck_of_cards(self): suit_list = ["Clubs", "Diamonds", "Hearts", "Spades"] rank_list = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] deck_arr = [None] * 52 # storing total cards for i in range(...
from Stack import * from Utility import * class BalancedParanthesis: utility = Utility() stack = Stack() # var_input = "((5+6)*(7+8)/(4+3)(5+6)*(7+8)/(4+3))" print("please enter expression") var_input = utility.input_str_data() my_array = list(var_input) open_para = "(" close_para = ")...
from collections import defaultdict def update_allergens(allergenDB, allergen): for key in allergenDB: if key != allergen and len(allergenDB[key]) > 1: allergenDB[key].difference_update(allergenDB[allergen]) if len(allergenDB[key]) == 1: update_allergens(allergenDB, ...
def console_execution(instructions): visited = set() acc = 0 line = 0 while line not in visited and line < len(instructions): visited.add(line) command, value = instructions[line] if command == "acc": acc += int(value) line += int(value) if command == "jmp"...
#Compilation of Object oriented stuff in python class first_class: var1=3 #this is a variable of a class atrribute def __init__(self,name,breed): #this initializes the constructor self.name="rocky" self.breed="blsck labrodor" def class_function(self,var): #this is a class meth...
# print prime numbers between 1 to 100 #count=0 #for n in range(2,100): #for i in range(1,n+1): #if n%i == 0: #count+=1 #if count==2: #print "%d" %n #count=0 ints=[32,45,67,78] for iv,key in enumerate(ints): print "the index is %d, the element is %d "%(iv,key)
# problem in output def func(*a,**keyword): for key in keyword: print keyword[key] func(1,2,3,4,5,6,b=1,a=0,c=2,d=9)
#create the name of the states states ={ "uttarpradesh":"up", "delhi":"dl", "andhrapradesh":"ap", "rajasthan":"rj" } #create the name of the cities in the states cities ={ "up":"agra", "dl":"noida", "ap":"hyderabad", "rj":"kota" } print "some cities name :" print "up has %s" %cities["up"] print "rj has %s" %c...
print "whats ur name :" x = raw_input() print "whats ur height:" h = raw_input() print "wats ur weight :" w = raw_input() print "so ur name is %s ur height is %s ur weight is %s" %(x,h,w)
from sys import argv script,user_name = argv pr = ">>>>>>>>>>" #it is just a string variable print "my script name is %s,my user name is %s" %(script,user_name) print "what do you lke %s" %(user_name) like =raw_input(pr) print "where do you live %s" %(user_name) live = raw_input(pr) print "whats ur favourite food %s" %...
def compute_mongo_age(birthYear, birthMonth, birthDay, currentYear, currentMonth, currentDay): ageInYears = (currentYear-birthYear) + (currentMonth-birthMonth)/15 + (currentDay-birthDay)/(15*26) return ageInYears print(compute_mongo_age(2879,8,11,2892,2,21))
from tkinter import * from tkinter import messagebox import random class MinesweeperCell(Label): '''represents a Minesweeper cell''' def __init__(self,master): '''MinesweeperCell(master) -> MinesweeperCell creates a new Minesweeper cell''' Label.__init__(self,master,height=1,width=2,te...
import random class Die: '''Die class''' def __init__(self,sidesParam=6): '''Die([sidesParam]) creates a new Die object int sidesParam is the number of sides (default is 6) -or- sidesParam is a list/tuple of sides''' # if an integer, create a die with sides ...
import turtle wn = turtle.Screen () hongweiBigPig = turtle.Turtle () for i in range(8): for j in range(4): hongweiBigPig.forward(-50) hongweiBigPig.left(90) hongweiBigPig.penup() hongweiBigPig.forward(50) hongweiBigPig.pendown() wn.mainloop()
n = int(input('Enter a positive integer n >= 3: ')) fiboOne = 1 fiboTwo = 1 for i in range(3,n + 1): fibo = fiboOne + fiboTwo fiboOne = fibo fiboTwo = fibo - fiboTwo print(fibo)
def compute_mongo_age(birthYear, birthMonth, birthDay, currentYear, currentMonth, currentDay): assert 0 <= birthMonth & birthMonth < 15, 'birthMonth: illegal argument' ageInYears = (currentYear-birthYear) + (currentMonth-birthMonth)/15 + (currentDay-birthDay)/(15*26) # computes the age of the Mongo resident in ...
f = open('africa.txt','r') text = f.read() f.close() eightLetterWords = [] wordList = text.split() for word in wordList: if len(word) == 8: eightLetterWords.append(word) print(len(eightLetterWords))
def rot13(string): encodedString = '' alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' for character in string: if character in alphabet: number = ord(character) if number < 78 or 96 < number < 110: newNumber = number + 13 else: ...
s = input() count_upper = 0 count_lower = 0 for c in s: if c.isupper(): count_upper += 1 if c.islower(): count_lower += 1 if count_upper > count_lower: print(s.upper()) else: print(s.lower())
#Breaking out of while loops import random class Enemy: hp = 200 def __init__(self, attack_low, attack_high): self.attack_low = attack_low self.attack_high = attack_high def get_attack(self): print(self.attack_low) def get_hp(self): print("Hp is", self.hp) enemy1...
binary_num = input("Please enter a binary number") i = 0 integer = 0 power = len(binary_num) - 1 while i < len(binary_num)-1: if binary_num[i] == "1": integer = integer + 2**power i = i + 1 power = power - 1 print(integer)
class MyClass (object): def method1(self, param_tuple): self.local_list = [] for element in param_tuple: if element > 10: self.local_list.append(element) def method2(self): self.sum_int = 0 for element in self.local_list: self.su...
def acronym (): str1 = input("What is your string?") str2 = str1.split("") firstlet = "" for i in str2: firstlet.append(i[0]) print(firstlet.upper()) acronym()
def grades (): i = int(input("Enter your grade: ")) if i >=90 and i <= 100: print ("A") if i >=80 and i <= 89: print ("B") if i >=70 and i <=79: print ("C") if i >=60 and i<=69: print ("D") if i <60: print ("F, drop the boyfriend. hes lowering y...
# MARLA ANDERSON # LAB 3 # got some help from Juan Pablo from random import randint # global variable of chutes and ladders # remenber to let your function know you're using this variable with 'global' chutes_ladders = {4 : 7, 8 : 15, 12 : 2, 14: 6} # Rolls a die of six sides and returns ...
import time import math from binary_search_tree import BSTNode start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] # Return ...
import unittest from sorting import DictionarySorting from operator import itemgetter class TestSorting(unittest.TestCase): instance = None def setUp(self): self.instance = DictionarySorting() def test_convertToList(self): x = {"aman": 23, "Tom": 35} self.assertEqual(id(self.inst...
low = 1 high = 1000 print('think of a number between 1 and 1000') input('Press ENTER to start') count = 0 # guess = high//2 while low != high: count = count + 1 guess = low + (high - low) // 2 high_low = input(f'My guess is {guess}. Should i guess higher or lower? ' 'Enter h for higher, l for...