text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""
注意审题
!!! It doesn't matter what values are set beyond the returned length. !!!
"""
count = 0
for i in range(len(nums)):
... |
import numpy as np
import random
import matplotlib.pyplot as plt
def print_header():
print("-------------------------------")
print(" TIC TAC TOE")
print("-------------------------------\n")
def create_board():
return np.zeros((3,3))
def place(board, player, position):
if board[positio... |
import unittest
from ... import CreditAccount
class TestCreditAccount(unittest.TestCase):
def setUp(self):
self.account1 = CreditAccount("Иван", 12345678, "+7900-600-10-20",
start_balance=300, negative_limit=-500)
self.account2 = CreditAccount("Василий", 1234567... |
import random
def generateList(l,r):
"""generate a list of [l,r)"""
ans = []
for i in range(l,r) :
ans.append(i)
return ans
def generateRandomList(n,l,r):
'''generate a n-element list where each element is in range [l,r)'''
ans = []
for i in range(0,n):
ans.append(random.r... |
def vekksort(filename):
summer = 0
liste = []
with open(filename, 'r') as file:
for line in file:
line = line.strip()
liste.append(int(line))
test = [0]
for i in range(0, len(liste)):
if test[-1] <= liste[i]:
test.append(liste[i])
return sum(te... |
pos = input('Posisjon: ')
bokstav = pos[0]
Svart = ['a', 'c', 'e', 'g', 'A', 'C', 'E', 'G']
Hvit = ['b', 'd', 'f', 'h', 'B', 'D', 'F', 'H']
SvartT =[1, 3, 5, 7]
HvitT = [2, 4, 6, 8]
c = len(pos)
if int(c) != 2:
print('Feil input. Du må skrive akkurat to tegn')
else:
tall = int(pos[1])
if bokstav in Svart a... |
#2a)
def load_bin(filename):
try:
with open(filename, 'r') as file:
binary_string = ''
for line in file:
binary_string += line.strip()
print(binary_string)
return binary_string
except:
print("Error: Could not open file " + filen... |
#2a)
def inputPerson():
name = input('Name: ')
ID = input('ID: ')
weight = int(input('KG: '))
size = int(input('Size: '))
numbers = []
numbers.append(name), numbers.append(ID)
numbers.append(weight), numbers.append(size)
return numbers
#2b)
def readDbFile(filename):
table = []
w... |
#4c)
import random
N = input('Antall unike tall: ')
minvalue = int(input('Min value: '))
maxvalue = int(input('Max value: '))
def generate_testdata(N, minvalue, maxvalue):
result = []
while len(result)<int(N):
g = random.randint(minvalue, maxvalue)
if g not in result:
result.append(g... |
def main():
facebook = []
newuser = ''
print('Hello, welcome to Facebook. Add a new user by writing "given_name surname age gender relationship_status".')
while newuser != 'done':
newuser = input('Add new user: ')
if newuser == 'done':
break
facebook.append(add_data(... |
import random
def pick_sentence(sentences):
return sentences[random.randint(0, len(sentences)-1)]
questions = ['Hva gjør du', 'Hvordan går det', 'Hvorfor heter du',
'Liker du å hete', 'Føler du deg bra', 'Hva har du gjort idag',
'Hva tenker du om framtida', 'Hva gjør deg glad', 'Hva gjør... |
#coding:utf-8
#设损失函数 loss=(w+1)^2,令w初值是常数5.反向传播就是求最优w,即求最小loss对应的w值
import tensorflow as tf
#定义带优化参数w初值赋值5
w = tf.Variable(tf.constant(5,dtype=tf.float32))
#定义损失函数loss
loss = tf.square(w+1)
#定义反向传播
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#生成会话,训练40轮
with tf.Session() as sess:
init_op = tf.gl... |
"""
binary trees have at most two child nodes.
binary serch trees are a special case of binary trees and they have
an order where the nodes on the left are smaller than the father and
the nodes on the right are grater than the father, olso elements are
unique. (serching hear is very easy).
en python se puede ocupar m... |
import heapq
import random
class BuySell:
def __init__(self):
self.buy = []
self.sell = []
self.gen_rand()
self.create_heap()
self.work()
def gen_rand(self):
for i in range(10):
self.buy.append(random.randint(0, 100))
self.sell.append(ran... |
def glosarium(huruf): #fungsi untuk memetakan huruf bisa menjadi versi alaynya
if (huruf == 'a'): return '@'
elif (huruf == 'i'): return '1'
elif (huruf == 'o'): return '0'
elif (huruf == 's'): return '$'
elif (huruf == 'e'): return '3'
else: return huruf
word = input('Enter a word:')
... |
def merge_ranges(meetings):
# Merge meeting ranges
meetings.sort()
out = [meetings[0]]
for i,j in meetings[1:]:
# k,l stand for the start and the end times of the previous held meeting
k,l = out[-1]
# now we want to know of l is smaller OR equal to j, then we will have to mer... |
import turtle as t
def dotting(distance, space):
for i in range(0, int(distance/space)):
t.penup()
t.forward(space)
t.dot()
t.shape('arrow')
t.speed('fast')
dotting(80,10)
t.left(360/7)
dotting(80,10)
t.left(360/7)
dotting(80,10)
t.left(360/7)
dotting(80,10)
t.left(360/7)
dotting(80,10)
t.l... |
def sort(arr, s_index):
arr_t = arr
if s_index == arr_t.__len__()-1:
return arr_t
for i in range(0, s_index):
if i<s_index-1:
if arr_t[i]>arr_t[i+1]:
temp = arr_t[i]
arr_t[i] = arr_t[i+1]
arr_t[i+1] = temp
return sort(... |
'''
list methods
lst.append(x) - Appends element x to the list lst.
lst.clear() - Removes all elements from the list–which becomes empty.
lst.copy() - Returns a copy of the list. Copies only the list, not the elements in the list (shallow copy).
lst.count(x) - Counts the number of occurrences of element... |
"""
Specification: The list.count(x) method counts the number of occurrences of the element x in the list.
"""
lst = [2,5,4,2,6,3,5,4,2,6,3,2]
print(lst.count(2)) #output: 4
"""
Return value: The method list.count(value) returns an integer value set to the number of times the argument
value appears in the list. If t... |
"""
The list.copy() method copies all list elements into a new list. The new list is
the return value of the method.
"""
# lst = [2,4,6,7,8,9,3]
# print(lst.copy()) #[2, 4, 6, 7, 8, 9, 3]
"""
Python List Copy Shallow
In object-oriented languages such as Python, everything is an object. The list is an object
and the... |
__author__ = 'Moran'
num_of_numbers = 100
sum_of_squares = sum(x**2 for x in xrange(1, num_of_numbers+1))
print sum_of_squares
square_of_sum = sum(x for x in xrange(1, num_of_numbers+1))**2
print square_of_sum
print square_of_sum - sum_of_squares
|
import string
cadenaADNPrueba =input("Poner la cadena de ADN a Analizar las cadenas promotoras: ")
solucion = []
while 'TATAAA' in cadenaADNPrueba :
restoCadena = cadenaADNPrueba.partition('TATAAA')[2]
cadenaPromotora=restoCadena.partition('TATAAA')[0]
solucion.append('TATAAA' + cadenaPromotora + 'TA... |
input = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4,... |
#creation of Bank account
import random,os
class Data_base:
def __init__(self):
self.current_users={}
class New_user(Data_base):
def create_user(self,user_name,initial_deposit):
self.new_password=random.randint(10000,9... |
import pyttsx3
#import pyaudio
import speech_recognition as sr
import os
import datetime
name=''
phno=''
r=sr.Recognizer()
c="is it correct?"
def say(command):
speaker=pyttsx3.init()
speaker.say(command)
speaker.runAndWait()
def speak():
while(1):
try:
with sr.Microphone() as sourc... |
#Challenge Code
# Add support for abbreviations you commonly use or search the internet for some.
#Allow the user to enter a complete tweet (160 characters or less) as a single line of text.
# Search the resulting string for abbreviations and print a list of each abbreviation along with its decoded meaning.
tweet = st... |
num = int(input())
factorial=1
if num<0:
print("no negative values")
elif num==0:
print("factorial is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print(factorial) |
def length(num):
leng=0
while num!=0:
leng+=1
num=num//10
return leng
num=int(input("enter a number:"))
temp=num
rem=sum=0
len=length(num)
while num>0:
rem=num%10
sum=sum+int(rem**len)
num=num//10
len-=1
if sum==temp:
print("it is a disarium number")
el... |
def NumberCheck(a):
if a>0:
print("number is positive.")
elif a<0:
print("number is negative.")
else:
print("number is zero.")
a= float(input("enter a value: "))
NumberCheck(a) |
class Solution:
#@param n: Given a decimal number that is passed in as a string
#@return: A string
def binaryRepresentation(self, n):
# write you code here
arr = n.split(".")
left = 0
right = 0
try:
left = int(arr[0])
right = float("0... |
class LRU_cache:
class d_link_list_node:
def __init__(self, val):
self.value = val
self.pre = None
self.next = None
# this is node -1
def __init__(self):
self.cache = self.d_link_list_node(0)
self.hash_map = {}
def print_lis... |
# Round 1 question 1
# a robot can move 1,2 or 3 steps determine how much steps we need to go to not
def ways_of_moving(n):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
dp = [0] * (n + 1)
dp [0:4] = [0,1,2,4]
for i in xrang... |
# implement a union find set
class union_find():
self.father = []
def __init__(self, arr):
self.arr = arr
self.father = [ 0 for i in range(len(arr) + 1)]
def find(self, val):
if father[x] == 0:
return x
father[x] = find(father[x])
retur... |
import urllib
from BeautifulSoup import *
url = raw_input ("Enter url or use 1 for Sample Problem, 2 for Actual Problem:")
position = (int(raw_input("Enter position of URL :"))) - 1
count = (int(raw_input("Enter count of execution :"))) - 1
if url == '1':
url = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/d... |
'''
9.4 Write a program to read through the mbox-short.txt and figure out who has
the sent the greatest number of mail messages. The program looks for 'From '
lines and takes the second word of those lines as the person who sent the mail.
The program creates a Python dictionary that maps the sender's mail address ... |
def add(number1,number2):
return number1+ number2
def sub(number1,number2):
return number1 - number2
def multi(number1,number2):
return number1 * number2
def div(number1,number2):
return number1 / number2
def factorial(number):
fact=1
for i in range(1,number+1):
fact=f... |
import matplotlib.pyplot as plt
import numpy as np
x = np.load('x_train.npy')
y = np.load('y_train.npy')
# loding data
w = np.zeros((len(x[0])))
lr = 1
iteration = 700
accum_square_grad = np.zeros((len(x[0])))
iter = []
loss_func = []
#print(w, accum_square_grad)
#train
for i in range(iteration):
socre = np.d... |
word = str(input("Please enter a word: "))
revsword = word[::-1]
print(revsword)
if word == revsword:
print ('It is a palindrome')
else:
print ('It is not a palindrome')
|
# File - New File - Writing... - run module(Hot key : F5)
print("#20180702","Made by joohongkeem",sep=' ',end='#\n')
print("--------------------------------------")
print("Hello Python")
print("--------------------------------------")
a="Hello"
print("a="+a)
print("a*3="+a*3)
print("--------------------------------... |
#改变浏览器窗口的位置
#driver.get_window_position()/不支持谷歌浏览器
import time
from selenium import webdriver
driver=webdriver.Firefox()
url="http://www.baidu.com"
driver.get(url)
time.sleep(5)
#获取当前浏览器在屏幕上的位置,返回的是字典对象
position=driver.get_window_position()
print("当前浏览器所在位置的横坐标:",position['x'])
print("当前浏览器所在位置的纵坐标:",position['y'])
... |
# A year is a leap year if it is divisible by 4, unless it is the first year of a century and it is not divisible by 400.
#
# For example:
#
# 1956 is a leap year because 1956 is divisible by 4.
# 1957 is not a leap year, because it is not divisible by 4.
# 1900 is not a leap year, despite the fact that it is divisible... |
import unittest
from mergesort import mergesort
from insertionsort import insertionsort
class TestSort(unittest.TestCase):
def test_mergesort(self):
data = [1, 4, 3, 9, 6, 12, 7, 4, 8]
dataS = data
mergesort(data, 0, len(data) - 1)
dataS.sort()
self.assertEqual(data, dataS... |
import math
def mergesort(array, p, r):
if p < r:
q = math.floor((p + r)/2)
mergesort(array, p, q)
mergesort(array, q + 1, r)
merge(array, p, q, r)
def merge(array, p, q, r):
n1 = q - p + 1
n2 = r - q
L = []
R = []
for i in range(n1):
L.append(array... |
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# load the data
# image size 28x28 px, output 1 int
# 60,000 training data, 10,000 test data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
# let there be model
x = tf.placeholder(tf.float32, [None, 784])
y_true = tf... |
"""
PkPy:
Package to develop a first order ODE Solver and Visualizer for PK in Python
Version1: Just solve one equation typed in interactively by user.
No GUI yet!
Author: Sudin Bhattacharya
7/28/16
"""
from sympy import *
from math import *
import parser
import numpy as np
import matplotlib.pyplot as plt
from sci... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
import zx
import time
LED_RED = 22
LED_YELLOW = 23
LED_GREEN = 24
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_RED, GPIO.OUT)
print("""
This example will recognise left/right swipes
and toggle GPIO pin 22 on and off.
You should also see the gesture... |
#print("Fuck you Keegan")
#Daryn = "Big Poppa"
#print("Hey " + Daryn + " I Love You!")
#print(f'Hey {Daryn} {69 * 420}')
import math
CalcFunctions = ["1. Addition", "2. Subtraction", "3. Multiplication", "4. Division", "5. Squared", "6. Cubed", "7. Square Root"]
CalcSymbols = ["+", "-", "*", "/", "²", "³", "√"]
def ... |
#nomenclature to bed format
import re
import os
print("Covert nomenclature to bed")
end = ''
for line in iter(input, end):
lo = re.search(r'(.*)\s(\d{1,2}|\w)(.*)[(](\d*)[_](\d*)[)](x|\s)(.*)', line)
chromelo = lo.group(2)
start=lo.group(4)
end=lo.group(5)
print("chr" + chromelo + "\t" +... |
#!/usr/bin/env python
# coding: utf-8
import sys
# メイン関数
def main():
a, b = set(), set()
with open(sys.argv[1]) as file:
for line in file:
w = line.rstrip('\n')
a.add(w)
with open(sys.argv[2]) as file:
for line in file:
w = line.rstrip('\n')
b... |
#The Canny edge detector is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images. It was developed by John F. Canny in 1986. wikipedia
#The Canny edge detection algorithm is composed of 5 steps:
# 1. Noise reduction
# 2. Gradient calculation
# 3. Non-maximum supp... |
class BankAccount:
interest_rate = 0.01
accounts = []
def __init__(self, balance = 0):
self.balance = balance
def deposit(self, credit):
self.balance += credit
return self.balance
def withdraw(self, debits):
self.balance -= debits
return self.balance
... |
#Decimal to Binary from challenge
#You are given a decimal (base 10) number, print its binary representation.
#Yan Zverev
#2015
def convertToBinary(number):
counter = 2
binaryNumber = ''
while counter*2 <=number:
counter = counter *2
while counter > 0:
if(number-counter) >= 0:
... |
def main():
program = []
with open('input.txt', 'r') as f:
for line in f:
program.append(line.strip())
# print(program)
# print(counter)
# Part 1
code, acc = computer(program)
print(f'Part 1: Code: {code} Accumulator: {acc}')
# Part 2
for index, instruction in... |
num1 = input("Enter your first number: ")
num2 = input("Enter your second number: ")
result = float(num1) + float(num2)
print(f"The result of your 2 number combine is {str(result)}")
data = 0
data += 1
print(data)
theA = int(2304)
print(theA)
|
# if you run lambda code in this kind of type the system will transform to a function
# because lambda is normally used when you need variable instead of function and 1 time use so just store variable instead function
# this will create a function that add 10
# add10 = lambda x: x+10
# so lambda then the input ... |
# Linear Regression
# Import Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Load Dataset
dataset = pd.read_csv('./dataset/Salary_Data.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
# Split Dataset into training set and test set
from sklearn.model_selection impo... |
# ライブラリのインポート
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
# データセットの読み込み
df = pd.read_csv("Social_Network_Ads.csv")
# ラベルエンコーデ... |
# 8.7 Calling a Method on a Parent Class
class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
#b = B()
#b.spam()
# Output:
# B.spam
# A.spam
# super() is the handling of the __init__() method to make sure that
# par... |
# 1.9 Finding Commonalities in Two Dictionaries
a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
# Find keys in common
key_comm = a.keys() & b.keys()
# Find keys in a that are not in b
key_diff = a.keys() - b.keys()
# Find (key, value) pairs in common
item_comm = a.items() &... |
# Class and Objects
class MyClass:
name = "pingsoli"
def print_info(self):
print("this is a message inside the class.")
myobj = MyClass()
#myobj.print_info()
# Exercise
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s... |
# List
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
# Add an element in the tail of linked list
def add_tail(self, node):
head = self.head
prev = None
wh... |
# __init__, __new__, __del__ methods
# __new__ used rarely, and not so much useful, when a object is created,
# __new__ method is frist to be called.
# __init__ is very useful to initialize a object.
# __del__ is used to comtome your own deleter.
from os.path import join
class FileObject:
def __init__(self, f... |
# 4.5 Iterating in Reverse
a = [1, 2, 3, 4, 5]
for x in reversed(a):
print(x)
# Output:
# 5
# 4
# 3
# 2
# 1
# Implementing __reversed__.
class Countdown:
def __init__(self, start):
self.start = start
# Forward interator
def __iter__(self):
n = self.start
while n > 0:
... |
# 13.6 Executing an External Command and Getting Its Output
import subprocess
out_bytes = subprocess.check_output(['ls', '-a'])
out_text = out_bytes.decode('utf-8')
#print(out_text)
# .
# ..
# 01.py
# 02.py
# 03.py
# 04.py
# 05.py
# 06.py
# .06.py.swp
# Example of catching errors and getting the output created along... |
# 2.8 Writing a Regular Expression for Multiline Patterns
import re
comment = re.compile(r'/\*(.*?)\*/')
text1 = '/* this is a comment */'
text2 = '''/* this is
multiline comment */
'''
#print(comment.findall(text1)) # [' this is a comment ']
#print(comment.findall(text2)) # []
comment = re.com... |
# 2.14 Combining and Concatenating Strings
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
#print(' '.join(parts)) # Is Chicago Not Chicago?
a = 'Is Chicago'
b = 'Not Chicago?'
#print('{} {}'.format(a, b)) # Is Chicago Not Chicago?
#print(a + ' ' + b) # Is Chicago Not Chicago?
# no + operator
#a = 'hello' 'world'
#... |
# 7.10 Carrying Extra State with Callback Functions
# callback functions, (event handles, completion callback, etc.)
# asynchronous processing.
def apply_async(func, args, *, callback):
# Compute the result
result = func(*args)
# Invoke the callback with the result
callback(result)
def print_result(... |
# Lambda Expression Learning
# Map, Filter, Reduce
# Basic usage
f = lambda x, y : x + y
#print(f(1, 1)) # 2
# Map
# map(function_to_apply, list_of_inputs)
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, items))
#print(squared) # [1, 4, 9, 16, 25]
def multiply(x):
return (x*x)
def add(x):
re... |
# 12.2 Determining If a Thread Has Started
from threading import Thread, Event
import time
def countdown(n, started_event):
print('countdown starting')
started_event.set()
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(2)
# Create the event object that will be used to signal s... |
# 2.2 Matching Text at the Start or End of a String
# usage: filename extensions, URL schemes and so on.
# str.startswith() and str.endswith()
filename = 'sample.txt'
#print(filename.endswith('.txt')) # True
url = 'http://www.python.org'
#print(url.startswith('http:')) # True
# Check multiple choice
import os
f... |
# 11.4 Generating a Range of IP Addresses from a CIDR Address
import ipaddress
net = ipaddress.ip_network('123.45.67.64/27')
# for a in net:
# print(a)
# 123.45.67.64
# 123.45.67.65
# 123.45.67.66
# ...
# 123.45.67.94
# 123.45.67.95
# Show all available ip address number
#print(net.num_addresses) # 32
net6 = i... |
# 1.16 Filtering Sequence Elements
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
# [1, 4, 10, 2, 3]
#print([n for n in mylist if n > 0])
pos = (n for n in mylist if n > 0)
for x in pos:
print(x)
# Output:
# 1
# 4
# 10
# 2
# 3
# Exception handling
values = ['1', '2', '-3', '-', '4', 'N/A', '5']
def is_int(val):
tr... |
# Generators, a bit difficult to understand.
import random
def lottery():
# return 6 numbers between 1 and 40
for i in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 45
yield random.randint(1, 45)
#for random_number in lottery():
# print("And the next number is... |
# 12.1 Starting and Stopping Threads
# thread library can be used execute any Python callable in its own
# thread.
# Code to execute in an indepentdent thread
import time
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5)
# Create and lanuch a thread
from threading im... |
"""Helper functions for several calculation tasks (such as integration)."""
import numpy as np
from ase.units import kB
from scipy import integrate
import mpmath as mp
def integrate_values_on_spacing(values, spacing, method, axis=0):
"""
Integrate values assuming a uniform grid with a provided spacing.
D... |
from Objects import *
# Validate a user’s password by passing the username and password, both strings.
# The program should clearly report
# - Success
# - Failure: no such user
# - Failure: bad password
def authenticate(user, password):
if any(x for x in allUsers if x.name == user):
for i in allUsers:
... |
import tkinter as tk
Large_Font = ("Verdana",12)
class seaoapp(tk.Tk):
#this will alwase run when you start your class
#like when you start computer there are programmes shoud be run
# args any number of variable to the functions
#kwargs to pass adictionary thro the function
def __init__ (self,*args,**kwargs):... |
def RFcheck(RF):
while (RF<1 or RF>3):
RF = raw_input("Please enter a valid reading frame ");
print RF;
print "success!"
|
#!/usr/bin/env python
def modify_string(original):
original += " that has been modified"
def modify_string_return(original):
original += " that has been actually modified"
return original
test_string = "This is my test string"
modify_string(test_string)
print(test_string)
test_string = modify_string_re... |
#!/usr/bin/env python
hello_str="Hello World"
# Creating variables
hello_int = 123
hello_bool = True
hello_tuple = (12,21,44)
hello_list = ["Hello",'this','is',"a",'list']
print(hello_list)
# Another way of creating a list
hello_list = list()
hello_list.append("HEllo")
hello_list.append("this")
hello_list.append('is'... |
import sqlite3
# connect to database
def connect_to_db(db_name):
return sqlite3.connect(db_name)
# insert to database
def insert(list_data):
conn = connect_to_db('home_test_db.sql')
c = conn.cursor()
try:
c.execute(
""" CREATE TABLE IF NOT EXISTS downloaded_tree_data ( id INTEGER... |
# LISTA
# LISTA GERALMENTE SÃO MUTAVEIS
# ELEMENTOS HOMOGENEOS
# append -> final da lista
# extend:
# insert: inserir um item em determinnada posição
# remove: removve o valor do ittem que é iguaal ao parametro
# pop: remomve o ultimo item da lista ou o da posição especifficada
# clear: limpa a lissta
# count: conta o... |
import itertools
import random
class Mapa():
def __init__(self):
self.dicionario = {}
self.inicio = (0, 0)
self.fim = (0, 0)
def reset(self):
self.dicionario = {}
self.inicio = (0, 0)
self.fim = (0, 0)
def gerarDicionario(self, numero_de_linhas: int):
... |
def solution(bridge_length, weight, truck_weights):
answer = 1
bridge = [0]*bridge_length
cur = 0
while cur > 0 or len(truck_weights) > 0:
cur -= bridge.pop(0)
answer += 1
if len(truck_weights) > 0 and weight >= cur + truck_weights[0]:
cur += truck_weights[0]
... |
#%%
# MODELO DE SIMULACION DE LIGA Y OPTIMIZACION DE MERCADO DE PASES DE LA PREMIER LEAGUE
# TP Final Investigación Operativa - Juan Martín Lucioni y Matías Ayerza
# SOBRE EL CODIGO
#El código está dividido en dos partes, en primer lugar hay una celda (esta) que se encarga de armar y cargar a la consola la lógica detr... |
# coding=utf-8
# https://github.com/Show-Me-the-Code/show-me-the-code
# **第 0004 题:**任一个英文的纯文本文件,统计其中的单词出现的个数。
# 打开文件
# 利用正则去匹配
# 把结果存到字典里面去
import re
file_path = r"./log.txt"
with open(file_path, encoding="utf-8") as f:
text = f.read()
# print(words)
words = re.findall("\w+", text)
print("words type... |
import numpy as np
def CreateInitialPopulation(CostFunction, nindividuals, dim, domain, initial_domain):
lower_bound, upper_bound = domain
initial_lower_bound, initial_upper_bound = initial_domain
if initial_lower_bound != None and initial_upper_bound != None:
lower_bound = initial_lower_bound
... |
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
"""
Initial thoughts:
We move a first pointer k positions forward and save a reference to the node.
Then we crea... |
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
# Related Topics: Hash Table, Two Pointers, String, Sliding Window
# Difficulty: Medium
class Solution:
# Time complexity: O(n) where n is the length of the input string
# Space complexity: O(1) since the dictionary has never more... |
from typing import List
class Solution:
# Time complexity: O(m * n) where m and n are the sides of the grid
# Space complexity: O(1)
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
R, C = len(grid), len(grid[0])
k = k % (R * C)
res = [[0]*C for _ in range(R)... |
from typing import List
class Solution:
# Time complexity: O(n)
# Space complexity: O(1)
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3: return False
found_peak = False
for i in range(1, len(arr)-1):
if not found_peak:
if ... |
# https://leetcode.com/problems/smallest-string-starting-from-leaf/
# Related Topics: Tree, DFS
# Difficulty: Medium
# Initial thoughts:
# Using a DFS approach, we are going to log each path from root to leaf.
# Whenever we encounter a leaf, we are going to reverse the built path and
# compare it to the answer that... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import random
class Solution:
def __init__(self, head: Optional[ListNode]):
self.data = []
while head:
self.data.append(head.val)
... |
# https://leetcode.com/problems/range-sum-query-immutable/
# Related Topics: Dynamic Programming
# Difficulty: Easy
# Initial thoughts:
# The naive approach is to look at each and every element every time
# and sum them. This would have a Time Complexity of O(n) and a Space Complexity of O(1)
# Optimization:
# Us... |
# https://leetcode.com/problems/minimum-path-sum/
# Related Topics: Array, Dynamic Programming
# Difficulty: Medium
# Initial thoughts:
# We can look at the problem as a tree where each cell is a node in the tree
# that is connected to two other cells (one to its right and one to its bottom)
# We are looking for t... |
from typing import List
class Solution:
# bottom up itetrative solution
# Time complexity: R * C^2 where R is the number of rows and C the number of columns of the grid
# Space complexity: C^2 (we only need to look back one row)
def cherryPickup(self, grid: List[List[int]]) -> int:
R, C = len(g... |
from typing import List
class Solution:
# Time complexity: O(n)
# Space complexity: O(n)
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
R, C = len(board), len(board[0])
temp = [row[:] for row in b... |
# https://leetcode.com/problems/path-sum/
# Related Topics: Tree, DFS
# Difficulty: Easy
# Initial thoughts:
# Using a DFS algorithm we are going to check every path from root to its leafs
# and subtracts the the nodes values from the given sum. If at the end sum turns
# out to be zero, we have a path with the giv... |
# https://leetcode.com/problems/add-two-numbers/
# Related Topics: Linked List, Math
# Difficulty: Easy
# Initial thoughts:
# Creating a new linked list, we need to loop over the given
# linked lists, adding their values and moving any remaining
# carry to the next digit.
# Keep in mind that some carry may remain ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.