text stringlengths 37 1.41M |
|---|
_dict1 = {
1: "one",
"two": 2
}
_list1 = [101, False, "Hello", [3, 4, 5], _dict1]
print(_list1)
print(_list1[0])
print(_list1[1])
print(_list1[2])
print(_list1[3])
print(_list1[4])
a = "123.456"
b = float(a)
print(type(b), b)
c = '{}{}{}'.format(a[0], a[1], a[2])
c = int(c)
print(type(c), c) |
from data_structures.graph.graph import Graph, Vertex
def get_edges(route_map: Graph, itinerary: list) -> tuple:
"""Determine if the given itinerary is possible with direct flights and how much it will cost
Args:
route_map (Graph): Map of the existing cities
itinerary (list): List of cities
... |
def binary_search(arr: list, target: int) -> int:
"""Uses binary search algorithm to search the given array for a given element. Returns index of the element if found and -1 otherwise
Args:
arr (list): Sorted array
target (int): Element to look for in the given array
Returns:
int: ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
values = []
def traverse(head: ListNode):
nonlocal values
... |
from data_structures.stacks_and_queues.stacks_and_queues import Queue
def tree_intersection(bt1: object, bt2: object) -> set:
output = set()
q1 = q2 = Queue()
if bt1.root and bt2.root:
q1.enqueue(bt1.root)
q2.enqueue(bt2.root)
while not (q1.is_empty() and q2.is_empty()):
el1,... |
import plotly.express as px
import csv
with open('cups of coffee vs hours of sleep.csv', newline='') as f:
df=csv.DictReader(f)
fig=px.scatter(df, x="sleep in hours", y="Coffee in ml")
fig.show() |
import time
def timerfunc(func):
"""
A timer decorator
"""
def function_timer(*args, **kwargs):
"""
A nested function for timing other functions
"""
start = time.time()
value = func(*args, **kwargs)
end = time.time()
runtime = end - start
... |
from io import open
"""
archivo = open("/home/fhc/Desktop/Software Engineering Career/0. Python desde 0 a Experto/Avanzado/0. TratamientoDeErrores/archivo2.txt", "w")
frase = input("Ingrese por favor el contenido del archivo: -->")
archivo.write(frase)
archivo.close()
archivo = open("/home/fhc/Desktop/Software Engin... |
def evaluacionEdad(edad):
if edad<0:
raise TypeError("Ingrese una edad valida") #Error de tipeo
if edad<20:
return "Eres muy joven"
elif edad<40:
return "Eres joven"
elif edad<65:
return "Eres maduro"
elif edad<100:
return "Too old..."
edadD = int(input("Ingr... |
# Uses python3
import sys
def gcd_naive(a, b):
current_gcd = 1
for d in range(2, min(a, b) + 1):
if a % d == 0 and b % d == 0:
if d > current_gcd:
current_gcd = d
return current_gcd
def gcd(a, b):
result = 1
if max(a,b) % min(a,b) != 0:
return gcd(b%a, a%b)
result... |
#!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the ... |
#리스트 생성
d = []
#리스트에 입력받기(9개)
for i in range(9):
d.append(int(input()))
#최댓값 구하기
print(max(d))
#오프셋은 0부터 시작하므로 1 더해준다
print(d.index(max(d))+1)
|
my_list = [1, 2, 3, 4, 5, 6, 7]
first_element = my_list[0]
last_element = my_list[-1]
new_list = []
new_list.append(first_element)
new_list.append(last_element)
print('first and last:', new_list)
|
import sys
import csv
def inputs_checker():
"""Check command line arguments and if all are correct return them"""
try:
csv_file_path = sys.argv[1]
velocity = int(sys.argv[2])
if not csv_file_path.endswith('.csv'):
print("WARNING! First argument needs to be a .csv file.")
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Imports
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
# Application logic
# https://www.tensorflow.org/tutorials/layers
# The MNIST dataset comprises 60,000 training ... |
"""contains every function needed to get the data
from the database according to the user's choices"""
from constants import *
def categories_display(cursor):
"""displays categories and returns the user's choice"""
user_input = False
while not user_input: # until the user chooses a category
... |
elements = ['Adam', 'Alicja', 'Olaf', 'Elżbieta']
for x in elements:
print(x)
for x in range(2,5):
print(x)
for x in range(len(elements)):
print(x, elements[x])
print(range(6), type(range(6)))
my_range = list(range(6))
print(my_range, type(my_range))
cond = True
i =1
while cond:
print(cond)
# ... |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, world!"
@app.route("/jack")
def david():
return "Hello, Jack!"
@app.route("/<string:name>")
def hello(name):
name1 = ""
names = name.split(" ")
for name in names:
name1 += name.capitalize() + " "
... |
from scipy import integrate
def f(x,y):
return x*y # Maybe default return to 1 for triple integration(cartesian)
def bounds_y(): # args are what function is in terms of
return [0, 0.5]
def bounds_x(y):
return [0, 1-2*y]
area = integrate.nquad(f, [bounds_x, bounds_y]) # Inner to outer with nquad
# possib... |
# -*- coding : utf-8 -*-
# # install : pip install -U memory_profiler
# # usage : python -m memory_profiler Memory_Profiler/1.Getting_Start.py
@profile
def Fibonacci_Recursion(val):
if (val == 1):
return 0
elif (val == 2):
return 1
else:
return Fibonacci_Recursion(val - 1... |
words = []
maxLengthList = 50
while len(words) < maxLengthList:
item = input("Enter your words to the List: ")
words.append(item)
print (words)
print ("That's your words List")
print (words)
|
import numpy as np
""" Function that normalizes each row of the matrix x (to have unit length). """
def normalizeRows(x):
# Compute x_norm as the norm 2 of x.
x_norm = np.linalg.norm(x, ord = 2, axis = 1, keepdims = True)
# Divide x by its norm.
x = x / x_norm
# x -- The normalized (by ... |
import random
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", type=int, help="number of users to extract (default: 3)", default=3)
parser.add_argument("-f", "--file", type=str, help="Gradebook.md file to be processed (default: ../final-gradebook.md)", default='../fi... |
# edgelist_to_adjlist.py
def printAdjList(adjList):
for i in range(len(adjList)):
print(i, ":", adjList[i])
#----------------------------------------------------------------
def main():
edge_u = [0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4]
edge_v = [1, 3, 4, 0, 2, 3, 4, 1, 3, 0, 1, 2... |
#!/usr/bin/env python3
#Kevin Wong
#kmw396 - 14240214
#10/28/2018
#Lab 5 - Python Intro - Q2
#Imports UTF-8 file ids, removes whitespace and splits name from number, sorts name and numbers, and prints output
import sys
if len(sys.argv) == 1:
print("Missing Arguments")
sys.exit()
else:
f = open(sys.argv[1], "r") #o... |
"""This module contains a collection of functions related to
geographical data."""
from floodsystem.utils import sorted_by_key
from floodsystem.haversine import haversine
'''Function that recieves a list of monitoring station objects,
and a longitude and latitude coordinates in the form of a touple,
then returns a l... |
# coding: utf-8
# In[9]:
import networkx as nx
import pandas as pd
import numpy as np
from networkx.algorithms import bipartite
# This is the set of employees
employees = set(['Pablo',
'Lee',
'Georgia',
'Vincent',
'Andy',
'Frida'... |
class Bucket(object):
"""
Objects of this class simulate a memory limited list of numbers.
It also proxies any other methods straight to the list implementation
contained within.
"""
def __init__(self, size, seed_numbers=None):
self.size = size
if seed_numbers is None:
... |
"""
The permit predictor is an example application using a trained model to predict
the confidence that a building permit is issued
"""
import numpy as np
from data_io import restore_object
from constants import CATEGORICAL_FEATURES, NUMERIC_FEATURES, PCA_PICKLE_FILE, ENCODER_PICKLE_FILE, MODEL_PICKLE_FILE
def main(... |
"""
This program generates interesting graphviz game trees for Tic-Tac-Toe.
Probably you want to use it in a pipeline:
python gentree.py heuristic | dot -Tpdf -o heuristic.pdf
"""
import sys
import ttt
class Trees:
def rational():
"""Tree of all rational moves, up to symmetry. This is how all
... |
from turtle import Turtle
ALIGNMENT = 'center'
FONT = ('Courier', 13, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.color('white')
self.penup()
self.l_score = 0
self.r_score = 0
self.show_score()
def... |
"""
長方形の中に円が含まれるかを判定するプログラムを作成してください。次のように、長方形は左下の頂点を原点とし、右上の頂点の座標 (W,H) が与えられます。
また、円はその中心の座標 (x,y) と半径 r で与えられます。
"""
W, H, x, y, r = map(int,input().split())
print("Yes" if x>=r and x+r<=W and y>=r and y+r<=H else "No") |
import sys
from socket import *
# Get the server hostname and port as command line arguments
argv = sys.argv
host = argv[1]
port = argv[2]
sourceadd = argv[3]
destadd = argv[4]
subjekt = argv[5]
text = argv[6]
timeout = 1 # in second
endmsg = '\r\n.\r\n'
# Create socket called cl... |
# Create Allergy check code
# then PASTE THIS CODE into edX
# [ ] get input for input_test variable
input_test = input("Categories of food eaten in the last 24 hours: ")
# [ ] print "True" message if "dairy" is in the input or False message if not
print("It is", "dairy".capitalize().lower().upper().swapcase() in i... |
import tweepy
from tweepy import Stream
import StreamListenerClass as strm
import time
seeds = ["#disgusted", "#fearful", "#angry", "#surprised", "#scared", "#lonely", "#excited", "#wonderful", "#sleepy"]
"""
authenticates into the twitter API using the authentication handler and returns the authentication object
For... |
#getting current time and date
from datetime import datetime
now=datetime.now()
print now
#extracting information
from datetime import datetime
now=datetime.now()
current_year=now.year
current_month=now.month
current_day=now.day
print now.year
print now.month
print now.day
#Hot Date
from datetime import datetime
now... |
givenNumber = int(input('Enter number: '))
def square_dictionary(given_number):
dictionary = dict()
for i in range(1, given_number+1):
key, value = i, i*i
new_data = {key: value}
dictionary.update(new_data)
return dictionary
print(square_dictionary(givenNumber)) |
givenString = input('Enter string: ')
def exchange_first_last_character(given_string):
return given_string[-1] + given_string[1:-2] + given_string[0]
print(exchange_first_last_character(givenString))
|
givenDictionary =[
{"name": "Sid", "age": 20},
{"name": "Sid", "age": 5},
{"name": "Ajay", "age": 20},
{"name": "Sam", "age": 20},
{"name": "Ram", "age": 22},
{"name": "Shyam", "age": 11}
]
def sort_dictionary(given_string):
sorted_list = sorted(given_string, key=lambda i: (... |
given_tuple = ('a','p','p','l','e')
print(f"Old Tuple: {given_tuple}")
string = ''.join(given_tuple)
print(f"String: {string}")
|
dictionary = {'a': 100, 'b': 20, 'c': 50, 'd': -100}
print(f"Sum of dictionary values are {sum(dictionary.values())}")
|
given_tuple = (1,2,3,4,5,6)
print(f"Given Tuple: {given_tuple}")
temp_list = list(given_tuple)
to_remove = 3
print(f"To remove: {to_remove}")
temp_list.remove(to_remove)
new_tuple = tuple(temp_list)
print(f"New Tuple: {new_tuple}")
|
givenString = input('Enter string: ')
def reverse_string(given_string):
answer = ""
for i in reversed(given_string):
answer += i
return answer
print(reverse_string(givenString)) |
givenString = input('Enter string: ')
def remove_odd_index(given_string):
return given_string[1::2]
print(remove_odd_index(givenString)) |
import unittest
from Counter import Counter
class TestCounter(unittest.TestCase):
def setUp(self):
#Default Constructor Counter
self.defaultCounter = Counter()
def test_constructor(self):
c = Counter(32, 10, 61, True)
expected = [8, 10, 1, True]
cValues = [... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from scipy.io import loadmat
import urllib
import time
class PerceptronLearningAlgorithm(object):
def __init__(self, inputs, labels, epochs=1, test_amount=10000):
self.inputs = self.prepare_input(inputs... |
#Python program to get the difference between a given number and 17, if
#the number is greater than 17 return double the absolute difference.
def difference(n):
diff=n-17
if(diff>=17):
return diff*2
return abs(diff)
print(difference(14))
print(difference(34))
|
#Python program to get the n (non-negative integer) copies of the first 2
#characters of a given string. Return the n copies of the whole string if the
#length is less than 2
n=int(input("enter number"))
def string(str1):
lenght=len(str1)
if lenght >2:
return str1[0:2]*n
return st... |
#Write a Python program that accepts an integer (n) and computes the value of
#n+nn+nnn. Go to the editor
#Sample value of n is 5
#Expected Result : 615
n=int(input("enter the number"))
no1=n
no2=(n*10)+no1
no3=(n*100)+no2
total=no1+no2+no3
print(total)
|
# Python program to calculate the sum over a containe
sum=0
lis1=[1,4,5,2]
for elements in lis1:
sum=sum+elements
print(sum)
|
# Write a Python program to get a string which is n (non-negative integer)
# copies of a given string
def string(str1):
n=int(input("enter num"))
return n*str1
print(string("renu"))
|
#To find the given value is in the list or not
def grp_data(elements,n):
for values in elements:
if values==n:
return True
return False
print(grp_data([2,4,6,7],2))
print(grp_data([2,4,6,7],8))
|
#This program is used to find reverse the the name
first_name=(input(""))
sec_name=(input(""))
#This print is print the sec_name
#in reverse manner and first_name as like sec_name
print(sec_name[-1::-1] ,first_name[-1::-1])
#This print is uded to print the sec_name and first_name
print(sec_name,first_name)
|
#Greatest of the Three numbers:
a, b, c = map(int, input().split())
if(a>b and a>c):
print("a is Greatest")
elif(b>a and b>c):
print("b is Greatest")
elif(c>a and c>b):
print("c is Greatest")
else:
print("all are equal")
|
import string
def create_cypher_dict(cypher_key):
cypher_key = int(cypher_key)
alphabet = string.ascii_lowercase
alphabet_offset = alphabet[cypher_key:] + alphabet[0:cypher_key]
return alphabet_offset
def caesar(text_str, cypher_key) :
alphabet = string.ascii_lowercase
alphabet_offset = create... |
# Создание файла учетных записей
import shelve
import QuestandAnsw
########################################
''' Создаю функцию, в ней пишу код добавления новых учетных записей.
Введенные значения записываю как ключ и значение соответственно в файл.
'''
def add_account():
while True:
... |
import sys
def deleteContent(fName):
with open(fName, "w"):
pass
def file_len():
count = (len(listOfTasks) + 1)
return count
listOfTasks = []
listOfMarkedItems = []
f = open("marked.list","r")
d = open("tasks.list","r")
for line in f:
listOfMarkedItems.append(bool(line))
for line in d:
... |
import numpy as np
def derivative(x, y):
dy_dx = np.zeros(y.shape,np.float)
dy_dx[0:-1] = np.diff(y)/np.diff(x)
dy_dx[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])
return dy_dx
|
"""You know these Create a new password forms? They do a lot of checks to make sure you make a password that is hard to guess and you will surely forget.
In this Bite you will write a validator for such a form field.
Complete the validate_password function below. It takes a password str and validates that it:
is bet... |
mypizzas=['margherita','hawaii','pepperoni']
friendpizzas=mypizzas[:]
mypizzas.append('cheese')
friendpizzas.append('ham')
print("My favorite pizzas are:")
for pizza in mypizzas:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friendpizzas:
print(pizza)
|
""" My Product class
"""
class Product:
def __init__(self, name="", price=0.0, is_on_sale=False):
self.name = name
self.price = price
self.is_on_sale = is_on_sale
def __str__(self):
on_sale_string = ""
if self.is_on_sale:
on_sale_string = " On Sale"
... |
""" Word Occurrences """
words_str = str(input("Enter string of words: "))
words_list = words_str.split()
words_list_sorted = words_list.sort()
word_count_dict = {}
for word in words_list:
if word in word_count_dict:
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
print()
print("T... |
"""
CP1404/CP5632 - Practical
Program to determine grade from score
"""
def decide_score(score):
# function to decide grade from score
if score > 100 or score < 0:
return "Invalid score"
elif score > 90 <= 100:
return "Excellent"
elif score >= 50 < 90:
return "Passable"
else... |
import collections
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Tree:
def __init__(self, base):
self.base = base
def levelOrder(self, root):
if not root:return
res=[]
queue=... |
import datetime
def car(user_input):
_running = False
while(user_input != "quit"):
if(user_input == "help"):
print(f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} >",
"Commands:\n",
"<START> - starts the engine\n",
"<STOP> -... |
# two dimensional plotting
import pylab as p
# three dimensional plotting
import mpl_toolkits.mplot3d.axes3d as p3
def visualize(R):
# can only plot 2D or 3D
if R.shape[0] > 3:
print('can only plot 2D or 3D')
return
fig = p.figure()
# scatter3D requires a 1D array fo... |
# CTI-110
# Converts kilometers to miles
# Eihab Ghanim
# 10/26/2017
# Converting kilometers to miles.
CONVERSION_FACTOR = 0.6214
# The distance in kilometers.
def main():
kilometers = float (input('Enter a distance in kilometers: '))
show_miles(kilometers)
def show_miles (km):
miles = km *... |
# Напишите по одному позитивному тесту для каждого метода калькулятора
from app.calculator import Calculator
class TestCalc:
def setup(self):
self.calc = Calculator
def test_multiply_calculator_correctly(self):
assert self.calc.multiply(self, 2, 2) == 4
def test_division_calculator_corre... |
# Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
# In the case of ties, print the first substring
s = 'azcbobobegghakl'
# s = 'abcbcd'
compare_str = ' '
final_str = ''
length = 0
for letter in s:
if letter >... |
a = input ("Enter your text: ") #enter the text to convert it's first letter capital.
print (a.capitalize()) |
#imports
import random
import sys
loopnum = 0
many = input("How many to generate: ") # asks for how many links to generate
f= open("output.txt","w+") # creating output.txt
while loopnum < int(many): # loop
result_str = ''.join((random.choice('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz123... |
from listas import lista_ligada
from mapas import associacao
# 0: ("primos", 3) ("par", 20)
# 1: 15, 25, 35,
# 2: 16, 26, 36
# 3 (150:200):
class Mapa():
def __init__(self):
self.__elementos = lista_ligada.ListaLigada()
self.__numero_categorias = 10
for i in range(self.__numero_categorias... |
def longestPalindromic(s):
if len(s) == 1 or s == '':
return str(len(s))
else:
if s == s[::-1]:
return s
else:
for i in range(len(s)-1, 0, -1):
for j in range(len(s)-i+1):
temp = s[j:j+i]
if temp == temp[::... |
cipher_grille = (
'X...' ,
'..X.' ,
'X..X' ,
'....' )
letters = ('itdf',
'gdce',
'aton',
'qrdi')
def recall_password(cipher_grille, letters):
"""
returns password based upon cipher_grille, the cipher_grille is rotated 3 times 90 degrees to right
"""
coordinates = []
... |
def most_frequent(data: list) -> str:
"""
determines the most frequently occurring string in the sequence.
"""
frq_dict = {}
for lt in data:
if lt not in frq_dict:
frq_dict[lt] = 1
else:
frq_dict[lt] += 1
max_val = max(frq_dict.values())
for key... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 29 21:16:59 2018
@author: JOOST
"""
nums = [1,2,3]
nums.__iter__()
print(dir(nums))
print(next(nums))
i_nums = nums.__iter__()
# is the same as
i_nums = iter(nums)
next(i_nums)
print(i_nums)
print(dir(i_nums))
sentence = ' joost is gek'
class Sentence:
def __i... |
import sys
def flatten_with_precedence(arr, parenthise=False):
"""
Creates a string representation for the types created as arrays.
"""
# if the type is already a str, leave it as it is.
if isinstance(arr, str):
return arr
result = []
for x in range(len(arr)):
elem = arr[x]
# if the elemen... |
# Project Euler problem 51
# Find the smallest prime which, by replacing part of the number (not necessarily
# adjacent digits) with the same digit, is part of an eight prime value family.
import math
import time
primes = {}
def is_prime(n):
for i in range(2, int(math.sqrt(n))+1):
if n%i == 0 :
return 0
ret... |
# Project Euler problem 67
# Similar with problem 18
# Solution 1 : bottom up. Build maximum path from bottom. So initial triangle becomes:
# 3
# 7 4
# 2 4 6
#9 5 9 3
#
# 3
# 7 4
# 11 13 15
#9 5 9 3
#
# 3
# 20 19
# 11 13 15
#9 5 9 3
#
# 23
# 20 19
# 11 13 15
#9 5 9 ... |
# Project Euler problem 21
# returns the sum of proper divisors of n
def d(n):
sum = 0
for i in range(1, n/2+1):
if(n%i == 0):
sum += i
return sum
def solve():
sum = 0
divs_sum = {}
for i in range(1, 10000+1):
divs_sum[i] = d(i)
fo... |
class Student(object):
def __init__(self,name):
self.name=name
def show(self):
print(f'姓名:{self.name}')
def pr():
print('1')
#print(__name__)
if __name__=='__main__':
pr()
stu=Student('张三')
stu.show() |
array = []
total = 0
print ('MENGHITUNG NILAI RATA-RATA')
n = int(input("Masukkan banyaknya siswa: "))
for x in range(n-1):
nilai = float(input("Masukkan nilai siswa ke-{} : ".format(x+1)))
array.append(nilai)
kamu = int(input("Masukkan nilai kamu: "))
rata = (sum(array) + kamu)/ n
print("Hasil r... |
from Animal import Animal
from Tail import Tail
class Fish(Animal):
def __init__(self, type):
self.tail = Tail(type)
def __str__(self):
return "Fish tail: %s" % self.tail
|
import zipfile, os
def backup(folder):
folder = os.path.abspath(folder)
n = 1
while True:
zip1 = os.path.basename(folder) + '_' + str(n) + '.zip' #Name of the zip file = nameOfThebackedUpFolder_<backupcount>.zip
if not os.path.exists(zip1):
break
n = n + 1
... |
user_input = input("WHat is your Name? ")
User_age = input("What is your age? ")
hobby = input("What is favorite thing to do ")
print(f"Hello {user_input}, you really are {User_age}, I didnt know your hobby was {hobby}")
print(f"I HOPE YOU ENJOY BASE CAMP {user_name}!!!!!") |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import click
import glob
# Command line tool to search for files by type
@click.command()
# Option to specify the file path
@click.option(
"--path",
default=".",
prompt="Enter the file path to search in!!",
help="Path to search for files",
)
... |
"""Additional click types used in the project"""
import json
import click
class StringListParamType(click.ParamType):
"""Converts a comma-separated list of strings and returns a list of strings."""
name = 'string list'
def convert(self, value, param, ctx):
return value.split(',')
class JsonPar... |
# coding=utf-8
'''
定义一个学生类,用来形容学生
'''
# 定义一个空类
class Student():
# 一个空类,pass代表直接跳过
#此处pass必须有
pass
# 定义一个对象
mingyue = Student()
'''
#再定义一个类用于描述听Python的学生
class PythonStudent():
#用None给不确定的值赋值
name = None
age = 18
course = "python"
#需要注意
#1,def doHomework的缩进层级
#2,系统默认有一个self参数
... |
file = open('input.txt')
lines = file.readlines()
file.close()
def part_1(lines):
questions = set()
total = 0
for line in lines:
if line == '\n':
total += len(questions)
questions = set()
for char in line.strip():
questions.add(char)
total += len(que... |
#This program will automatically load from a csv file into a database, prompting the user for the servername, a database name and a tablename. When you supply these, and select a file, it will do the rest.
import os
import sys
from sys import argv
import pyodbc
from sqlalchemy import create_engine
import pandas as p... |
# -*- coding: utf-8 -*-
print '%4.2f'%(100000/3.0)
print 2*3
print 2**100 #乘方
print len(str(2**100)) #长度
import math,random
print math.pi #math 常用的数学模块
print math.sqrt(9)
print math.floor(2.5)
print math.trunc(3.4)
print random.random()
print random.randint(0,9) #随机0-9自然数
print random.choice(['+','-','*','/'])
pri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 14:43:17 2021
@author: shivakesh
"""
T = int(input())
for i in range(T):
a = input()
A = set(input().split())
b = int(input())
B = set(input().split())
print(A.issubset(B)) |
def formatcoord(coord):
col = ord(coord[0])-ord('a')
row = 8- int(coord[1])
return (row,col)
def pawn_move_tracker(moves):
print(moves)
board = [
[".",".",".",".",".",".",".","."],
["p","p","p","p","p","p","p","p"],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".... |
#Asks the user to enter a cost and either a country or state tax.
#It then returns the tax plus the total cost with tax.
print('What is the cost?')
cost = input()
print('What is the tax rate? (in %)')
rate = input()
rate = float(rate) / 100
tax = float(rate) * float(cost)
tc = tax + float(cost)
... |
"""
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
"""
# 对于有序数组,要么从小到大,要么从大到小
# 所以只需要判断相邻的值是否一样
class Solution:
@staticmethod
def remove_duplicates(nums):
# 从数组下标0开始
i = 0
# 如果数组下标小于(数组长度-1),也就是数组最大的下标
while i < len(nums) - 1:
... |
import random
import time
player = random.randint(1,6)
print("You rolled " + str(player) )
ai = random.randint(1,6)
print("The computer ross...." )
time.sleep(2)
print("The computer rolled " + str(ai) )
if player > ai :
print("You Win.") #notice indentation
elif player == ai :
print("Tie Game.")
else:
pr... |
#Time Complexity: O(n)
#Space Complexity:O(n)
#Ran successfully on Leetcode: Yes
# Algorithm :
# traverse the string,
# Traverse the string given
# Whenever we encounter '[', we append currdtring and currnum in to the stack
# if we encounter closing bracket, we pop out num and the char in string and evaluate curr st... |
import random
def play():
user = input("What's your Choice? 'r' for rock, 'p' for papper, 's' for scissors\n")
computer = random.choice(['r', 'p', 's'])
if user == computer:
return "It's a tie"
if is_win(user, computer):
return "You won!"
return " You lost!"
# r > s... |
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root,text='One',variable=v,value=1).pack(anchor= W)
Radiobutton(root,text='Two',variable=v,value=2).pack(anchor= W)
Radiobutton(root,text='Three',variable=v,value=3).pack(anchor= W)
mainloop()
|
from tkinter import *
root = Tk()
'''
listbox = Listbox(root)
listbox.pack(fill=BOTH,expand=True)
for i in range(10):
listbox.insert(END,str(i))
'''
Label(root,text='red',bg="red",fg="white").pack(side=LEFT)
Label(root,text='green',bg="green",fg="black").pack(side=LEFT)
Label(root,text='red',bg="blue",fg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.