text
stringlengths
37
1.41M
#! /usr/bin/env python ''' visitor pattern creates new operations by adding new subclass to hierarchy, without altering base class. from GoF UML, concretVisitor class override Visitor Class operations to implement visitor-specific behaviors for the ConcretVisitable class, and once AbstractVisitable accept visitor, i...
#! /usr/bin/env python # divide-conquer, merge sort complexity O(n lg n) def merge(lst1, lst2): result = list() i, j = 0, 0 while i <len(lst1) and j <len(lst2): if lst1[i] <= lst2[j]: result.append(lst1[i]) i += 1 else: result.append(lst2[j]) ...
'''Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.''' a = input('Enter str: ') b = int(input('Enter num: ')) c = int(input('Enter another num: ')) print('Your line: {}\nYpur number: {}\nYour second number: ...
'''Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict.''' def SeasonList(date): year = [('зима', 1, 2, 12), ('весна', 3, 4, 5), ('лето', 6, 7, 8), ('осень', 9, 10, 11)] for i in range(len(...
'''6. Реализовать два небольших скрипта: а) итератор, генерирующий целые числа, начиная с указанного, б) итератор, повторяющий элементы некоторого списка, определенного заранее.''' from itertools import count, cycle def a(n: int): return count(n) def b(l: list): return cycle(l) def tester(): num ...
#Printing positive numbers in a given range list1 = [12, -7, 5, 64, -14] print("List 1") for number in list1: if number > 0: print(number) print("\n") list2 = [12, 14, -95, 3] print("List 2") for number in list2: if number > 0: print(number)
# ========================================= # Передача функции в качестве аргумента # Функции - объекты первого порядка # ========================================= # Функции в python являются объектами первого класса (First Class Object). # Это означает, что с функциями вы можете работать, также как и с данными: #...
#!/usr/bin/env python from operator import itemgetter from load_data import load # returns a 2-tuple of the similarity between two users # first element is the scoring difference, where 0 is identical and a positive # score is a sum-squared difference; if nothing in common, None # second element is the numbe...
#!/usr/bin/env python # # Homework from w/b 06/03/2017 # 1.Create a list to hold the colours of the rainbow. # Experiment with retrieving the colours from the list. rainbow = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'] print("\n\n") homework = "HOMEWORK 1 - make list of raibow colours, and select...
#!/usr/bin/env python # week 2 - example 3, range import sys # so I can use sys.stdout.write instead of print in python 2 & 3 # python 2: print number, python 3: print(number, end="") numbers = range(100, 10, -2) # range to print in reverse order for number in numbers: sys.stdout.write("%d\t" % (...
m = int(input("введите целое число: ")) n = int(input("введите целое число: ")) p = int(input("введите целое число: ")) x = 0 if m < 0: x += 1 if n < 0: x += 1 if p < 0: x += 1 #print(f"Количество отрицательных чисел = {x}") print("Количество отрицательных чисел = ", x)
# encoding:utf-8 # 参考文献:贝叶斯优化调参 笔记前面这些链接,代码来自http://36kr.com/p/5114423.html import numpy as np import matplotlib.pyplot as plt x_obs = [-4,-2,0] # 初始值 训练数据 会变化 y_obs = [] # 初始值 训练数据 会变化 coefs = [6, -2.5, -2.4, -0.1, 0.2, 0.03] def f(x): total = 0 for exp, coef in enumerate(coefs): total += coef...
def evaluate(x,y,op): if op == "+": r = x + y elif op == "-": r = x - y elif op == "*": r = x * y elif op == "/": r = x / y return r
import math import par as par num = int(input('Digite um numero inteiro: ')) if (num%2) == 0: print('O numero é par!') else: print('O numero é impar')
nome = str(input('Qual é p seu nome? ')).title() if nome == 'Gustavo': print('Que nome bonito') elif nome == 'Paulo' or nome == 'Ana' or nome == 'João': print('Seu nome é bem popular no Brasil!') else: print('Seu nome é bem normal!') print('Tenha um bom dia {}!'.format(nome))
def notas(*num, sit=False): """ => Cria um dicionario com total de notas, maior nota, menor nota, média e situação :param num: recebe varias notas :param sit: recebe uma condição para exiber ou não a situação do aluno :return: retorna um dicionario """ media = sum(num) / len(num) aluno =...
from time import sleep def contador(): print('-=' * 20) print('Contagem de 1 até 10 de 1 em 1') for c in range(1, 11): sleep(0.5) print(c, end=' ') print('FIM', end=' ') print() print('-=' * 20) print('Contagem de 10 até 0 de 2 em 2') for c in range(10, -1, -2): ...
def voto(ano): from datetime import date i = date.today().year - ano if i < 16: return f'Com {i} anos: NÃO VOTA.' if 18 <= i < 65: return f'Com {i} anos: VOTO OBRIGATÓRIO.' if i >= 65: return f'Com {i} anos: VOTO OPCIONAL.' print('=-'*20) nasc = int(input('Em que ano você na...
lista = [] c = 1 while True: lista.append(int(input('Digite um número: '))) r = str(input('Quer continuar...[S/N]: ')) if r in 'Nn': break if 5 in lista: print('O número 5 esta na lista') else: print('O número 5 não esta na lista') print(f'Foram digitados {len(lista)} números') lista.sort(re...
n = float(input('Digita um número: ')) d = n * 2 t = n * 3 r = n ** 0.5 print('O dobro é {}, o triplo é {} e a raiz quadrata é {}'.format(d, t, r))
nome = str(input('Digite seu nome: ')).strip() print('Possui Silva no nome? {}'.format('SILVA' in nome.upper()))
print('-=-'*12) n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo número: ')) print('-=-'*12) print(''' MENU [1] - Somar [2] - Multiplicar [3] - Maior [4] - Novos números [5] - sair do progarma ''') opcao = int(input('Informe a opção desejada: ')) sair = False while not sair:
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite uma valor para [{l}], [{c}]: ')) print('=-'*25) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') print() print('=-'*25) soma = 0 for v, n ...
velo = float(input('Qual foi a velocidade do carro? ')) multa = (velo - 80) * 7 if velo > 80: print('Você foi multado, multa é de R${} reais'.format(multa))
from datetime import date date = date.today().year maior = 0 menor = 0 for c in range(1, 8): ano = int(input('{}ª ano de nascimento: '.format(c))) idade = date - ano if idade < 21: menor = menor + 1 else: maior = maior + 1 print('{} ainda não atingiram a maioridade'.format(menor)) pr...
def maximum(*numbers): largest = numbers[0] for x in numbers: if x > largest: largest = x return largest def main(): print(maximum(1, 3, 6, 200, 90)) if __name__ == "__main__": main()
class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # Instantiate the Cat Object with 3 cats cat1 = Cat('Garfield', 4) cat2 = Cat('Solly', 6) cat3 = Cat('Tom', 7) cats_ages = [cat1.age, cat2.age, cat3.age] oldest_age = max(cats_ages) print(f'The olde...
class Pets(): def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__(self, name, age): self.name = name self.age = age def walk(self): retur...
def generator_function(num): for i in range(num): yield i # yield only keeps the most recent data in memory, unlike lists which store all items # this makes it a lot faster for item in generator_function(1000): print(item) def gen2(num): for i in range(num): yield i * 2 # yield pauses...
# works on list, set, dictionaries my_list = [] for char in 'hello': my_list.append(char) print(my_list) my_list = [char for char in 'hello'] # same as above, for char in hello, add char to list # list 2 creates a list with numbers ranging from 0 to 99 my_list2 = [num for num in range(0, 100)] # for number in r...
#Amaris Efthimiou #amaris.efthimiou66@myhunter.cuny.edu #october 21, 2019 #Borough stats import matplotlib.pyplot as plt import pandas as pd pop = pd.read_csv('nycHistPop.csv',skiprows=5) b = input('Enter a borough:') print('Minimum Population:', pop[b].min()) print('Average Population:', pop[b].mean()) print('Maxi...
import csv with open('out.csv' ,'w') as outFile: fileWriter = csv.writer(outFile) with open('user.csv','r') as inFile: fileReader = csv.reader(inFile) for row in fileReader: fileWriter.writerow(row) with open('out.csv','r') as outFile: fileReader = csv.reader(outFile) for r...
import sqlite3 def create_db(): with sqlite3.connect('company.db3') as conn: # Создаем курсор - это специальный объект который делает запросы и получает их результаты cursor = conn.cursor() cursor.execute("""DROP table if exists Terminal""") cursor.execute("""DROP table if exists ...
# program to input angles of a triangle and check whether triangle is valid or not ang1 = int(input("Enter the degree of the first angle: ")) ang2 = int(input("Enter the degree of the second angle: ")) ang3 = int(input("Enter the degree of the third angle: ")) if ang1 + ang2 + ang3 == 180: print ("It is a Triangl...
# cook your dish here for t in range(int(input())): s=input() count=0 while (len(s)>1): if s[:2]=='xy'or s[:2]=='yx': s=s[2:] count+=1 else: s=s[1:] print(count)
#coding: utf-8 # Day 5 of month of API # Looking at local air quality data and what the last 24 hours have been like in your local area # Greg Jackson 05/12/15 gr3gario on twitter ang gregario on github import requests import json url = "http://api.erg.kcl.ac.uk/AirQuality/Data/SiteSpecies/SiteCode=IS2/SpeciesCode=N...
h = list(map(int, input().strip().split(' '))) word = input().strip() alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] dictionary = {} for i, j in enumerate(alphabet): dictionary[j] = h[i]...
def total(a=5, *numbers, **phonebook): print("a", a) for number in numbers: print("number", number) for key, value in phonebook.items(): print(key, value) print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.right(90) some_turtle.forward(100) def draw_art(): window = turtle.Screen() window.bgcolor("white") # create the turtle brad - Draws a Square brad = turtle.Turtle() brad.shape("turtle") brad.color("purple") brad.spee...
num1 = int(input("escribe un numero")) num2 = int(input("escribe otro numero")) total = 0 while num1 <= num2: total = total + num1 num1 += 1 print(f"El resultado es {total}")
# modulo de ejemplo def sumar(numero1, numero2): print(f"(módulo_mate_A): La suma es {numero1+numero2} ") def restar(numero1, numero2): print(f"(módulo_mate_A): La resta es {numero1-numero2} ")
num = int(input("elige un numero del 1 al 10")) numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] total = 0 for n in numeros: total = num*n print(f"{num} x {n} = {total}") n += 1 if n > 10: break
class clsCoche: def __init__(self, matricula, marca): self.matricula = matricula self.marca = marca self.kilometros_recorridos = 0 self.gasolina = 0 def suficiente(self, gasolina, kilometros): max_km = gasolina / 0.1 if kilometros <= max_km: return Tr...
lista = [6,14,11,3,2,1,15,19] def rango(num): if num < 21 and num > 0: print("Numero en rango") return True else: print("Numero fuera de rango") return False def enlista(num): for n in lista: if n == num: print("Numero en lista") num = int(input("Escrib...
# -*- coding: utf-8 -*- """ Created on Tue Mar 7 11:54:07 2017 @author: JM """ import math def media(x): media = 0 for score in x.values(): media += score return (media / len (x.values())) """ Recibe los items, usuarios que han puntuado los dos items y el conjunto de todos los usuarios """ def similarity(item...
#Problem 24 solution (part 1) #Given a tile (from input), it return its coordinates # using "Cube coordinates" def getTileCoordinates(tile): x,y,z = 0,0,0 while tile != '': if tile.startswith('e'): x += 1 y -= 1 tile = tile[1:] elif tile.startswith('w'): ...
import itertools #Problem 3 solution (part 1) def p3(fileName, slope): with open(fileName, 'r') as f: treeMap = [line.strip() for line in f] row, column = 0,0 numTrees = 0 numColumns = len(treeMap[row]) while row < len(treeMap)-1: row = row + slope[0] ...
# coding=utf-8 """ The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50...
""" Quick Sort """ def _partition(array: list, left, right): """ partition with last element as a pivot """ pivot = array[right] smaller = left - 1 for i in range(left, right): if array[i] <= pivot: smaller += 1 array[i], array[smaller] = array[smaller], array[...
""" Merge Sort """ def _merge(array, middle, left, right): left_len = middle - left+1 right_len = right - middle left_arr = [0]*left_len right_arr = [0]*right_len for g in range(0, left_len): left_arr[g] = array[left+g] for g in range(0, right_len): right_arr[g] = array[middl...
# coding=utf-8 """ Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. """ import unittest def lpstr(array): """ Longest Palindromic Substring. Dynamic Programming approach :param array: given strin...
planet_list = ["Mercury", "Mars"] print(planet_list) planet_list.append('Jupiter') print(planet_list) planet_list.append('Saturn') print(planet_list) planet_list.extend(['Neptune', 'Uranus']) print(planet_list) planet_list.append('Pluto') print(planet_list) rockey_planets = planet_list[slice(0, 2)] print('The Rockey P...
text = input('Text: ') # 0.0588 * L - 0.296 * S - 15.8 # creates all the necessary variables r = len(text) words, letters, sentence = len(text.split()), 0, 0 # look into each character in the string for i in range(r): if text[i].isalpha(): letters += 1 elif text[i] == '!' or text[i] == '?' or text[i]...
import random def end(enemy_health,your_health): if your_health > 0: print(" ") print("You slay the Enemy") print('Пошли') else: print(" ") print("You were slain...") print('Перезапустите игру') time.sleep(1000) def your_first(): enemy_health = 20 ...
from math import * class KalmanFilter: @staticmethod def gaussian_f(mu, sigma2, x): """ Gaussian likelihood with a mean and variance at input, `x` Args: mu: mean sigma2: variance x: Returns: (float) probability """ ...
def LowestPosInt(IntList): #Give the lowest possible positive int Lowest=1 #Sort the List SortedList = sorted(IntList) #For every value in the sorted list, if it is equivilent to the lowest value that means that the lowest value exist, so we should bump up the lowest value by 1 for i in SortedLi...
def gcd(a,b): if (b>a): if (a==0): return b return gcd(a, b%a) if (a>b): if (b==0): return a return gcd(b , a%b ) x = eval(input("Enter first number : ")) y = eval(input("Enter second number : ")) z = gcd(x , y) print("GCD of the numbers :...
from datetime import datetime import time as t currentTime = None while True: # time_stamp = t.time() # number of seconds since 1-1-1970 UTC time # current_time = datetime.fromtimestamp(time_stamp).strftime("%d-%B,%H:%M:%S") # print(current_time) current_date = datetime.now().strftime("%d-%B,%H:%M:%S") ...
""" ***** A/B-Tests ***** > are run on websites, where one segment of the users see the old website and another part the changed websites > then the impact on user behavior is measured > can be algorithmic, design, pricing changes, etc. > first, choose what you are trying to influence: times sold, speed, ad clicks...
""" ***** K-Nearest Neighbours ***** > you already have a scatterplot along any dimensions with classified data points > a new data point is classified by identifying its k nearest neighbours and then classify the data points depending on the class most of the k data points have """ """ ***** Dimensionalit...
import numpy as np def rotateImage(a): a=np.array(a) a=a.transpose() a=a.tolist() for i in range(0,len(a)): a[i].reverse() return a
dict1={} dict2={} x=int(input()) dict1[x]=int(input()) y=int(input()) dict2[y]=int(input()) print("First Dictionary") print(dict1) print("Second Dictionary") print(dict2) print("Concatenated dictionary is") dict3={} dict3.update(dict1) dict3.update(dict2) print(dict3) print("The Values of Dictionary") print(list(dict3....
n=int(input()) lst=list(map(int,input().split())) s=int(input()) import math lst_fact=[] for i in lst: lst_fact.append(math.factorial(i)) c=0 for i in range(n): if s==lst_fact[i]: print(lst[i]) c=1 break if c==0: print("Not found")
import random #modulo para generar valores aleatorios def busqueda_lineal(lista, objetivo): match = False for elemento in lista: #O(n) if elemento == objetivo: match = True break return match def main(): tamano_lista = int(input('De que tamaño será la lista: ')) objetivo = int(input('Numero a encontrar...
class Automovil: #super class def __init__(self, modelo, marca, color): self.modelo = modelo self.marca = marca self.color = color self._estado = 'en reposo' #variables privadas con "_variable" self._motor = None def __repr__(self): """Para muchos tipos, esta función intenta devolver una cadena que prod...
import enumeracion as en import busqueda_binaria as binbus import aproximacion as aprox objetive = int(input('Ingrese un número entero: ')) print("Escoja una de las siguientes opciones...") opcion = int(input('1- EE 2- BB 3-Aprox. :')) while opcion != 4: if opcion == 1: en.objetivo = objetive en.enumerar() ...
class Persona: def __init__(self, nombre): self.nombre = nombre def avanza(self): return 'Ando caminando' class Ciclista(Persona): def __init__(self, nombre): super().__init__(nombre) def avanza(self): return 'Ando en bici' class Motociclista(Persona): def __init__(self, nombre): super().__init__(no...
class Coordenada: def __init__(self, x, y): """Método constructor. self == this en JS """ self.x = x self.y = y def distancia (self, otra_coordenada): """Cada función dentro de una clase se llama "método" Calculamos con método euclidiano """ x_diff = (self.x - otra_coordenada.x)**2 y_diff = ...
""" Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. """ class Solution: def backspaceCompare(self, S: str, T: str) -> bool: stackS = [] stackT = [] for ch in S: if ch == '#': ...
""" https://leetcode.com/problems/search-a-2d-matrix/ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. """ class ...
""" https://leetcode.com/problems/single-element-in-a-sorted-array/ You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. """ class Solution: def singleNonDuplicate(sel...
# https://leetcode.com/problems/unique-binary-search-trees/ # Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? class Solution: def numTrees(self, n: int) -> int: self.d = {1:1,0:0} def bst(n): if n in self.d: ret...
""" https://leetcode.com/problems/odd-even-linked-list/ Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nod...
""" https://leetcode.com/problems/01-matrix/ Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. """ class Solution: def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix or not matrix[0]:...
""" https://leetcode.com/problems/power-of-two/ Given an integer, write a function to determine if it is a power of two. """ class Solution: def isPowerOfTwo(self, n: int) -> bool: if n <= 0: return False x = math.log10(n) / math.log10(2) return x.is_integer()
""" Write a program to find the node at which the intersection of two singly linked lists begins. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked s...
# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ # Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). # Definition for a binary tree node. # class TreeNode: # def __i...
""" https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. No...
""" https://leetcode.com/problems/ransom-note/ Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can o...
# https://leetcode.com/problems/power-of-four/ # Given an integer (signed 32 bits), write a function to check whether it is a power of 4. class Solution: def isPowerOfFour(self, num: int) -> bool: if num < 1: return False return log(num, 4).is_integer()
""" https://leetcode.com/problems/largest-divisible-subset/ Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. """ class Solution: def large...
""" https://leetcode.com/problems/jump-game/ Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Output:...
""" https://leetcode.com/problems/bitwise-and-of-numbers-range/ Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. """ class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: if m == 0 or m == n: return m ...
""" Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displa...
""" https://leetcode.com/problems/linked-list-cycle-ii/ Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1...
""" https://leetcode.com/problems/sort-colors/ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectiv...
# https://leetcode.com/problems/robot-bounded-in-circle/ # On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: # "G": go straight 1 unit; # "L": turn 90 degrees to the left; # "R": turn 90 degress to the right. # The robot performs the instru...
# https://leetcode.com/problems/number-of-recent-calls/ # You have a RecentCounter class which counts the number of recent requests within a certain time frame. # Implement the RecentCounter class: # RecentCounter() Initializes the counter with zero recent requests. # int ping(int t) Adds a new request at time t...
""" https://leetcode.com/problems/subsets/ Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. """ class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: result = [[]] arr = [] ...
# https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ # Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 1...
def grade(num, rank): import math n = math.ceil(rank / (num / 10)) if(n == 1): return "A+" elif(n == 2): return "A0" elif(n == 3): return "A-" elif(n == 4): return "B+" elif(n == 5): return "B0" elif(n == 6): return "B-" elif(n == 7): ...
import random class Poketmon(): def __init__(self, name, lv): self.name = name self.lv = lv self.hp = random.randint(100,150) * lv self.power = random.randint(1,5) * lv self.speed = random.randint(1,4) * lv def fight(self, enemy): for i in range(1...
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): sub = "th" # the sub string, t...
# Exercise 1 def get_list(L): return L # Exercise 2.1 def get_sum_of_elements_in_list_with_for_loop(L): sum = 0 for k in range(len(L)): sum = sum + L[k] return sum # Exercise 2.2 def get_sum_of_elements_in_list_with_while_loop(L): sum = 0 i = 0 while i < len(L): sum += L[i]...
# 3. Longest Substring Without Repeating Characters # Given a string, find the length of the longest substring without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", wi...
# Vanessa Koelling, August 11th, 2017. This document contains some notes and code examples in Python 3 from "Python for Biologists". # Chapter 6 notes # conditional tests print(3 == 5) print(3 > 5) print(3 <= 5) print(len("ATGC") > 5) print("GAATTC".count("T") > 1) print("ATGCTT".startswith("ATG")) print("ATGCTT".end...
# Vanessa Koelling, August 11th, 2017. # Chapter 6, exercise 4: complex condition input_file = open("/Users/vkoelling/Desktop/Python_practice_files/Python_for_Biologists_exercises_and_examples/Chapter_6/exercises/data.csv") for row in input_file: new_row = row.rstrip("\n").split(",") species = new_row[0] sequence ...
# Vanessa Koelling, August 9th, 2017. # Ch. 4 exercise 2: Multiple exons from genomic DNA # open the genomic DNA file genomic_dna = open("/Users/vkoelling/Desktop/Python_practice_files/Python_for_Biologists_exercises_and_examples/Chapter_4/exercises/genomic_dna.txt") # read the contents of the file into a new variabl...
#encoding=utf-8 #!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associate...
#creates folder for each file specified as second argument #the folder has the same name of the file, but has no extension and the first letter is lower import subprocess import sys argvalues = sys.argv if(len(argvalues) > 1): directory=sys.argv[1] if(directory[len(directory)-1] != '/'): directory+='/' else: ...