text stringlengths 37 1.41M |
|---|
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
# O(n) Linear Time
# def threes_and_fives(max):
# sum = 0
# for i in range(1, max):
# if i % 3 == 0 or i % 5... |
"""
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Exa... |
"""
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val ... |
# ----------------------------------------
# "bitwise right shift" ('>>' Operator)
# Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros).
# This is the same as multiplying x by 2**y.
a = 240 # 11110000
a >> 2 # 00111100 -> 60
a = 79 # 1001111
a >> 2 # 0010011 ... |
# Remove all elements from a linked list of integers that have value val.
# Example:
# Input: 1->2->6->3->4->5->6, val = 6
# Output: 1->2->3->4->5
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, ... |
import time
def countPrimes(n: int) -> int:
start_time = time.time()
prime_numbers = 0
for i in range(2, n):
for j in range(2, i):
if i % j == 0:
break
else:
prime_numbers += 1
end_time = time.time()
print(f"total time: {(end_time - start_tim... |
class Point:
def __init__(self, coordX, coordY):
self.coordX = coordX
self.coordY = coordY
class Rectangle:
def __init__(self, starting_point, broad, high):
self.starting_point = starting_point
self.broad = broad
self.high = high
def area(self):
return self... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# https://towardsdatascience.com/understanding-logistic-regression-using-a-simple-example-163de52ea900?gi=cfca5849c2e7
# https://github.com/yiuhyuk/Basketball_Logit_Blog/blob/master/basketball_logit_code.ipynb
# Dumb Logit ... |
r"""Provides Support for Dictionary List Manipulation.
Recursively walk over a Dictionary of python and combine the keys by a joiner.
e.g.
dict = {
name: "rehan",
schooling: {
masters : "PAF KIET"
}
}
d = Dict.walk_recursive(dict)
print(d)
{ name: 'rehan', 'schooling_masters': 'PAF KIET'}
"... |
import sys;
import matplotlib.pyplot as plt;
from random import uniform;
'''
This is a normal distribution simulator.
If a call of 'map.py 10 5' is called then 5 vectors of length 10, is made.
Then a change of normal distribution is made by finding the middle point
in this case '5'. Then the index number is dividied b... |
ch=''
while ch!='quit':
print("1.Read File ")
print("2.Read One line from File ")
print("3.Write/Append Content to the File")
print("4.Overwrite the Content of File")
print("5.Delete the File")
ch=input("Enter your choice : ")
if ch=='1':
f = open("myfile.txt")
... |
import json
import numpy as np
class SVM():
def __init__(self, num_classes, k=100, max_iterations=100, lamb=0.1, t=0.):
self.num_classes = num_classes
self.k = k
self.max_iterations = max_iterations
self.lamb = lamb
self.t = t
def objective_function(self, X, y, w):
... |
"""
Classe "Player", contenant les caractéristiques
du joueur
"""
class Player():
def __init__(self, x, y):
self.x = x
self.y = y
self.inventory = 0
def addtoInventory(self, item):
print(f"{item} ajouté à l'inventaire.")
self.inventory += 1
|
g = lambda a,b : a+b
f= lambda a,b : a*b
h = lambda a,b :a-b
q = lambda a,b :a//b
print("Addition is",g(3,3))
print("Multiplication is",f(2,90))
print("Substraction is",h(4,3))
print("Division is",q(102,3)) |
# Reading csv Files
import csv
with open("../Resources/Employee.csv", "r") as fh:
ereader = csv.reader(fh)
print("File Employee.csv contains :")
for rec in ereader:
print(rec)
|
# Calculating GCD using Recursion
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
d = gcd(n1, n2)
print("GCD of", n1, "and", n2, "is:", d)
|
def sum(l, n):
if n == 0:
return l[0]
else:
return l[n] + sum(l, n-1)
list1 = [10, 20, 30, 40, 50, 60, 70]
size = len(list1)
print("Sum =", sum(list1, size-1))
|
x=int(input())
y=int(input())
while x != 0 and y != 0:
if x > y :
x %= y
else:
y %= x
gsd = x+y
print(gsd)
|
from string import ascii_lowercase
def eof(initial_length, current_position, current_length):
return current_length == 0 or current_position >= initial_length - 1 or current_position >= current_length - 1
def are_polarised(l, r):
return r.upper() == l.upper() and r != l
def remove_at(cursor, data):
re... |
import re
def is_multiple_of(number, base):
return not number % base
def get_counter_clockwise(circle, current_index, how_many):
new_index = current_index - how_many
if new_index < 0:
new_index = len(circle) + new_index
return new_index
def get_new_index(current_index, current_length, diff... |
def fizz_buzz(number):
if number%3==0 and number%5==0:
return 'FizzBuzz'
if number% 3==0 and number%5 !=0:
return 'Fizz'
elif number%5==0 and number%3 !=0:
return 'Buzz'
else:
return 'number' |
# Question 3
# Progarmlarin Ismimleri tutacagiz
Programs = []
# Birinci Programin Ratingler icin
ProgramOneRatings = []
# Ikinci Programin Ratingler icin
ProgramTwoRatings = []
# Ucuncu Programin Ratingler icin
ProgramThreeRatings = []
TotalOfProgramOne = 0
TotalOfProgramTwo = 0
TotalOfProgramThree = 0
for i in range... |
"""
You are given N numbers. Store them in a list and find the second largest number.
Input Format
The first line contains N. The second line contains an array A[] of N integers each separated by a space.
Constraints
2 <= N <= 10
-100 <= A[i] <= 100
Output Format
Output the value of the second larges... |
import math as m
x = float(input())
if x <= -2:
print(-1)
elif x > 0 and x <=100:
print((1)/(3+2/x))
elif x >=105:
print(200)
else:
print(0)
|
YEAR_PYTHON = 1991
DELTA = 16
year_user = float(input('Год создания python: '))
delta_user = abs (year_user - YEAR_PYTHON)
if delta_user ==0:
print('good!!!')
elif delta_user <= DELTA:
print("go to wiki")
else:
print("Вообще не попал!!")
|
first_name = input('Enter first name: ')
second_name = input('Enter second name: ')
if first_name:
print("empty")
else:
print('{} {}'.format(first_name, second_name)) |
first = float(input('first number >>> '))
operation = input('operation >>> ')
second = float(input('second number >>> '))
pattern_output = '{} {} {} = {}'
res = None
if operation == '+':
res = first + second
elif operation == '-':
res = first - second
elif operation == '*':
res = first - second
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 14 15:57:05 2018
@author: actionfocus
"""
class node():
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
class biTree():
rootnode = None
def InsertNode(self, root, x):
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 22:21:41 2018
@author: actionfocus
"""
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_questions(self):
print question
def store_response(self, new_response)... |
from cs50 import get_string
import sys
def main():
if len(sys.argv) != 2:
print("enter the key as a non negative number argument as an arg!!!")
return 1
k = int(sys.argv[1])
if k <= 0 :
print("enter the key as a non negative number argument ")
return 2
print("type th... |
#!/usr/bin/python
import socket
import sys
print ("Address is: %s" % str(sys.argv[1]))
print ("Port number is: %s" % str(sys.argv[2]))
print ("Message is: %s" % str(sys.argv[3:]))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = str(sys.argv[1])
port = int(sys.argv[2])
s.connect((host, port))
# print s... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
'''
Creat an empty list.
While True:
Let user enter a value as input
if input is 'done',
then print out the list
break
else
add the input to the list.
while True:
Let user enter a index which must be a vaild integer,
wh... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
res = list()
while(True):
value = input("Please enter a value: ") # Let user enter a value
if value.lower() == 'done': # If user want to end, then stop and print
print(res)
mini = -len(res)
maxi = len(res) - 1 # Calculate the range of po... |
# while useing pop method
Dic= {
1: 'NAVGURUKUL',
2: 'IN',
3: {
'A' : 'WELCOME',
'B' : 'To',
'C' : 'DHARAMSALA'
}
}
add=Dic.get(3)
add.pop('A')
Dic[3]=add
print(Dic)
# while useing del method
Dic= {
1: 'NAVGURUKUL',
... |
list1 = ["one","two","three","four","five"]
list2 = [1,2,3,4,5,]
dic={}
i=0
while i<len(list1):
dic[list1[i]]=list2[i]
i=i+1
print(dic)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EGE DOĞAN DURSUN - 05170000006
CEM ÇORBACIOĞLU - 05130000242
EGE ÜNİVERSİTESİ
MÜHENDİSLİK FAKÜLTESİ
BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
2019-2020 BAHAR DÖNEMİ
İŞLEMSEL ZEKA VE DERİN ÖĞRENME DERSİ - CIDL2020-P1
PROJE 1 - SORU 3 - ALTERNATİF 3: GENETİK ALGORİTMALARLA TRAVEL... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EGE DOĞAN DURSUN - 05170000006
CEM ÇORBACIOĞLU - 05130000242
EGE ÜNİVERSİTESİ
MÜHENDİSLİK FAKÜLTESİ
BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
2019-2020 BAHAR DÖNEMİ
İŞLEMSEL ZEKA VE DERİN ÖĞRENME DERSİ - CIDL2020-P1
PROJE 1 - SORU 3 - ALTERNATİF 3: GENETİK ALGORİTMALARLA TRAVEL... |
"""
problem70.py
https://projecteuler.net/problem=70
Euler's Totient function, φ(n) [sometimes called the phi function], is used to
determine the number of positive numbers less than or equal to n which are
relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than
nine and relatively prime to nin... |
"""
problem56.py
https://projecteuler.net/problem=56
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
"""
def digit_sum(n):
return sum(map(int, (str(n))))
def problem56():
return max(digit_sum(a**b) for a in range(100) for b in range(100))
if __name__ == "__... |
"""
problem75.py
https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form
an integer sided right angle triangle in exactly one way, but there are many
more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: ... |
"""
problem69.py
https://projecteuler.net/problem=69
Euler's Totient function, φ(n) [sometimes called the phi function], is used to
determine the number of numbers less than n which are relatively prime to n. For
example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to
nine, φ(9)=6.
It can be... |
def palindrome(str):
str = str.replace(" ", "")
str = str.lower()
return str[::-1] == str
def main():
word = input("Write in a word:")
palindrome(word)
if __name__ == '__main__':
main()
|
from abc import abstractmethod, ABC
class BaseMetric(ABC):
"""Abstract base class for metrics.
"""
def __init__(self):
self.score = None
@abstractmethod
def update(self, y_true, y_pred):
"""Updates the metric with given true and predicted value for a timestep.
Args:
... |
def multiplication(a,b):
my_answer = a*b
print("Calculating...")
return my_answer
print("Let's Multiply stuff...")
answer = multiplication(5,6)
answer = str(answer)
print("The answer is..." + answer)
#Let's Multiply stuff...
#Calculating...
#The answer is...30 |
current_speed = int(input("please enter current speed"))
average_speed = int(input("please enter average speed"))
calc = current_speed - average_speed
demerit = calc//5
print( "points" , demerit)
if demerit > 12:
print("time to go to jail")
if (0<= demerit<=12):
print("ok")
|
def display(a):
while(a>0):
print("*")
a=a-1
def main():
i=int(input("accept number from user to print *"))
display(i)
if __name__=="__main__":
main() |
caixaaa = 0
caixabe = 0
caixace = 0
while caixaaa < 1 or caixaaa > caixabe or caixabe > caixace or caixace >1000:
caixaaa = int(input('O tamanho da caixa A é de:'))
caixabe = int(input('O tamanho da caixa B é de:'))
caixace = int(input('O tamanho da caixa C é de:'))
if caixaaa < caixabe:
if caixace =... |
def group(parts, k):
parts.sort(reverse=True)
avg=sum(parts)/k
truck_no=1
part_no=0
while truck_no<=k and truck_no<=k:
load=[]
load_sum=0
while load_sum<avg and part_no<len(parts):
load.append(parts[part_no])
load_sum+=parts[part_no]
part_n... |
def BMI(x, y):
y = y/100
BMI = x/(y*y)
print("BMI anda adalah : {:.2f}".format(BMI))
if BMI < 18.5:
print("Anda Termasuk Kekurangan Berat badan")
elif 25 > BMI >= 18.5:
print("Anda Termasuk Normal")
elif 30 > BMI >= 25:
print("Anda Termasuk Kelebihan Berat Badan")
el... |
total = ((int(input()) * 100 + int(input())) * int(input()))
print(total // 100, total % 100, sep=' ')
|
m, n = 0, int(input())
while n:
if n > m:
m = n
c = 1
elif n == m:
c += 1
n = int(input())
print(c)
|
m1, m2, n = 0, 0, int(input())
while n:
if n >= m1:
m2 = m1
m1 = n
elif n <= m1 and n >= m2 and m2 <= m1:
m2 = n
n = int(input())
print(m2)
|
myDict = {}
for line in open('input.txt'):
for w in line.split():
myDict[w] = myDict.get(w, -1) + 1
print(myDict[w], end=' ')
|
class Time():
@staticmethod
def _counter(m, n):
lis = []
minute_addin = m // 60
minute_remains = m % 60
second_addin = n // 60
second_remains = n % 60
if minute_remains < 0:
minute_remains += 60
minute_addin -= 1
if secon... |
class QueueUnderflow(ValueError):
pass
class LNode():
def __init__(self, elem, next_ = None):
self.elem = elem
self.next = next_
#add elements at tail, delete at head
class Linkqueue():
def __init__(self):
self._head = None
self._rear = None
self._count... |
import Assoc as As
class BiTreeNode():
def __init__(self, key, value):
self.node = As.Assoc(key, value)
self.left = None
self.right = None
class SortBiTree():
def __init__(self):
self._root = None
def is_empty(self):
return self._root == None
... |
#采用邻接矩阵来构造图,但存储形式采用邻接表
class GraphError(ValueError):
pass
inf = float('inf')
class GraphL():
def __init__(self, matrix, uncount = 0):
var = len(matrix)
for each in matrix:
if len(each) != var:
raise GraphError('The matrix is not square')
self._... |
class Assoc():
def __init__(self, index_, value_):
self.key = index_
self.value = value_
def __lt__(self, another):
return self.key < another.key
def __le__(self, another):
return self.key <= another.key
def __str__(self):
return 'Assoc key is {0},... |
"""
https://mp.weixin.qq.com/s?__biz=MzU1NDk2MzQyNg==&mid=2247484282&idx=1&sn=74af38dd9a4b169121c32cfa2ae575b9&chksm=fbdadbf7ccad52e1aa63d609c1524adcc295882ab286c8727fbca9857819460af75f0eafda65&scene=21#wechat_redirect
第92天:Python Matplotlib 进阶操作
"""
import numpy as np
import matplotlib.pyplot as plt
# 绘制 x 轴数据
x = ... |
def ex5():
filename = "valores.txt"
file = open(filename, "r")
print("ficheiro {filename}")
minimos = []
line = file.readline()
while line:
print(line)
numeros = line.split(";")
minimo = min(numeros)
minimos.append(minimo)
line = file.read... |
import pygame
class ViewInfo:
# default background color
BACKGROUND_COLOR: tuple = (0, 0, 30)
# window size in unit
SIZE_UNITS_X: int = 35
SIZE_UNITS_Y: int = 21
# on-startup unit size
DEFAULT_UNIT: float = 32.0
# unit size - display unit of measure
unit: float = DEFAULT_UNIT
... |
from src.map_module.worldmap import WorldMap
from random import random
class SingleWallReplacer:
"""
Iterates over the map and randomly places a wall tile of given id
:param wmap - the map being worked on
:param wall_id - id of the wall tile spawned
:param possible_wall_ids - ids of the walls tha... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 14 11:44:39 2017
@author: Admin
"""
def splitString(funny):
a,b,c,d,e = funny.split(" ")
print(a)
print(b)
print(c)
print(d)
print(e)
return;
def secondLetter(funny):
a,b,c,d,e = funny.split(" ")
print(a[1]+b[1]+c[1]+d[1]+e[1])
r... |
contador = total = 0
while True:
idades = int(input())
if idades > 0:
total += idades
contador += 1
else:
break
print(f'{total/contador:.2f}')
|
# line 3 will access and open a file in the folder named "um-server-01.txt"
# it will save the file into a new variable called log_file
log_file = open("um-server-01.txt")
# line 7 is the opening of a function in python named sales_reports
# the function will take in a parameter titled log_file
def sales_reports(log_f... |
from beautifultable import BeautifulTable
#Prints in a pretty, table fashion a query result
def printTable(query, headers):
table = BeautifulTable(max_width=160)
table.set_style(BeautifulTable.STYLE_GRID)
table.column_headers = headers
for row in query:
table.append_row(row)
print(table)
... |
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
# Color space is a specific organization of colors
# They provide a way to categorize colors and represent them in digital images
# RGB Thresholding doesn't work well under varying light conditions
# or under vary... |
# # Predicting the final grade of a student
#
# The data used is from a Portuguese secondary school. The data includes academic and personal characteristics of the students as well as final grades. The task is to predict the final grade from the student information. (Regression)
#
# ### [Link to dataset](https://arch... |
"""
Реализовать базовый класс Worker (работник).
определить атрибуты: name, surname, position (должность), income (доход);
последний атрибут должен быть защищённым и ссылаться на словарь, содержащий элементы: оклад и премия,
например, {"wage": wage, "bonus": bonus};
создать класс Position (должность) на базе класс... |
class node:
def __init__(self,data):
self.data = data
self.next_pointer = None
def get_data(self,data):
return self.data
def set_data(self,new_data):
self.data = new_data
def get_next_pointer(self):
return self.next_pointer
d... |
def range_function(num):
i = 0
while i < num:
yield i
i = i+1
gen_num = range_function(20)
# printing the output of custom range function
for i in range(20):
print gen_num.next()
|
from random import randint
def run_guess(guess, answer):
if 0 < guess < 11:
# Check if no. is right guess otherwise ask again.
if guess == answer:
print("You are Genius!")
return True
else:
print("you lost!")
else:
print("Hey dumbo! I said 1 ... |
# First we are gonna install virtual environment here in web_server folder.
# By typing python -m venv venv
# Now we are gonna activate virtual environment by typing venv/Scripts/activate
# Now, we finally install Flask, by typing pip install Flask.
from flask import Flask, render_template # This render_template is u... |
# Find Duplicates (Exercise) Using Comprehension.
# Check for duplicates in list and print them in a list.
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = []
for value in some_list:
if some_list.count(value) > 1:
if value not in duplicates: # This is imp. to not print b and n twice in o... |
# Logical Operators (Exercise)
is_magician = True
is_expert = False
# Check if magician and expert
if is_magician and is_expert:
print("You are a master magician")
# Check if magician but not expert
elif is_magician and not is_expert:
print("At least you are getting there...")
# Check if you are not a magic... |
ammount=int(input("enter the cash ammount:"))
print("number of 500 notes are:",ammount//500)
ammount=ammount%500
print("number of 200 notes are:",ammount//200)
ammount= ammount%200
print("number of 100 notes are:",ammount//100)
ammount= ammount%100
print("number of 50 notes are:", ammount//50)
ammount=ammount%50
print(... |
def check_nice(line):
vowels = "aeiou"
vowelCounter = 0
hasDouble = False
blacklist = ["ab", "cd", "pq", "xy"]
for b in blacklist:
if b in line:
return False
for i, c in enumerate(line):
if i < len(line) - 1 and c == line[i+1]:
hasDouble = True
if c in vowels:
vowelCounter += 1... |
"""Assume you have a method isSubstring which checks if one words is a substring of another.
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g. "waterbottle" is a rotation of "erbottlewat")"""
# TODO: come back and actually use isSubstring in the solut... |
def check_seat(lines, i, j):
if lines[i][j] == "L":
if i > 0:
if lines[i-1][j] == "#":
return False
if j > 0 and lines[i-1][j-1] == "#":
return False
if j < len(lines[i]) - 1 and lines[i-1][j+1] == "#":
return False
if i < len(lines) - 1:
if lines[i+1][j] == "#"... |
def check_memo(lines, memo):
memoKey = "".join(str(x) for x in lines)
if memoKey in memo:
return memo[memoKey]
else:
result = find_arrangements(lines, memo)
memo[memoKey] = result
return result
def find_arrangements(lines, memo):
if len(lines) == 1:
return 1
if len(lines) == 0:
return... |
"""Write an algorithm such that if an element in an MxN matrix is 0, the entire row and column are set to 0"""
def zero_matrix(m):
zcols = set()
zrows = set()
for i, row in enumerate(m):
for j, cell in enumerate(row):
if cell == 0:
zrows.add(i)
zcols.add(... |
""" An implementation of merge sort in Python """
def merge_sort(l):
length = len(l)
if length == 1 or length == 0:
return l
mid = int(length/2)
left = merge_sort(l[:mid])
right = merge_sort(l[mid:])
return merge(left, right)
def merge(l1, l2):
merged_list = []
while len(l1) > 0 and len(l2) > 0:
... |
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
@题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
@解题思路
很简单,用栈遍历结点就好啦。
下面的解法用了两个栈的原因在于要求每一层输出一行,那么用一个栈来表示当前层,一个栈用来存下一层的结点,当前层遍历完就使下一层等于当前层,循环上述过程,直到下一层没有新的结点入栈。
'''
class Soluti... |
# -*- coding:utf-8 -*-
'''
@题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
@解题思路
看了讨论区各种插入排序什么的,搞了半天时间复杂度也就是O(n)甚至更高,不如直接遍历一下不好吗?
尝试过快排的思想一个从左找偶数一个从右找奇数互换,但是这题的要求需要相对位置不变,因此也不合适,还是遍历吧。
开两个list,一个放奇数一个放偶数,最后合并,简单有效。
'''
class Solution:
def reOrderArray(self, array):
... |
# -*- coding:utf-8 -*-
'''
@题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
@解题思路
后序遍历:左节点 右节点 父节点
结合后序遍历和二叉搜索树的特点,数组最后一个数为根节点,比根节点小的都是左子树,比根节点的的是右子树。因此,判断是否是后序遍历的结果,就是判断能否根据root结点的值将数组分为小于root和大于root的两部分,可递归求解。
'''
class Solution:
def isBST(self, sequence):
# 递归结束的条件,只剩一个结点或0个结点
if le... |
# -*- coding:utf-8 -*-
'''
@题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
'''
import math
class Solution:
def Power(self, base, exponent):
# write code here
#return base**exponent #用python可一行解决
if base == 0:
return 0
if exponent == 0:
... |
# abc = [1, 2, 3, 6, 5, 4]
#
# for number in abc:
# print('Hi ' + str(number) + '!')
# for i in range(1, 6):
# print(i)
i = 0
while i < 5:
print(i)
i += 1 |
def palindromo(palabra):
palabra= palabra.replace(" ", "")
palabra=palabra.lower()
palabra_in= palabra[::-1]
if palabra==palabra_in:
return True
else:
return False
def run():
palabra=input("Escribe una palabra: ")
es_palindromo= palindromo(palabra)
if es_palindromo==True... |
def mensaje():
#Def sirve para no repetir una serie de pasos varias veces
print("Imprime este mensaje")
print("Para que se repita 3 veces")
mensaje()
mensaje()
mensaje()
#Parametros
#Ejemplo largo sin pasos comunes
opcion=input("Elige una opción (1,2,3) ")
if opcion=="1":
print("Hola")
print("¿C... |
def two_sum(nums: [int], target: int):
for (index, n) in enumerate(nums):
for (second_index, m) in enumerate(nums):
if index == second_index:
continue
if n + m == target:
return [index, second_index]
if __name__ == '__main__':
print(two_sum([1, 3... |
def is_palindrome(s: str) -> bool:
chars = [c for c in s.lower() if 97 <= ord(c) <= 122 or 48 <= ord(c) <= 57]
if len(chars) == 1:
return True
for i, c in enumerate(chars[::-1]):
if c != chars[i]:
return False
return True
if __name__ == '__main__':
print(is_palindrom... |
def validBookObject(bookObject):
#if "keyName" in dictionaryObject
if ("name" in bookObject
and "price" in bookObject
and "isbn" in bookObject):
return True
else:
return False
valid_object = {
'name' : 'sample',
'price' : 4.5,
'isbn' : 963
}
missing_name = {
'price' : 4.5,
'isbn' : 963
}
missing... |
# Take for input a credit card number
# Determine the provider
# Perform Luhn's algorithm to verify legimity
from sys import exit
import cs50
def main():
# Init
providers = {
1: "VISA",
2: "MASTERCARD",
3: "AMEX"
}
# Prompt credit card number
while True:
credit_ca... |
number = int(input("Please insert positive number"))
i1 = 1
i2 = 1
i3 = 2
hold = 0
while(i2 < number):
hold = i1
i1 = i2
i2 = hold + i1
i3 += i2
print(i3)
|
lst = [4, 2, 59, 32]
mx=lst[0]
index_max=0
mn=lst[0]
index_min=0
for i in range(len(lst)):
if mx < lst[i]:
mx = lst[i]
index_max=i
elif mn > lst[i]:
mn = lst[i]
index_min=i
print("max member is: ",mx, index_max)
print("min member is: ", mn, index_min) |
def fibonaci(n):
if n==0:
return 0
elif n == 1:
return 1
return fibonaci(n-1) + fibonaci(n-2)
print(fibonaci(2)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# from __future__ import print_function
from functools import wraps
from math import log
from random import randint, seed
from time import perf_counter
import matplotlib.pyplot as plt
def BubbleSort(array):
# array に対し破壊的
for i in range(len(array) - 1):
... |
'''
for i in range(A):
if A[:i] is palindrome,
then recursive call A[i:] -> list of lists
for each list in lists:
add A[:i] and make a new list of lists
'''
def palindrome(s):
if not s:
return False
if s == s[::-1]:
return True
class Solution:
... |
class Solution:
# @param A : string
# @return a strings
def simplifyPath(self, A):
stack = []
for path in A.split('/'):
if path == '.' or path == '':
continue
elif path == '..':
if stack:
stack.pop()
... |
class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self, A):
last_word_len = 0
current_word_len = 0
for char in A:
if char == ' ':
if current_word_len != 0:
last_word_len = current_word_len
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.