text stringlengths 37 1.41M |
|---|
import math
import re
from math import cos, sin, atan2
eps = 1e-14 # precission
R = 1 # radius of sphere
def signum(x):
return -1 if x < 0 else 1
def equal(a, b):
return abs(a - b) < eps
def less(a, b):
return a < b and not equal(a, b)
def less_or_equal(a, b):
return a < b or equal(a, b)
de... |
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# Step 1 Read the data
df = pd.read_csv('linear_classifier.csv')
df.head()
# Step 2 Plot the classes using scatter plots
plt.figure(figsize=(10, 7))
for label, lab... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
df = pd.read_csv('synth_temp.csv')
df = df.loc[df.Year > 1901] # Filter data with > 1901
df_group_year = df.groupby('Year').agg(np.mean) # Group by mean aggregated
window = 10
rolling = df_group_ye... |
# Feature Extraction with RFE
from pandas import read_csv
from numpy import set_printoptions
from sklearn.feature_selection import RFE
from sklearn.tree import DecisionTreeClassifier
def main():
PATH = "../pima-indians-diabetes.data.csv"
columns = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'cla... |
import streamlit as st
import numpy as np
import pandas as pd
# TITLE COMMANDS
# st.title("Royce")
# WRITE COMMANDS
# st.write("Here's our first attempt at using data to create a table:")
# st.write(pd.DataFrame({
# 'first column': [1, 2, 3, 4],
# 'second column': [10, 20, 30, 40]
# }))
# MAGIC COMMANDS
... |
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
ways = {
1: 1,
2: 2,
}
for step in range(3, n + 1):
ways[step] = ways[step-1] + ways[step-2]
return ways[n]
|
__author__ = 'Ondrej Prenek'
class MyPlayer:
""" Hrac nejdrive spolupracuje, pote se prizpusobi """
# class Myplayer can be created with 1 or 2 arguments
def __init__(self, payoff_matrix, number_of_iterations=0):
self.payoff_matrix = payoff_matrix
self.number_of_iterations = nu... |
# Import random number generator
import random
keepplaying = True
my_number = 0
guess = 0
quitvariable = " "
while keepplaying == True:
my_number = random.randrange(1,101)
print()
print("Guess the random number between 1 and 100")
print()
guess = int(input("Guess the number: "))
... |
# Sequencing-Reads
Python code for reading and basic sequencing of DNA reads
##My modified Naive Matching algorithm that allows for two mismatch per alignment
def revComp(t): ##for reverse complement of a pattern t
complement={ 'A': 'T', 'G': 'C', 'T':'A', 'C':'G' , 'N':'N' }
tc = '' ##stores reverse complemen... |
# Syntax : Basses on Indentation
# Standard : 1 tab == 4 space
def f1():
print("Inside f1")
print("Indentation 1 tab = 4 space")
def f2():
print("Inside f2")
print("Indentation 1 tab = 2 space")
def f3():
print("Inside f3")
print("Indentation 1 tab = 1 space")
def f4():
print("Inside f4")
... |
import pickle
class Employee:
def __init__(self, eid, name, salary = None):
self.eid = eid
self.name = name
self.salary = salary
def salaryRaise(self, increment):
self.salary *= increment
print(self.salary)
def main():
name = 'Nehal Ram'
eid = 'ABC'
sal = ... |
fname = input('Enter the file name: ')
fhand = open(fname)
lines = fhand.read()
lines.rstrip()
words = lines.split()
Newlist = list()
for item in words: #this just uses the for loop directly to iterate
if item in Newlist: continue
Newlist.append(item)
print(Newlist)
#or
'''
# this method uses the indices(p... |
# Exercise
num = None
count = 0
num1 = 0
while True:
try:
num = input("Enter a number: ")
if num == "done": break
num2 = int(num)
num1 += num2
count += 1
except ValueError :
print("Invalid input")
print(num1,count,num1/count)
'''
input_variable = " "
... |
import random
def number():
number = random.randint(0,10)
guess = int(input("guess the number:"))
print(number)
if guess == number:
print("wow! Correct")
else:
print("Wrong, try again")
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from DictofUSStatesAbbr import states_dict
from GroupingRegion import region_color, region_dict
def cluster_region(params='region'):
'''
This function creates region-based scatter-plot. It can also be used... |
#!/usr/bin/env python
"""Concatenate many "extracted features" files into one file. This is
actually very simple -- the only item of notice is that first line must be
the total number of sentences, so we read the number of sentences in each
file, then read the remaining contents of each input file in order."""
# David... |
from maze import Maze
from state import State
from cardinal import *
class Problem:
"""Representação de um problema a ser resolvido por um algoritmo de busca clássica.
A formulação do problema - instância desta classe - reside na 'mente' do agente."""
def __init__(self):
self.initialState = Stat... |
import sys
import os
import math
## Importa os tipos de malha disponíveis
sys.path.append(os.path.join("pkg", "mesh"))
import mapSquare, mapTriangle
## Classe que define o labirinto onde o agente esta
class Maze:
"""Maze representa um labirinto com paredes. A indexação das posições do labirinto é dada por par ord... |
# 2.0.3
""" The idea to slove for primes is not a new one
version 1.0.0, I used brute force. I ' divided the number by every number that
preceads it. I know its amatuer.
init time= 1.4115116905247785e-05
process time = 0.021677825450753425 '1 process'
0.9991394055995951 '1000 proces... |
#! /usr/bin/python
#This will define a class that implements
# a text label with a number next to it
# in pygame.
import pygame
class LabelPair:
def __init__(self, in_pos, in_string, in_color_default = (255, 255, 255), in_size = 20, in_good_color=None, in_good_thresh=0, in_bad_color=None, in_bad_thresh=0):
... |
#find length of HTML on a page
from mathematicians import simple_get
raw_html = simple_get('https://www.quokkachallenge.com/')
print len(raw_html)
#once you have the html file, read through it to find specific ID's and associated Text
from bs4 import BeautifulSoup
raw_html = open('contrived.html').read()
html = Beau... |
import sys
print('Hello World')
print('The sum of 2 and 3 is 5.')
sum = int(sys.argv[1]) + int(sys.argv[2])
print ('The sum of {0} and {1} is {2}.'.format(sys.argv[1],sys.argv[2],sum)) |
# Tic tac toe game, not ussing IA, just random numbers
from tkinter import *
def fun_console_version():
root.destroy()
import TicTacToe_V1
def fun_gui_version():
root.destroy()
import TicTacToe_V2
def fun_exit():
root.destroy()
root = Tk()
root.title('TIC TAC TOE')
la... |
# 5. Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы)
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from functools import reduce
def... |
# 3. Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
a = [el for el in range(20,241) if el%20 == 0 or el%21 == 0]
print(a) |
# Создать текстовый файл (не программно). Построчно записать фамилии сотрудников
# и величину их окладов (не менее 10 строк).
# Определить, кто из сотрудников имеет оклад менее 20 тысяч, вывести фамилии этих сотрудников.
# Выполнить подсчёт средней величины дохода сотрудников.
# Пример файла:
# Иванов 23543.12
# Петров... |
import cv2,time
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video=cv2.VideoCapture(0) # create VideoCapture object..it triggers the camera
a=1 #a count variable for no. of frames
while True :
a+=1 #count to count no. of frames
check ,frame=video.read() # a method of ... |
see_results = False
validation_routine = False
if see_results == True:
#File Location - .csv file containing data to be interpolated
file_name = "Interpolation_data_csv.csv"
#Define cubic spline increments (number of plotted points for each interval in x data)
cubic_spline_increments = 100
import pan... |
professor_wizards = [
{'name': '덤블도어', 'age': 116},
{'name': '맥고나걸', 'age': 85},
{'name': '스네이프', 'age': 60},
]
# 이번엔, 반복문과 조건문을 응용한 함수를 만들어봅시다.
# 마법사의 이름을 받으면, age를 리턴해주는 함수
def get_age(name, wizards):
# wizards! 윗 줄 함수 선언에서 사용한 변수죠? 함수 사용하는 쪽에서 쓰는 변수명 아닙니다!
for wizard in wizards:
if wi... |
# ==================================================
# Title: Exercise 9.2 - Querying and Creating Documents
# Author: Professor Krasso
# Date: 16 May 2021
# Modified By: Mark Watson
# Description: This program shows how to create and query a
# document in MongoDB with Python.
# =====================================... |
from tkinter import *
from tkinter import messagebox
class MyFrame(Frame):
def __init__(self,master):
Frame.__init__(self,master)
frame1 = Frame(master)
frame1.grid(row=0,column=0)
dumyLabel1 = Label(frame1,width = 1)
dumyLabel2 = Label(frame1,width = 1)
dumyLabel3... |
"""
Darius Jones
5/22/2018
Useful Algorithms Implemented in Python
"""
import random
# Binary Search, very fast and useful
# O(log n) -> log base 2 number of elements
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = low + ((high - low) / 2)
... |
class Car():
"""an attempt to represent a car"""
object = "car"
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def get_name(self):
return f"{self.year} {self.brand.title()} {self.model.title()}"
my_car = Car("bmw", "x2", ... |
import random
class Event:
def __init_(self):
pass
def happen(self):
options = random.choices(range(-100, 100), k = random.choice([2,3,4]))
options = [x/100 for x in options]
return options
class Subject:
def __init__(self):
self.result = 0
def take_action(self, options):
choice = ... |
ticket=input("enter ticket number (6 digits): ")
#ticket="103100"
def valid(ticket):
tmin=10**5; tmax=10**6-2
try:
ticket=int(ticket)
if ticket >= tmin and ticket <= tmax:
return True
else:
return False
except:
print(ticket, "is invalid")
import sys; sys.exit(1)
def lucky(ticket):
if valid(tick... |
from pynput.mouse import Button, Controller
import time
mouse = Controller()
print(mouse.position)
time.sleep(3)
print('The current pointer position is {0}'.format(mouse.position))
#set pointer positon
mouse.position = (277, 645)
print('now we have moved it to {0}'.format(mouse.position))
#鼠标移动(x,y)个距离
mouse.move... |
class Automata(object):
def __init__(self, name=None, orig=None):
if orig==None:
self.nonCopyConstructor(name)
else:
self.copyConstructor(orig)
def nonCopyConstructor(self,name):
self.name=name
rint "nonCopyConstructor of Automata"
def copyConstructo... |
import os
def rename(dir_name,newnames_list):
"""
dir_name = #enter path here as a raw string
Example: r"C:\Users\Fardin\Desktop\Coop\datasets\google_videos\drowning"
Insert newfile names here as strings in an iterable, if your file name has an extension just append the extension at the end of every item ... |
class Order(object):
def __init__(self, order_id, size, side, timestamp):
self.order_id = order_id
self.quantity = size
self.timestamp = timestamp
self.side = side
def get_order_id(self):
return self.order_id
def get_timestamp(self):
return self.timestamp
... |
# ответить на вопрос - какую роль играет init() ?
# init() --> pentru caracterizarea unui obiect
# почему метод init - принимает аргумент self и откуда он берется?
# din motivul că self primește esența caracteristicilor după care obiectul poate fi identificat după numiți parametri
class Product:
def __init__(... |
# 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 generateTrees(self, n: int) -> List[TreeNode]:
if n < 1:
return []
... |
from collections import deque # use it as a queue
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
degrees = [0] * n
leaves = deque()
adj_list = [[] for _ in range(n)]
for e in edges:
degrees[e[0]] += 1
degrees[e[1]... |
#Sidhant Puntambekar
#TempConverter
#input
fahrenheitTemp = input("Please enter degrees Fahrenheit: ")
fahrenheitTemp = int(fahrenheitTemp)
#processing
celsiusTemp = (fahrenheitTemp-32) * (5/9)
#output
print(fahrenheitTemp,"degrees F is equal to", celsiusTemp, "degrees C.")
|
# coding: utf-8
# In[17]:
import os
def rename_files():
#(1)get the filenames from the folder - path of the folder
file_list = os.listdir("/Users/yogeshsharma/Documents/UDACITY/prank")
print(file_list)
#define what is current directory
saved_path = os.getcwd()
print("The current working direc... |
import sys
import re
import os
assert (len(sys.argv) > 1), "An argument must be given"
dir = sys.argv[1]
def list_files_recursive(path):
"""
Function that receives as a parameter a directory path
:return list_: File List and Its Absolute Paths
"""
files = []
# r = root, d = directories, f =... |
#Assignment 5
'''
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
Once 'done' is entered, print out the largest and smallest of the numbers.
If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore t... |
#perulangan percabangan
'''
made by : fiqri ardiansyah
ini adalah program login sederhana ,untuk user dan admin masing2 username dan
password sudah diset.maka program akan mengecek yang mana admin dan user dan
yang tidak ada .jika inputan salah maka program akan dilangi sebanyak 3 kali
masukan = username dan passwor... |
import math
print("======= latihan 15 (array) ========")
print()
angka = input("angka : ").split()
print("===== rata rata =====")
rata = 0
for i in angka:
rata += int(i)
print("rata : ",rata/(len(angka)))
print("==== standar deviasi ====")
n = len(angka)
xi=0
x2=0
for i in angka:
xi+=int(i)
x2+=int(i)... |
# uppercase alphabet caesar cipher
ciphertext = "<YOUR_ENCRYPTED_STRING_HERE>"
for shift in range(26):
possible_plaintext = ""
for character in ciphertext:
if character .isalpha():
possible_plaintext += chr((((ord(character)-65)+shift)%26)+65)
else:
possible_plaintext += character
print(possible_plainte... |
from __future__ import print_function
import logging as log
from cards import table
def split_choice(text):
''' Some choices can have associated conditions identified by @if.
This function splits both parts and returns both tables if relevant'''
lines = [e for e in text.split('\n')]
# Splitting pream... |
#递归
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
print(fact(5))
print(fact(100))
#解决递归调用栈溢出的方法是通过尾递归优化,事实上尾递归和循环的效果是一样的,所以,把循环看成是一种特殊的尾递归函数也是可以的。
#尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
#上面的fact(n)函数由于return n * fact(n - 1)引入了乘法表达式,所以就... |
# 匿名函数
#以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
print(list(map(lambda x:x*x,[1,2,3,4,5])))
#匿名函数lambda x: x * x实际上就是:
#def f(x):
# return x * x
#关键字lambda表示匿名函数,冒号前面的x表示函数参数。
#匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
#用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
f = lamb... |
#map/reduce
#map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def f(x):
return x*x
r=map(f,[1,2,3,4,5,6,7,8,9])
print(list(r))
#把这个list所有数字转为字符串:
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
#reduce
from functools import reduce
def add(x, y):
return x + y
print(reduce(add, [1,... |
#生成器
#创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
L = [x * x for x in range(10)]
g = (x * x for x in range(10))
print(L)
print(next(g))
print(next(g))
#每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。
g = (x * x for x in range(10))
#调用
for n in g:
print(n)
# 斐波那契数列
# def fib... |
size=int(input())
arr=input()
arr=list(map(int,arr.split(" ")))
prod=1
for x in range(size):
prod*=arr[x]
for x in range(size):
print(prod//arr[x],end=" ")
|
size=int(input());count=0
arr=input()
arr=list(map(int,arr.split(" ")))
size=len(arr)
for i in range(size):
for j in range(i+1,size):
for k in range(j+1,size):
if arr[i]>arr[j]>arr[k]:
count+=1
print(count)
|
def test_file(startFile, endFile):
alphabet = "abcdefghijklmnopqrstuvwxyz"
fileName = "google_financial_ngrams.txt"
with open(fileName, 'r') as f:
fileData = f.read()
fileData = fileData.lower()
lines = fileData.split('\n')
numLines = len(lines)
print "numlines= " + s... |
a=int(input('Enter a='))
b=int(input('Enter b='))
print('Сложение a+b =', a+b)
print('Вычитание a-b =', a-b)
print('Умножение a*b =',a*b)
print('Деление a/b =',a/b)
print('Возведение в степень a**b =',a**b)
print('Целочисленное деление a//b =',a//b)
print('Остаток от деления a%b =',a%b)
print('Модуль числа abs(a) =',ab... |
#!/usr/bin/env python
#--coding: utf-8 --
# Grafica la moduladora de un pulso formado por un paquete de ondas
# Permite especificar la cantidad de ondas superpuestas
# Saqué la variable que especifica el espaciado de frecuencias porque sólo
# afecta la escala horizontal.
from math import sin,e,pi
from matplotlib impo... |
import csv
import sqlite3
conn = sqlite3.connect('Hospital.db') #creates a database hospital
c = conn.cursor()
file1 = open('file.txt', 'r')
Lines = file1.readlines()
for line in Lines:
stripped = (line.strip() for line in Lines)
lines = (line.split("|") for line in stripped if line)
with ope... |
#opening files
#1st method
#r = read w = write b = binary (useful on some systems) + = editable, will write over existing
#o_file = open('path/to/filename', 'rwb+')
#file is now open and in memory as o_file
#to close a file use: o_file.close()
#example to play with:
o_file = open('method1.txt', 'rwb')
print '\nsee t... |
#Exercise 7
#Carolina
# Time spent: 1h30 minutes
# -*- coding: Latin-1 -*
""" Consider the following class:
class Coordinate(object): def __init__(self, x, y):
self.x = x
self.y = y
def getX(self): return self.x
def getY(self): return self.y
def __str__(self): return '<' + str(self.getX()) + ',' +
str(self.... |
#Exercise 6
#Carolina
# Time spent: 8 minutes
# -*- coding: Latin-1 -*
""" Write a program which will find all such numbers which are divisible by 7 but are not
a multiple of 5, between 77 and 777 (both included).
"""
for num in range(77, 778):
if (num % 7 == 0) and not(num % 5 == 0):
print num, |
def knapsack(items, capacity):
'''
A method to determine the maximum value of the items included in the knapsack
without exceeding the capacity C
Run O(nc) time | O(nc) space where n is the number of items
c is the capacity of the bag
'''
result = []
knapsack_values = [[0 for x in ra... |
#
# playing_cards module - PSP Assignment 2, sp2, 2020.
# DO NOT MODIFY!
#
import random
# Deck of cards - first letter represents the face value and
# second letter represents the suit
deck = ['AH','2H','3H','4H','5H','6H','7H','8H','9H','TH','JH','QH','KH',
'AD','2D','3D','4D','5D','6D','7D','8D','9D','TD'... |
import playing_cards
def display_hand(hand):
for card in hand:
if card[1]=='H':
print(card[0],'of Heart')
elif card[1]=='D':
print(card[0],'of Diamonds',)
elif card[1] == 'S':
print(card[0], 'of Spades')
elif card [1] == 'C':
print(ca... |
import random
#el jugador p lo vamos a denotar como el jugador persona y lo iniciamos en el espacio vacio
jugadorp=''
#el jugador maquina igual
jugadorm=''
#creamos un caracter vacio
vacio=''
#y una lista vacia de 9 digitos ya que vamos de 0 a 8
m=['','','','','','','','','']
#esta funcion le pregunta al u... |
#using user input
num = int(input('Enter a number'))
if num % 4 == 0:
if num % 100 == 0:
if num % 400 == 0:
print('Leap Year')
else:
print('Not a Leap Year')
else:
print('Leap Year')
else:
print('Not a Leap Year')
#using definition
def che... |
# In functional programming we can use global variable anywhere in program.
# That means it can also be used inside class.
x = 100 # Global variable
class Test:
def m1(self):
print(x) # accessing global variable inside class
def m2(self):
print(x)
t = Test()
t.m1()
t.m2()
pri... |
# Here we will see why and how we can use Setter and Getter methods
class Student:
pass
s1 = Student()
s1.name = 'raju'
s1.marks = 345
print("Hi", s1.name)
print("Your marks are:", s1.marks)
# here in above example, we are assigning some data to Student object and then accessing that data.
# But this is the w... |
# Here we will see 3 ways to declare instance variables
# 1) inside __init__
# 2) inside instance method
# 3) outside the class
class SoftEngg:
def __init__(self, id, name, sal):
self.id = id
self.name = name # instance variable inside constructor
self.sal = sal
... |
import random
toss_range = 100
heads = 0
tails = 0
print('Welcome to the Heads/Tails game! For', toss_range, 'tosses, you have:')
for i in range(toss_range):
flip = random.randint(0, 1)
if flip == 1:
heads = heads + 1
else:
tails = tails + 1
print(heads, 'heads')
print(tails, 'tails.') |
class Solution:
def __init__(self):
self.data = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
def func1(self, s):
res = []
if ... |
class Solution1:
def reverse_int(self,x:int):
if not x: return 0
# 如何区分是错误还是0的反转
s = str(x)
sign = True if s[0] is "-" else False
res = []
for w in s:
res.insert(w, 0)
new_s = int("".join(res).lstrip("0"))
|
# class Solution:
# def groupAnagrams(self, strs):
# if not strs:
# return []
#
# info = {}
# for s in strs:
# tmp = []
# for c in s:
# tmp.append(c)
# tmp = tuple(tmp)
# # 不可改变,但有顺序
# if tmp not in info.... |
class Sender:
"""
Отправляемые сообщения
"""
def __init__(self, remote):
self.remote = remote
def start(self):
self.remote.send('start')
def score(self, val, car_x):
self.remote.send('score', {'val': val, 'car_x': car_x})
def wall(self, arr):
self.remote.se... |
import datetime
class BikeRental:
def __init__(self, stock=0):
'#'constructor class that instantiates bike rental shop.
self.stock = stock
def displaystock(self):
'#'Displays the bikes currently available for rent in the shop.
print("""We have currently {} bikes available to
... |
'''
This entire file is our own implementation
It uses multithreading to show the plots without locking the execution of the main game.
'''
import threading
import matplotlib.pyplot as plt
import numpy as np
class PlotContainer(threading.Thread):
def __init__(self, threadID=None):
threading.Thread.__ini... |
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees m... |
"""
Link: https://www.hackerrank.com/challenges/python-lists/problem
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
"""
def list_operations():
N = int(input())
arr = []
for i in range(N)... |
def highest_product_of_3(list_of_ints):
assert list_of_ints
assert(len(list_of_ints) >= 3)
list_of_ints.sort()
min_prod = list_of_ints[0] * list_of_ints[1]
max_prod = list_of_ints[-2] * list_of_ints[-3]
maxe = list_of_ints[-1]
return max((min_prod * maxe), (max_prod * maxe))
out = highe... |
"""
You are given a string and your task is to swap cases.
In other words, convert all lowercase letters to uppercase letters and vice versa.
For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
"""
def swap_case(s):
return ''.join([i.upper() if i.islower() else i.lower() for i in list(s... |
"""
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
You are given scores. Store them in a list and find the score of the runner-up.
Sample Input 0
5
2 3 6 6 5
Sample Output 0
5
"""
if __name__ == '__main__':
n = int(input())
arr = map(int, in... |
"""
Link: https://www.hackerrank.com/challenges/minimum-swaps-2/problem?
h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
"""
def minimum_swaps(arr):
temp = [0 for i in range(len(arr))]
count = 0
for i in range(len(arr)):
while temp[i] == 0:
if i... |
"""
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286
4
... |
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
return None
return self.items.pop()
def peek(self):
if not self.items:
return None
return self.ite... |
"""
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
def longest_palindrome(s):
n = len(s)
if n == 0 or n == 1:
r... |
class Solution:
def solve(self, expression):
def isMatchingPair(char1, char2):
if char1 == '(' and char2 == ')':
return True
if char1 == '{' and char2 == '}':
return True
if char1 == '[' and char2 == ']':
return True
... |
# Suppose you are working for an e-commerce company and the marketing team is trying to decide if they should launch a new webpage. They ran an A/B test and need help analyzing the results. They provided you with this dataset, which contains the following fields:
# user_id: the user_id of the person visiting the websi... |
# Using this dataset, write code to compute how often the oldest person alive dies (length of time they were recognized as oldest person before passing away and being replaced by a new oldest person). Visualize this information for a stakeholder.
import matplotlib.pyplot as plt
import datetime
import numpy as np
impor... |
# Suppose you are given the following dataframe containing food, weight, and calories. You'll notice the foods have varying weights associated with them:
# food grams calories
# 0 bacon 50 271
# 1 strawberries 200 64
# 2 banana 100 89
# 3 spinach 200 46
# 4 chicken breast 50 80
# 5 peanuts 100 567
# Using Python (Pan... |
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# It's important to remember what a palindrom is in order to solve this problem. A palidrome is a string that is the same if it is reversed. One way to solve this problem then, is to... |
print('Задача 1.')
file = open('task_1.txt', 'w')
# Для последовательного ввода нескольких строк создаем цикл:
str_list = []
# В цикле к каждой введенной строке добавляем знак переноса строки:
while True:
record = input('Сделайте запись в файл. Для окончания записи введите пробел: ')
enter = '\n'
string =... |
# coding: utf-8
# In[ ]:
from numpy import *
from matplotlib import pyplot as plt
g = 9.8
vO = eval(input("Input initial velocity, m/s \n"))
t1 = eval(input("Input time range, seconds \n"))
a = eval(input("Input accelaration, m/s**2 \n"))
t = np.linspace(0, t1, 50)
distance = vO*t + 0.5*a*t**2
velocity = vO + a*t
pl... |
from random import randint, choice
__author__ = 'Hazel'
battleshipLengthsAvailable = [6,5,5,4]
class GameBoard:
'''
Class that holds information about the game board (such as full and masked states, how many ships have been hit)
'''
def __init__(self):
'''
:return: nil
Genera... |
import plotly.express as px
import csv
import numpy as np
def getDataSource(data_path):
ice_cream_sales = []
temperature = []
with open(data_path)as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
ice_cream_sales.append(float(row["Ice-cream Sales... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 16 15:04:46 2021
@author: Navodit
"""
def disp(ml):
print('{}|{}|{}\n------\n'.format(ml[0],ml[1],ml[2]))
print('{}|{}|{}\n------\n'.format(ml[3],ml[4],ml[5]))
print('{}|{}|{}\n\n'.format(ml[6],ml[7],ml[8]))
def check(ml,char):
for i in ra... |
a = int(input("Wpisz wartość liczby a: "))
b = int(input("Wpisz wartość liczby b: "))
def nwd(k, n):
while k != n:
if k > n:
k -= n
else:
n -= k
return k
def nww(k, n):
result = nwd(k, n)
return (k * n) // result
print(f"NWD: {nwd(a, b)}")
print... |
# -*- coding: utf-8 -*-
import json
# codigo para criar arquivo de opcoes options.json
# Gera um template para que o bot apresente estas opcoes para o usuario
# Gerador de Opcoes para Bot 1.0
print (f"Gerador de opcoes para bot 3.0\n")
# Se nao for valor inteiro, sai
try:
z=int(input ("Quantas opcoe... |
# define the string true if panagram
import string
def ispanagram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet :
if char not in str.lower() :
return False
return True
string = input ( 'write your sentence: ' )
if(ispanagram(string)== True) :
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.