text stringlengths 37 1.41M |
|---|
class Progression:
def __init__(self, start=0):
self._current = start
def _advance(self):
self._current += 1
def __next__(self):
if self._current is None:
raise StopIteration()
else:
answer = self._current
self._advance( )
ret... |
# ps0.py
import math
x = int (input ("Please enter the value of 'x': "))
y = int (input ("Please enter the value of 'y': "))
print (x**y)
print (math.log(x,2)) |
import numpy as np
number = int(input())
feature=np.zeros([number,3])
for i in range(number):
temp = input().split(" ")
if temp[2]=="LOVELIYZ":
temp[2]=1
else:
temp[2]=0
feature[i]=temp
|
def max_pairwise_product(n, arr):
res = 0
for i in range(0, n):
for j in range(i + 1, n):
if arr[i] * arr[j] > res:
res = arr[i] * arr[j]
return res
def max_pairwise_product_fast(n, numbers):
numbers.sort()
return numbers[-1] * numbers[-2]
if __name__ == '__m... |
# nums = [int(x) for x in input('Enter 2 digits').split()]
def sum_nums(a, b):
return a + b
if __name__ == '__main__':
a, b = map(int, input().split())
print(sum_nums(a, b))
|
n, operations = [int(x) for x in input().split()]
primary = [n+int(x) for x in range(0, n)] + [n+int(x) for x in range(0, n)]
size_array = [0 for x in range(0, n)] + [0 for x in range(0, n)]
def find(x):
if x == primary[x]:
return x
else:
primary[x] = find(primary[x])
return primary[x... |
"""
Hung Nguyen
Description: sets up a GUI for users to select which they want to see
"""
import tkinter as tk
import numpy as np
import sqlite3
import webbrowser
import tkinter.messagebox as tkmb
class mainWin(tk.Tk):
#The main ... |
# -*-coding:utf-8-*-
if __name__=='__main__':
map={}
map['name']='张三'
map[2]='男'
map['studentNo']=200154524657
for key,value in map.items():
print("{}->{}".format(key,value))
for key in map.keys():
print("{}->{}".format(key,map.get(key))) |
#! /usr/bin/env python3
import os
import sys
import json
import requests
import postgres
PG_AUTH = os.environ['PG_AUTH']
def word_intersects(word, db, en, fr):
""" Find if a word is present in three collection of words. """
is_en = word in en
is_fr = word in fr
in_db = db.one("SELECT id FROM words W... |
import numpy as np
from collections import Counter
def is_prime(x):
prime = True
if x==1:
prime=False
if x==2:
prime=True
elif x%2==0:
prime=False
else:
for i in range(3,int(x**0.5)+1,2):
if x%i==0:
prime=False
... |
def is_prime(x):
prime = True
if x==1:
prime=False
if x==2:
prime=True
elif x%2==0:
prime=False
else:
for i in range(3,int(x**0.5)+1,2):
if x%i==0:
prime=False
break
return prime
def n_prime(nb):
cou... |
"""Perform search and extract counts from Google Scholar"""
import logging
import pyautogui
import pytesseract
import re
# CONFIGURE THE BELOW POSITION AND REGION VALUES
# BASED ON YOUR SETUP
# TO FIND (X, Y) COORDINATES UNDER YOUR MOUSE CURSOR
# YOU CAN USE `xdotool getmouselocation --shell` in LINUX
SEARCH_BUTTON_P... |
"""
Problem: Two players play a game. The game starts with S = 0
Player 1 draws random numbers and adds it to S till S > 100, at which point
Player 1 notes their last number.
Player 2 continues to add numbers to S till S > 200, at which point Player
2 notes their last number.
Player 2 wins if lastNum(Player 2) > la... |
# sqllite3 to create a database
import sqlite3
db_locale = 'users.db'
connie = sqlite3.connect(db_locale)
c = connie.cursor() #use to create commands
#command
c.execute("""
INSERT INTO questions (title, name, details) VALUES
('WHAT IS THE USE OF QUORA', 'MR. THINKER', 'I AM HUGE EXCITED TO KNOW THE PURPOSE TO USING... |
from sys import exit
from random import randint
class Game(object):
def __init__(self, start):
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be proud. If she were smarter"
"Such a luser.",
"I have a small puppy that is better at thi... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import csv
import json
def read_csv(csv_path):
csv_file = open(csv_path)
usr_csv = csv.reader(csv_file)
usr_list = list(usr_csv)
csv_file.close()
return usr_list
def calculator(income):
start_point = 5000 # 起征点
social_insurance_poin... |
# # # # -*- coding: utf-8 -*-
import functools
if __name__ == '__main__':
def add(a,b):
"""
Returns sum of two ints
:param a: int
:param b: int
:return: int
"""
return a+b
# functools.partial
# print (add(3,4))
add3 = functools.partial(add,3) # T... |
mi_int = 3
mi_float = 2.2124
mi_str = "Esto es un string"
print(type(mi_int))
print(type(mi_float))
print(type(mi_str))
mi_int = "Ahora esto es un str"
print(type(mi_int))
|
"""This is the main flask app file"""
from flask import Flask, render_template
import names
app = Flask(__name__)
def generate_names(numberofnames):
"""Generate random names"""
nlist = []
for i in range(numberofnames):
nlist.append(names.get_full_name())
print(i)
return nlist
listnam... |
# -*- conding:utf-8 -*-
#Author:lyc
import os, sys
# 题目:
# 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
#
# 示例:
# 输入:n = 3
# 输出:[
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
class Solution:
def generateParenthesis(self, n: int) -> [str]:
"""
... |
# -*- conding:utf-8 -*-
#Author:lyc
import os, sys
# 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
#
# 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
#
# L C I R
# E T O E S I I G
# E D H N
# 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
#
# 请你实现这个将字符串进行指定行数变换的函数:
#
# string convert(string s, int numRows);
# 示例 1... |
# -*- conding:utf-8 -*-
#Author:lyc
import os, sys
# 题目:
# 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。
# 如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
# 如果不存在最后一个单词,请返回 0 。
#
# 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。
#
# 示例:
# 输入: "Hello World"
# 输出: 5
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s.strip()
... |
peso = float ( input ("Digite su peso en kg "))
altura = float ( input ("Digite su altura en Mts "))
total = (peso/(altura*altura))
print("")
if total<=18.5:
print("Usted esta bajo de peso con un IMC de: ",total)
elif total>=18.5 and total<=24.9:
print("Usted esta con un peso Normal con un IMC de: ",total)
el... |
#! /usr/bin/env python
'''#######################################################################################
# geographic_calculations.py
#
# This file contains functions that implement calculations on geographic information.
#
# NOTE: Any plotting is set up for output, not viewing on screen.
# So, it will ... |
from util import *
class SentenceSegmentation():
def naive(self, text):
"""
Sentence Segmentation using a Naive Approach
Parameters
----------
arg1 : str
A string (a bunch of sentences)
Returns
-------
list
A list of strings... |
import random
import math
# Function to evaluate g(x)
def funcG(x):
return math.exp(-(x**2))
# Function to evaluate h(y)
def funcH(y):
return funcG((1/y) - 1) / (y**2)
# Initialize values
iterations = input("Ingrese la cantidad de iteraciones: \n")
theta = 0
# Main loop to
for i in range(1, iterati... |
# Autor: Alejandro Cortes
# Descripsion:
# Este programa simula una venta
# de periodicos, para ayudar a un
# vocero.
import random
# Variables importantes
ventas = 0
saldoFinal = 0
numPeriodicos = input("Cuantos periodicos desea comprar al dia?\n -> ")
# Se calcula el dinero que se ha gastado...
saldo = num... |
from math import sin, cos, sqrt, atan2, radians
def calculate_distance(lat1, long1, lat2, long2):
"""
Calculates distance between 2 points (lat1, long1) => (lat2, long2)
Returns: Distance in kms
"""
earth_radius = 6373.0
lat1, long1, lat2, long2 = list(map(radians, (lat1, long1, lat2, long2)))
dlon = long2 - l... |
"""Operacion entre conjuntos"""
"""Alexis Eliseo Kauil Dzib"""
from clase_conjunto import Conjuntos
set_one={9,6,5,2,7,10} #Definir un conjunto, empleamos sets
set_two={12,7,4,10,11}
print("Selecciona una opción: ")
print("\t1 - Eliminar un elemento de un conjunto")
print("\t2 - Ingresar un elemento a un conjunto... |
# Create a file with the User class, including the __init__ and make_deposit methods
# Add a make_withdrawal method to the User class
# Add a display_user_balance method to the User class
# Create 3 instances of the User class
# Have the first user make 3 deposits and 1 withdrawal and then display their b... |
#!/usr/bin/env python
'''
I am always X. opfor is always O.
'''
import sys
import copy
def score(board):
# Really simple heuristic.
# Counts the number of x's in the longest column
def score(col):
return sum([1 if row == 'x' else 0 for row in col])
return max(map(score, board.columns))
def m... |
print ("***Program to check if the numbers are equal ot not***")
a = input ("Enter First number: ")
b = input ("Enter Second number: ")
if a==b:
print("yay! it's equal")
elif (a !=b):
#if (type(a) or type(b)) != int)
#print("Oops! there is type error")
#else:
print ("Oops! There is mismatch")
els... |
Coding:
def forbid(s,w):
if w not in s:
return 0
else:
return 1
s=str(input())
w=str(input())
if forbid(s,w):
print("YES")
else:
print("NO")
|
cars=100
cars_in_space=5
drivers=20
pasengers=70
car_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_percar=passengers/cars_driven
print("There are", cars,"cars availble")
print("There are only",drivers,"drivers availble")
print("There will be",car_not_driven,"... |
mystuff={'apple':"I AM APPLES"}
print(mystuff['apple'])
def apple():
print("I AM APPLES!")
tangerine="Living reflection of a dream"
mystuff['apple']
class Mystuff(object):
def _init_(self):
self.tangerine="And now a thousand years between"
def apple(self):
print("I AM CLASSY APPLES!")
thin... |
import networkx as nx
import pydot
from .my_logger import logger
class MakeGraphFile:
"""This class is used to create a graph out of the list of
emails.
This class reads the duplicated list of emails, then creates a
Directed Graph out of it, using NetworkX library. Finally, it
creates a .png file for the graph.... |
import csv
import random
class DataDict:
def __init__(self, mail_dicts, max_rep=10):
self.mail_dict_list = mail_dicts
self.max_rep = max_rep
self.duplicated_dict_list = []
def duplicate_data(self):
# Get an entry from the email dictionary
for mail in self.mail_dict_list:
# Choose a random number fro... |
#·
# Utility to plot x-y data from CSV file.
#
# Assumes that x-values are in first column
# Assumes curve titles are in first row
# Plots a curve for each column in addtion to·
# the x-data
#
# Usage:
# python plotxy.py <CSV input file name> <PNG output file name>
#
import sys
import matplotlib
matplotlib.rcParams[... |
class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
def inorder(root):
if root is not None:
# traverse left
inorder(root.left)
# traverse root
print(str(root.key)+"->",end=" ")
# traverse right
inorder(root.right)
d... |
class Node:
def __init__(self,item):
self.left = None
self.right = None
self.value = item
def inorder(root):
if root:
inorder(root.left)
print(str(root.value)+"->",end = "")
inorder(root.right)
def preorder(root):
if root:
print(str(root.value)+"->",... |
import random
name = "Simon"
question = "Is there alien life on Earth?"
answer = ""
random_number = random.randint(1,12)
#print(random_number)
if random_number == 1:
answer="Yes - definitely."
elif random_number == 2:
answer="It is decidedly so."
elif random_number == 3:
answer="Without a doubt."
elif random_n... |
from decks import Card
from decks import Deck
from players import Player
class Blackjack(object):
list_of_players = []
def __init__(self):
while True:
try:
num_decks = int(input("How many decks would you like to play with? "))
if not 1 <= num_decks <= 10:
... |
#Problem Set:
# https://www.codingame.com/training/medium/shadows-of-the-knight-episode-1
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
# w: width of the building.
# h: height of the building.
w, h = [int(i) for i in input().spl... |
'''
Created on Jun 30, 2014
@author: mohark1
'''
import csv
class fileWriter:
def csvWrite (self, headings, data, filePath):
c = csv.writer(open(filePath, "wb"))
c.writerow(headings)
for li in data:
c.writerow(li)
... |
'''
Created on Oct 28, 2016
@author: moosas1
'''
from datetime import *
from time import *
def logicalToActualConversion():
fw = open('convertedActualToLogicalTime.txt', 'w')
#Read the input file
with open('dateToLogicalDate.txt') as f:
content = f.readlines()
... |
def missing_number(lst, max_num):
"""Given a list of numbers 1...max_num, find which one is missing."""
lst.append(max_num + 1)
lst.sort()
current = 1
for item in lst:
if item == current:
current += 1
else:
return current
raise Exception("None a... |
def show_evens(nums):
"""Given list of ints, return list of *indices* of even numbers in list."""
evens = []
for index, num in enumerate(nums):
if num % 2 == 0:
evens.append(index)
return evens |
def has_unique_chars(word):
"""Does word contains unique set of characters?"""
if len(word) == len(set(word)):
return True
else:
return False |
#Cifrado sustitucion simple
cr = ''
archivo = open('alfabeto1.txt','r')
alfabeto1 = archivo.read().split(',')
archivo.close()
archivo = open('alfabeto2.txt','r')
alfabeto2 = archivo.read().split(',')
archivo.close()
if len(alfabeto1)!=len(alfabeto2):
print("Los alfabetos deben tener la misma cantidad de letras!!!")
... |
#CONTEXT
#Implements software for the local library. The user of the software will be the
#librarian, who uses your program to issue library cards, check books out to patrons, check
#books back in, send out overdue notices, and open and close the library.
#Objects, Classes, Methods
#Srihari Menon
############... |
# Take input
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
#Initialize variables
portion_down_payment = 0.25
current_savings = 0
r = 0.04
months... |
# An application that connects to a site and pulls all https links,
# saving them to a searchable index file.
# Import HTML request library
import requests
# Import Beautiful Soup for parsing HTML
from bs4 import BeautifulSoup
def URL_input():
# User inputs a URL
URL = input('Please enter a URL to find all l... |
#-----------------------------------------------------------------------------
# Name: Exercise 3 (Exercise3.py)
# Purpose: Using inputs, concatenation, and converting to strings
#
# Author: vonlugersbutter
# Created: Wednesday, October 10, 2018
# Updated: Friday, October 12, 2018
#-------------... |
#-----------------------------------------------------------------------------
# Name: Exercise 14 (Exercise14.py)
# Purpose: Display understanding of reading files
#
# Author: vonlugersbutter
# Created: Monday, December 10, 2018
# Updated: Friday, December 14, 2018
#----------------------------------------------------... |
#Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListN... |
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
s = s.strip() #默认删除空白符号('\r','\n',' ')
ans = 0
for si in s[::-1]:
if si != ' ':
ans += 1
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 31 19:15:03 2019
@author: araman
"""
"""
You are given an array of integers, where each element represents the maximum
number of steps that can be jumped going forward from that element. Write a
function to return the minimum number of jumps you must take in order to g... |
# User enters the number
number = int(input("Enter number: "))
# checking the number
if number < 0:
print("O número é negativo.")
elif number > 0:
print("O número é positivo.")
elif number == 0:
print("O número é zero.")
else:
print("A entrada não é um número")
|
import numpy as np
def heuristic_aux(x, y, x_g, y_g, name):
"""Admissible heuristics
Parameters
----------
x, y: int
state coordinate
x_g, y_g: int
goal coordinate
name: str
heuristic function name
Return
------
Float:
Corresponding heuristic value for a single coordinate
"""
if... |
#
# Use k-means clustering to find the most-common colors in an image
#
import cv2
import numpy as np
from sklearn.cluster import KMeans
def make_histogram(cluster):
"""
Count the number of pixels in each cluster
:param: KMeans cluster
:return: numpy histogram
"""
numLabels = np.arange(0, len... |
#Making the rocket for exercise 12-3. We will:
#1. Add the rocket to the center of the screen
#2. Allow the player to move the rocket up, down, left, or right.
#3. Make sure the rocket can't go beyond any edge of the screen
import pygame #Lets us work with pygame
class Rocket(object):
"""Manages most of the behav... |
import pygame #Lets us work with pygame
class ShipSideways(object):
"""Manages most of the behaviour of the player's ship"""
def __init__(self,ai_settings,screen):
"""Initializes the ship and its starting position"""
self.screen = screen #The screen we draw the ship on is the same as the s... |
#1. Make an empty screen
#2. Print event.key attribute whenever a pygame.KEYDOWN event happens
import pygame
import sys #Lets us exit the game when the player quits
def check_events():
"""Checks to see if a key was pressed"""
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: #Prints the ... |
"""
@vysery98
Dadas las siguiente ciudades, filtrar aquellas que tienen un número par como longitud en sus caracteres.
Loja, Pichincha, Guayaquil, Zamora, Ibarra, Manabi, Machala, Portoviejo, Macas
"""
ciudades = ["Loja", "Pichincha", "Guayaquil", "Zamora", "Ibarra", "Manabi", "Machala", "Portoviejo", "Macas"]
... |
#!/usr/bin/env python
# Get data from an ACS table
import sys
import argparse
import string
import doctest
import csv
def transpose_csv(from_fn, to_fn):
""" Flip a CSV's fields so horizontal tables become vertical.
Takes two filenames of CSVs, it writes the second.
"""
with open(to_fn, 'wb') as... |
# wartosc przyszla
# lewis_lu 13/10/2019
def future_save(p,i,t):
F = p * ((1+i/100)**t)
return F
def main():
money = float(input('\n\tPodaj aktualne saldo konta: '))
interest = float(input('\tMiesieczna stopa procentowa: '))
months = int(input('\tOkres oszczedzania w miesiacach: '))
future_save(money, i... |
# odchudzanie
# lewis_lu 17/07/2019
loss_weight = 2
weight = float(input('\n\t\tPodaj aktualna mase ciala w kg: '))
print('\n\t Aktualna waga', format(weight, '.2f'), 'kg, miesieczny spadek', format(loss_weight, '.2f'), 'kg.')
print('\t\tMiesiac\t\t\tOczekiwana waga')
for n in range(6):
weight -= loss_weight
prin... |
# srednie opady deszczu
# lewis_lu 14/07/2019
print('\n\tProgram oblicza srednie opady deszczu')
ile_lat = int(input('\tPodaj ile lat ma dotyczyc badany okres: '))
print()
opad_total = 0.0
ile_miesiecy = ile_lat * 12
for l in range(ile_lat):
for m in range(12):
print('\tMiesac', m+1, end='')
opad = float(input... |
#Learn how to use Turtle
#Try to deploy as much Turtle function as possible
import turtle
import datetime
#Get Today's date
#currentDate = datetime.date.today()
#print('Today is ' + currentDate)
#Explain what this program do
print("This is a program to draw any sharpe with multiple sides")
print("You can ask the progra... |
class node(object):
def __init__(self,data, next_node = None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_data(self,data):
self.data = data
def set_next(self,new_node):
self.next_node = new_node
class Linked... |
import numpy as np
import matplotlib.pyplot as pt
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
data = pd.read_csv("Data/train.csv").values
clf = DecisionTreeClassifier()
# Define Train and Data
train_test_ratio = int(input("Please enter the ratio of train data to test data: "))
last_train = 420... |
#!/usr/bin/python
import sys
import json
import heapq
heap = []
prev_student_id = None
prev_student = {}
def add_student(heap, student):
"""Prints out a student."""
# create strings for courses
marks = student['courses'].values()
if len(marks) > 4:
value = float(sum(marks)) / len(marks)
... |
import string
import random
def myfun(n):
return "".join(random.choice(characters) for x in range(n))
n=int(input("How Many Character in Your Password:"))
characters = string.ascii_letters + string.punctuation + string.digits
password=myfun(n)
print("Password is:",password) |
import random
min = 1
max = 100
roll_again = "ye"
while roll_again == "ye" or print("tf ur so booring"):
print (random.randint(min, max))
roll_again = input("Again? ") |
# -*- coding: utf-8 -*-
'''
Document object.
Each document has: text, unique identifer, content hash,
list of tokens and bag of words (dict[token] = number of occurrences).
'''
import hashlib
class Document(object):
def __init__(self):
self.text = ""
self.identifier = ""
self.content_h... |
guest_list = ['tim', 'michelle', 'regina', 'carlotta', 'roel', 'tom']
guest_list.insert(0,'aragorn')
guest_list.insert(3, 'gandalf')
guest_list.insert(5, 'saruman')
print ("Hereby I extend an inivitation to " + guest_list[0] + " to join my dinner.")
print ("Hereby I extend an inivitation to " + guest_list[1] + " to... |
#!/usr/bin/env python
# coding: utf-8
# In[14]:
import pandas as pd
import os
# In[15]:
file = os.path.join("budget_data.csv")
# In[16]:
data = pd.read_csv(file)
print (data)
# In[17]:
count = len(data)
print(count)
# In[18]:
#The net total amount of "Profit/Losses" over the entire period
column_sum... |
# This is example is for the SparkFun Qwiic Joystick.
# SparkFun sells these at its website: www.sparkfun.com
# Do you like this library? Help support SparkFun. Buy a board!
# https://www.sparkfun.com/products/15168
"""
Qwiic Joystick Example 4 - example4_joystick_output.py
Written by Gaston Williams, Jun... |
'''
find lines that above a specified length.
outputs a CSV with details of the long files.
Created on 6 Nov 2012
@author: astaveley
'''
import os;
import csv;
def find_long_lines_in_files(rootdir, line_limit):
total_violations = [];
for path, dirs, files in os.walk(rootdir):
for file in files:
... |
reg=input("registeriin dugaar oruulna uu:")
reg1=reg[:1]
reg2=reg[2:9]
if reg1.isalpha() == True and reg2.isdigit() == True:
print("registeriin dugaar mon bna")
else:
print("registeriin dugaar bish bna") |
### helper function
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
a = 0
b = 0
# since arrA and arrB already sorted, we only need to compare the first element of each when merging!
for i in range( 0, elements ):
if a >= len(arrA): # all eleme... |
print("hello","world")
x = 1
y = 1
z = 2
if x==y:
print("x==y")
elif x!= y:
print("x!=y")
else:
print("else")
list = ["one","two","three"]
for num in list:
print(num)
a = input("please input a num:")
print(a)
def get_int(msg):
while True:
try:
i = int(input(msg))
... |
re = iter(range(5))
try:
for i in range(100):
print re.next()
except StopIteration:
print 'here is end', i
print 'hahahahahaha'
|
f = open('file.txt', "r")
content = f.readline()
f.close()
print content
f = open('file.txt', "w")
f.write('I write a line')
f.close()
f = open('file.txt', "r")
content = f.readlines()
print content
f.close()
|
class Bird(object):
have_feather = True
way_of_reproduction = 'egg'
def move(self, dx, dy):
position = [0, 0]
position[0] = position[0] + dx
position[1] = position[1] + dy
return position
summer = Bird()
print summer.way_of_reproduction
print 'after move:', summer.move(5, 8... |
i = 1
if i > 0:
print 'positive i'
i = i + 1
elif i == 0:
print 'i is 0'
i = i * 10
else:
print 'negative i'
i = i - 1
print 'new i:',i
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
profit = int(raw_input("Please input the profit in this month:"))
reward = 0
if (profit > 1000000):
reward += 0.01*(profit-1000000)+400000*0.015+200000*0.03+200000*0.05+100000*0.075+100000*0.1;
elif(profit > 600000)and(profit <= 1000000):
reward += 0.15*(profit-600000)... |
#!/usr/bin/python
# coding:utf-8
'''
sunday
monday
tuesday
wednesday
thursday
friday
saturday
'''
def inputchar():
ch = raw_input();
return ch
def main():
print "Please input the char of week:"
week_ch = inputchar()
if week_ch == 's':
print "Please input the next char:"
week_c... |
''' sqlite3 related codes references from Lab3 slides/examples
cursor.fetchall() reference from https://stackoverflow.com/questions/34463901/how-to-iterate-through-cur-fetchall-in-python'''
from ui import message, displayRow
import sqlite3
import traceback
import os
import sys
def setup():
''' initial setup to cr... |
import cv2
import numpy as np
import medvision as mv
def vflip(img):
""" Flip an image vertically.
Args:
img (ndarray): image to be flipped.
Returns:
(ndarray): the vertically flipped image.
"""
return np.ascontiguousarray(img[::-1, ...])
def hflip(img):
""" Flip an image h... |
print('The Game will take several number and print the summ and Average og them')
count=int(input('how many numbers would you like to sum '))
cornt_count=0
summ=0
while cornt_count < count:
number=float(input('Enter the number: '))
summ +=number
cornt_count +=1
print('Summ of all numbers = ',s... |
# Uses python3
import sys
def binary_search_right(a, x):
left, right = 0, len(a) - 1
while left <= right:
mid = left + (right - left) // 2
if a[mid] > x:
right = mid - 1
else:
left = mid + 1
return left, mid, right
def binary_search_left(a, x):
left, rig... |
# python3
import sys
import threading
class Node:
def __init__(self, data):
self.child = []
self.data = data
def addchild(self, childnode):
self.child.append(childnode)
def compute_height(n, parents):
# Replace this code with a faster implementation
nodes = [0] * n
fo... |
class TreeNode(object):
def __init__(self, key, val, left=None, right=None, parent=None):
self.key = key
self.payload = val
self.leftChild = left
self.rightChild = right
self.parent = parent
def hasLeftChild(self):
return self.leftChild
def hasRightChild(sel... |
from node import Node
"""
append(item) adds a new item to the end of the list making it the last item in the collection.
It needs the item and returns nothing. Assume the item is not already in the list.
index(item) returns the position of item in the list. It needs the item and returns the index.
... |
def quickSort(alist):
quickSortHelper(alist, 0, len(alist)-1)
def quickSortHelper(alist, first, last):
if last > first:
splitpoint = partition(alist, first, last)
quickSortHelper(alist, first, splitpoint -1)
quickSortHelper(alist, splitpoint +1, last)
def partition(alist, first, last)... |
def mergeSort(alist):
print("Splitting, {}".format(alist))
if len(alist) > 1:
mid = len(alist) // 2
leftHalf = alist[:mid]
rightHalf = alist[mid:]
mergeSort(leftHalf)
mergeSort(rightHalf)
print("leftHalf, {}".format(leftHalf))
print("rightHalf, {}".format... |
from stack import Stack
"""
Create an empty stack called opstack for keeping operators. Create an empty list for output.
Convert the input infix string to a list by using the string method split.
Scan the token list from left to right.
If the token is an operand, append it to the end of the output list.
If the token is... |
#!/usr/bin/python3
from math import gcd
#encontrar o mínimo múltiplo comum entre 1 e 20
def mmc(numeros):
x = 1
for n in numeros:
x = x * n // gcd(x, n)
return x
numeros = range(1, 21)
print("O número mais pequeno que é divisível por todos os números de 1 até 20 é o", mmc(numeros))
|
"""Module that calculate the metrics as the exercise requests
"""
import json
import time
import pandas as pd
import numpy as np
class MetricsCalculation():
"""Class that ensembles the metrics calculator.
"""
@staticmethod
def calculate_metrics(channels: dict, parameters: dict,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.