text stringlengths 37 1.41M |
|---|
def greet(lang):
if lang == 'es':
print ('Hola')
elif lang == 'fr':
print ('Bonjour')
else:
print ('Hello')
greet('en')
greet('es')
greet('fr') |
'''
Take input of negative and positive integers.
Output numbers, negative numbers first, then positive integers, preserving order
Why?
How might this be used?
What's the size of the input?
Any other requirements?
Solution brainstorm:
Scan input twice, once for negative, once for positive values, out... |
import random
import re
# Take an input and remove all the spaces, then convert it entirely to
# lowercase. Then, make sure that the last char of the string is a number or
# letter.
def cleanse(input):
input = (input.replace(" ","")).lower()
if re.match('[0-9a-zA-Z]', input[len(input)-1]):
return inpu... |
"""
https://www.pyimagesearch.com/2015/11/16/hog-detectmultiscale-parameters-explained/
--image switch is the path to our input image that we want to detect pedestrians in.
--win-stride is the step size in the x and y direction of our sliding window.
--padding switch controls the amount of pixels the ROI is padded... |
# Convert C To F
C=eval(input("Enter the Temperature in Cel. : "))
F =(C*9/5)+32
print(f"The Temperature : {F} in F")
|
# reverse of digit
n= eval(input("Enter the no."))
d=0
rev=0
while n!=0:
d=n%10
rev=rev*10+d
n//=10
print(rev)
|
# Funcionalidad relacionada con el menú
"""
Autores: Nicolás Olabarría
Fecha: 9 de Junio de 2021
Tema: Menú
"""
import pandas as pd
def menu():
"""
The menu() function asks for a route and stores it in a string variable.
:return: A list of strings with the routes to the files
"""
... |
# Project 1 for Numerical Algorithms
#Charles Rohart, Ingrid Odlen, Laroy Sjödahl, Niklas Lindeke
import CSplines as CS
from numpy import *
"""
Testing environment for the Cubic Spline algorithm
"""
class dtest:
"""
Test class devised to investigate the relationship of the first and second derivative
... |
import twitter
import sys
from collections import Counter
def collect_hashtags(tweets):
""" Retieve the hashtags of a list of tweets """
hashtags = Counter()
for tweet in tweets:
hashtags.update([hashtag['text'] for hashtag in tweet.get('entities').get('hashtags')])
return hashtags
if __name... |
"""Скрипт, принимающий на вход json-файл, в котором указанны параметры предметов культурного наследия, и возвращающая
для каждого типа кол-во предметов и среднее значения года создания"""
import json
from collections import namedtuple
Result = namedtuple('Result', 'count average')
data = {} # json_data into data
wi... |
a=int(input("Enter first no.= "))
b=int(input("Enter second no.= "))
c=int(input("Enter third no.= "))
if(a>b and a>c):
print(a)
elif(a>b and a<c):
print(c)
else:
print(b)
|
import requests
#import os
from datetime import datetime
api_key = '12f3fe0150a34c3e74ba3e458f6e0b7d'
location = input("Enter the city name: ")
complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+location+"&appid="+api_key
api_link = requests.get(complete_api_link)
api_data = api_link.js... |
from pandas import DataFrame
dframe = DataFrame({'city': ['Alma', 'Brian Head', 'Fox Park'],
'altitude':[3158,3000,2752]})
state_map = {'Alma':'Colorado', 'Brian Head':'Utah', 'Fox Park':'Wyoming'}
print (dframe)
dframe['state'] = dframe['city'].map(state_map)#state_mapのcityに紐づいたデータの列が出来る
prin... |
VERTICAL, HORIZONTAL = 0, 1
MOVE_UP, MOVE_DOWN, MOVE_LEFT, MOVE_RIGHT = "u", "d", "l", "r"
VALID_NAMES = {"Y", "B", "O", "W", "G", "R"}
# Message text:
INVALID_ORIENTATION = "You had entered an invalid orientation"
CAUSE_THE_CAR = "Causes the car to go"
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
class Car... |
# 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 largestValues(self, root: TreeNode) -> List[int]:
if not root:
return []
result = []... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
result = []
self.helper(result, head)
return result
def helper(self, result: List[int], no... |
def extract_bits(number):
str_num = bin(number)
str_num = str_num.replace("0b", "")
bits = [int(x) for x in str_num]
bits.reverse()
return bits
def extract_8_bits(number):
str_num = bin(number)
str_num = str_num.replace("0b", "")
bits = [int(x) for x in str_num]
return [0] * (8 - ... |
import numpy as np
def pad_image(img, size, value):
# Measure difference from the desired width
width = size-img.shape[0]
# Check if even or odd
if(width%2!=0):
width_b = int(width/2)
width_a = width_b+1
else:
width_b = int(width/2)
width_a = width_b
# check i... |
#! usr/bin/env python3.7
from random import random
from tkinter import *
def hide_show():
if label.winfo_viewable():
label.grid_remove()
else:
label.grid()
root = Tk()
label = Label(text='Я здесь!') # Выводит текст
label.grid()
button = Button(command=hide_show, text='Спрятать/Показать') # ... |
#!/usr/bin/python
import os
from random import *
class Board():
def __init__(self):
self.cell = [" "," "," "," "," "," "," "," "," "," "]
def display(self):
print (" %s | %s | %s " %(self.cell[1], self.cell[2],self.cell[3]))
print ("-----------")
print (" %s | %s | %s " %(self.cell[4], self.cell[... |
# -*- coding: utf-8 -*-
"""
This is HW for stable-matching algorithm.
"""
import random
def stable_matching(men, women):
"""
:param men: list
:param women: list
:return: list
"""
assert isinstance(men, list) or isinstance(men, tuple)
assert isinstance(women, list) or isinstance(women, tup... |
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
index = len(s)//2
for i in range(index):
j = len(s)-1-i
temp = s[i]
s[i] = s[j]
... |
# Rope
# to do:
# - insert
# - delete
# - substring
# - concatenation
def to_rope(string):
return Rope(string)
class Rope:
def __init__(self, string):
self.string = string
def __str__(self):
return "abc"
assert str(to_rope("abc")) == "abc" |
Ex1:
tuple1 = (10, 20, 30, 40, 50)
tuple1 = tuple(reversed(tuple1))
print(tuple1)
EX2:
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))
print(tuple1[1][1])
Ex3:
tuple1 = (10, 20, 30, 40)
a, b, c, d = (10, 20, 30, 40)
print(a, b, c, d)
Ex4:
tuple1 = (11, 22, 33, 44, 55, 66)
tuple2 = tuple1[3:-1]
print(... |
from collections import deque
my_string = 'abracadabra'
my_deque = deque(my_string)
my_deque.appendleft('5')
my_deque.append('5')
print(my_deque) |
#List
#Ex1:
list1 = [100, 200, 300, 400, 500]
list1.reverse()
print('Reversed list:', list1)
#Ex2:
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].insert(1,'7000')
print(list1[2][2])
#Ex3:
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
list1[2][1][2].exten... |
"""Python Set Exercise"""
# Exercise 1: Return a new set of identical items from a given two set
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
print(set1 & set2)
# Exercise 2: Returns a new set with all items from both sets by removing duplicates
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
print(... |
def isPrimeNumber(num):
if num > 1:
seq = int(num**0.5)
for x in range(2, seq):
if (num % x) == 0:
print("the number is not prime")
return
else:
primeNumber = "the number is prime"
print(primeNumber)
else:
print("A prime number is a natural number greater than 1... |
# Exercise 1: Below are the two lists convert it into the dictionary
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
# Expected output: {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
x = dict(zip(keys, values))
print("Exercise 1, output:", x)
# Exercise 2: Create a new dictionary with the following keys from a b... |
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even += 1
else:
count_odd += 1
print ("Number of even_numbers :", count_even)
print ("Number of odd_numbers :", count_odd)
|
# Exercise 1: Return a new set of identical items from a given two set
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
# Expected output: {40, 50, 30}
x = set1.intersection(set2)
print("Exercise 1, output:", x)
# Exercise 2: Returns a new set with all items from both sets by removing duplicates
set1 = {1... |
import re
statement = 'Please contact us at: levon-grigoryan@gmail.com, lgrigor@submarine.com'
pattern = re.compile(r'[:,]')
address = pattern.split(statement)
print(address)
|
var = 1
while var == 0:
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!\n\n\n"
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Then fruits is :', fruits[index]
print "Good bye!\n\n\n"
print tuple('abcd'); |
'''
Tara Walton tara1984 Test 1
Calculate a global sum using multiple processes
'''
import sys
import multiprocessing as mp
def readfile(fname):
'''Reads a text file; returns a list of integers'''
f = open(fname, 'r')
contents = f.read()
numbers = contents.split()
for i in range(len(numbers... |
#!/usr/bin/env python3
"""
Collects the sensor configuration file to be parsed and reads it into a list
"""
import sys
import os
config_path = "./config/"
def get_command_line_config_file():
"""Collects configuration file to be use by command line argument, prompting
the user or by using the default test file... |
# Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
# Example 1:
# Input: [1,3,5,4,7]
# Output: 3
# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
# Even though [1,3,5,7] is also an increasing subsequence, it's not a... |
# -*- coding: utf-8 -*-
import numpy as np
from .datatuple import DataTuple
__all__ = [
'floatX', 'split_dataframe_to_arrays', 'split_numpy_array', 'slice_length',
'merge_slices', 'merge_slice_indices', 'merge_slice_masks',
'minibatch_indices_iterator', 'adaptive_density',
]
def floatX(array):
"""En... |
"""
This file contains helper methods
"""
def validate_email(email):
if '@' in email and '.com' in email:
return True
raise ValueError("Invalid email address -- " + email)
def input_prompt():
"""
renders display for receiving user input
"""
return input(">>> ")
def user_response_c... |
from Libreria_Num_Complejos import *
#verificar la longitud de un vestor
def lenght(vector, vetor1):
if len(vector) == len(vetor1):
return True
else:
return False
#suma de vectores
def sumVector(vector, vector1):
"""funcion que suma vectores (list, list)-> list"""
if lenght(vector, ... |
#Implementation of Two Player Tic-Tac-Toe game in Python.
''' We will make the board using dictionary
in which keys will be the location(i.e : top-left,mid-right,etc.)
and initialliy it's values will be empty space and then after every move
we will change the value according to player's choice of move. '... |
# This file represents a very simple implementation of an sklearn Linear Regression in Python.
# This is from Dataquest's "Linear Regression for Machine Learning" course.
# Very simple, but powerful for certain types of problems.
# Dropping NA values and one of the features (feature with very low variance in the dat... |
# -------------------------------- Task ---------------------------------------------------
# Given a Book class and a Solution class, write a MyBook class that does the following:
# Inherits from Book
# Has a parameterized constructor taking these 3 parameters:
# *string title
# *string author
# ... |
from game_square import GameSquare
from random import randint
class GameBoard(object):
def __init__(self, rows: int, columns: int, number_of_values: int):
self.board = []
for i in range(rows):
self.board.append([])
for j in range(columns):
self.board[i].append(GameSquare(randint(0, number_of_values - 1... |
x = ''
if type(x) == int:
if x >= 100:
print "That's big number!"
if x < 100:
print "That's small number!"
if type(x) == str:
if len(x) >= 50:
print "Long sentence"
if len(x) < 50:
print "Short sentence"
if type(x) == list:
if len(x) >= 10:
print "Big list"... |
import numpy as np
def kmeans(x, k):
'''
KMEANS K-Means clustering algorithm
Input: x - data point features, n-by-p maxtirx.
k - the number of clusters
OUTPUT: idx - cluster label
ctrs - cluster centers, K-by-p matrix.
iter_ctrs - cluster cen... |
#
# @lc app=leetcode.cn id=437 lang=python3
#
# [437] 路径总和 III
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if n... |
def count_stair_ways(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return count_stair_ways(n-1) + count_stair_ways(n-2)
def count_k(n, k):
if n == 0:
return 1
else:
if n >= k:
return add_k(count_k, n, k)
else:
return cou... |
def is_sorted(n):
"""
>>> is_sorted(2)
True
>>> is_sorted(22222)
True
>>> is_sorted(9876543210)
True
>>> is_sorted(9087654321)
False
"""
if n // 10 == 0:
return True
else:
if n % 10 <= (n//10) % 10:
return is_sorted(n // 10)
... |
a=list(map(int,input().split()))
x=a[0]
y=a[1]
x=x^y
y=x^y
x=x^y
print(x, end=' ')
print(y)
|
num=int(input())
b=1
if num==0:
print('1')
else:
for i in range(1,num+1):
b=b*i
print(b)
|
def binary_search(list,target):
first = 0
last = len(list)-1
while first <= last:
midpoint = (first + last)//2
if list[midpoint] == target:
return midpoint
elif list[midpoint] < target:
first = midpoint + 1
else:
last = midpoi... |
s=input("Enter word:")
vowels="AEIOUaeiou"
count=0
for x in s:
if x in vowels:
count +=1
print("Vowels:",count) |
def sumofmulti(limit):
for i in range(1,limit+1):
if (i % 3 == 0 or i % 5 == 0):
print(i,end=" ")
limit = int(input("Enter a number: "))
print("The multiples of 3 and 5 of",limit,"is ")
sumofmulti(limit) |
num_1 = float(input("Enter a number: "))
if num_1 % 2 == 0:
print("The number is even")
else:
print("The number is odd")
"""
The Answer of Q.2 is 1 3 4 8 9 10 11
The Answer of Q.3 is 1 4
The Answer of Q.4 is 0 1 3 4 5 6
""" |
A=[23,54,22,98,45,65,37,31,82,64]
even=0
odd=0
for x in A:
if x%2==0:
even +=1
else:
odd +=1
print("There are:",even,"even numbers")
print("There are:",odd,"odd numbers")
|
import numpy as np
def L2(v, *args):
"""Returns the computed L2 norm of a vector v.
INPUTS
=======
v: list,
vector in form of list of numbers
*args: optional, list
vector of weights & must be same length at v
RETURNS
========
L2: float
L2 norm of a ... |
# A 3-dimensional vector class to be used in the development of
# computer simulations of various physical systems.
#
#
# The 3-dimensional vector represents a standard cartesian vector
# given by <b> xi + yj +zk</b> where <b>i</b>, <b>j</b>, and <b>k</b> are unit
# vectors in the x, y, and z direction respectively.
... |
def create_txt(filename):
fp = open(filename,"w+")
ch = input('输入字符串:\n').upper()
while ch != '#':
fp.write(ch)
## fp.write('\n')
fp.seek(0,0)
print(fp.read())
ch = input('').upper()
fp.close()
def merge_txt():
with open('111.txt') as fp:
a = fp.read(... |
for i in range(100,1000):
s=str(i)
one=int(s[-1])
ten=int(s[-2])
hun=int(s[-3])
if i == one**3+ten**3+hun**3:
print(i)
for i in range(100,1000):
if i == (i//100)**3+((i%100)//10)**3+(i%100%10)**3:
print(i)
def Narcissus():
for each in range(100,1000):
temp = each
... |
class Pagination(object):
def __init__(self):
self.links = []
self.cursor = 0
def add_item(self, link):
if link in self.links:
return
self.links.append(link)
def reset_next(self):
self.cursor = 0
def has_next(self):
return self.cursor <= len... |
####################################
# instructions
####################################
instructions = '''
Use the record button to record music played to the microphone.
Music sheet will be created from this music.
Use the upload button to upload previously saved music. Music
sheet will be created from this.
Once ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
df = pd.read_csv('Boston_Housing.csv')#import the data set
train,test= train_test_split(df, test_size= 0.20, random_state=1)#Split 80% of data as the training set and rest as the tes... |
# Remove Specified Item
# The remove() method removes the specified item.
# Example
# Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
# Remove Specified Index
# The pop() method removes the specified index.
# Example
# Remove the second item:
thislist = ["apple",... |
# Append Items
# To add an item to the end of the list, use the append() method:
# Example
# Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
# Insert Items
# To insert a list item at a specified index, use the insert() method.
# The ins... |
# Loop Through a Dictionary
# You can loop through a dictionary by using a for loop.
# When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Example
# Print... |
""" 10. Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10.
O usuário deve informar de qual numero ele deseja ver a tabuada.
A saída deve ser conforme o exemplo abaixo:
Tabuada de 5:
5 X 1 = 5
5 X 2 = 10
...
5 X 10 = 50
"""
num = int(input('Digite o numero :'))
print('... |
# Loop Through a Tuple
# You can loop through the tuple items by using a for loop.
# Example
# Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
# Learn more about for loops in our Python For Loops Chapter.
# Loop Through the Index Numbers
# Yo... |
# Python Indentation
# Indentation refers to the spaces at the beginning of a code line.
# Where in other programming languages the indentation in code is for readability only,
# the indentation in Python is very important.
# Python uses indentation to indicate a block of code.
# Example:
if 5 > 2:
print("Five is g... |
""" 10.Faça um Programa que peça a temperatura em graus Celsius,
transforme e mostre em graus Fahrenheit.
Fórmula : (C × (9/5)) + 32 = F
"""
cel = float(input('Digite a temperatura em Celsius:'))
print('A temperatura em Fahrenheit é: ', (cel * (9/5)) + 32)
|
""" 8.Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
Calcule e mostre o total do seu salário no referido mês."""
hr = float(input('Digite o valor ganho por cada hora trabalhada: '))
qtde = float(input('Digite a quantidade de horas trabalhadas no mês: '))
amount = hr * ... |
""" 16. A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,...
Faça um programa que gere a série até que o valor seja maior que 500.
"""
n = 1
u_1 = 1
u_2 = 1
count = 0
lista = [1, 1]
for vic in range(n, 14):
count = u_1 + u_2
u_1 = count
u_2 = (count - u_2)
lista.append(count)
... |
""" 8.Palíndromo. Um palíndromo é uma seqüência de caracteres cuja
leitura é idêntica se feita da direita para esquerda ou vice−versa.
Por exemplo: OSSO e OVO são palíndromos.
Em textos mais complexos os espaços e pontuação são ignorados.
A frase SUBI NO ONIBUS é o exemplo de uma frase palíndroma onde os espaços foram ... |
""" 10. Faça um programa que receba dois números inteiros e gere os números inteiros
que estão no intervalo compreendido por eles.
"""
n1 = int(input('Digite um numero: '))
n2 = int(input('Digite um numero: '))
for i in range(n1 + 1, n2):
print(i, end=' ')
|
'''
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。
之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
思路:用栈实现,遍历str,如果栈为空,则入栈,如果栈顶元素和字符串元素相等,则stack.pop栈顶元素,如果不等,就入栈
'''
'''
joi... |
import math
from random import seed
from random import randint
class Deck:
def __init__(self, name):
self.name = name
self.deck = []
def splitDeck(self):
firstHalf = []
secondHalf = []
for i in range(0, math.floor(len(self.deck)/2)):
firstHalf.append(s... |
#Multiple Linear Regression with Gradient Descent Algorithm in Linear Algebra Style
#more than one input variable
"""
File: Patients.txt
schema: id,name,age,wgt,hgt,cholestral
features:age,wgt,hgt
label: continuous type- cholestarl
"""
#step1: read data and seperate features and labels
f=open("C:/Users/ic76275... |
#!/usr/bin/env python
class Clock:
def __init__(self, decimal_hours, decimal_minutes):
self.minutes = decimal_hours*60 + decimal_minutes
def _to_dec(self):
decimal_hours = (self.minutes//60) % 24
decimal_minutes = (self.minutes - (decimal_hours*60)) % 60
return (decimal_hours,... |
import json
from collections import Counter as counter
# TODO no need for this global variable, place it in __ini__ method
class TweetRank:
"""
TF: Term Frequency, which measures how frequently a term occurs in a document.
Since every document is different in length, it is possible that a term would
a... |
#def greet(name = 'Reddy',time = 'afternoon'):
#print(f'Good {time} {name}, hope you are well')
#name = input('enter your name:')
#time = input('enter the time of day:')
#greet(name='vijeet')
def area(radius):
return 3.142 * radius * radius
def vol(area,length):
print(area*length)
radius ... |
# Faster sin/cos function by using a lookup table
# Example code for Daniel Shiffman made by Ewoud Dronkert
# https://twitter.com/ednl
# https://github.com/ednl
# Only needed for lookup table generation and validation
from math import sin, cos, tau
# Quadrants and circle below are not in degrees but in "index units" ... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Get the CSV file.
signals_file = pd.read_csv('signals-1.csv', header=None)
# Observe some basic information.
number_of_signals = len(signals_file.loc[:, 0])
size_of_signal = len(signals_file.loc[0, :])
print('Number of signals: %s' %(number_... |
# coding: utf-8
# In[2]:
import matplotlib.pyplot as plt
from sklearn import datasets
# our support vector machine classifier!
from sklearn import svm
# load digits dataset
digits = datasets.load_digits()
# In[3]:
# let's see what this dataset is all about
print digits.DESCR
# In[15]:
# let's see what keys t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print(abs(-10))
print(int('123'))
print(int(12.34))
print(float('12.34'))
print(str(123))
print(bool(1))
print(bool(''))
print(hex(1080))
# 定义函数
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError("bad operand type")
if x >= 0:
r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 传入函数
def add(x, y, f):
return f(x) + f(y)
print(add(5, -6, abs))
# map/reduce
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8])
# Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list
print(list(r))
print(list(map(str, [1, 2, 3])))
from functools imp... |
import random
import pygame
import dependencies.consts as c
def distance(p1: (int, int), p2: (int, int)) -> float:
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** .5
class Dot:
"""
Class used to create a dot object.
"""
def __init__(self, name: str, r_size: int, color: (int, int, int), ... |
'''
File name: homicide_year_sort.py
@author: Simen Davanger Wilberg
Date created: 4/30/2017
Date last modified: 5/8/2017
Finds the number of homicides for each year, and sorts the list in a descending orders.
'''
def sort_years(homicide_array,outfile):
f = open(outfile,"a")
years = ... |
import sys
sys.stdin = open("cons_input.txt")
N = int(input())
global_max = 0
temp_max = float(input())
for _ in range(N-1):
now = float(input())
temp_max *= now
if temp_max > global_max:
global_max = temp_max
if temp_max < 1:
temp_max = now
print(round(global_max, 3))
|
import sys
sys.stdin = open("n_root_input.txt")
def digitroot(n):
if n < 10:
return n
return digitroot(n//10) + n%10
def recurse(n):
answer = n
while answer >9:
answer = digitroot(n)
return answer
print(recurse(65536))
|
places = ['los angeles', 'cremona', 'berlin', 'paris', 'tokyo']
print(places) #print your list in its original order
print(sorted(places)) #use sorted() to print your list in alphabetical order
print(places) #show that your list is still in its original order
print(sorted(places,reverse=True)) #use sorted() to prin... |
names = ['mozart', 'beethoven', 'bach']
for name in names:
message = f'{name.title()}, i would like to invite you to chicken dinner!'
print(message)
message = f'{names.pop(1)} can`t make it'
print(message)
names.append('haydn')
for name in names:
message = f'{name.title()}, i would like to invite you to chi... |
#SQUARE-MATRIX-MULTIPLY
def square_matrix_multiply(A,B):
len_row = len(A)
len_col = len(A[0])
C = [[0 for _ in range(len(A))] for _ in range(len(B[0]))]
for i in range(len_row):
for j in range(len(B[0])):
for k in range(len_col):
C[i][j] += A[i][k] * B[k][j]
ret... |
favorite_places = {
'kim': ['los angeles', 'japan', 'korea'],
'park': ['paris', 'spain', 'cheongju'],
'kang': ['busan', 'park', 'gym'],
}
for name, places in favorite_places.items():
print(name + ": ")
for place in places:
print("\t" + place)
|
def build_profile(first, last, **user_info):
"""build a dictionary containing every thing we know about a user."""
profile ={}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profi... |
def swap(arr,x,y):
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
return arr
def quickSort(arr,low,high):
if low<high:
#print("The arr before sort:",arr[low:high+1])
pivot = arr[low]
i = low+1
j = low+1
while j <= high:
if arr[j]<=pivot:
if i!=j:
swap(arr,i,j)
i = i+1
j = j+1
#print("T... |
import threading
import random
import time
class Philosopher(threading.Thread):
running = True
def __init__(self, name, forkOnLeft, forkOnRight):
threading.Thread.__init__(self)
self.name = name
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
def run(self):
... |
string1 = input()
string2 = input()
def anagram(s1, s2):
all = list(s1+s2)
a = list(set(s2) - set(s1))
b = list(set(s1) - set(s2))
c = list(a+b)
# removing different char
result = list(set(all)-set(c))
return c
agr = anagram(string1, string2)
ooutput = str(len((agr))) + " # " + "removing... |
#Multiple Linear Regression
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,[0,1]].values #now we will have 3 columns as 0,1,2 as index
y = dataset.iloc[:,4].values
#Encoding t... |
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
def IP(a, b):
if len(a) != len(b):
return -1
else:
n = len(a)
ans = 0
for i in range(n):
ans += a[i]*b[i]
return ans
def steepest(A, b):
x = [0 for i in range(len(b))]
step = 10
Xaxis = [i fo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return x
is_negetive = x < 0
if is_negetive:
x = -x
new_x = 0
while x:
new_x = new_x * 10 + x % 10
x //= 10
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.