text
stringlengths
37
1.41M
def avg(num1): i=0 s=0 while i<num1: num2=int(input("enter the number ")) s=s+num2 i=i+1 a=s/3 print(a) avg(num1=3)
def sum_ques(nums): i=0 s=0 while (i<len(nums)): s=s+nums[i] i=i+1 print(s) sum_ques(nums=[1,2,3,4,5]) # SUM OF NUM IN FUNCTION
from fractions import Fraction def expansion_binaria(fraccion): #fraccion = str(input('Ingrese la fracción diadica en formato "1/denominador" : ')) try: num_fraccion = fraccion.split('/') numerador = float(num_fraccion[0]) denominador = float(num_fraccion[1]) except: pass ...
x="5103720101070215" card_number = list(x.strip()) # Remove the last digit from the card number check_digit = card_number.pop() # Reverse the order of the remaining numbers card_number.reverse() processed_digits = [] for index, digit in enumerate(card_number): #store double of the number if even indexed. ...
from turtle import Turtle square_position =[(0, 0), (-20, 0), (-40, 0)] UP = 90 DOWN = 270 RIGHT = 0 LEFT = 180 class Snake: def __init__(self): self.segments=[] self.create_snake() self.head = self.segments[0] def create_snake(self): for i in square_position: ...
outFile = open("YOUR_ASSIGNMENT.txt", "w") # open the first text file in output mode first (create a new file) print("Enter data for the first text file. Entering a $ shall result in termination of input\n") someShit = input() for matter in someShit: # for every character in the input, write the character to outFil...
''' Some starter code for your A* search '' # for GUI things ''' from tkinter import * # for parsing XML import xml.etree.ElementTree as ET # for math import math import struct import numpy as np # some constants about the earth MPERLAT = 111000 # meters per degree of latitude, approximately MPERLON =...
# ----------[ 7 ]---------- # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.What is the # 10 001st prime number? num = 2 i = 1 while num < 10001: i += 2 n = int(i ** 1 / 2) if i % 5 == 0: i += 2 n = int(i ** 1 / 2) for j in range(3,...
print('Fibonacci Sequence') a = int(input('Enter a Number: ')) b = 1 c = 0 e = 2 print(c) print(b) while e <= a: d = b+c print(d) c = b b = d e += 1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 18 14:43:10 2019 @author: niang """ import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt fig = plt.figure(figsize=(8,8)) fig, ax = plt.subplots(1) N=150 T=[] def cercle(a,b,R): for k in range(N+1): T.append...
# name: Persistent Bugger # url: https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec # Write a function, persistence, that takes in a positive parameter num and returns its # multiplicative persistence, which is the number of times you must multiply the digits # in num until you reach a single digit. def persistence...
# name: Binary Addition # url: https://www.codewars.com/kata/551f37452ff852b7bd000139 # Implement a function that adds two numbers together and returns their sum in binary. # The conversion can be done before, or after the addition. # The binary number returned should be a string def add_binary(a,b): mult = a + b ...
# Задание на оператор 'if' # При решении задачи использовал исключительно оператор 'if' # С циклами код был бы значительно короче cities = ['Москва', 'Париж', 'Лондон'] users = [{'name': 'Иван', 'age': 35}, {'name': 'Мария', 'age': 22}, {'name': 'Соня', 'age': 20}] tourists = [{'user': users[0], 'c...
import name_tools as nt import json papers = {} with open('papers.txt', encoding='utf-8-sig') as f: papers = json.load(f) def is_int(n): try: int(n) return True except ValueError: return False # name_tools.match is slow, so we use a preliminary check to reduce how often we have to...
arr1 = ['a', 'b', 'c', 'd', 'x'] arr2 = ['z', 'x', 'y'] def contains_common_item(arr1, arr2): big_array = arr1 + arr2 big_set = set(big_array) if len(big_array) == len(big_set): return False return True print(contains_common_item(arr1, arr2))
"""Utility functions""" import os import pandas as pd import matplotlib.pyplot as plt import numpy as np def symbol_to_path(symbol, base_dir="data"): """Return CSV file path given ticker symbol.""" return os.path.join(base_dir, "{}.csv".format(str(symbol))) def get_data(symbols, dates): """Read stock da...
def si(y) : if y > 7 : print("yes!") else : print("no") def age(age) : if age<18 : print("Quelle es ton école?") elif 17 < age < 65 : print("Ou travailles-tu?") else : print("Wow... T'es vieux.vieille")
"""Generate Markov text from text files.""" from random import choice # import random import sys def open_and_read_file(file_path): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ #...
class Node(object): """ class used to represent a Node. """ def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def __iter__(self): nodes = [self] while nodes[-1].has_next(): nodes.append(nodes[-1].next_node) ...
import re def all_matching_strings(regex, out_length): if out_length == 0: return output = [0] * out_length for x in range(2**out_length): r = ''.join(['a','b'][i] for i in output) if regex.match(r): yield(r) i = 0 output[i] += 1 while (i<out_length) and (output[i]==2): output[i] = 0 ...
t = int(input().strip()) def solve(passwords, loginAttempt): dead_end = set() stack = [] stack.append(([], loginAttempt)) while stack: acc, cur = stack.pop() if cur == "": return acc is_dead_end = True for password in passwords: ...
def rgb_to_cmyk(r,g,b): cmyk_scale = 100 if (r == 0) and (g == 0) and (b == 0): return 0, 0, 0, cmyk_scale c = 1 - r / 255. m = 1 - g / 255. y = 1 - b / 255. min_cmy = min(c, m, y) c = (c - min_cmy) / (1 - min_cmy) m = (m - min_cmy) / (1 - min_cmy) y = (y - min_cmy) / (1 ...
''' Calculate GPA for classes. ''' gradePoints ={'A':4, 'B':3, 'C':2, 'D':1, 'F':0} ''' Function addClass: Add classname to dictionary of classes ''' def addClass(classes, className, grade, credits): if takenClass(classes, className): return False else: #classes[className] = [gr...
class Employee: def __init__(self, name, date): self.name = name self.date = date def details(self): print("Employee Name:", self.name) print("Employee joining date:", self.date) emp = Employee("john", "18-02-2020") emp.details()
# Write a program that asks for two numbers # Thw first number represents the number of girls that comes to a party, the # second the boys # It should print: The party is exellent! # If the the number of girls and boys are equal and there are more people coming than 20 # # It should print: Quite cool party! # It there ...
# - Create a function called `factorio` # that returns it's input's factorial def factorio(numb): summ = 1 for n in range(1, numb + 1): summ = summ * n return summ print(factorio(5))
from d1_e3_Domino import Domino def initialize_dominoes(): dominoes = [] dominoes.append(Domino(5, 2)) dominoes.append(Domino(4, 6)) dominoes.append(Domino(1, 5)) dominoes.append(Domino(6, 7)) dominoes.append(Domino(2 ,4)) dominoes.append(Domino(7, 1)) return dominoes dominoes = initia...
# - Create a variable named `aj` # with the following content: `[3, 4, 5, 6, 7]` # - Reverse the order of the elements in `aj` # - Print the elements of the reversed `aj` aj = [3, 4, 5, 6, 7] # rj = 0 # for i in range(len(aj) - 1, -1, -1): # rj.append(i) # print(aj = rj) aj[4], aj[3], aj[2], aj[1], aj[0] = aj[0...
# Create a method that decrypts encoded-lines.txt # def decrypt(file_name): # textfile = open(file_name) # textdec = open('file10dec.txt', 'w') # textorig = textfile.read() # text = '' # for i in textorig: # charval = ord(i) # text += chr(charval - 1) # textdec.write(text) # ...
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() # reproduce this: # [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/purple-steps-3d/r4.png] x = 5 for i in range(1, 6): x *= 2 canvas.create_rectangle(x, x, x+x, x+x, fill='...
# Given base and n that are both 1 or more, compute recursively (no loops) # the value of base to the n power, so powerN(3, 2) is 9 (3 squared). def topower(base, power): if base == 0 or power == 0: return 1 else: return base * topower(base, power - 1) print(topower(3, 4))
# Write a program that reads a number from the standard input, then draws a # square like this: # %%%%% # %% % # % % % # % %% # % % # %%%%% # The square should have as many lines as the number was numi = int(input("Dobj ide nekem egy numit haver:" )) for n in range(1, numi +1): print("%")
#User function Template for python3 def countOfElements( arr, total_num, x): count=0 for i in range(total_num): if(arr[i]<=x): #print(arr[i]) count = count + 1 #print(count) else: exit return count def main(): T = int(input()) while...
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # STRETCH: implement Linear Search def linear_search(arr, target): for i in arr: if i == target: return True return False linear_search(my_list, 8) # STRETCH: write an iterative implementation of Binary Search def binary_search(arr, target): ...
def readInteger(): try: sNumber = raw_input() return int(sNumber) except ValueError: print "Skipping value '",sNumber,"'. Not a number" exit() print "This will find indexes/positions of numbers from the list." print "Enter size of the 1st list (the original data):" iSizeDataset...
import random class Ability: def __init__(self, name, attack_strength): '''Create Instance Variables: name:String max_damage: Integer ''' self.name = name self.attack_strength = attack_strength # TODO: Instantiate the variables listed in the docstr...
valor_1 = 100 valor_2 = 14 #Soma valor_soma = valor_1 + valor_2 print('O valor da soma eh ', valor_soma) #Subtração valor_sub = valor_1 - valor_2 print('O valor da subtração eh ', valor_sub) #Divisão valor_div = valor_1 - valor_2 print('O valor da divisão eh ', valor_div) #Multiplicação valor_mult = valor_1 * valo...
import exceptions import os class FileNotFound(Exception): def __init__(self,val): self.val = val def __str__(self): return repr(self.val) class ReadMonthlyMass: ## # Initialize the monthly mass constructor # @param filename Filename for the monthly mass file to read def __init...
'''Dynamic programming example used for calculating in which order whould we arrange a certain thing example bag''' def knapsack(val,wt,W,n): if n==0 or W==0: return 0 if wt[n-1]>W: return knapsack(val,wt,W,n-1) else: return max(val[n-1]+knapsack(val,wt,W-wt[n-1],n-1),knapsack(val,wt,W,n-1))#return largest val...
arr=[] top=-1 while(1): print("choose:") print("1.push 2.pop 3.top") ch = int(input()) if(ch==1): top=top+1 arr.insert(top,int(input("Enter num to push:"))) print("Entered element is:",arr[top]) elif ch==2: if top == -1: print("STACK UNDERFLOW") else: print("popped element is ",arr[top]) top=t...
import sys import os ########## WRITING FILE OUT ########## #open file to write and read f = open('read_write.txt', 'w+') for number in range(1, 10): #write number to file (with a new line) f.write("{0}\n".format(number)) #create a list of letters to output to our file letters = ['a', 'b', 'c', 'd', 'e...
# https://leetcode.com/problems/longest-palindromic-substring/ # Time out class Solution: def longestPalindrome(self, s: str) -> str: for length in range(len(s), 0, -1): for start_index in range(len(s) - length + 1): word = s[start_index : start_index + length] ...
x=input("Enter the radius of the cirlcle") area=3.14*r* print("Area of cirlcle is",area)
from copy import deepcopy import board as b class HumanPlayer: def __init__(self, black) -> None: self.black = black def _get_action_input(self, phase): pos_1 = None pos_2 = None pos_3 = None if phase == 1: x_y = input("Enter target x and y:") x ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 8 21:17:15 2020 @author: dogukan """ # %% # list liste = [1,2,3,4,5,6] print (type (liste)) liste_str = ["pazartesi", "sali", "carsamba"] type(liste_str) value = liste [1] print (value) last_value = liste [-1] print(last_value) liste_divide = li...
def update(x): print(id(x)) x=8 print(id(x)) print("x",x) a=10 print(id(a)) update(10) print("a",a) def update(lst): print(id(lst)) lst[1]=25 print(id(lst)) print("x",lst) lst=[10,20,30] print(id(lst)) update(lst) print("lst",lst)
def fact(n): f=1 for i in range(1,n+1): f=f*i return f x=4 result =fact(x) print(result)
from tkinter import* from tkinter import ttk class Ventana(Frame): def __init__(self, master=None): super(). __init__(master, width=680,height=260) self.master = master self.pack() self.create_widgets() def fNuevo(self): pass def fModificar(self): p...
#Class: CS 4308 Section 01 #Term: Summer 2021 #Name: Ruthana, Jorge, Seth #Instructor: Deepa Muralidhar #Project: Deliverable 3 Interpreter - Python import scanner import descent_parser # TODO: 1. Open and Read file def main(): #scanner now handles file input directly through get_char funct...
import json ''' >wikiのマークアップ早見表 wikiのデータ形式に関することは以下のリンク先に書かれている https://ja.wikipedia.org/wiki/Help:%E6%97%A9%E8%A6%8B%E8%A1%A8 ''' class Section_3(): #ss1-ss9で利用 jsonを読んでデータを返す def read_json(self): f = open('jawiki-country.json','r') for count,line in enumerate(f): data_json = json.loads(line) if data...
import numpy as np import plotly.graph_objects as go import pandas as pd from sklearn.linear_model import LinearRegression pd.options.plotting.backend = "plotly" def get_best_fit(data, verbose=False): ''' Gets a curve of best fit with the given data. It is assumed that companies generally increase their d...
filename = "input.txt" file = open(filename) #read in the lines passwords = [] line = file.readline() while line: passwords.append(line) line = file.readline() #do the thing: scrape counter = 0 for full_line in passwords: rule, password = full_line.replace(" ","").split(":") okay_index = int(rule.split("-")[0]...
# 2. Реализовать класс Road (дорога). # определить атрибуты: length (длина), width (ширина); # значения атрибутов должны передаваться при создании экземпляра класса; # атрибуты сделать защищёнными; # определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; # использовать формулу: длина * шир...
from math import pi, e, factorial, sqrt, pow import math as mt def constante(exp): #esta funcao substitui as funcoes em numeros para utilizar no calculo exp = exp if "π" in exp: exp = exp.replace("π", str(pi)) if "e" in exp: exp = exp.replace("e", str(e)) return exp def fatorial(...
import random WORDS = ("terorysta","marchewka", "smaczne", "koronawirus", "mercedes") word = random.choice(WORDS) correct = word jumble = "" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print("Witaj w grze") print("zgadnij jakie ...
def enter_radius(): radius = input("Enter value for radius: ") return eval(radius) def calc_area(radius): pi = 3.14159 area = 2 * pi * (radius * radius) return print("Area: " + area) calc_area(enter_radius())
sum = 0 for i in range(1, 21): if i % 2 == 0 or i % 3 == 0: sum += i print(sum)
for i in range(1, 31): print("{:3d}".format(i), end=" ") if i % 7 == 0: print()
import math print("{0:<10} {1:<10} {2:<10}".format("degree", "sin", "cos")) for i in range(0, 370, 10): print("{0:<10} {1:<10.4f} {2:<10.4f}".format(i, math.sin(math.radians(i)), math.cos(math.radians(i))))
number = 1000 count = 0 for i in range(1, number): if i % 2 == 0 or i % 3 == 0 and i != 2: print(i, "is not prime") elif i == 2: print(i, "is prime") count += 1 else: print(i, "is prime") count += 1 print("Number of primes", count)
import turtle1 angle = 90 d = 5 turtle1.speed(1000) for i in range(300): turtle1.forward(d) turtle1.right(angle) turtle1.circle(30) d += 2 turtle1.done()
import time # for i in range(9, 0, -1): # time.sleep(1) # print(i) # print("Boom") factor = 1 for step in range(3): for i in range(9, 0, -1): print(factor * i) time.sleep(0.5) factor *= 0.1 print("Boom")
""" Creates new set of books based on user's query. Function is called in route: add_books with POST method. """ import requests from datetime import datetime from flask_sqlalchemy import SQLAlchemy def get_new_books(book, link: str, db: SQLAlchemy) -> None: """ Passes the query to the Google Book API, retri...
import MyResources import random import MyEvents class Ship: def __init__(self): self.Gold = 0 self.ShipHpBeg = 0 self.ShipHp = 0 self.CrewHpBeg = 0 self.CrewHp = 0 self.Fame = 0 self.Infamy = 0 self.Happiness = 0 self.Wealth = 0 self...
""" Anagram functions Algorithms with different orders of magnitude """ import unittest from collections import OrderedDict def anagram_first(first, second): """ Strategy: Tick off """ if first == second: return True if not len(first) == len(second): return False for char ...
""" Linked List implementation run tests: python3 list.py """ import unittest class Node: def __init__(self, value): self.next = None self.value = value class LinkedList: def __init__(self): self.head = None def append(self, value): if self.is_empty(): ...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def getResult(self, root, result, level): if not root: return None if len(result) <= level: result.insert(0, []) ...
class Solution(object): def longestPalindromeSubseq(self, s): """ :type s: str :rtype: int """ d = {} def findIn(s): if s not in d: max_length = 0 for i in set(s): i, j = s.find(i), s.rfind(i) ...
from tree_generator import TreeGenerator # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def check(self, root, min, max): if not root: return True if (m...
# Uses python3 import sys def get_change(m): # List will hold min number of change coins for values 0 - m min_num_coins = [0] * (m + 1) # Change coins coins = [1, 3, 4] # Looping through all the money values from 0 to m to find the change for each for money in range(1, m + 1): min...
""" there is no 9 digit number exist for condition """ # how many digit numbers ref = set("02468") f = lambda x:set(str(x+int(str(x)[::-1]))).isdisjoint(ref) count = 0 for digit_len in range(2,9): for first_digit in range(1,10): def get_numbers(first_digit, digit_len, num): global count ...
from prime import is_prime l1 = 2 l2 = 8 l3 = 20 l2_size = 2 # 6*l2_size corner_gape_l2 = 1 count = 2 # first 1 second 2 current_ans = 2 while(True): start_point = l2 end_point = l2+6*l2_size-1 start_ele_pd = 0 end_ele_pd = 0 if is_prime(abs(6*l2_size-1)): start_ele_pd+=1 end_ele_pd+=1 # for start start_...
import re def min_and_max(iterable): iterator = iter(iterable) # Assumes at least two items in iterator minim, maxim = sorted((next(iterator), next(iterator))) for item in iterator: if item < minim: minim = item elif item > maxim: maxim = item return (mi...
total = 0 for h in range(24): #시간 for m in range(60): #분 if '3' in str(h) or '3' in str(m): total += 60 print (total)
n1 = float(input("Digite primer número: ")) n2 = float(input("Digite segundo número: ")) while(True): print("****MENU****") print("1.- Sumar dos números") print("2.- Restar dos números") print("3.- Multiplicar dos números") print("4.- Salir del programa") opcion = input("Opción: ") ...
from tkinter import * window = Tk() window.title("Welcome to LikeGeeks app") # set window size - sets window width to 350 pixels and the height to 200 pixels window.geometry('350x200') """ Common Steps 1. Create widget 2. Position widget in grid 3. Add attributes (font, forground color, background color...
#counts number of sequences in File import sys file = sys.argv[1] f = open(file, "r") cnt = 0 for line in f: if line[0] == "#": # 3 lines with "#" per sequence cnt+=1 print(cnt, cnt/3)
#!/usr/bin/python # -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python in...
#!/usr/bin/python2 for i in range(1,5): print i else : print 'the for loop is done '
class Tank(object): def __init__(self,name): self.name = name self.alive = True self.shells = 5 self.armor = 60 def __str__(self): if self.alive: return "%s (%i shells, %i armor)" % (self.name, self.shells, self.armor) else: return "%s is...
#!/usr/bin/python2 #Filename is docstring.py def printMax(x,y): '''Print the maximum of the two numbers. The two numbers must be integers''' x = int(x) y = int(y) if x > y : print x ,'is the maximum one ' else: print y ,'is the maximum one ' printMax(3,5) print printMax.__doc__...
#!/usr/bin/python2 #Filename is using_file.py poem = '''\ program amming is fun when the work is done if you want to make your work also fun: use Python! ''' f = file('poem.txt','w')#open for 'w'riting f.write(poem) f.close() f = file('poem.txt') #if no mode is specified ,'r'ead mode is assumed by default while Tr...
a=int(input("enter a")) b=int(input("enter b")) n=a+b if n%2==0: print("even") else: print("odd")
# Наследование """class Person: name = "Ivan" age = 10 def set(self, name, age): self.name = name self.age = age class Student(Person): course = 1 igor = Student() igor.set("Igor", 19) print(igor.course) vlad = Person() vlad.set("Влад", 25) print(vlad.name + " " + str(vlad.age)) iv...
import sqlite3 from sqlite3 import Error class File_database(object): def __init__(self): self.conn = sqlite3.connect("file database management.db") self.cur = self.conn.cursor() self.username = "" self.conn.execute("""CREATE TABLE IF NOT EXISTS users( us...
import scrabble def is_palindrome(word): return word == word[::-1] count_palindromes = 0 longest = "" for word in scrabble.wordlist: if is_palindrome(word): count_palindromes += 1 if len(word) > len(longest): longest = word print("\nTotal number of palindromes: {:d}".format(count...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class BSTIterator: # Use a stack to store nodes; if it is not empty, then it has Next # Initialize: get all left nodes...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(self, root: "TreeNode") -> None: """ Do not return anything, modify root in-pl...
def recur_fibo(n,m): """Recursive function to print Fibonacci sequence""" if n < 1: return 0 elif n==1: return 1 else: for i in range(1,m+1): return recur_fibo(n-m,m) c=recur_fibo(5,2) print(c)
import numpy as np import pylab def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) x = np.array(range(1, 100)) / 100 b = -40 w = 500 # 一个神经元的输出 # y = sigmoid(w * x + b) # # pylab.plot(x, y, 'r-', label=u'b -40 w 100') # pylab.legend() # 两个神经元 s1 = 0 s2 = .2 h1 = -.3 h2 = .3 s3 = .2 s4 = .4 h3 = -1.3 h4 = 1.3...
def x_win(game): for i in range(3): if game[3 * i] == game[3 * i + 1] == game[3 * i + 2] == "X": return True elif game[i] == game[i + 3] == game[i + 6] == "X": return True if game[2] == game[4] == game[6] == "X": return True elif game[0] == game[4] == game[8] ...
import math import numpy as np import matplotlib.pyplot as plt import sys ## USER DEFINED INPUTS -- call cmd: python RKT2.py A B C # A. Defines where on Earth the Rocket starts at def getLaunchPadAngle(): try: return float(sys.argv[1]) except ValueError: print("Invalid Velocity...
import math def test_palindrome1(strings,answer): print (palindrome1(strings)==answer) def test_palindrome2(strings,answer): print (palindrome2(strings)==answer) def test_palindrome3(strings,answer): print (palindrome3(strings)==answer) def test(): test1 = "abba" test_palindrome3(test1,True) ...
import math def test(expected,answer): print(expected==answer) def test_multiply_left_right_array(): test1 = [1,2,3,4] test(multiply_left_right_array(test1),21) test2 = [4,5,6] test(multiply_left_right_array(test2), 44) test3 = [] test(multiply_left_right_array(test3),0) test4 = [10,9,8...
def test(output,expected): print(output==expected) def test_list_to_string(): test1 = "g e e k s f o r g e e k s" test(list_to_string(test1),"geeksforgeeks") test2 = "p r o g r a m m i n g" test(list_to_string(test2),"programming") def list_to_string(strs): strs = list(strs) for i in range...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) <= 1: return s out = s[0] for i in range(len(s)-1): l = len(out)/2 tmp = sel...
import l98 # import l102 # level order traversal class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(3) root.left = TreeNode(1) root.right = TreeNode(5) root.left.left = TreeNode(0) root.left.right = TreeNode(2) root.right.left ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # recursive """ def postorderTraversal(self, root): if root is None: return [] retu...
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix)-1 if n <= 0: return None for i in range((n+1)/2): for j in ra...
import matplotlib.pyplot as plt # x_values = [1, 2, 3, 4, 5] x_value = list(range(1, 1001)) # y_values = [1, 4, 9, 16, 25] y_values = [x ** 2 for x in x_value] plt.scatter(x_value, y_values, s=20, edgecolors='none', c=y_values, cmap=plt.cm.Blues) # 设置图表标题,并给坐标轴加上标签 plt.title("Square Numbers", fontsize=24) plt.xlabel(...