text
stringlengths
37
1.41M
#jogo de advinhar o numero do pc, porem, tentar de novo ate acertar aquele numero pensado from random import randint from time import sleep pc = randint(0, 10) # faz o computador sortear print('-=-' * 20) print('Vou pensar em um numero entre 0 e 10. Tente advinhar!') print('-=-' * 20) pl = int(input('Em que numero est...
# Time: O(n) # Space: O(1) # # Given a non-negative number represented as an array of digits, plus one to the number. # # The digits are stored such that the most significant digit is at the head of the list. class Solution: """ :type digits: List[int] :rtype: List[int] """ def plusOne(self, dig...
from random import randint class Matrix: def __init__(self, data_list, m=0, n=0): if not isinstance(data_list, list): raise ValueError('Not list in arguments') if not(isinstance(m, int) and isinstance(n, int)): raise ValueError('M*N not integer in arguments')...
# -*- coding: utf-8 -*- """ Created on Sun Nov 29 12:53:18 2020 @author: Ian """ import pandas as pd df = pd.read_csv('C:/Users/Ian/Desktop/Twitter Ids/dict.csv', index_col=False) df = df[['follower_id']] print("df lenght:", len(df['follower_id'])) df = df.drop_duplicates(subset=['follower_id']) #remov...
import os import pygame pygame.init() class Button(): #the class for my buttons def __init__(self, pos, color, size, text, text_size): self.pos = pos self.size = size self.color = color self.text = text self.text_size = text_size def dra...
#!/usr/bin/env python # coding: utf-8 # In[1]: p = open("//Users/vinayreddymeka/Desktop/example.txt", 'r') # opens text file from user defined location j = p.read() # reads the file i = j.split() # converts the string into the list i= [element.upper() for element in i] ; i # converts all lower case to uypper case p...
def greatestOfTwoNumbers(a,b): """ Function to find the greatest of 2 numbers """ if(a>b): print("a",a, "is the greatest") else: print("b :",b," is the greatest") greatestOfTwoNumbers(1,4) ctr=222 def incCounter(): ctr=0 print("Ctr before increment",ctr) ctr=ctr+1 ...
# All basic usage of numpy import numpy as np # prints the version of numpy print(np.__version__) # Whether element is a numpy array el = np.array(list()) # Below command resolves to true if isinstance(el, np.ndarray): print("Element is a numpy array.") array1 = np.array([1, 2, 3, 4]) # It performs element wise o...
# if else elseif ticket_status="Confirmed" luggage_weight=32 weight_limit=30 #Weight limit for the airline extra_luggage_charge=0 if(ticket_status=="Confirmed"): if(luggage_weight>0 and luggage_weight<=weight_limit): print("Check-in cleared") elif(luggage_weight<=(weight_limit+10)): extra_lugga...
temperature = int(input('Enter a temperature in Celcius\n>>>')) if temperature >= 50: print('Too hot! try not to go out!') elif temperature > 30: print('You\'ll be needing shorts today!') elif temperature <= 30 and temperature > 20: print('It\'s warm but not shorts weather!') elif temperature <= 20 and temp...
total = 0 data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] for num in data: total = total + num print('The sum of the data is', total)
# Date: 22/12/19 # This is a secret number guessing game import random print('Hello! What is your name?') Name = input() secretNumber = random.randint(1, 20) print('Lets play a secret number game shall we?') print('Well ' + Name + ' I am thinking of a number between 1 and 10') for gussesTaken in range(1, 6): pri...
findMax = 0 data = [10, 123, 1224324, 54645, 4564567, 879789, 67, 1] for num in data: if num > findMax: findMax = num print('The highest value of', data, 'is', findMax)
num_1 = int(input('Enter the first number\n>>>')) num_2 = int(input('Enter the second number\n>>>')) print('The product of ', num_1, 'and', num_2, 'is', num_1 * num_2)
#논리연산자 a = 20 b = 30 print(not a > b) print(a < b and a != b) print(a == b or a > b) #True -> 1, False -> 0 print(True+1) print((a>b)+1) #캐스팅 b = bool(10) print(b, type(b)) print(bool(None))
# 다른 언어에서처럼 소수점을 포함하거나 e나 E로 지수로 표현할 수 있다. a = 1.2 print(type(a)) print(isinstance(a, float)) print(a.is_integer()) b = 3e3 print(b) c = -0.2e-4 print(c) # is_integer() 는 값이 정수 인지만 판단한다. b = 3.0 print(b.is_integer())
# Problem Set 2, hangman.py # Name: # Collaborators: # Time spent: # Hangman Game # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string WORDLIST_FILEN...
""" GradientGenerator Generate a gradient between two color points By Dylan Hamer """ def rgbToHex(r, g, b): """Convert RGB to six digit hex""" if r <= 255 and g <= 255 and b <= 255: colorHex = "#%02x%02x%02x" % (r, g, b) else: raise ValueError("Values can not be more than 255") return ...
# Accepts a list and checks if the content og the list is lists # eg: [[1],[2]] - True # eg: [[2], 4]] - Flase my_list = [[1], [2]] def list_check(list1): l = all(isinstance(ellement, list) for ellement in list1) print(l) list_check(my_list)
import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from perceptron import Perceptron #from pr import Perceptron ''' Here we make our training data using Sklearn library The function make_blobs() makes training data n_samples = no. of ...
#!/usr/bin/env python3 """ Alex Kendal * * A program that reads a transcript and outputs a count * * of how many words each person mentioned within the * * script says. * """ import argparse import sys """ clear_special_characters: Function takes in a string ...
import pygame import json import content import camera TILE = {} class Tile(pygame.sprite.Sprite, camera.View): def __init__(self, group, pos, size, name, image, walk): super(Tile, self).__init__(group) self.name = name self.image = image #The image the tile has self....
#declearing f vatiable f =0 # Global vs. local variables in functions def someFuction(): global f f="def" print(f) someFuction() print(f) del f #delete f #with out global f this will print "0" and "def" #with global f this will print "def" and "def"
import numpy import string import random print("### Please use Integer values, and strings only.") char_list = ["Word: "] def find_word(): # obtain word, checking word length, testing whether it needs a random extra character. global word word ...
balance = 4842 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 t=0 for i in range (12): print "Month:", print i+1 p = monthlyPaymentRate * balance print "Minimum monthly payment:", print ("%.2f" % p) balance = (balance - p)*(1 + annualInterestRate/12) print "Remaining ...
# edges表示邻接矩阵 edges = [[0, 1, 12, -1, -1, -1], [-1, 0, 9, 3, -1, -1], [-1, -1, 0, -1, 5, -1], [-1, -1, 4, 0, 13, 15], [-1, -1, -1, -1, 0, 4], [-1, -1, -1, -1, -1, 0]] dis = {2: 1, 3: 12, 4: -1, 5: -1, 6: -1} visited = [] def dijkstra(): min_dis = float("inf") min_p...
""" Read a .txt file and count the occurrence of a keyword """ def main(): filename = 'log-20200611.txt' keyword = "SELECT" file = open(filename) # read content of file to string data = file.read() # get number of occurrences of the substring in the string occurrences = data.count(keyword...
''' Tic Tac Toe 1.0 Developed by Sean Kaczanowski No Copyright May 2020 Functional Tic Tac Toe Game - Still in development! - One or Two Player Mode - Gameboard Graphics with Xs and Os - Function to determine if win outcome is met - Computer Player Artificial Intelligence Known Bugs - Win does not terminate getatt...
# Word count by iterating through a string until you reach end of string # Every iteration should stop at whitespace which counts all the text before # the whitespace as a word def wc(s): # Use the split function # split splits the string into a list of iterables # with space as the delimiter (turns string...
class Node: def __init__(self,value,previous=None,next=None): self.value = value self.next = next self.previous = previous class DoublyLinkedList: def __init__(self,value,next=None,previous=None): self.head = Node(value=value) self.tail = self.head self.length...
with open('test.txt', 'w') as f: #must use 'w', if the txt file does not exist, then created f.write('Hello, World!') with open('test.txt') as f: p1 = f.read(5) print(p1) #print 'Hello' p2 = f.read() print(p2) #print ', World!' #with can replace open(), close()
#============ Implement stack Using List =============== #1 we can implement stack using list #2 we can implement stack using modules #When we using list as stacks: # for push ---> append # for pop ---> pop # Example: Here Operation is performed in LIFO ''' stack = [] # creating a blank list stack.append(10) print...
# ====== Queue Implementation Using List =============== ''' Implement queue in two ways 1 - list 2 - Modules ''' # Queue Work in first in first out method. # Enqueue : process of adding elements to queue. # Dequeue : process of removing the element from the queue. ''' Enqueue --> append method Dequeue --> pop me...
#========== Trying To make complete binary tree with all operations ========== # =========== I will do it later ================ class Node: # we make this class to create node of tree def __init__(self,key): # this function is a constructor of class Node.(key-->data) self.key = key self.left_ch...
#============= LinkedList Implementation of Queue ============ # ====== So here we make linkedlist class ===== # and we just show linked list is behaving like queue. class Node: def __init__(self,data): self.data = data self.next = None class Linkedlist_queue: def __init__(self): s...
#=========== Infix to Prefix ========= class Stack(): def __init__(self,n): self.stack = [] self.size = n self.top = None def push(self,data): if len(self.stack) == self.size: print("Stack Overflow") else: self.stack.append(data) s...
#======== Catalan Numbers Application ======== ''' Catalan numbers are a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. ''' #======= Code for find nth Catalan Number ========= def nth_Catalan(n): result = 0 if n <= 1: return 1 ...
# ======= 7 Best Problems on Recursion ======= #Problem: ''' Reverse a string using recursion ''' # str ="imawsog jaknap" ''' def Reverse_str(str,i): if i == len(str): return else: Reverse_str(str,i+1) print(str[i],end ="") return Reverse_str(str,0) # pr...
#========== Problems which are asked in Top MNC's ============ # Problem : ''' First Repeating elements: input -> 1,5,3,4,3,5,6 output -> 2 Explanantion-> 5 is apprearing twice and its first appearance is at index 2 which is less than 3 whose first occurring index is 3. ''' ''' a = [2,2,3,4,3,5,6] j = 0 while(j<l...
#============ Heap Introduction======= ''' it is basically a complete binary tree: we have 2 heaps Max heap: Root > rest of the elements present in its subtree and it apply on every node. Min heap: Root < rest of the elements present in its subtree and it apply on every node. ''' # How to Convert an array into a ...
#===== Lowest common Ancestor(LCA) pf two given values in Binary Tree =============== class Node: def __init__(self,data): self.data = data self.lchild = None self.rchild = None def preorder(node): print(node.data,end = " ") if node.lchild: preorder(node.lchild) if nod...
# ============= Detection and Removal of cycle in linked list ============ ''' Floyed's Algorithem OR Hare and Tottoise Algorithm ''' class Node: def __init__(self,data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None def print_LL(se...
# ========= Here we solve Problems related to linked list ========== #========== Append last k nodes to start of linked list ============== class Node: def __init__(self,data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None def print_...
#kh The function to test if score is above 100 using if/else def testScore(x): if (x > 100): print("High") else: print("Low") #kh test testScore() function with 3 inputs in main def main(): testScore(120) testScore(100) testScore(90) #kh Call the main() main()
import csv import os #get relative file path csv_path = os.path.join("Resources", "budget_data.csv") #initialize two list to pick up the data in each column month = [] profit = [] # open csv file, read the data and store in variable and list with open (csv_path, "r", newline="") as csv_file: csv_reader = cs...
### 5-8. Hello Admin: Make a list of five or more # usernames, including the name 'admin'. Imagine you # are writing code that will print a greeting to each user # after they log in to a website. Loop through the list, #and print a greeting to each user: # • If the username is 'admin', print a special greeting, # such ...
# 10-4. Guest Book: Write a while loop that prompts users for their # name. When they enter their name, print a greeting to the screen # and add a line recording their visit in a file called guest_book.txt. # Make sure each entry appears on a new line in the file. filename = "guest_book.txt" while True: name = in...
### 6-10. Favorite Numbers: Modify your program from # Exercise 6-2 (page 102) so each person can have more # than one favorite number. Then print each person’s # name along with their favorite numbers. names_and_numbers = { 'alice': [8, 22, 43, 24,], 'bob': [2, 13, 46, 77,], 'carl': [3, 11,], 'dave':...
# 8-7. Album: Write a function called make_album() that # builds a dictionary describing a music album. # The function should take in an artist name and an # album title, and it should return a dictionary containing # these two pieces of information. Use the function to make # three dictionaries representing different ...
### 7-9. No Pastrami: Using the list sandwich_orders # from Exercise 7-8, make sure the sandwich # 'pastrami' appears in the list at least three times. # Add code near the beginning of your program to print # a message saying the deli has run out of pastrami, # and then use a while loop to remove all occurrences of # '...
### 7-5. Movie Tickets: A movie theater charges different # ticket prices depending on a person’s age. If a person # is under the age of 3, the ticket is free; if they are # between 3 and 12, the ticket is $10; and if they are # over age 12, the ticket is $15. Write a loop in which # you ask users their age, and then t...
# 9-6. Ice Cream Stand: An ice cream stand is a specific kind of # restaurant. Write a class called IceCreamStand that inherits # from the Restaurant class you wrote in Exercise 9-1 (page 166) # or Exercise 9-4 (page 171). Either version of the class will # work; just pick the one you like better. Add an attribute call...
name_is_a_very_long_name = "Tom" def add(a,b): return a+b class index(): def sub(self,a,b): return a-b print(name_is_a_very_long_name) print(add(1, 4)) i=index() print(i.sub(4, 2))
#!/usr/local/bin/python3 # # arrange_pichus.py : arrange agents on a grid, avoiding conflicts # # Submitted by : CHAITANYA SHEKHAR DESHPANDE, cdeshpa # # Based on skeleton code in CSCI B551, Spring 2021 # import sys # Parse the map from a given filename def parse_map(filename): with open(filename, "r") as f: retu...
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def smallest_no_rem(limitNum): numToTest = limitNum #has to be larger than our limit for i in (range(2, limi...
import requests import re class Mapper: """ This is just a simple class to separate out some of the functionality of the google maps api.Although it is possible to make the api call directly from the client side, a server side call avoids having to expose the api keys in the html page. """...
"""Various methods for manipulating/formatting names. """ from __future__ import absolute_import, division, print_function # Names can be rendered in different formats FMT_SURNAME_FIRST = 0x1 # Smith Jane FMT_COMMA = 0x2 # Smith, Jane -- only if surname is first FMT_MAIDEN = 0x4 # Jane Smith (Sawyer) -- maiden n...
import math print("\n") print("let first column be its name of your data.(include in number of column)") num_column_data=input("enter number of columns in your dataset:") num_rows_data=input("enter number of rows(tuples) in your dataset:") data=[] for i in range(0,num_rows_data): data.append([]) for j in range(0,num...
''' This file preprocesses the data. ''' def removesStressPhonemes(speech): ''' Removes stress and phoneme markers. Stress markers are '0-9', and primary stress markers are '1' ''' result = "" for line in speech: #removes stress and phonemes result += line.replace("1", "").replace("0", "").replace("2", "")....
#first_name = 'Moses' #last_name = 'Mwangi' first_name = input('Please enter your First name: ') last_name = input('Please enter your Last name: ') print('This is just outputting a string') print(first_name + ' '+ last_name) print('') print('This is just outputting a string but capitalizing the fist letter using the ...
cars = 100 space_in_a_car = 4 drivers = 30 passengers = 90 cars_not_driven = 0 #assuming for now that there will be no cars not drinen cars_driven = cars #assuming for now that all cars will be drinen drivers_not_in_cars = drivers ...
"""Provides a StateMachine class, subclass and define transitions to use class MyStateMachine(StateMachine): transitions = { "initial": { "success": "accepted", "fail": "denied" }, "accepted": {"fail": "denied"} } # To define callbacks for transitions use: @MyS...
import matplotlib.pyplot as plt import numpy as np import pandas as pd def plotBars(y1, y2, y3): # importing package import matplotlib.pyplot as plt import numpy as np # create data x = np.arange(4) width = 0.2 # plot data in grouped manner of bar type plt.bar(x - 0.2, y1, width, colo...
"""Top-level implementation of Micro Panel screens. Each screen consists of a set of data that can be shown to the user, can be updated through events from OctoPrint's main event system, and can react to user interaction through button presses. Screens must implement the `draw()` method at a minimum, but can implement...
a = int(input()) if 0 <= a <= 7: print ('Ночь') elif 7 < a <= 11: print ('Утро') elif 12 <= a < 17: print ('День') elif 17 <= a <= 23: print ('Вечер') else: print('Ярык, будь человеком, нет такого часа!')
# -*- coding: utf-8 -*- """ Created on Sat Nov 4 13:10:53 2017 @author: Fabian """ class ABBADiv1(object): def canObtain(self,initial,target): stringinitial = initial stringtarget = target #check if initial in target or reversed Stack = [stringinitial] if (st...
""" .. module:: QCollection QCollection ****** :Description: QCollection Collection of questions :Authors: javier :Version: :Date: 30/07/2014 """ __author__ = 'javier' from Question import Question import json import random from Quiz import Quiz class QCollection: """ Collection of multiple ch...
import turtle import random import math import time def drawCircle(pen, colorFill, size, x, y): pen.penup() pen.color(colorFill) pen.fillcolor(colorFill) pen.goto(x,y) pen.begin_fill() pen.circle(size) pen.end_fill() pen.pendown() def drawTarget(pen): drawCircle(pen, "#000000", 152, 0,-152) dr...
# Definition of functions for the calculation of the various statistical estimates in section "Descriptive Statistics" def genMean(x, m): """ Calculation of a generalized mean """ S = 0 for value in x: mean = value**m S += mean mean_x = (1./len(x) * S)**(1./m) return mean_x ##...
def hanoi(n, src, dst, mid): global count; if n == 1: print("{}:{}->{}".format(n, src, dst)) count += 1 else: hanoi(n-1, src, mid, dst) print("{}:{}->{}".format(n, src, mid, dst)) count +=1 hanoi(n-1, mid, dst, src) count = 0; num = 3 hanoi(num, "A","C","B") p...
""" The aim of the simulation is to be able to determine the initial energy of the e- by analizing the trajectory of the scattering using NN Index to follow: 1. Introduction to e- 2. Multiple scattering through small angles 3. Results obtained by the simulations of the e- scattering in Xenon 4. Results...
import numpy as np import time import Utils class Versus(): def __init__(self, player1, player2, game, show = False): self.player1 = player1 self.player2 = player2 self.game = game self.show = show def play_game(self): players = [0, self.player1, self.player2] ...
# import modules import os import csv # Make data file into variable # filepath = 'Resources/budget_data.csv' budget_data = os.path.join('Resources', 'budget_data.csv') # make empty variables totalMonths = 0 monthlyProfits = [] monthlyChange = [] monthYear = [] greatest = 0 least = 0 # open csv file, analyse data u...
# import csv module import csv # Setting up variables numOfVotes = 0 winner = '' # Setting up dictionary voteCount = {} # Opens input csv file and reads data row by row with open('election_data.csv') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') next(csvreader) for row in csvreader: ...
#!/usr/bin/python # -*- coding: utf-8 -*- # database.py _metaclass_ = type class User: def setName(self, name): self.name = name def hi(self): print "hello ,I'm %s. " % self.name user = User() user.setName("Chenwei") user.hi()
def leap(): running=True while running: y=input('root!leapyear!:请输入年份:') if y=='<<': break elif not y.isdigit(): print("请输入数字年份,如‘1994’。") else: year=int(y) if year%4==0 and year%100!=0 or year%400==0: ...
from sys import argv # scritpName, first, sec = argv # print('here is argv', argv) # print('this is script name', scritpName) # print('Here is first',first,'sec is' ,sec) # def func(a, b): # c = a + b # return c # print('chunchun is smart') # if __name__ == "__main__": # ans = func(1, 2) # print(an...
#Функция приведения вводимого значения к числовому (FLOAT), на входе число, на выходе float def digitalize_prompt(num): if num.isdigit(): return float(num) else: try: float(num) return float(num) except ValueError: print('Неверно введено число') ...
# # Author: Wouter Coppieters # # 1. Brackets # # Determine whether a given string of parentheses is properly nested. # Task description # A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: # S is empty; # S has the form "(U)" or "[U]" or "{U}" where U...
### move zero def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ lastzerofound = 0 for i in range(len(nums)): if nums[i]!=0: # found none zero # exchange the positio...
import csv, cs50, sys str = [] string = "" dna_list = [] dna_temp = "" y_list = [] # Opening files for initial read try: with open(sys.argv[1],"r", newline =None) as STR_table: first_line = STR_table.readline() with open(sys.argv[2],"r") as dna_seq: dna = dna_seq.read() except: print("Usa...
n=100 sum=0 counter=1 while counter<=n: sum+=counter counter+=1 print('1到 %d 之和为: %d'%(n,sum)) num=1 #while num==1: # num2=int(input("输入一个数字:")) # print('你输入的数字是:',num2) print("666") count=0 while count<5: print(count,'小于5') count=count+1 else: print(count,'>或=5') languages = ["C", "C++",...
import sys '''while True: try: #x=int(input('输入个数字')) break except ValueError: print('输入有误') try: f=open('myfile.txt') s=f.readline() i=int(s.strip()) except OSError as err: print('os error:{}'.format(err)) print("unknow error:",sys.exc_info()) except ValueError: ...
# help(max.__doc__) # !/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 miles = 1000.0 name = "runoob" print(counter) print(miles) print(name) a = b = c = 1 # 以上实例,创建一个整型对象,值为1,三个变量被分配到相同的内存空间上。 # 您也可以为多个对象指定多个变量。例如: a, b, c = 1, 2, "runoob" a, b, c, d = 20, 5.5, True, 4 + 3j print(type(a), type(b), type(c)...
# Pentagon numbers limit = 10000 pentagon = [n*(3*n-1)/2 for n in range(limit)] pentagon_set = set(pentagon) def check(p1, p2): if p1 + p2 not in pentagon_set: return False if p1 - p2 not in pentagon_set: return False return True candidate = [] for i1 in range(1,limit): for i2 in rang...
# Largest product in a grid number = open("data/11.txt").read() number = number.split("\n") number = [row.split() for row in number] number = [map(int, row) for row in number] max_multiple = 0 p = 4 m = len(number) n = len(number[0]) # horizontal for i in range(m): for j in range(n-p): c = 1 for...
# Triangular, pentagonal, and hexagonal def T(): n = 0 while True: n += 1 yield n*(n+1)/2 def P(): n = 0 while True: n += 1 yield n*(3*n-1)/2 def H(): n = 0 while True: n += 1 yield n*(2*n-1) tg, pg, hg = T(), P(), H() t, p, h = tg.next(), pg.n...
# Coin sums import numpy as np coins = [1, 2, 5, 10, 20, 50, 100, 200] target = 200 method = [0]*(target+1) method[0] = 1 #for coin in coins: for coin in coins: for i in range(coin, target+1): method[i] += method[i - coin] print method[target]
# Digit factorials from math import factorial f = [factorial(i) for i in range(10)] def check(n): digit = map(int, str(n)) sum_f = sum(f[d] for d in digit) if n == sum_f: return True else: return False candidate = [] limit= f[9] * 7 for i in range(3,limit): if check(i): ca...
# Coded triangle numbers import string words = open("data/42.txt").read() words = words.split(",") words = [w.strip("\"") for w in words] limit = max(map(len, words)) * 26 triangle = [i*(i+1)/2 for i in range(1, 30)] triangle_set = set(triangle) d = {x:i+1 for i,x in enumerate(string.uppercase)} def check(word): ...
# Largest palindrome product def check_palindrome(n): n = str(n) half_length = len(n)/2 for i in range(half_length): if n[i] != n[-i-1]: return False return True max_palindrome = 0 for i in range(999,99,-1): for j in range(999,99,-1): n = i*j if n > max_palindro...
import copy # Dictionaries store mappings empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} # Deep cope dictionary copy_dic = copy.deepcopy(filled_dict) # Note keys for dictionaries have to be immutable types. This is to ensure that # the key can be converted to a consta...
def palindrome(s: str): i = 0 j = len(s) - 1 while i <= j: if s[i] == s[j]: i += 1 j -= 1 else: return False return True print(palindrome("abba")) print(palindrome("abbaa"))
# You have numbers 3 # => 3 # Math is what you would expect 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 # Except division which returns floats, real numbers, by default 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on...
#!/usr/bin/python import sys # dicionarios servidor = {'nome':'DNS', 'vcpus': 4, 'memoria': 2048, 'disco': [{'vda':'50G'},{'vdb':'50G'}] } for letra in 'python': if letra == 'h': print 'letra H encontrada' # matrizes matriz = [[1, 2, 3, 4], [5, ...
import unittest import day13 EXAMPLE = ("Alice would gain 54 happiness units by sitting next to Bob.", "Alice would lose 79 happiness units by sitting next to Carol.", "Alice would lose 2 happiness units by sitting next to David.", "Bob would gain 83 happiness units by sitting next to Alice.", "Bob would lose 7 happin...
dupe_letters = ("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm", "nn", "oo", "pp", "qq", "rr", "ss", "tt", "uu", "vv", "ww", "xx", "yy", "zz") naughty_letters = ("ab", "cd", "pq", "xy") vowels = ("a", "e", "i", "o", "u") NAUGHTY = "naughty" NICE = "nice...
import itertools GUESTS = ("Alice", "Bob", "Carol", "David", "Eric", "Frank", "George", "Mallory", "Me") #David would gain 75 happiness units by sitting next to George. def parse_line(line): tokens = line.strip()[:-1].split(" ") guest1 = tokens[0] verb = tokens[2] amount = int(tokens[3]) guest2 = ...
#Sue 367: children: 4, vizslas: 5, akitas: 4 SUE_DATA = { "children": 3, "cats": 7, "samoyeds": 2, "pomeranians": 3, "akitas": 0, "vizslas": 0, "goldfish": 5, "trees": 3, "cars": 2, "perfumes": 1 } def parse_line(line): line = line.strip() tokens = line.split(" ") ...
#body.py: Body class for gravitational simulation from codinglib import * class Body: def __init__(self, mass, x, y, vx, vy, pixel_radius, r, g, b): #initializes a Body object (9 lines) self.mass = mass self.x = x self.y = y self.vx = vx self.vy = vy self.p...