text
stringlengths
37
1.41M
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example: "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Return 0 / 1 ( 0 for false, 1 for true ) for this problem ''' class Solution: # @param A : string # @...
''' Write a function that takes an unsigned integer and returns the number of 1 bits it has. Example: The 32-bit integer 11 has binary representation 00000000000000000000000000001011 so the function should return 3. Note that since Java does not have unsigned int, use long for Java ''' class Solution: # @param ...
x=int(raw_input('enter the number to add')) y=int(raw_input('enter the number to add')) def add(): sum=x+y print sum add()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: eman-saeed """ #CNN #Part -1 -Building the CNN """ - A convolutional neural network is just a artificial neural network , in which you use this convolution trick to add some convolutional layers. - we make the convolution trick to preserve the special struc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 29 20:04:24 2020 @author: eman-saeed """ #importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataset dataset = pd.read_csv('Ads_CTR_Optimisation.csv') """ #Implementation of random select...
''' Reto #8 “Divide la cuenta” Instrucciones: vas con tus amigos a tu restaurante favorito y acuerdan dividir la cuenta. Para facilitar las cosa pedirás al usuario que indique el total a pagar, entre cuantas personas se dvidirá la cuenta, porcentaje de propina a incluir, un porcentaje de impuestos, total a pagar inc...
def decimals(n1, n2): return n1 * n2 def main(): n1 = float(input("Enter the first number with decimals: ")) n2 = float(input("Enter the second number with decimals: ")) print(decimals(n1, n2)) if __name__ == '__main__': main()
from math import pi, sqrt def triangleArea(base, height): return (base * height) / 2 def squareArea(side): return side**2 def pentagonArea(p, a): return (p * a)/2 def rectangleArea(base, height): return base * height def circleArea(radius): return pi * (radius**2) def menu(): print("1. Ca...
def multiplyDecimals(n1, n2): result = round(n1*n2, 4) return result def main(): n1 = float(input("Enter the first number with decimals: ")) n2 = float(input("Enter the second number with decimals: ")) print(multiplyDecimals(n1, n2)) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 13 09:32:50 2017 @author: sunt@mit.edu """ # 1_ps2 1C # Name: Tuo Sun # Collaborators: none # Time Spent: 0:45 # Late Days Used: 0 "initialize information" # initial_deposit initial_deposit = float(input("Enter the initial deposit: ")) "default...
# Problem Set 2, hangman.py # Name: Tuo Sun # Collaborators: None # Time spent: 3 # 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 ...
def part_b(annual_salary, portion_saved, total_cost, semi_annual_raise): "default information" #the portion of the cost needed for a down payment portion_down_payment = 0.18 #start with a current savings of $0 current_savings = 0 #an annual return rate r = 0.03 #the number of months required months = 1 ...
theBoard = {'1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9'}; def boardPrinter(board): print(board['1'] + '|' + board['2'] + '|' + board['3']); print('-+-+-'); print(board['4'] + '|' + board['5'] + '|' + board['6']); print('-+-+-'); p...
#!/usr/bin/env python # 爬楼梯 class Solution: def climbStairs(self, n: int) -> int: if n == 1: return 1 if n == 2: return 2 dp = [1] * (n+1) dp[2] = 2 for i in range(3, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] # 位1的个数 class Solution: def hammingWeight(self, n: int) -> in...
n = input("enter the no of student:") student = [] for i in range(0,n): roll_no=input("enter the roll no") name=input("enter the name") stud_class=input("enter the class") dict={'roll_no':roll_no,'name':name,'class':stud_class}
## HW 2: Build a piece of software for a financial institution to model one of their clients' portfolios. # Jeong # A portfolio can consist of 3 types of items: # 1. Cash # 2. Stock # 3. Mutual Funds # + Bonds import random # import random library to use random.uniform() class Portfolio(): def __init__(self): # In...
# -*- coding: utf-8 -*- """ Created on Sat Mar 8 18:09:47 2014 @authors: Sidd Singal James Jang Filippos Lymperopoulos Software Design Homework 6: Video Game Floppy Paul For our Software Design Homework 6 Assignment, we made a knockoff of Flappy Bird, except we replaced the bird in the game with Paul's face. The p...
""" Demonstration of Python Scientific computing. Uses Newton Raphson's method as a vehicle. """ import matplotlib.pyplot as plt import scipy as sp def myfunc(x): """ Generic function. Parameters ---------- x: float or array_like The value or array at which to calculate the function ...
from collections import deque def solution(queue1, queue2): answer = 0 q1, q2 = deque(queue1), deque(queue2) tot1, tot2 = sum(q1), sum(q2) total = tot1 + tot2 limit = len(q1) * 3 if total % 2 != 0: return -1 while(True): if tot1 > tot2: target = q1.poplef...
n=int(input()) for i in range(1,6): p=i*n print(p,end=' ')
q=int(input()) d=0 i=[] for u in range(q): i.append(input()) for u in range(q): if sorted(i[u])==sorted('kabali'): d=d+1 print(d)
def longestCommonPrefix( a): size = len(a) if (size == 0): return "" if (size == 1): return a[0] a.sort() end = min(len(a[0]), len(a[size - 1])) i = 0 while (i < end and a[0][i] == a[size - 1][i]): i += 1 pre = a[0][0...
e,r=input().split() e=int(e) r=int(r) for i in range(e+1,r): if(i%2==0): print(i,end=' ')
#!/opt/anaconda/bin/python """ This script cleans the data presented in the raw data csv and turns it into the format of that easily can be migrated to a database. This is done by opening each file, and parsing through line-by-line. First commas contained within double quotes are turned into periods. After, substrings...
import streamlit as st import pandas as pd import numpy as np import altair as alt import plotly.express as px from datetime import date from datetime import datetime def page_clusters(): # st.text('page_clusters') DATA_URL = ('data/clusters_page/cluster_tweets.csv') @st.cache def load_data(nrows): ...
class Io(): @staticmethod def read(filename: str): """Opens a text file and returns the data""" with open(filename, 'r') as f: lines = f.readlines() return lines @staticmethod def write(filename: str, data) -> None: """Writes data to a text file""" wi...
input_data = '1901,12.3\n1902,45.6\n1903,78.9' print('input data is:') print(input_data) as_lines = input_data.split('\n') print('as lines:') print(as_lines) for line in as_lines: fields = line.split(',') year = int(fields[0]) value = float(fields[1]) print(year, ':', value)
# 3. Write a program which will find all the numbers which are divisible by # 7 but are not a multiple of 5, between 1000 and 1500 (both included). The # numbers obtained should be printed in a comma-separated sequence on a single # line. # Moemen Ahmed - 1May2021 print("List of numbers that are divisible by 7, but no...
import queue from copy import copy, deepcopy class Board: def __init__(self, _board): self.board = deepcopy(_board) self.N = len(self.board) self.M = len(self.board[0]) ##### locked is 2d array storing whether piece should be allowed to move self.locked = [ [0]*self.M for i ...
def f(n,m): dp = [[x for x in range(m+1)] for y in range(n+1)] dp[0] = [0 for x in range(m+1)] for i_n in range(2,n+1): for i_m in range(m-1): def height(n,m): if (n==0 or m==0): return 0
""" This program takes array and queries and solves the queries""" #taking length of array and number of queries as string nqS=raw_input() count=0 #counting the number of spaces in string count=nqS.count(" ") #checking whether space is 1 if count>1 or count<1: print("ERROR:Wrong input") exit(0) #split t...
input = raw_input('What is my name? ') while input != 'Nikhil': if input != 'Nikhil': print 'Thats not my name.' input = raw_input('What is my name? ') print 'Yes! My name is ' + input
lst = [] count = 0 numsum = 0 highest = None lowest = None while True: line = input("enter a number or Enter to finish: ") if not line: print("count =", count," sum = ", numsum," lowest = ", lowest,"highest = ", highest," mean = ", numsum/count) break try: num = int(line) ...
import unittest from functionsToTest import eat, nap class ActivitiesToTest(unittest.TestCase): def test_eat_healthy(self): self.assertEqual(eat("broccoli", is_healthy=True), "I'm eating broccoli because my body is a temple") def test_eat_unhealthy(self): self.assertE...
"""classes for driver.py""" #pylint: disable=too-few-public-methods # above disables R0903 -- too few public methods in Node class class Node(object): """make an empty node """ def __init__(self): self.cargo = None self.next = None class LinkedList(object): """initialize the list ...
""" Does the work for converting <img> """ def the_work(text): """ This function takes in the text from convert() then checks each word for image indicators. If one is found it removes the character and puts a <img>. After, returns the new text to convert(). """ new_text = "...
# # def SayHello(): # print "HelloWorld!" # # SayHello() def ProcessList_Modify(list, completed_list): """ Process item in 'list' and move to 'completed_list' when it's done. :param list: work list :param completed_list: completed item :return: """ while list: item = list.pop...
from for_field_of_miracles import * import random import time class Game: def __init__(self, base_words: list, players: list): self.base_words = base_words self.player = input('Print your name (10 letters)\n') self.players = players self.score = [0, 0, 0] self.use_letters =...
# Basic examples def countdown(i): print(i) if i <= 0: return else: countdown(i-1) countdown(10) #Call stack with recursion def factorial(i): if i == 1: return 1 else: return i * factorial(i-1) print(factorial(10))
#EXAMPLES OF LISTS #list.index = apple fruit = ["mango", "orange", "tomato", "banana", "strawberry"] print(fruit) print(fruit[0]) print(fruit[4], fruit[3]) print(fruit[-4]) family = ["mom", "dad", "brother1", "brother2"] #indexing: tells position of the thing in the list family.ind("dad") #output: 1 for fam in e...
class multiplicacion_diagonal(object): def __init__(self): pass def matriz(self,matriz1,matriz2): if isinstance(matriz1,list) and matriz1!=[] : return self.multiplicacion(matriz1,matriz2,0,0,0,0,0) def multiplicacion(self,matriz1,matriz2,indice,fila,columna,...
from datetime import datetime import time class Loger: def __init__(self, path): self.path = path def __enter__(self): self.file = open(self.path, 'a', encoding='utf8') global program_start program_start = datetime.now() self.file.write(f'program started at {program_st...
import shutil, os, hashlib #importih os and hashlib def menu(): #defining the function menu print('1. Encrypt') #defifn the different choices of the menu print('2. Decrypt') print('3. Exit') def encrypt(string): #creating the function encrypt cipher = '' for ch...
# -*- coding: utf-8 -*- import time,random class Hero(): def __init__(self,name,level=1,HP=100,Q_hurt=10,W_hurt=15,E_hurt=20): self.name=name self.level=level self.HP=HP self.Q_hurt=Q_hurt self.W_hurt=W_hurt self.E_hurt=E_hurt def Q_attack(self,enemy): ...
""" This file provides functions to read from brainParts.json into a python list. note: brainParts.json must be in the same directory as this script @author Justin Bonner """ """ Dictionary Format: "vtkFileName" "synonyms" "name" "containers" a list of strings "subComponents" ""...
a = [[1,2,3],[4,5,6]] print(a) a = a[::-1] print(a)
# 斐波那契数列 # 大家都知道斐波那契数列,现在要求输入一个整数n, # 请你输出斐波那契数列的第n项(从0开始,第0项为0)。 class Solution: def Fibonacci(self, n): if n<=1: return n first,second,third = 0,1,0 for i in range(2,n+1): third = first +second first = second second = third return t...
# 输入一个矩阵, # 按照从外向里以顺时针的顺序依次打印出每一个数字, # 例如,如果输入如下4 X 4矩阵: # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): rows = len(matrix) cols = len(matrix[0]) result = [] if row...
2行是中序遍历的代码, 分别是第8、16行;3行是更改节点指向的代码, 为13-15行。9-11行的if语句只有在中序遍历到第一个节点时调用, 自此之后listHead不变,listTail跟随算法的进度。 class Solution: def __init__(self): self.listHead = None self.listTail = None def Convert(self, pRootOfTree): if pRootOfTree==None: return self.Convert(pRootOfTree....
## 把只包含质因子2、3和5的数称作丑数(Ugly Number)。 # 例如6、8都是丑数,但14不是,因为它包含质因子7。 # 习惯上我们把1当做是第一个丑数。 # 求按从小到大的顺序的第N个丑数。 class Solution: def GetUglyNumber_Solution(self, index): if index == 0: return 0 baselist = [1] min2, min3, min5 = 0, 0 ,0 #找到初始的没有乘2,或3,或5的数 CurIndex = 1 while...
def solveSudoku(self, board: List[List[str]]) -> None: rows = [set(range(1,10)) for _ in range(9)] cols = [set(range(1,10)) for _ in range(9)] boxes = [set(range(1,10)) for _ in range(9)] empty = [] #应该放置数字的位置 for i in range(9): for j in range(9): if board[i][j] != '.': ...
import turtle import random from Salmon import* # Represents a bear in the simulation class Bear: def __init__(self): self.turtle = turtle.Turtle() self.turtle.speed(0) self.turtle.up() self.turtle.shape("bear.gif") self.turtle.turtlesize(.5, .5, .5) self...
import string def print_rangoli(size): # your code goes here letter = string.ascii_lowercase pattern = [] for i in range(0,size): s = "-".join(letter[i:n]) pattern.append((s[::-1]+s[1:]).center(4*n-3, "-")) print('\n'.join(pattern[:0:-1]+pattern)) if __name__ == '__main__': n =...
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) setA = set(map(int, input().split())) m = int(input()) setB = set(map(int, input().split())) final = sorted(setA.difference(setB).union(setB.difference(setA))) for ele in final: print(ele)
#!/bin/python3 import math import os import random import re import sys # Complete the kaprekarNumbers function below. def kaprekarNumbers(p, q): result = [] for i in range(p, q + 1): x = str(int(pow(i, 2))) l = x[0:int(len(x) / 2)] if x[0:int(len(x) / 2)] else 0 r = x[int(len(x) / 2):...
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) d = dict() for _ in range(n): temp = input() if temp in d: d[temp] += 1 else: d[temp] = 1 print(len(d)) for value in d.values(): print(value,end=" ")
#!/bin/python3 import math import os import random import re import sys from itertools import combinations_with_replacement # Complete the stones function below. def stones(n, a, b): mas = [] res = list(combinations_with_replacement ([a,b],n-1)) for a in res: mas.append(sum(list(a))) return ...
# Enter your code here. Read input from STDIN. Print output to STDOUT import math def check_prime(num): if num == 1 : return "Not prime" sq = int(math.sqrt(num)) for x in range(2, sq+1): if num % x == 0: return "Not prime" return "Prime" for _ in range(int(input())): n...
num = 2 if num%2 == 0: print("It is Even") else: print("It is odd") "This line will be ignored" print("Pylenin loves Python") """ Bigger comments can be written over multiple lines. This is a multi-line comment. """ print("Pylenin loves Python") def addition(x,y): """Takes x and y and returns their sum"...
""" You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" ...
for a in range(1, 10): for b in range(1, a + 1): print(a * b, end="\t") print("\n")
class RockPaperScissors: def __init__(self, player_one, player_two): self.player_one = player_one self.player_two = player_two def moves(self): return ["ROCK", "PAPER", "SCISSORS"] def play(self): player_one_move = self.player_one.pick_action(self.moves()) player_t...
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self, another_person=None): if another_person is None: print("Hello, my name is", self.name) print("I am ", self.age) else: print("Hello", another_person.n...
# coding: utf-8 # # Linear Regression with GD # very usefull tutorial from https://towardsdatascience.com/step-by-step-tutorial-on-linear-regression-with-stochastic-gradient-descent-1d35b088a843 # In[311]: import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt # ## Data #...
size_input = input("What size are you? ") text_input = input("What text would you like on the t-shirt? ") def tshirt(size, text): """Docstring - function that collects t-shirt size and text""" print(f"Your size is {size}") print(f"Here's the text you wanted {text}") tshirt(size=size_input, text=text_input...
alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'blue', 'points': 10} alien_2 = {'color': 'red', 'points': 15} # Nesting aliens = [alien_0, alien_1, alien_2] alien_list = [] # Make 30 new aliens for alien_number in range(30): new_alien = {'color': 'yellow', 'points': 5, 'speed': 'slow'} alien_l...
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(full_name) #Additional formatting print(f"Hello, {full_name.title()}!") # Use with older version of Python 3 (<3.6) full_name = "{} {}".format(first_name, last_name) print(full_name) # Adding Whitespace print("\tpython") #Elimin...
#introdução a get() e set() em código modularizado class Pyladies: def __init__ (self, Nome, Qtd_membros, tem_homens,nome_membros,data_criacao): self.__Nome = Nome self.__Qtd_membros = Qtd_membros self.__Tem_homens = tem_homens self.__Nome_membros = nome_membros self.__Data_...
# Program Author: Regan Setter # Program one - Math Functions # February 4th, 2021 # A program written in Python that allows you to perform six different mathematics functions between two numbers # Define add def add(x, y): return x + y # Define subtract def subtract(x, y): return x - y # Define multipl...
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company wants to ...
from pynput.keyboard import Key, Controller # will probably be replaced by microft import speech_recognition as sr ##### import time def recognize_my_voice(): # initialize r to recognize our audio r = sr.Recognizer() # initializing our source as a microphone with sr.Microphone() as source: #...
import argparse import random def parse_arguments(): parser = argparse.ArgumentParser("Blog-post") parser.add_argument('--algorithm', default='intrinsic', type=str, help='Algorithm to run multiplication') parser.add_argument('--N', ...
import os print (os.path.join('folder1', 'folder2', 'folder3', 'file.png')) #to get the current working directory cwd... print(os.getcwd()) #to change current directory os.chdir('/') print(os.getcwd()) os.chdir('/Users/btdrew/WorkDocs') print(os.getcwd()) print(os.path.abspath('test.jpg')) # some other os commands pr...
# class wordLength(): # """takes a list of words and returns a tuple with the longest, shortest words and average of all words""" empty_list = [] result = [] list_input = int(input("Enter the number of words for this list: \n")) for word in range(0, list_input): word = input("Enter word" + str(word+1)+ ": ") ...
import time import os class LoudIterator(): def __init__(self, data): print('\tNow in __init__') self.data = data self.index = 0 #creates an index attr that keeps track of our current position def __iter__(self): print('\tNow in __iter__') return self def __next__...
# -*- coding: utf-8 -*- """ Created on Mon May 10 15:34:28 2021 @author: Jinal """ # top points to the location where the element has to be inserted, so insert the value and then increment the top import numpy as np class Stack: def __init__(self, size): self.size = size self.stac...
# CS342 Final Project #2 # Ezgi Cakir # Template Design Method for Doctors and Nurses from abc import ABC, abstractmethod class HealthProfessional(ABC): def patient_procedures(self, label): self.id = label self.wear_mask() # self.sanitize_hands() self.read_patient_file() s...
#Dylan Fox #Write a program that accepts a number N from stdin and prints out the volume of a sphere with radius N meters. import math r = float(input("radius: ")) print("volume is: ", (4/3) * math.pi * r ** 3)
#Review def addDigits(num): if num == 0: return 0 else: return (num%10) + addDigits(num//10) print(addDigits(456))
import random def dice_throw(): dubbel = 0 while dubbel != 2: dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) throw = dice1 + dice2 if dice1 == dice2: print(f'{dice1} + {dice2} = {throw} (Dubbel)') dubbel += 1 else: print(f...
def encrypt(typed_input): orderd_plus = [ord(char) + 300 for char in input_user] char = [chr(i) for i in orderd_plus] line = ''.join(char) print(line) naam = input("Uw naam: ") beginstation = input("Uw beginstation: ") eindstation = input( "Uw eindstation: ") input_user = (f'{naam} {beginstation} {eind...
import datetime def leap_year(year): """ :param year: an integer representing a year :return: True if the year is leap and False otherwise """ if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True else...
import time import io import sys import itertools # skolem sequences are lists 2*k units long (so a skolem sequence of order 4 looks is 8 elements # long), with each number, n, from 1 to k, n units apart. One example of a # skolem sequence of order 4 would be: 1 1 4 2 3 2 4 3 - note that each number here is n units ...
print("learning variable") name = "Anh Tuan" print("name: ", type(name)) age = 20 print("age: ",age) print("type age: ",type(age)) name = input("enter your name: ") print(name) year_born = int(input("enter your year of birht: ")) year_current = int(input("enter current year: ")) age = int(year_current) - int(...
# Dictionary = unordered, changable, index #Making dictionary # student = { "name" : "duraan", "email" : "duran@gmail.com", "age": 30} # student2 = dict(name="abdi", email="abdi@gmail.com", age=25) # print(student) # print(student2) # accessing key # student = { "name" : "duraan", "email" : "duran@gmail.com", "age":...
from random import randrange from math import ceil print("Bonjour et bienvenue dans notre Casino !") print("Nous sommes heureux de vous proposer une partie de roulette") portefeuille = 500 print("Au début de la partie, vous disposer de {}$".format(portefeuille)) regles = input("Avez vous besoin d'un rappel des règles?...
# 풀이 1 a = int(input()) for i in range(1, a+1): if i%3==0: continue print(i)
# 풀이 1 x = input() for i in range(len(x)): print("'"+x[i]+"'") # 풀이 2 x = input() x = list(x) for i in x: print("'"+i+"'") # 풀이 3 x = input() for i in x: print("'"+i+"'")
# 풀이 1 print(hex(int(input()))[2:].upper()) # 풀이 2 a = int(input()) print(format(a, 'x').upper()) # 풀이 3 a = int(input()) print(('%x' % a).upper()) # 풀이 4 a = int(input()) print('%X' % a)
# 풀이 1 print(int(input(), 8)) # input()에 들어간 값을 8진수로 인식하고 10진수로 변환 # 풀이 2 a = input() print(int(a, 8))
''' 使用openpyxl实现以下需求 使用excel 写入一组数据,姓名,身高,体重 计算是否为健康体重,如果是健康体重,则在旁边备注健康,并将姓名打印出来 健康体重计算公式:(身高cm-70)×60% ''' from openpyxl import Workbook, load_workbook class Practice(): #定义一个练习类 def __init__(self): #定义data方法,用来存放待写入数据 self.name = ["小红","小华","李雷","韩梅梅"] #定义姓名列表 self.data1 = {160:51...
# *****************逆序对问题****************** import copy # 测试数组,(可修改) # array = [3, 15, 30, 18, 20, 7, 45] array = [49, 38, 65, 97, 76, 13, 27] # 临时数组 用于归并时临时存储归并排序结果 temp_array = [0] * len(array) # 存储逆序对数组 interval = [] # 归并 def merge(left_, mid_, right_): i = left_ j = mid_ + 1 k = left_ # 查找逆序对,i <...
#Um ransonware simples codado em pyhton a título de estudos #O material de base foi um curso gratuíto na Udemy # #Autor: Marco Antonio Damaceno #Data: 21/01/2021 # #Módulo de Criptografia import pcrypt def change_files(filename, crytoFn, block_size=16): with open(filename, 'r+b') as _file: raw_value = _fi...
""" python中的list结构 Python中的list是可变的,这是和字符串和元组的最重要的区别 意思即是:list可修改,而字符串和元组不可修改 """ # 保存姓名的list nameList = ["fenghaixin", "ranran", "liyi", "chenyou"] print(nameList) # 利用enumerate函数同时遍历列表的索引和值 for index, value in enumerate(nameList): print("%s" % index + " : " + value) # 该方法用于向list尾部添加元素 nameList.append...
""" Dictionary数据结构: 类似java中的map结构 """ dic = {"name": "fenghaixin", "age": 22, "home": "深圳市"} # dictionary数据结构取值 print(dic["home"]) print(dic["name"]) # 添加,修改Dictionary数据结构中的数据 dic["school"] = "成都大学" print(dic["school"]) print(dic) # 字典结构同时遍历key和value for key, value in dic.items(): print(key + ":%s " % va...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 14 16:36:49 2019 @author: ep9k """ x = [1, 2, 3, 4] if type(x[1]) is float: print("its an integer")
# https://codecombat.com/play/level/explosive-sorting # Sort the bombs by their health to clear the passage. # The function swaps elements and bombs in the array. def swap(array, index1, index2): temp = array[index1] array[index1] = array[index2] array[index2] = temp # Voice control! hero.say(inde...
# Манчкины атакуют! # Враги периодически атакуют группами. # Если можешь, используй cleave, чтобы уничтожить толпу врагов. while True: enemy = hero.findNearestEnemy() # Используй if с isReady, чтобы проверить "cleave": if (enemy and hero.isReady('cleave')): hero.cleave(enemy) # Руби! (cleav...
# http://codecombat.com/play/level/kithgard-enchanter # This level is on mountain. I don't know why! # Define your own simple movement functions. # Define moveRight # Note: each function should move the hero 12 meters! def moveRight(): target = {"x": hero.pos.x + 12, "y": hero.pos.y} while hero.distanceTo(tar...
# https://codecombat.com/play/level/key-stack # Open doors and collect treasures. peasant = hero.findByType("peasant")[0] goldKey = peasant.findByType("gold-key")[0] silverKey = peasant.findByType("silver-key")[0] bronzeKey = peasant.findByType("bronze-key")[0] # Command the peasant to pick up the gold and silver ke...