text stringlengths 37 1.41M |
|---|
import numpy as np
data_list = [0,1,2,3,4,5,6,7,8,9]
mean = np.mean(data_list)
median = np.median(data_list)
std = np.std(data_list)
print("mean -> ",mean)
print("median -> ",median)
print("std -> ",std)
|
import fileinput
from typing import List, Dict
orbits: Dict[str, str] = {}
def listOrbits(obj: str) -> List[str]:
if obj in orbits:
chain: List[str] = listOrbits(orbits[obj])
chain.append(obj)
return chain
else:
return []
def main():
for line in fileinput.input():
... |
print("Hello World")
message = "Hello World"
print(message)
def printme( str ):
"This prints a passed string into this function"
print (str)
return
printme("Hello")
def main():
print("I have defined main here")
return
main()
|
__author__ = '100068'
# coding:utf-8
# !/usr/bin/env python
#乘法运算符重载
class mulList(list):
def __mul__(self, b):
result=[]
a=self[:]
c=b[:]
if len(a)>=len(c):
for i in range(len(c)):
result.append(a[i]*b[i])
else:
for i in range(len(a)):... |
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def print_level_order(root):
for h in range(1, height(root) + 1):
print_given_level(root, h)
print()
def print_given_level(root, level):
if root is None: return
if leve... |
animal = ['dog', 'cat', 'parrot', 'goldfish']
for x in animal:
print('%s %d' % (x, len(x)))
|
num = int(input())
for i in range(1, num+1):
print (i, i * i)
|
"""Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this nod... |
#Creating two functions to check whether the received values meets the required criteria
def check1():
while True:
try:
n=input("Enter an integer: ")
if int(n)<0 or int(n)>255:
print("Please enter value between 0 and 255.")
else:
br... |
#import random
from random import randint
player_wins = 0
computer_wins = 0
winning_score = 2
while player_wins < winning_score and computer_wins < winning_score:
print("Player score:{} Computer score: {}".format(player_wins,computer_wins))
print("Rock...")
print("Paper...")
print("Scissors...")
... |
from typing import Sequence
class Helper():
def merge_sort(array: Sequence[str]):
"""merge sort implementation
Base Case: return if the array len is 1 since we can assume this is a sorted array
Recursion: breaks the array down to one
Args:
Array: ... |
# Sa se scrie o functie care primeste un numar nedefinit de parametrii
# si sa se calculeze suma parametrilor care reprezinta numere intregi sau reale
print('-> This is the first exercise: ')
def test_is_number(param):
if not isinstance(param, bool): #am inceput prin a exclude variabilele de tip bool (pentru ca... |
# Dak Prescott
# Aka: air resistance in two dimensions
import numpy as np
import matplotlib.pyplot as plt
from numpy.core.fromnumeric import argmax
# Parameters to start off
g = 9.81 # m/s**2
v0 = 30 # m/s, initial velocity
theta = 30 # degrees, initial angle
vt = 45 # m/s, terminal velocity of a football
# The vari... |
'''
Lyapunov exponent example from class
Measures if a system is chaotic or not.
'''
import numpy as np
import matplotlib.pyplot as plt
# Initial values
dx = 0
sumd = 0
n = 10000
r = np.linspace(0.01, 1.0, 1000)
lamb = np.zeros(r.size)
'''
Lambda > 0: chaos
Lambda < 0: other type of behavior
'''
# Iteratic the... |
def areYouPlayingBanjo(name):
return name + (' plays' if name[0].lower() == 'r' else ' does not play') + " banjo";
def count_sheeps(sheep):
return sheep.count(True)
array1 = [True, True, True, False,
True, True, True, True ,
True, False, True, False,
True, False, Fa... |
#Escribir un programa que pida al usuario una palabra
#y la muestre por pantalla 10 veces.
word=str(input("Ingrese palabra a repetir: "))
for i in range(10):
print(word) |
import numpy as np
import time
from typing import Optional, Tuple, Iterable
# Analysis functions for strategy
class Analysis:
def get_future_ball_array(self):
"""Samples incrementally to return array of future predicted ball positions"""
ball_pos = self._gs.get_ball_position()
# this defini... |
import time
import euler
start_time = time.time()
# The number, 197, is called a circular prime because all rotations of
# the digits: 197, 971, and 719, are themselves prime.
#
# There are thirteen such primes below 100:
# 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#
# How many circular primes are there be... |
import time
start_time = time.time()
# In the United Kingdom the currency is made up of pound (£)
# and pence (p). There are eight coins in general circulation:
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p).
# It is possible to make £2 in the following way:
# 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
# How m... |
import time
from math import factorial
start_time = time.time()
# n! means n × (n − 1) × ... × 3 × 2 × 1
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
# Find the sum of the digits in the number 100!
total = 0
for x in str(f... |
#!/usr/bin/env python3
""" Complex types - list of floats """
import typing
def sum_list(input_list: typing.List[float]) -> float:
""" function sum_list which takes a list input_list
of floats as argument and returns their sum as a float """
return sum(input_list)
|
# 4. Исправьте класс Word, чтобы указанный ниже код не вызывал ошибки.
class Word:
def __init__(self, text):
self.text = text
class Sentence:
def __init__(self, content):
self.content = content
def show(self, words):
sentence = ''
count = 0
for word_number in self.... |
#!/usr/bin/env python3
# HW06_ch09_ex02.py
# (1)
# Write a function called has_no_e that returns True if the given word doesn't
# have the letter "e" in it.
# - write has_no_e
# (2)
# Modify your program from 9.1 to print only the words that have no "e" and
# compute the percentage of the words in the list have no "... |
string1 = "taco"
i = ['a', 'b', 'c',]
def missing_char(i):
strin_missing = list()
for i in string1:
string1.replace(i, '')
return "".replace(i, '')
missing_char(i, '') |
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
def powers_of_two(nums):
for numbers in nums:
print(2**numbers)
powers_of_two(nums) |
class parent():
'This gives the declaration of the parent class'
def __init__(self,var1,var2):
self.var1=var1
self.var2=var2
def ope(self):
print "parent class sum : ",self.var1+self.var2
class child(parent):
'This gives the declaration of the parent class'
def __init... |
dict={'key':'value','hyd':'sec'}
#not converting to string representation
print "dictionary",dict
dict['abc']='xyz'
#converting to string representation
print "dictionary",str(dict)
|
print "enter var1"
var1=input()
print "enter var2"
var2=input()
print "enter var3"
var3=input()
if(var1>var2 and var1>var3):
print "Max is ", var1
elif(var2>var1 and var2>var3):
print "Maxi is ", var2
else:
print "Max is", var3
|
dict={'key':'value','hyd':'sec'}
dict['abc']='xyz'
print "dictionary length : ",len(dict)
|
list=[6,6,4,3,2,2,5,7,8]
var=0
while(var<len(list)):
print "element",list[var]
var=var+1
|
class a():
'This gives the declaration of the parent class'
def disp(self):
print " class 'a' calling"
class b():
'This gives the declaration of the child class'
def disc(self):
print "class 'b' calling"
class c():
'this is class c'
def calling(self):
obj_p=a()
... |
tuple1=(2,5,6,7,1,9,0)
tuple2=(7,5,7,9,3,1,3,5,6,2,5,6,7,1,9,0)
print "all elements",tuple1+tuple2
|
list1=[2,5,6,7,1,9,0]
print "all elements",list1
list1.append(100)
print list1
list=[7,5,3,2,4,6,7,5,4,0]
list1.extend(list)
print list1
list1.insert(10,10)
print list1
list1.pop()
print list1
list1.pop(0)
print list1
print list1.count(6)
print list1.index(10)
list1.sort()
print list1
#print list1.sort() - will not wor... |
# Python Crash Course 2nd Edition
# Page 173 (Inheritance)
# Section 9-6: Ice Cream Stand
# An ice cream stand is a specific kind of restaurant. Write a class called IceCreamStand that
# inherits from the Restaurant class you wrote in Exercise 9-1 (page 162) or Exercise 9-4
# (page 167). Either version of the class wi... |
# Python Crash Course 2nd Edition
# Page 127 (While Loops with Lists and Dictionaries)
# Section 7-8: Deli
# Make a list called sandwich_orders and fill it with the names of various sandwiches. Then make
# an empty list called finished_sandwiches. Loop through the list of sandwich orders and print a
# message for eac... |
# Python Crash Course 2nd Edition
# Page 150 (Arbitrary Number of Arguments)
# Section 8-12: Sandwiches
# Write a function that accepts a list of items a person wants on a sandwich. The function should
# have one parameter that collects as many items as the function call provides, and it should
# print a summary of th... |
# Python Crash Course 2nd Edition
# Page 155 (Functions in Modules)
# Section 8-15: Printing Models
# Put the functions for the example printing_models.py in a separate file called
# printing_functions.py. Write an import statement at the top of printing_models.py, and modify
# the file to use the imported functions. ... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg')
px = img[100,100]
# Display 3 channels of pixel
print px
# accessing only blue pixel
blue = img[100,100,0]
print blue
#You can modify the pixel values the same way
img[100,100] = [255,255,255]
print img[100,100]
img.... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
sess = tf.InteractiveSession()
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
# initial parameters
width = 28
height = 28
flat = width * height
class_output = 10
# input and output
x = tf.placeholder(tf.float32, sh... |
def climbingLeaderboard(scores, alice):
scores = sorted(list(set(scores)))
index = 0
rank_list = []
n = len(scores)
for i in alice:
while (n > index and i >= scores[index]):
index += 1
rank_list.append(n+1-index)
return rank_list
'''
def climbingLeaderboard... |
import csv
import datetime
import shutil
from tempfile import NamedTemporaryFile #imported class
# these are all built in functions in Python
#figure out the number of rows
def get_length(file_path):
with open("data.csv", "r") as csvfile:
reader = csv.reader(csvfile)
reader_list = list(reader) #li... |
import csv
with open("data.csv", "w+", newline='') as csvfile: #I found newline in documentation to avoid auto add of blank line
... writer = csv.writer(csvfile)
... writer.writerow(["Title", "Description", "Col 3"])
... writer.writerow(["Row 1", "Some Desc", "another"])
... writer.writerow(["Row 1", "... |
__author__ = "Michał Kuśmierczyk (kusm@protonmail.ch)"
__date__ = "29.01.15"
__license__ = "Python"
scales = ("C", "F", "K", "R", "DE", "N", "RE", "RO")
def convert_temp(temp, from_scale, to_scale):
"""Convert temperature to a different scale
possible scale inputs:
"C" for Celsius
"F" for Fahrenheit... |
__author__ = "Michał Kuśmierczyk (kusm@protonmail.ch)"
__date__ = "30.01.15"
__license__ = "Python"
def encryptor(key, message):
"""Encrypt a message using Ceasar Cipher"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
encrypted_message = []
for letter in message:
if not (letter.lower() in alphabet)... |
#-*- coding: utf-8 -*-
print('Teste de palíndromo')
texto = str(input('Digite um texto: '))#entrada de dados (strings)
texto = texto.replace(" ","")#remove todos os espaços
if texto == texto[::-1]:
print('Esse texto é palíndromo!') # testa se a string X é igual a string X inversa
else:
print('Esse texto não é pa... |
#importa bibliotecas
from random import randint
#escolhe um número aleatório de 1 a 10
while True:
print('='*50)
print('JOGO DA ADIVINHACAO 3.1')
print('Acerte o numero que o computador escolher')
print('Escolha o tamanho do grupo de numeros para jogar:')
print('[1]facil: 1 ate 10')
print('[2]medio: 1 ate... |
## первая задача
print("Введите длину")
n=float(input())
while(n<0):
print("Введите длину")
n=float(input())
print("Введите ширину")
m=float(input())
while(m<0):
print("Введите ширину")
m=float(input())
if(m>n):
temp=n
n=m
m=temp
print("Введите растояние до от одного из дл... |
# 11. Write a Python program to convert a list to a tuple.
def convert (list):
return tuple (list)
list = [1, 2, 3, 4, 5]
print (convert (list))
|
# 5. Write a Python program to add an item in a tuple.
# Jeden sposób:
krotka = (1, 2, 3, 4, 5)
krotka = krotka + (6,)
print (krotka)
# Drugi sposób:
krotka1 = 7
krotka = krotka + (krotka1,)
print (krotka)
|
"""
14. Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
"""
from datetime import date
d1 = date(2019, 9, 11)
d2 = date(2019, 9, 18)
d3 = d2 - d1
print(d3.days)
"""
15. Write a Python program to get the volume of a sph... |
"""
21. Write a Python program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user.
"""
x = int(input("Enter the number: "))
if (x % 2) == 0:
print("The number is even")
else:
print("The number is odd")
"""
22. Write a Python program... |
# 生成器
L = [x * x for x in range(10)]
print(L)
g = (x * x for x in range(10))
for n in g:
print(n)
# 斐波拉契数列 Fibonacci
# 如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
def fib(max):
print('begain')
n, a, b = 0, 0, 1
while n < max:
yield(b)
a, b = b, a + b
n += 1
return 'done'
print(fib(10))
def odd():
p... |
#Daniel Lu
#07/23/2020
#Converts degrees Fahrenheit to Celsius
f = int(input("Please enter the degrees in Fahrenheit: "))
c = ((f - 32)* 5/9)
print("That is " + str(c) + " degrees Celsius")
|
import math; #diifieHellman
n=int(input("1st prime"))
g=int(input("2nd prime"))
x=int(input("1st private number"))
y=int(input("2nd private number"))
a=pow(n,x)%g #n and g interchangeble
b=pow(n,y)%g
k1=pow(a,x)%g
k2=pow(b,y)%g
if(k1==k2):
print("Successful")
else:
print("unsuccessful")
|
#Write a function named avoids that takes a word and a string of forbidden letters, and that returns
# True if the word doesn’t use any of the forbidden letters.
def avoid(string,forbidden_str):
for i in string:
if forbidden_str in string:
return True
else:
return False
string=str(i... |
#Modify the above program to print only the words that have no “e” and compute the percentage of the words
# in the list have no “e.”
def has_no_e(list1):
list2=[]
count=0
for i in list1:
if "e" in i:
list2.append(i)
print((len(list2)/len(list1))*100)
str1=str(input())
list1=str1.spl... |
#Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function
# called is_anagram that takes two strings and returns True if they are anagrams.
def is_anagram(str1,str2):
str1=list(sorted(str1))
str2=list(sorted(str2))
if str1==str2:
return True
else:
... |
#valume of sphere
'''def vol_sphere(r1):
global pi
return (4/3)*pi*r*r*r
pi=3.142
r=int(input())
print(vol_sphere(r))'''
#Suppose the cover price of a book is Rs.24.95, but bookstores get a 40% discount. Shipping costs
#Rs.3 for the first copy and 0.75p for each additional copy. What is the total wholesale co... |
import unittest
from unittest.main import main
from calculate import calc
class TestCalculate(unittest.TestCase):
def test_calculate(self):
case1 = ["Ya", "Ya", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak", "Tidak"]
case2 = ["Tidak", "Tidak", "Tidak", "Ya", "Tidak", "Tidak", "Tidak", "Tidak"]
... |
### SCRIPT FOR MULTIPLE PAGES ###
from requests import get
from bs4 import BeautifulSoup
"""We’ll scrape the first 4 pages of each year in the interval 2000-2017. 4 pages for each of the 18
years makes for a total of 72 pages. Each page has 50 movies, so we’ll scrape data for 3600 movies
at most. But not all ... |
# get current weather data
def k2c(k):
return k-273.15
# Python program to find current
# weather details of any city
# using openweathermap api
# import required modules
import requests, json
# Enter your API key here
api_key = "9a6f64de069cb85d600ee405159a85f3"
# base_url variable to store url
base_ur... |
import dictionary as dict
def encryptor(text):
encrypted_text= ""
for letter in text:
if letter != " ":
encrypted_text= encrypted_text + dict.MORSE_CODE_DICT.get(letter) + " "
else:
encrypted_text += " "
print("The morse code is : ",encrypted_text)
return(encrypte... |
import random
def start_game():
import sys
# to invoke sys.exit when player does not want to play another game
print('Welcome to the Number Guessing Game! \nCan you guess the number I have in mind?')
scores = []
while True:
answer = random.randint(1, 100)
# generate random answer f... |
str = input()
str2 = reversed(str)
if list(str)==list(str2):
print("you inputted a strong string")
else:
print("you inputted a weak string") |
#Author: Maple0
#Github:https://github.com/Maple0
#1st Sep 2016
#print pyramid by using *
def print_pyramid1(rows):
for x in range(0,rows):
print("*"*(x+1))
def print_pyramid2(rows):
i=rows
while i>0:
print("*"*i)
i-=1
def print_pyramid3(rows):
for i in range(0,rows):
print(' '*(rows-i-1) + '*' * (2*i+1)... |
#Author: Maple0
#Github:https://github.com/Maple0
#3st Sep 2016
#convert the decimal number into binary and vise-versa
def decimal_to_binary1(num):
temp=int(num)
remainder=0
binary=0
i=1
while temp >0:
remainder=temp%2
temp=int(temp/2)
binary+=remainder*i
i*=10
print(binary)
def decimal_to_binary2(num):... |
class Node:
"""
Class to represent one node in a parse tree
"""
def __init__(self, tree, tree_id, pos):
self.tree = tree
self.tree_id = tree_id
self.pos = pos
def __str__(self):
string = "id " + str(self.tree_id) + "\n"
string += "pos " + str(self.pos) + "\n... |
"""
print(2+2)
print('')
x=2
print(x)
print('')
print (x+2)
print('')
print(2+2*3)
"""
"""
print('Spam' == 'Eggs')
print('')
spam = 'Eggs'
print(len(spam))
print('')
x = 2
print(x == 2)
print(type(x))
y = 2.5
print(type(y))
print(x==y)
print(x)
"""
number_of_pupils=16
number_of_sweets=47
number_of_sweets_per_pupil=nu... |
#!/usr/bin/python3
""" module that defines a class Base """
from json import dumps, loads
import csv
class Base:
""" class Base definition """
__nb_objects = 0
def __init__(self, id=None):
""" class Base object Constructor"""
if id is not None:
self.id = id
else:
... |
#!/usr/bin/python3
""" function find_peak """
def find_peak(list_of_integers):
'''finds peak'''
if len(list_of_integers) > 0:
list_of_integers.sort()
return list_of_integers[-1]
else:
return None
|
#!/usr/bin/python3
def roman_to_int(roman_string):
numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000}
if type(roman_string) is not str or roman_string is None:
return 0
strg = list(roman_string[::-1].upper())
flag = 1
sum = 0
for l in range(len(s... |
#!/usr/bin/python3
""" a module for a function that prints a square with the character #. """
def print_square(size):
""" function that prints a square with the character #.
Args:
size: type int the size of the squares side
Raises:
TypeError: type of ize must be int
ValueError: siz... |
import random
def method1():
diceCount = [0, 0, 0, 0, 0, 0, 0]
throws = 100
diceList = []
for i in range(1, throws+1):
randomThrow = (random.randrange(1,6+1))
diceList.append(randomThrow)
face1 = diceList.count(1)
face2 = diceList.count(2)
face3 = diceList.count(3)
face4... |
class BankAccount:
__defaultBalance = 100
def __init__(self, accountId, pin, balance=__defaultBalance):
self._accountId = accountId
self._pin = pin
self._balance = float(balance)
#getter
@property
def accountId(self):
return self._accountId
@property
def pi... |
#PROPERTIES - MORE PYTHONIC WAY LOL
class Student():
def __init__(self, name):
self._name = name
#getter
@property
def name(self):
return self._name
#setter
@name.setter
def name(self, value):
self._name = value
student1 = Student("bali")
print(student1.name)... |
#POLYMORPHISM
print("START PROGRAM ... ")
print("----------------")
class Student():
def __init__(self, name, age, school, role):
self.name = name
self.age = age
self.school = school
self.role = role
def work(self):
print("I am working as a normal student!")
class Sof... |
numbers = [6, 10, 2]
a = dict()
for x in numbers:
a[x] = x[0]
a.append((x))
a.sort()
print(a) |
def new_set():
A,p = [],1
while p!=0:
p = int(input('Want to enter a new element? '))
if p == 0: break
x = int(input('Enter a new element. '))
if x not in A: A.append(x)
return A
def union_set(A,B):
C = []
for i in range(len(A)): C.append(A[i])
for i in range(len(... |
import pygame
from SudokuSolver import solve, valid_move
import time
pygame.font.init()
class Grid:
board = [
[8, 0, 9, 3, 0, 1, 0, 0, 0],
[0, 6, 0, 9, 0, 7, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 6, 9],
[3, 0, 5, 6, 0, 0, 0, 1, 4],
[1, 0, 6, 2, 0, 4, 5, 0, 3],
[4, 2, 0, ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 13:35:55 2019
@author: Mateusz.Jaworski
"""
import random
ints = range(33,127)
password = ''
for i in range(10):
password += chr(random.choice(ints))
print(password) |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 18:56:58 2019
@author: Mateusz.Jaworski
"""
i = 10
result = 1
for j in range (1,11):
result *= j
print(i, result)
print('------NEW------')
list_noun = ['dog', 'potato', 'meal', 'icecream', 'car']
list_adj = ['dirty', 'big', 'hot', 'colorful', 'fast... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 11:36:35 2019
@author: Mateusz.Jaworski
"""
import math
degree1 = 360
radian=pi*degree/180
print("%d degree is %f radians" % (degree1, radian))
degree2 = 45
radian=pi*degree/180
print("%d degree is %f radians" % (degree2, radian))
math.radians(degree1)
math.rad... |
import math
x = math.radians(float(input("X = ")))
y = math.radians(float(input("Y = ")))
print(math.cos(x))
print(math.sin(y))
if (math.cos(x) - math.sin(y)) == 0:
print("Решений не существует")
elif x*y % math.radians(180) == math.radians(90):
print("Решений не существует")
else:
a = ((math.sin(x) - math.... |
import math
print("Введите высоты")
a = float(input("a = "))
b = float(input("b = "))
c = float(input("c = "))
if a <= 0 or b <= 0 or c <= 0:
print("Решений не сушествует")
else:
p = (a+b+c) / 2
s = math.sqrt(p*(p-a)*(p-b)*(p-c))
h1 = 2*s / a
h2 = 2*s / b
h3 = 2*s / c
print("h1 = " + str(h... |
n = int(input())
count = 2*n - 1
a = 1
for i in range(count):
if i <= n - 1:
print("*"*a)
a += 1
# print("i: ", i)
# print("a: ", a)
else:
a -= 1
print("a: ", a)
print("*"*(a-1))
# print("i: ", i)
# print("a: ", a) |
def divisible(x):
for i in xrange(1, 21):
if x % i != 0:
return False
return True
current = 20
while not divisible(current): current += 20
print current |
def is_palindrome(x):
str_arr = list(str(x))
l = len(str_arr)/2 # int
for i in xrange(l):
if str_arr[i] != str_arr[-1 * (i+1)]: return False
return True
current = 0 # current max
a, b = 999, 999
# Iterate down for a
# When a * b is less than current max, decrement b and reset a to 999
# Finish when b is l... |
class ListQueueSimple:
def __init__(self):
self._L = []
def enqueue(self, item):
self._L.append(item)
def dequeue(self):
return self._L.pop(0)
def peek(self):
return self._L[0]
def __len__(self):
return len(self._L)
def isempty(self):
return l... |
# 计算每道题每次提交的平均分
import json
f = open('../test_data.json', encoding='utf-8')
res = f.read()
data = json.loads(res)
exc = {}
req = {}
for key in data:
cases = data[key]['cases']
for case in cases:
case_id = case['case_id']
if case_id not in exc:
exc[case_id] = {}
exc[cas... |
# 对5个维度进行pca降维(基于mle)
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.decomposition import PCA
pd_data = pd.read_csv('../matrix/matrix.csv')
temp = pd_data
pd_data = pd_data.iloc[:, 1:6]
pca = PCA(n_components='mle')
pca.fit(pd_data)
print(pca.explained_variance_ratio_)
print(pca.explained_variance_)... |
# 4
def check_parentheses(expr):
s = []
for i in range(len(expr)):
if expr[i] == '(' or expr[i] == '[' or expr[i] == '{':
s.append(expr[i])
continue
if len(s) == 0:
return False
if expr[i] == ')':
x = s.pop()
... |
from random import randint
from pygame.locals import K_UP, K_DOWN, K_RIGHT, K_LEFT
class StateMachine:
def __init__(self):
self.states = {}
self.active_state = None
# 为实体添加其会拥有的状态
def add_state(self, state):
self.states[state.name] = state
def think(self, current_time, scree... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 10:18:44 2020
@author: bluem
"""
#import necessary module re
import re
import pandas as pd
#read the file and extract the sequence as strings
file_name1=input("please input the first fasta file name:")
file_name2=input("please input the second fasta file n... |
def divisible_under_20():
reached=lowest=20
i=380
while reached > 0:
if i%reached==0:
reached-=1
if reached < lowest:
lowest=reached
print reached, i, lowest
else:
reached=20
i+=380
return i
divisible_under_20()... |
def anti_vowel(text):
no_vowels=""
print no_vowels
for char in text:
if not isVowel(char):
print char
no_vowels+=char
print no_vowels
return no_vowels
def isVowel(char):
char=char.lower()
if char in ('a' or 'e' or 'i' or 'o' or 'u'):
print True
... |
# Time Complexity : O(N)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#p0 left ... |
# a little program that counts how many times bob is in a string
s = 'azcbobobegghakl'
count = 0
for letter in range(0, len(s)):
if s[letter: letter + 3] == 'bob':
count += 1
print(count)
# same thing just as function count_bob()
def count_bob(st):
count = 0
for letter in range(0, len(st)):
... |
# Escribe un programa que pida notas y los guarde en una lista. Para terminar de introducir notas, escribe una nota que
# no esté entre 0 y 10. El programa termina escribiendo la lista de notas.
lista = []
notas = float(input("Escribe la nota: "))
while notas > 0 and notas < 10:
lista.append(notas)
notas = float... |
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
sol = Solution()
print(sol.removeElement([3, 2, 2, 3], 3)) |
from random import randint
game_board = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
winner = None
piece_placed = []
def print_board(board):
display = ''
for i in range(0, len(board)):
for j in range(0, len(board[0])):
if j < 2:
display += board[i][j]+'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.