text
stringlengths
37
1.41M
import random uppercase_gens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase_gens = uppercase_gens.lower() digits_gens = "0123456789" symbols_gens = ":()[]{},.;'>?</\\ #$%^&*@!" upper, lower, digits, symbols = True,True,True,True temp = "" if upper: temp += uppercase_gens if lower: temp += lowercase_gens if digits: ...
import numpy as np def step_function(sum_of): if sum_of >= 1: return 1 else: return 0 # sigmoid muito usada para retornar probabilidades def sigmoid_function(sum_of) -> float: return 1 / 1 + np.exp(-sum_of) def sigmoid_derivative(x): return x * (1 - x) def tahn_function(sum_of): ...
import os import csv import pandas as pd election_csv = os.path.join("Resources", "election_data.csv") analysis_path = os.path.join("Analysis", "analysis.txt") #df=pd.read_csv(election_csv) #print(df.groupby(['Candidate'],as_index=False).count()) #print(df.count()) candidates = [] #candidate dictiona...
import random import datetime def bubble_sort(list): start = datetime.datetime.now() for i in range(len(list)-1): for j in range(len(list)-1): print("Before Swap: " + str(list)) if list[j]>list[j+1]: (list[j], list[j+1])= (list[j+1], list[j]) print("A...
import random import datetime def bubble_sort(list): start = datetime.datetime.now() for i in range(len(list)): for j in range(len(list) - 1): if (list[j] > list[j + 1]): (list[j], list[j + 1]) = (list[j + 1], list[j]) # tuple swap end = datetime.datetime.now() return end - start # create list of rand...
from flask import Flask, render_template, session, request, redirect import random app = Flask(__name__) app.secret_key = 'my_secret_key' @app.route('/') def index(): if not 'gold' in session: session['gold'] = 0 if not 'activities' in session: session['activities'] = [] return render_temp...
def CoinToss(): import random newArr = [] tails = 0 heads = 0 for count in range(1000): random_num = random.random() newArr.append(round(random_num)) for count in range(len(newArr)): if(newArr[count] > 0): heads += 1 elif(newArr[count] == 0): tails += 1 print 'Number of Head Tosses: ', heads prin...
def multiply(a, num): for x in range(0, len(a)): a[x] = a[x] * num return a a = [2, 4, 10,16] print multiply(a, 5)
''' Create a program that simulates tossing a coin 5,000 times. Your program should display how many times the head/tail appears. ''' import random head_count = 0 tail_count = 0 string_result = 'invalid' print('Lets start tossing that coin...') for index in range(1, 5001): toss_result = round(random.random()) ...
import re def get_matching_words(): words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive", "paranoia...
ex = ' vvalley the word for bo0000bby in assassin the aeiou regular regula' import re # re.search(pattern, string) finds the first thing that passes what you're looking for and stops there. you use print match.group() to see what you got #re.findall(patter, string) finds all instances that match your search paramter an...
def odd_even(a,b): for x in range(1,2000): if x % 2 == 1: print 'Number is ' + str(x) + '. This is an odd number.' else: print 'Number is ' + str(x) + '. This is an even number.'
my_list = [4, 'dog', 99, ['list', 'inside', 'another'],'hello world!'] for element in my_list: print element
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {...
#Create a program that prints the sum of all the values in the list: a = [1,2,5,10,255,3] b = sum(a) print b
from flask import Flask, render_template, session, request, redirect import random app = Flask(__name__) app.secret_key = 'my_secret_key' @app.route('/') def index(): if not 'gold' in session: session['gold'] = 0 if not 'activities' in session: session['activities'] = [] return render_temp...
def selection_sort(list): for item in range(len(list)): min = list[item] for ele in range(item, len(list)): if min >= list[ele]: min = list[ele] index = ele if temp = list[item] list[item] = min list[index] = temp re...
import random import datetime def selectsort(list): start = datetime.datetime.now() for i in range(len(list)): minIndex = i for j in range(i,len(list)): if list[minIndex] > list[j]: minIndex=j #print('List before swap: ', str(list)) (list[minIndex],...
import re def get_matching_words(regex): words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive"...
import unittest from data_structures import heap_pq class TestHeapQueue(unittest.TestCase): ascending_list = [i for i in range(0, 11, 1)] descending_list = [i for i in range(10, -1, -1)] @staticmethod def less_than_function(a, b): return a < b @staticmethod def greater_than_functi...
import time import datetime as dt import calendar as cal import pandas as pd import numpy as np # New cities can be added here without requiring changes to the funtions CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } city_opts =...
def factorial(n): #espaios en blanco causan problemas i = 2 temp = 1 while i <= n: temp = temp*i i = i+1 return temp if __name__ == "__main__": a = int(input("ingresa un numero")) print(factorial(a))
from typing import List import networkx class OrdinalAgent(object): def best_room(self, prices: List[int]) -> int: """ INPUT: the prices of the n rooms. OUTPUT: the index of room that the agent most prefers in therese prices. index is between 0 and n-1. """ raise NotImplem...
txt = "belajar Python Sangat Menyenangkan" x = txt.capitalize() print (x) txt = "belajar python sangat menyenangkan" x = txt.capitalize() print (x) txt = "belajar PYTHON SANGAT MeNyEnAnGkAn" x = txt.capitalize() print (x)
list_buah = ['Apel', 'Jeruk', 'Mangga', 'Pisang'] print("List buah :", list_buah) # menampilkan posisi buah apel print("Indeks buah apel :", list_buah.index('Apel')) # menampilkan posisi buah anggur, yang tidak ada di dalam list print("Indeks buah anggur :", list_buah.index('Anggur'))
bil = 10 # variable bil dengan tipe integer bil_string = str(bil) # varible bil di casting kedalam string bil_integer = int(bil) # variable bil di casting kedalam integer bil_float = float(bil) # variable bil di casting kedalam float print(bil_string) print(type(bil_string)) print(bil_integ...
txt = "12345" x = txt.isdigit() print(x) txt = "0.123" x = txt.isdigit() print(x) a = "\u0030" #unicode for 0 b = "\u00B2" #unicode for ² print(a.isdigit()) print(b.isdigit())
x = 15 y = 10 print(x == y) print(x != y) print(x > y) print(x < y) print(x >= y) print(x <= y)
dict_mahasiswa = {"nama":"Nursalim", "npm":"201843500121", "jurusan":"Teknik Informatika", "ipk":3} print("dict_mahasiswa :", dict_mahasiswa) # menggunakan get() untuk mendapatkan nama, NPM, jurusan dan IP print("Nama :", dict_mahasiswa.get("nama")) print("NPM :", dict_mahasiswa.get("npm")) print("Jurusan :", dict_ma...
# Iterator tuple tuple_buah = ("Apel", "Mangga", "Jeruk", "Anggur") iter_buah = iter(tuple_buah) print(next(iter_buah)) print(next(iter_buah)) # iterator pada set set_mobil = {"Honda", "Suzuki", "Mazda", "BMW"} iter_mobil = iter(set_mobil) print(next(iter_mobil)) print(next(iter_mobil)) # iterator string txt = "Pyt...
from datetime import datetime import pytz def float_hour_to_time(fh): h, r = divmod(fh, 1) m, r = divmod(r*60, 1) return ( int(h), int(m), int(r*60), ) def get_date_time(value): dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(value) - 2) hour, minute,...
#Anton Gefvert antge210, Aleksi Evansson aleev379 #3. Bearbetning av listor #Uppgift 3A """ vikho394: OK! Enkelt och bra. Inga konstigheter. Ni har dock docstrings som är längre än 79 tecken. De bör göras radbrytningar :) om man ska vara petig """ def split_it(string): """ Given a string, returns two new str...
"""Simple timer for Pomodoro technique, etc.""" import sys from PyQt5 import Qt, QtCore, QtGui, QtWidgets def time_to_text(t): """Convert time to text.""" if t <= 0: return '--:--' elif t < 3600: minutes = t // 60 seconds = t % 60 return '{:02d}:{:02d}'.format(minutes, se...
class Problem(object): def __init__(self, state): self.action_sequence = [] self.state = state self.goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] def goal_test(self): print("Checking Goal") if self.state == self.goal: return True return False def act...
import os import sqlite3 from sqlite3 import Error def database_connection(): # Conexão com o banco de dados path = "menu_database.db" con = None try: con = sqlite3.connect(path) except Error as ex: print(ex) return con def query(connection, sql): # INSERT, DELETE e UPDATE ...
"""simple BTree database The ``btree`` module implements a simple key-value database using external storage (disk files, or in general case, a random-access `stream`). Keys are stored sorted in the database, and besides efficient retrieval by a key value, a database also supports efficient ordered range scans (retriev...
''' 4-10. Slices: Using one of the programs you wrote in this chapter, add several lines to the end of the program that do the following: • Print the message The first three items in the list are:. Then use a slice to print the first three items from that program’s list. • Print the message Three items from the mi...
''' 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1 (page 56). Make a copy of the list of pizzas, and call it friend_pizzas. Then, do the following: • Add a new pizza to the original list. • Add a different pizza to the list friend_pizzas. • Prove that you have two separate lists. Print th...
''' 2-4. Name Cases: Use a variable to represent a person’s name, and then print that person’s name in lowercase, uppercase, and title case. ''' name = "Zhaozhi Li"; print(name.upper()); print(name.lower()); print(name.title());
''' 5-10. Checking Usernames: Do the following to create a program that simulates how websites ensure that everyone has a unique username. • Make a list of five or more usernames called current_users. • Make another list of five usernames called new_users. Make sure one or two of the new usernames are also in the ...
''' 4-3. Counting to Twenty: Use a for loop to print the numbers from 1 to 20, inclusive. ''' count = [value for value in range(1, 21)]; print(count);
''' 5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elifelse chain. • If the alien is green, print a message that the player earned 5 points. • If the alien is yellow, print a message that the player earned 10 points. • If the alien is red, print a message that the player earned 15 point...
''' 3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite. • Start with your program from Exercise 3-4. Add a print() call at the end of your program stating the name of the guest who ...
import time class Playlist: """This class describes the playlist""" time = '' def __init__(self, song, play=False): """Initialization method.""" self.song = song self.title = song[0] self.time = song[1] self.name = song[2] self.album = song[3] self...
"""Your task is to code up and run the randomized contraction algorithm for the min cut problem and use it on the above graph to compute the min cut (i.e., the minimum-possible number of crossing edges). """ from random import choice from copy import deepcopy def contract(v1, v2, G): """Contracts two vertices fro...
# Sales by Match # Problem Statement: # There is a large pile of socks that must be paired by color. # Given an array of integers representing the color of each sock, # determine how many pairs of socks with matching colors there are. # Example # arr = [10, 20, 20, 10, 10, 30, 50, 10, 20] # There is two pair of color ...
#! /usr/bin/python weekdays = { 0 : "Monday", 1 : "Tuesday", 2 : "Wednesday", 3 : "Thursday", 4 : "Friday", 5 : "Saturday", 6 : "Sunday", } start = ( 0, 0, 1901 ) end = ( 30, 11, 2000 ) dayspermonth = { 0 : 31, 1 : 28, 2 : 31, 3 : 30, 4 : 31, 5 : 30, 6 : 31, 7 : 31, 8 : 30, 9 : 31, 10 : ...
#! /usr/bin/python def letterStats(letters) : stats = {} for letter in letters : if not stats.has_key(letter) : stats[letter] = 0 stats[letter] += 1 for letter in stats.keys() : print str(letter) + " = " + str(stats[letter]) letters = [] cipher = "" f = file("59...
#! /usr/bin/python dict = { 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five", 6 : "six", 7 : "seven", 8 : "eight", 9 : "nine", 10 : "ten", 11 : "eleven", 12 : "twelve", 13 : "thirteen", 14 : "fourteen", 15 : "fifteen", 16 : "sixteen", 17 : "seventeen", 18 : "eighteen", 19 : "nineteen", 20 ...
def 입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴01(x) : return x * 2 print(list(map(입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴01, [1, 2, 3, 4]))) # [2, 4, 6, 8] print(list(map(lambda a : a * 2, [1, 2, 3, 4]))) # [2, 4, 6, 8] def 입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴02(x): return x + 1 print(list((map(입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴02, [1, 2, 3, 4]))...
prompt = """ 1. Add 2. Del 3. List 4. Quit Enter number: """ number = 0 while number != 4: print(prompt) number = int(input()) # coffee = 10 while True: money = int(input("돈을 넣어주세요: ")) if money == 300: print("커피를 줍니다.") coffee = coffee - 1 elif money > 30...
s1 = set([1, 2, 3]) print(s1) # {1, 2, 3} s2 = set("Hello") print(s2) # {'o', 'e', 'H', 'l'} l1 = list(s1) print(l1) # [1, 2, 3] print(l1[0]) # 1 t1 = tuple(s1) print(t1) # (1, 2, 3) print(t1[0]) # 1 s1 = set([1, 2, 3, 4, 5, 6]) s2 = set([4, 5, 6, 7, 8, 9]) 교집합 = s1 & s2 print(교집합) # {4, 5, 6} 교집합02 = s1.intersec...
#das brauche ich später noch um die dateien mit funktionen abzurufen """class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@gmx.at" def fullname(self): return "{} {}".form...
class Stack(object): def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): return self.stack.pop() def __str__(self): return str(self.stack) + ' <-Enter' def __bool__(self): if self.stack: ...
class Person: # 情報(属性) def __init__(self, name): self.name = name # 機能(メソッド) def greet(self): print('hello') def sleep(self): print('zzz') def run(self): print('run!!!') Alice = Person('Alice') Alice.sleep() # zzz Alice.run() # run!!!
# What's today? day = int(input('Day (0-6)? ')) if day == 0: print('Today is Sunday.') elif day == 1: print('Today is Monday.') elif day == 2: print('Today is Tuesday.') elif day == 3: print('Today is Wednesday.') elif day == 4: print('Today is Thursday.') elif day == 5: print('Today is Friday....
def jogar(): print('################################') print('### Seja bem-vindo a Forca! ###') print('################################') palavra_secreta = "uva" letras_acertadas = [] for letra in palavra_secreta: letras_acertadas.append('_') acertou = False enforcou = False ...
#!/usr/bin/env python # -*- coding:UTF-8 -*- import os import socket import threading import SocketServer SERVER_HOST = "localhost" SERVER_PORT = 0 # Lells the kernel to pick up a port dynamically BUF_SIZE = 1024 def client(ip, port, message): """ A client to test threading mixin server """ sock = socket.socket(so...
#!/usr/bin/python #-*- coding:utf-8 -*- # a=input('>>>') # print(a) # b=[] # for i in range(len(a)): # if a[i]=='[' or a[i]==']' or a[i]==',': # continue # else: # b.append(int(a[i])) # print(b) b=[] a=[1,[[2],3,4,5,6]] # a=str(a) # for i in range(len(a)): # if a[i] =='[' or ']' or ' ' or '...
#Desafio 1 Daily coding problems ''' Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? ''' numList = [10,15,3,5] k = 20 # Usando While def desafio1_1(list...
#Neil Moran 27th March 2019 #Solution Question9 second.py #This imports the sys module to take in the file name as an arguement and assign it to a variable for the filename to be read import sys # The line below sys.argv[1] was adapted from the program test.py from this link https://www.tutorialspoint.com/python/pyth...
#Neil Moran #Solution Question1 sumupto.py #Prompts the user to enter a positive integer and assigns the value to x x = int(input("Please enter a positive integer: ")) #This while loop checks the inputed value of x to ensure it is a positive integer. #If it isn't it prompts the user to try again. while (x < 1): p...
mes=int(input("Ingrese el numero de mes para obtener su nombre y cantidad de dias que este posee: ")) if mes == 1: print("Enero = 31") if mes == 2: print("Febrero = 28") if mes == 3: print("Marzo = 31") if mes == 4: print("Abril = 30") if mes == 5: print("Mayo = 31") if mes == 6: print("Junio = 30") ...
def sumofsquares(x): return sum([i ** 2 for i in range(1, x + 1)]) def squareofsum(y): return sum(range(1, y + 1)) ** 2 print squareofsum(100) - sumofsquares(100)
#!/usr/bin/python import re def main(): n = int(raw_input()) strings = [raw_input() for i in xrange(n)] regex = re.compile('^hi [^d]', re.IGNORECASE) for s in strings: if regex.search(s): print s if __name__=="__main__": main()
class Solution: def reverseList(self, head: ListNode) -> ListNode: cur,prev = head,None while cur: cur.next,prev,cur = prev,cur,cur.next return prev
# f(n) = f(n-1) + f(n-2) from functools import lru_cache class Solution: @lru_cache(None) def climbStairs(self, n: int) -> int: if (n <= 2): return n return self.climbStairs(n-1) + self.climbStairs(n-2)
# Rock Paper Scissors from random import randint options = ['rock', 'paper', 'scissors'] rock = { "beats": "scissors", "beaten_by": "paper" } scissors = { "beats": "paper", "beaten_by": "rock" } paper = { "beats": "rock", "beaten_by": "scissors" } print(options) print(options[0]) print(roc...
#Codeacademy's Madlibs from datetime import datetime now = datetime.now() print(now) story = "%s wrote this story on a %s line train to test Python strings. Python is better than %s but worse than %s -------> written by %s on %02d/%02d/%02d at %02d:%02d" story_name = raw_input("Enter a name: ") story_line = raw_inpu...
import pandas as pd ''' recebe uma lista de listas basicamente recebe várias séries primeiro argumento do dataframe: dados em si segundo argumento do dataframe: nome das séries ''' df = pd.DataFrame([ ['fchollet/keras', 11302], ['openai/universe', 4350], ['pandas/dev/pandas', 8168] ], columns=['repository...
# Importando las librerias from tkinter import* #Declaracion de variables (operadores de asignacion) a = 10 #funciones def ejecutar(): texto = txt_entrada.get() #print("El texto de la caja de texto es: ",texto) texto2 = txt_entrada2.get() #print("En texto de la caja 2 es", texto2) #Conve...
####There are many procedures and functions built into ####Python without any prerequisites needed. A simple example is print. ####Modules ( or Libraries) are collections of extra, pre-written functions and procedures. ####These are available to use, but we need to import them into our code at the start. import math ...
#### A while loop will continue to execute a block of code while a condition is True. #### If the condition is never True then the while loop will never start. # number = 1 # while number < 5: # print(number) # number += 1 ####+= this adds one to the variable preventing the loop from running infiintley ####s...
#Anton Danylenko #05/15/19 # A): Number of Games=255168 # B1): X Wins=131184 # B2): O Wins=77904 # B3): Draws=46080 # C): Number of Intermediate+Final Boards=5478 # D): Number of Unique Boards=765 cliques = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def printBoard(board): for i in...
class PQueue: def OrdinaryComparison(self,a,b): if a < b: return -1 if a == b: return 0 return 1 def __init__(self, comparator = None): if comparator == None: comparator = self.OrdinaryComparison self.queue = [0] self.length = 1 self.cmpfunc = comparator def __str__(self): ...
#!/usr/bin/python # -*- coding: UTF-8 -*- print ("hello,world") print(45678+0x12fd2) print("Learn Python") print(0xff==255) a = 'imooc' # a变为字符串 print (a) print u'中文' classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) L = ['Adam', 'Lisa', 'Bart'] L.append('Paul') print L ['Adam', 'Lisa', 'Bart', 'Paul'] t...
#!/usr/bin/python # -*- coding: UTF-8 -*- print ("你好,世界") print(4+5) print(1 + 2*3) print(2**3) print( 9*7 + 5*7 ) print( (17*6) - (9*7 + 5*7) ) print((3 + 32) - 15//2) print((1 + 2 + 4)/13) # " // "来表示整数除法,返回不大于结果的一个最大的整数,而" / " 则单纯的表示浮点数除法 print(15//2) # floating-point number print(3/4) print(3 + 2.5) pri...
#!/usr/bin/python # -*- coding: UTF-8 -*- rainfall = 5 # decrease the rainfall variable by 10% to account for runoff rainfall *= .9 print(rainfall) print(1 < 2) str_1 = 'qbc' str_2 = 'ABLVG' print(str_1 + str_2) salesman = '"I think you\'re an encyclopaedia salesman"' print(salesman) ai_length = len("dflkjdlkf...
# -*- coding: utf-8 -*- 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) # list 是一种有序的集合,支持添加和删除元素,类似php中的索引数组。 # len() 函数可以获得集合中元素个数,类似php中的count()函数 # 索引越界会抛出IndexError的错误,想要获取最后一...
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) """ 任务4: 电话公司希望辨认出可能正在用于进行电话推销的电话号码。 找出所有可能的电话推销员: 这样的电话总是向其他人拨出电话, 但从来不发短信、接收短信或是收到来电 请输出如下内容 "These numbers could be telemarketers...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ 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) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信息: "<telephone number...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ 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) """ 任务1: 短信和通话记录中一共有多少电话号码?每个号码只统计一次。 输出信息: "There are <count> different te...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ 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) """ 任务4: 电话公司希望辨认出可能正在用于进行电话推销的电话号码。 找出所有可能的电话推销员: 这样的电话总是向其他人拨出电话, 但从来不发短信...
# -*- coding: utf-8 -*- 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) t_tels = set() c_tels = set() s_tels = set() for text in texts: t_tels.add(text[0]) t_tels.add(text[...
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) """ 任务4: 电话公司希望辨认出可能正在用于进行电话推销的电话号码。 找出所有可能的电话推销员: 这样的电话总是向其他人拨出电话, 但从来不发短信、接收短信或是收到来电 请输出如下内容 "These numbers could be telemarketers...
import pprint import math width = 4 height = 4 players = ['x', 'o'] def print_board(board): for row in range(height): print(" ".join(board[row])) def make_move(board, player_idx, column): player = players[player_idx] if board[0][column] != '-': # column full return False la...
#! /usr/bin/python3 """ This script is used to find duplicate files in folder provided by user.""" __author__ = '__tp__' import os import sys import hashlib import argparse parser = argparse.ArgumentParser(description="Find duplicate files in given folder !!!") parser.add_argument('-p', '--path', help='Path of folder...
#!/usr/bin/python import random arith = ['+', '-', '/', '*', '//', '%'] logic = ['or', 'and', '^'] compare = ['>', '>=', '==', '<', '<=', '<>'] def generate(mode, depth): random.seed() operation = random.randint(0, 2) print '(', if (operation == 0) or (depth == 0) : # literal if mode == 0 : # logic random...
from tp3 import * print ("|####################################################|") print ("| |1| |2| |3| |4| |5| |6| |7| |8| |9| |10| |11| |12| |") print ("|Para salir ingrese --------------------------->|13| |") print ("|####################################################|") a = int(input("INGRESE EL N° DE OPCIÓN: "...
movies_list_master = [ {"movie_name": "Black Panther", "director": "j ross", "release_year": 2007, "genre": ("action", "sci-fi"), "actors": ("Chadwick Boseman", "Lupita Nyong") }, {"movie_name": "Inception", "director": "Christopher", "release_year": 2010, "genre": ("acti...
import os.path i = 0 contador_coluna = 0 palavra = "" class lista: def __init__(self): self.raiz = None def push(self, classe, lexema): novo_token = token(classe = classe, lexema = lexema) if(self.raiz == None): self.raiz = novo_token return self.rai...
import copy class Solution: """ @param S: A set of numbers. @return: A list of lists. All valid subsets. """ def subsetsWithDup(self, S): # write your code here result =[] # Input Validations if S is None or len(S) == 0: return result ...
nums = [1, 2, 3, 4, 8, 6, 9] def bubble_sort(arr): for i in range(len(arr)): print(i) isSorted = True for idx in range(len(arr) - i - 1): if arr[idx] > arr[idx + 1]: isSorted = False # swap(arr, i, i + 1) # replacement for swap function arr[idx], arr[idx + 1] = arr[i...
# a = [1, 2, 3, 4, 5] # a.append(10) # a.append(20) # print(a.pop()) # print(a.pop()) # print(a.pop()) # print(a.pop()) # print(a.pop()) # word = input('Input a word : ') # word_list = list(word) # # result = [] # for _ in range(len(word_list)): # result.append(word_list.pop()) # print(result) # print(word[::-1]) ...
from collections import deque deque_list = deque() for i in range(5): deque_list.append(i) print(deque_list) deque_list.appendleft(10) print(deque_list) deque_list.rotate(2) print(deque_list) print(deque(reversed(deque_list)))
for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v) print('\n\n') mylist = ["a", "b", "c", "d"] a = list(enumerate(mylist)) print(a) b = {i: j for i, j in enumerate('Gachon University is an academic institute\ located in South Korea'.split())} print(b) print("\n\n") a_list = ['a1', 'a2', 'a3'] b_list ...
vector_a = [1, 2, 10] # List로 표현했을 경우 vector_b = (1, 2, 10) # Tuple로 표현했을 경우 vector_c = {'x': 1, 'y': 2, 'z': 10} # Dict로 표현했을 경우 print(vector_a, vector_b, vector_c) u = [2, 2] v = [2, 3] z = [3, 5] result = [] for i in zip(u, v, z): result.append(sum(i)) print(result) result = [sum(t) for t in zip(u, v, z)] ...
# General result = [] for i in range(10): result.append(i) print(result) # List comprehension result = [i for i in range(10)] print(result) result = [i for i in range(10) if i % 2 == 0] print(result) print('\n\n') word_1 = 'Hello' word_2 = 'World!' result = [i+j for i in word_1 for j in word_2] print(result) p...
a = 'Hello World!' print(a) print(len(a)) print(a.upper()) print(a.lower()) print(a.capitalize()) print(a.title()) print(a.count('abc')) print(a.find('abc')) print(a.rfind('abc')) print(a.startswith('abc')) print(a.endswith('abc')) print(a.split(" ")) print(a.split(" ")[0]) print(a.split(" ")[1]) print(a.split("o")) b ...
#!python2 """ (C) Michael Kane 2017 Student No: C14402048 Course: DT211C Date: 29/09/2017 Title: Master Forgery Assignment. Introduction: 1. Clean Boss.bmp to give a more convincing and usable signature for your forged documents. 2. Make sure the system cleans the whole picture and not just the signature...