text stringlengths 37 1.41M |
|---|
#!/usr/bin/python
alist=['a','b','c','d','e','f']
orb_pairs=[(i,j) for i in range(len(alist)) for j in range(len(alist)) if i<=j]
print orb_pairs
count=0
for pindex1 in range(len(orb_pairs)):
for pindex2 in range(0,pindex1+1):
print "Left side of intrgral = ", orb_pairs[pindex1]
print "Right side ... |
#ask for age
age = int(input('How old are you? : '))
if age != '':
if age<=6:
#is a child <=6
print('Child discount')
elif age >6 and age<11:
#is a family >6 or <=11
print('Family discount')
elif age >11 and age<=13:
#is a teen >11 or <=13
print('Teen dis... |
# task2.1.py implements a hill climbing algorithm to find a solution for the n-queens problem from a random given pos
import random
import sys
def main():
# input
n = int(sys.argv[1]) # board dimension given by user
queens = []
# 100 iterations each time
itr = 0
while itr < 1... |
# original code
"""Generate sales report showing total melons each salesperson sold."""
salespeople = []
melons_sold = []
# make a file object "f" from the sales report file
f = open('sales-report.txt')
# iterate over each line in the file (each order)
for line in f:
# get rid of extra whitespace/new lines, etc.... |
# # In this version, the program generates a random number with number of digits equal to length.
# # If the command line argument length is not provided, the default value is 1. Then, the program prompts the user to type in a guess,
# informing the user of the number of digits expected. The program will then read th... |
# User Input and Type Converting
# Accepting User Input
# accepting and outputting user input
print(input("What is your name?"))
# Storing User Input
# saving what the user inputs
ans = input("What is your name?")
print("Hello {}!".format(ans))
# Python defines type conversion functions to directly convert one data t... |
# Creating a User Database with CSV Files
# import all necessary packages
import csv
from IPython.display import clear_output
# handle user registration and writing to csv
def registerUser():
with open("users.csv", mode="a", newline="") as f:
writer = csv.writer(f, delimiter=",")
print("To registe... |
import random
secret = random.randint(1, 100)
guess, tries = 0, 0
#for i in range(6):
while tries < 6:
print("pls guess the number:")
guess = int(input())
if guess == secret:
print("You are a lucky man! You guessed it! The number is %d" % secret)
print("You guessed %d times!" % (tries+1)) ... |
n = int(input("Number of white balls: "))
m = int(input("Number of black balls: "))
k = int(input("Number of sampled balls: "))
ballsNumber = n + m # number of all balls
twoWhite = 1
twoBlack = 1
if n>=k:
tmp = ballsNumber
i = k
while i>0:
twoWhite *= (n/tmp)
n -= 1
tmp -= 1
... |
def find_max_crossing_subarray(A, low, mid, high):
left-sum = -floot('inf')
sum = 0
for i in range(mid,low-1, -1):
sum = sum + A[i]
if sum > left-sum
left-sum = sum
max-left = i
right-sum = -floot('inf')
sum = 0
for j in range(mid+1,high+1):
sum = sum + A[j]
if sum > right-sum:
right-sum = sum
... |
import numpy as np
import sympy
def riemann_curvature_tensor(list2d, syms):
"""
Function to calculate Riemann Curvature Tensor of a given metric
Parameters
----------
list2d : list
d list (Matrix) representing metric, containing ~sympy expressions
syms : list
1d list containin... |
import numpy as np
import random
import PriorityQueue
EMPTY = 0
WALL = 1
GHOST = 2
PACMAN = 3
class Board:
def __init__(self, row, column):
self.row = row
self.column = column
self.board = np.zeros(row*column).reshape(row, column)
self.board[0][0] = PACMAN #default - can be chang... |
#Write a function named feed_to_inches that accepts a number of feet as an argument and returns the number of inches in that many feet
def feet_to_inches(feet):
return 12.0 * feet
# Function that gathers data from user and calculates
def main():
feet = float(input('Enter the number of feet you would like conve... |
#Begin Wifi troubleshooting
print('Welcome to the Wifi fixer 9000.')
begin = input("Reboot the computer and try to connect. Did that fix the problem? Yes/No: ")
#If answer yes, end program with you're welcome. Otherwise, proceed to the next step
if begin == "Yes" or begin == "yes":
print("You're welcome.")
else:
r... |
"""
This module handles logic for tokenizing rules scripts into
tokens, ready for parsing
"""
import regex
def tokenize_string(string):
"""
Splits a given string into tokens, ready for parsing
Arguments:
string - The string to split
Returns:
A list of tokens from the string
"""
... |
def phoneLetter(digs):
if not digs:
return []
keyboard = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
res = []
if len(digs) == 0:
return []
if len(digs) == 1:
... |
# import the random module
import random
# generate a random value between 1 and 6 for each of the three die
# store the three values in a list
playerDie1 = random.randint(1,6)
playerDie2 = random.randint(1,6)
playerDie3 = random.randint(1,6)
playerDice = [playerDie1, playerDie2, playerDie3]
# Display the value of ... |
# This program will demonstrate the use of variables in python (just few of them)
x = 'Dipak Bari'
y = 27
print(x)
print(y)
|
print("Demonstrates the indentations and their values in Python!")
def main():
print("Inside the main function") #This will called later
print("Doesn't relate with main function") #This will called first at executioin
if __name__ == "__main__": main() #executing the main function |
# Key to sort array by number
def sort_key(val):
return val[1]
# Key to sort array by alphabet
def sort_key2(val):
return val[0]
if __name__ == '__main__':
# adds inputs to an array
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([... |
# append times tables to existing file, first col right justified
with open(".\\Section 10\\challenge.txt", 'w') as existing:
print("Existing", file=existing)
with open(".\\Section 10\\challenge.txt", 'a') as append:
for i in range(1, 13):
# what does > do exactly? doesnt seem nevessary
print(... |
for i in range(17):
print("{0:>2} in binary is {0:>08b}".format(i))
# 0b to indicate binary
x = 0b101010
print(x) # 42
|
ipAddress = "192.168.0.1"
print(ipAddress.count("."))
parrot_list = ["not pinin'", "no more", "a stiff", "bereft of life"]
parrot_list.append("a Norwegian Blue")
for state in parrot_list:
print("This parrot is " + state)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = even + odd # concats
numbers.sort() ... |
for i in range(10):
print(i)
# same as above
i = 0
while i < 10:
print(i)
i += 1
available_exits = ["east", "north east", "south"]
chosen_exit = ""
while chosen_exit not in available_exits:
chosen_exit = "east" # choose a direction, could be from input
# point is that you don't know in advance wh... |
# shelve good if you don't want to read things
# entirely into memory before pickling them
# shelf is a dict with string key and picklable val
# calling file needs to be called something other than shelve.py
import shelve
# creates bak, dat and dir files i.e. a database
with shelve.open(".\\Section 10\\ShelfTest") as... |
'''1. Write a Python function to find the Max of three numbers.'''
# def max_func(a,b,c):
# if a > b and a > c:
# print("{} is greater".format(a))
# elif b > a and b > c:
# print("{} is greater".format(b))
# else:
# print("{} is greater".format(c))
# max_func(10,20,30)
# max_func(15,20,5)
# max_func(20,10,5)
... |
import random
import time
# The following code defines how to remove spelling and punctuation.
def removepunc(listx):
def removeall (listy, removed):
while listy.count (removed) > 0:
listy.remove(removed)
return(listy)
listx = removeall(listx, ".")
listx = removeall(listx, ","... |
valor_1 = 100
valor_2 = 14
#soma
valor_soma = valor_1 + valor_2
print 'O valor da soma eh ', valor_soma
#subtracao
valor_sub = valor_1 - valor_2
print 'O valor da subtracao eh ', valor_sub
#divisao
valor_div = valor_1 / valor_2
print 'O valor da divisao eh ', valor_div
#multiplicacao
valor_mult = va... |
#declarando uma lista vazia
lista = []
#Adicionar elementos
lista.append('Joelma')
lista.append('Chimbinha')
lista.append('Safadao')
lista.append('Annita')
print lista
#inserir elemento em uma posicao especifica
lista.insert(0,'Mc Troinha')
print lista
#remover um elemento pelo valor
lista.remove('Ann... |
#######################################################################################
# File: chatroom.py
# Author: Wameedh Mohammed Ali
# Purpose: CSC645 Assigment #1 TCP socket programming
# Description: This class represents a chat room object that users can create. It stores
# ... |
import sqlite3
conn = sqlite3.connect("db.db")
c = conn.cursor()
def select_with_fetchone():
cmd = "SELECT * FROM users WHERE user_id=%d" % 1000
c.execute(cmd)
result = c.fetchone()
print(result)
def select_with_fetchall():
cmd = "SELECT * FROM users"
c.execute(cmd)
result = c.fetchall()... |
import random
adivina = random.randint(1,10)
numeroPersona = int(input("Dime un numero: "))
if numeroPersona > 10 or numeroPersona < 0:
print("Te has pasado de los limites entre 0 y 10")
if numeroPersona == adivina:
print("Enhorabuena as adivinado el numero")
else:
print("Has fallado")
print("El numero... |
num_repeticiones = int(input("Cuantas repeticiones quieres"))
for a in range(num_repeticiones):
print("Hola")
for a in range (1, num_repeticiones +1):
print(a) |
import wat
# """
# atdo Exception
# """
class myException(Exception):
def __init__(self, msg, num):
self.msg = msg
self.num = num
try:
raise myException('aaaa', 3)
except myException as e:
print('------')
wat.d(e.msg, e.num)
|
# coding:utf8
#
# aa=None
#
# def d():
# aa=23
#
# def e():
# print aa
#
# d()
#
# e()
s='1234你好 '
print s.__len__()
print s.decode('utf-8').__len__()
print s.decode('utf-8').encode('gbk').__len__() |
'''Python generator:
This is an example of python generator. It's very handy to write
memory efficient codes because it doesn't holdv values into memory, it just
uses them when it needs it.
To illustrate it, let's write a Fibonacci sequence generator using that concept'''
def gen_fibonacci(n):
#Starting by the in... |
from turtle import Turtle,Screen
class Paddle(Turtle):
def __init__(self,x,y):
super().__init__()
self.penup()
self.color("white")
self.shape("square")
self.shapesize(stretch_wid=1,stretch_len=5)
self.goto(x,y)
def Left(self):
if (self.xcor()!=-320):
... |
"""
Complexity: O(log(n))
return: Index of Peek
"""
def PeekFinder1D(Array, low, high):
mid = int((low + high) / 2)
if mid < high and Array[mid] < Array[mid + 1]:
return PeekFinder1D(Array, mid+1, high)
elif mid > 0 and Array[mid] < Array[mid - 1]:
return PeekFinder1D(Array, 0, mi... |
"""
Python Review of classes
"""
import math
class MyFirstClass:
pass
class Point:
"""
Represents a point in a 2-D geometric coordinates
"""
def __init__(self, x=0, y=0):
"""
Initializes the position of a new point.
If they are not specified, the point defaults
... |
def my_range(start, end):
while start < end:
yield start
start += 1
range_object = my_range(0, 5)
# iterator = iter(range_object)
# print(next(iterator))
# print(next(iterator))
# print(next(iterator))
# print(next(iterator))
# print(next(iterator))
# print(next(iterator))
# for i in my_range(0,... |
to_square = lambda x, y: (x ** 2, y ** 2)
result = to_square(2, 4)
print(result)
def confirmer(func_obj, arg):
return func_obj(arg)
result = confirmer(lambda x: x ** 2, 10)
print(result)
list_of_numbers = [1, 2, 4, 8, 16]
list_of_numbers_2 = [2, 3, 5, 9, 17]
squares = []
for num in list_of_numbers:
squar... |
final_list = []
for i in range(100):
final_list.append(i)
print(final_list)
result = [1 if x > 50 else 0 for x in range(100) if x % 2 == 0]
print(result)
source_list = [1, 2, 4, 8, 16, 32]
result_dict = {i ** 2: i ** 3 for i in source_list}
print(result_dict)
result_set = {i for i in range(100)}
print(result_s... |
"""
Inheriting from the class Point, a canvas data attribute is
added to Point and a method to draw the point on the canvas.
The main program pops a new window with a canvas and draws ten
random points on the canvas.
"""
from tkinter import Tk, Canvas
from random import randint
from class_point import Point
class Sh... |
import unittest
from TrainTestVal_2 import *
import pandas as pd
from load_adult_data import *
data = main()
"""
### The following lines if for use if we want to use load_adult_data instead of manually ###
### loading pandas DataFrames ###
names = ['age', 'workclass', 'fnlwgt', 'education', 'education-num',
... |
import math, copy, string
import random
# CMU Graphics file from https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html
from cmu_112_graphics_final import *
from tkinter import *
from PIL import Image
# Word class stores the word dictionary and checks word membership
class Word(object):
# General readFile s... |
annual_salary = int(input("Enter your annual salary : "))
salary = annual_salary
lower = 0
upper = 10000
saving_percent = 5000
down_payment = 250000
steps = 0
while True:
savings = 0
salary = annual_salary
portion = (annual_salary / 12) * (saving_percent / 10000)
for r in range(1, 37):
savings... |
# -*- coding: utf-8 -*-
# l=[{'a':2,'b':2},{'a':1,'b':3}]
# def combine_dic(l):
# if l[0]['a']==l[1]['a'] and l[0]['b']!=l[1]['b']:
# l[0]['b'] = str(l[0]['b'])+'#'+str(l[1]['b'])
# l = l[0]
# return l
# else:
# return -1
# print(combine_dic(l))
# l.append(1)
# print(l)
# l.pop()... |
# -*- coding: utf-8 -*-
# 如何创建一个链表
class Node(object):
'''节点'''
def __init__(self, elem):
self.elem = elem
self.next = None
class Singerlinkerlist(object):
'''单链表'''
def __init__(self, node=None):
self._head = node
def is_empty(self):
'''判断是否为空'''
return... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 18 17:59:17 2021
@author: rachel
"""
# Python3 code for implementation of Newton
# Raphson Method for solving equations
# An example function whose solution
# is determined using Bisection Method.
# The function is x^3 - x^2 + 2
def func2( x, CS ... |
import numpy as np
import pandas as pd
def cluster(X, max_num_clusters=3, exact_num_clusters=None):
'''Applies clustering on reduced data,
i.e. data where power is greater than threshold.
Parameters
----------
X : pd.Series or single-column pd.DataFrame
max_num_clusters : int
Returns
... |
"""
doc_inherit decorator
Usage:
class Foo(object):
def foo(self):
"Frobber"
pass
class Bar(Foo):
@doc_inherit
def foo(self):
pass
class Baz(Bar):
@doc_inherit
def foo(self):
pass
Now, Bar.foo.__doc__ == Bar().foo.__doc__ == Foo.foo.__doc__ == "Frobber"
and Baz.... |
n1=int(input())
arr1=list()
for x in range(n1):
arr2=list(map(int,input().split()))
arr1=arr1+arr2
arr1=sorted(arr1)
for s in arr1:
print(s,end=" ")
|
v=input()
if v==v[::-1]:
print("yes")
else:
value=v.strip("0")
if value==value[::-1]:
print("yes")
else:
value=v.lstrip("0")
if value==value[::-1]:
print("yes")
else:
print("no")
|
#coding=utf-8
import urllib.parse
import urllib.request
URL = 'https://www.python.org'
resp = urllib.request.urlopen(URL)
# print(resp.read().decode('utf-8'))
print(type(resp))
print(resp.status)
print(resp.getheaders())
print(resp.getheader('Server'))
URL = 'http://httpbin.org/post'
data = {'word':'hello'}
# 将字... |
#! /usr/bin/python
# -*- coding:utf-8 -*-
import sys
import os
from xldef import *
from 小岚显示功能扩展js基准利率 import *
def rabbit_purple_radish():
one_type = input("\n一表看一年,才知没有钱~\n此功能用于基础图表显示\n")
while True:
if one_type == '基准利率':
map_show()
break
elif one_t... |
num_input = input("Please enter a number?")
ones = {
'0': "zero",
'1': "one",
'2': "two",
}
n_as_word = ones.get(num_input)
print(n_as_word) |
if __name__== '__main__':
stu = []
pythonStu = []
for _ in range(int(input("How many students"))):
name = input("Name: ")
score = float(input("Score: "))
single = [name,score]
pythonStu.append(single)
pythonStu=sorted(pythonStu, key=lambda stud: (stud[1]))
minim = py... |
class A:
"""Classe A, pour illustrer notre exemple d'héritage"""
pass # On laisse la définition vide, ce n'est qu'un exemple
class B(A):
"""Classe B, qui hérite de A.
Elle reprend les mêmes méthodes et attributs (dans cet exemple, la classe
A ne possède de toute façon ni méthode ni attribut)"""
... |
class Personne:
"""Classe définissant une personne caractérisée par :
- son nom ;
- son prénom ;
- son âge ;
- son lieu de résidence"""
def __init__(self, nom, prenom):
"""Constructeur de notre classe"""
self.nom = nom
self.prenom = prenom
self.age =... |
import math
angle = 0
angle2 = angle-45
angle3 = angle-90
a=50
c=50*math.sqrt(2)
def setup():
size(360,360)
def posLine1():
global x1,y1, angle
x1 = a*math.sin(math.radians(angle))
y1= a*math.sin(math.radians(90-angle))
def posLine2():
global x2,y2, angle2
x2 = c*math.sin(math.radians(ang... |
prompt = 'Please entere a score between 0.0 and 1.0: '
score = raw_input(prompt)
try:
score = float(score)
if score >= 0.9 and score <= 1.0:
grade = 'A'
elif score >= 0.8 and score < 0.9:
grade = 'B'
elif score >= 0.7 and score < 0.8:
grade = 'C'
elif score >= 0.6 and score < 0.7:
grade = 'D'
elif scor... |
## Problem 23 - Non-abundant sums
## A perfect number is a number for which the sum of its proper divisors
## is exactly equal to the number. For example, the sum of the proper
## divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
## A number n is called deficient if the sum of ... |
import AES as aes # Import AES to implement OFB
import random # It is used to generate random integer
WORD_LENGTH = 4 # Length of matrix
SIZE = 16 # Length of the texts
# It generates a random initialization vector with size 16
def generate_initialization_vector():
... |
import pygame
import column_logic
import random
#These two constants are the row and column of the game
ROW_NUM = 13
COLUMN_NUM = 6
class ColumnGame:
'''
This is a class represents the user interface of the column game,
which displays tha game
'''
def __init__(self):
self._ru... |
#Name: Eric Liu
#StudentID: 56277704
from pathlib import Path
from shutil import copyfile
#Part 1
#Read a line of input that specifies which files are eligible to be found
#Input
#D, followed by a space, followed by the path to a directory
#R, followed by a space, followed by the path to a directory
... |
from datetime import datetime
import wikipedia
import speech_recognition as sr # to talk to alexa
import pyttsx3 # pyttsx3 means python text to speech, use this so alexa can talk to us
import pywhatkit # to open applications like youtube
import pyjokes # used to tell jokes
listener = sr.Recognizer() # this... |
animals = {
"Dog":"Bow Bow",
"Cat":"Mewow"
}
#add items
it= animals["Cow"]="Maa"
print(animals)
#add items using python in-built function
it = animals.update({"Cat":"Mewow Mewow"})
print(animals) |
from moduloT2 import *
n = int(input("Introduzca un número: "))
fac = factorial(n)
primo = esPrimo(n)
print("El factorial de " + str(n) + " es: " + str(fac))
if primo:
print(str(n) + " es primo")
else:
print(str(n) + " no es primo")
|
"""
文件读写工具
---
read_file(file_path): 读取单个文件数据
read_folder(folder_path, file_suffix={'txt', 'csv', 'dat'}): 读取文件夹指定后缀文件
"""
from os import listdir
from os.path import isfile, join
def read_file(file_path):
""" 读取文件内容 """
pieces = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 08:48:27 2019
Problem Set 5
Problem 1: Periodic Points of a Word
Problem 2: Connected Components of Function
"""
from nose.tools import ok_
# =============================================================================
# Problem 1
# Given a word of length... |
# Benjamin Chappell
# Class used to classify all the actions one can take in poker
from enum import Enum, auto
class ActionTypes(Enum):
FOLD = 0
CHECK = auto()
CALL = auto()
RAISE = auto()
shove = auto()
class Action:
# Move is an enum value designating fold, check, call, raise, shove
# a... |
# Benjamin Chappell
# Hand value storage
from enum import Enum
from rank import Rank
class HandClass(Enum):
HIGH = 0
PAIR = 1
TWO_PAIR = 2
SET = 3
STRAIGHT = 4
FLUSH = 5
BOAT = 6
QUADS = 7
SFLUSH = 8
RFLUSH = 9
class Hand:
def __init__(self, type, rank, rank2=False) -> Non... |
from tkinter import *
root = Tk()
root.title('车牌识别系统')
frame1 = Frame(root)
frame2 = Frame(root)
frame3 = Frame(root)
var = StringVar()
var.set('欢迎进入车牌识别系统')
img = PhotoImage(file='D:/bg_GUI.png')
# img_label = Label(frame1, image=img)
# img_label.pack(side=RIGHT)
Label(frame1, image=img).grid(row=1, column=1, stic... |
def prefix_suffix(string):
if not string:
return 0
arr = [0] * (len(string) + 1)
for i in range(2, len(arr)):
arr[i] = arr[i - 1]
while string[i - 1] != string[arr[i]] and arr[i] > 0:
arr[i] = arr[arr[i]]
if string[i - 1] == string[arr[i]]:
arr[i] += 1... |
#!/usr/local/bin/python
def iterate_word(word):
for x in range(0,len(word)):
print("Forward:" , word[x], "Reverse", word[(len(word) -x -1)])
iterate_word('alphabet')
# doing this with list comprehension returning reversed tuple pairs:
In [240]: [(word[x], word[(len(word) - x - 1)]) for x in range(0,len(word))]
O... |
"""
Use any Object-Oriented language to complete this task.
# Create a class named LuckyNumber.
# The constructor for LuckyNumber should take a single argument: a string called first_name (e.g.: "Marc").
# In the LuckyNumber class create two methods, generate_data and display_data, that take no arguments.
# The ge... |
"""
- In a street there are five houses, painted five different colors.
- In each house lives a person of different nationality.
- These five homeowners each drink a different kind of beverage, smoke different brand of cigar and keep a different pet.
- The British man lives in a red house.
- The Swedish man keeps dogs... |
class Node(object):
def __init__(self,value):
self.value = value
self.next = None
class Stack(object):
def __init__(self):
self.head = None
def push(self,value):
"""
Somethis is borked in which self.head has no value
"""
if self.head is None:
... |
#!/usr/local/bin/python
import random
#Create an array X and fill the array with 10 values, each value being a random integer between 0 to 100. For example when your program is done, X could be something like this: [35, 15, 3, 39, 53, 93, 25, 39, 59, 21].Create an array X and fill the array with 10 values, each value... |
"""
a turn based number guesser player between a human and the computer.
At numbers < 100, The computer should solve the problem in 5 turns or less
Usage: python computer_human_number_guesser.py
"""
import random
def getguess():
"""
get the guess from the player
"""
guess = int(input("What's you... |
#!/usr/local/bin/python
"""
shift values one position to the right.
In this cast you wind up with the same final array
"""
my_array = [8,3, 33, 42, 10, 14, 2, 21, 4]
loop = 0
while loop < len(my_array):
print(my_array)
my_array.append(my_array[0])
my_array.pop(0)
print(my_array)
loop += 1
# doing something mor... |
#!/usr/bin/env python3
low = 353096
high = 843212
num_possible = 0
# Teil 1
for n in range(low + 1, high):
digits = list(str(n))
prev_digit = 0
has_ascending_digits = True
has_double_digit = False
for digit in digits:
digit = int(digit)
# Folgende Ziffer kle... |
fibs(lengths):
'return the list of Fibonacci sequence'
fiblist = [0, 1]
for i in range(lengths-2):
fiblist.append(fiblist[-2]+fiblist[-1])
return fiblist
print fibs(11)
|
#Aliasing in python, short hand for pyplot
import matplotlib.pyplot as plt
#x/y values of graph
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
#Uses one of the style available from plt.style.available
#plt.style.use('seaborn')
#plt.style.use('fivethirtyeight')
plt.style.use('Solarize_Light2')
#Common mat... |
#!/usr/bin/python3
def uppercase(str):
print("{}".format(str.upper()))
|
#Diocelina sierra martinez
#22/11/16
#ejercicio 3
area=input("encontrar el radio:")
pi=3.1416
r=4
resultado=pi*r**2
print "el area del circulo es"resultado
#el volumen de la esfera
esfera=input("encontrar el volumen:")
formula=4/3*pi*r**3
print "el volumen de la esfera es"formula
|
#Diocelina Sierra Martinez
#01/112/16
import math as r
def cos(ang):
return r.cos(r.radians(ang))
def sin(ang):
return r.sin(r.radians(ang))
def acos(ang):
return r.acos(r.radians(acos))
a1=float(input ("Introduzca latitud: "))
b1=float(input ("Introduzca longitud: "))
a2=float(input ("Introduzca latitud: "... |
def grid_traverse(x=0, y=0, min_sum=0):
global N, grid, result
if x == N-1 and y == N-1:
min_sum += grid[y][x]
result = min(result, min_sum)
return
if x < N and y < N:
min_sum += grid[y][x]
grid_traverse(x+1, y, min_sum)
grid_traverse(x, y+1, min_sum)
el... |
def is_correct(u):
stack = []
if u[0] == ')':
return False
for br in u:
if br == ')':
if not stack:
return False
else:
stack.pop()
else:
stack.append(br)
if not stack:
return True
else:
retu... |
from collections import deque
def solution(begin, target, words):
if target not in words:
return 0
change_dic = {}
si_cnt = 0
for word1 in words + [begin]:
for word2 in words:
for i in range(len(word1)):
if word1[i] == word2[i]:
si_cnt ... |
def binary_search(target, l, r, num_list, flag):
m = (l + r) // 2
if num_list[m] == target:
return m+1
if l > r:
return False
if target < num_list[m]:
if flag == 'R':
flag = 'L'
idx = binary_search(target, l, m - 1, num_list, flag)
else:
... |
#Write your code below this line 👇
#Hint: Remember to import the random module first. 🎲
import random
random_coinflip = random.randint(0,1)
if random_coinflip == 0:
print("Tails")
else:
print("Heads")
|
import time
starttime = time.time()
y = 1
sum = 0
for i in range(1, 101):
y *= i
print(y)
numbers = str(y)
for i in range(0, len(numbers)):
sum += int(numbers[i:i + 1])
print(sum)
print('Time:', time.time() - starttime) |
import time
from eulerfunctions import isprime
starttime = time.time()
x = 2
count = 0
while count < 10001:
if isprime(x):
count += 1
x += 1
print('Prime #', count, ' - ', x - 1)
print('Time: ', time.time() - starttime) |
import time
import math
from eulerfunctions import isprime
starttime = time.time()
sum = 0
for i in range(1, 2000001):
if isprime(i):
sum += i
print('Answer :', sum)
print('Time :', time.time() - starttime) |
i = 1
foo = 0
while i < 1000:
if i % 3 == 0 or i % 5 == 0:
foo += 1
i += 1
print(foo) |
import math
from fractions import Fraction
# x is the value of d in x^2-dy^2=1, and y is the how many times to recurse through the values.
# it will output a tuple of num,dom. Increase the value of y until num=x and dom=y are valid answers.
def pell(x, y):
xsqr = math.sqrt(x)
if int(xsqr) == xsqr:
... |
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
self_div_nums = list()
while not left > right:
isSDN = True
for x in str(left):
if int(x) == 0:
isSDN = False
break
... |
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
x_index = set()
y_index = set()
for x in range(0, len(matrix)):
for y in range(0, len(matrix[x])):
... |
class Frontier():
def __init__(self):
self.frontier = []
def newFrontier(self,state):
self.frontier.append(state)
def giveFrontier(self):
return self.frontier[len(self.frontier)-1]
class TicTacToe():
def __init__(self,initialturn,difficulty):
self.initialturn = bool(i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.