text stringlengths 37 1.41M |
|---|
# -*-coding:Utf-8 -*
"""
Définition d'une classe player
reprenant ces coordonnées
"""
class Player:
def __init__(self):
"""
Instance de joueur contenant ces coordonnées, son symbole et son nom
"""
self._x = 0
self._y = 0
self._symbol = ""
self._name = ""
... |
"""
The controller is to be executed as the main app in this MVC pattern demo.
Assumes a tkinter view.
Contains:
* Controller Class that handles data and requests to/from the model and
the view.
"""
import tkinter as tk
from view import View
import model
class Controller:
"""Class that in... |
# template for "Stopwatch: The Game"
import simplegui
import math
# define global variables
ds = 0 # Using deciseconds
num_stops = 0 # number of times the stopwatch is stopped
player_correct = 0 # number of times the player stops the watch on a whole number
clock_running = False # Boolean for whether the clock is run... |
# -*- coding: utf-8 -*-
import sys, math
defCRT = int("25")
# ユーザー入力
try:
Device = input("◇ご使用端末は?iOS(1) 又は Android(2)? : ")
except:
Device = "1"
print('\n\t\t\t[キャラのステータス]\n')
try:
StatusCRT = int(input("◇ステータス(CRT) : "))
except:
StatusCRT = int("1")
try:
SkillCRT = int(input("◇クリティカルUp Lv : "))
except:
Ski... |
class Classmates():
total_semesters = 8
def student(self, name):
if name is 'ariful':
print("rip ariful :( ")
elif name is 'logno':
print("logno went abroad")
elif name is 'paroma':
print("paroma in usa")
elif name is 'shaheen':
... |
# defining Hamming_distance function
def Hamming_distance(x,y):
# if the lengths are not equal
if len(x) != len(y):
raise ValueError("Unequal length !")
# else
return sum(ex != ey for ex, ey in zip(x,y))
print(Hamming_distance('67','p7')) |
m3 = float(input("Digite o valor em m³:"))
x = m3*1000
print("O valor de {}m³ em Litros ".format(x)) |
class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
# write your code here
from collections import deque
height = [-1] + height + [-1] # 两边添加-1避免特殊处理
stack = deque([]... |
class Solution:
"""
@param nums: A list of integers.
@param k: An integer
@return: The maximum number inside the window at each moving.
"""
def maxSlidingWindow(self, nums, k):
# write your code here
if k > len(nums) or not nums:
return []
from collections im... |
class Solution:
"""
@param: numCourses: a total of n courses
@param: prerequisites: a list of prerequisite pairs
@return: the course order
"""
def findOrder(self, numCourses, prerequisites):
# write your code here
in_degree = [0] * numCourses
neighbors = [[] for _ in rang... |
"""
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class Solution:
"""
@param n: An integer
@param m: An integer
@param operators: an array of point
@return: an integer array
"""
def numIslands2(self, n, m, operators):
... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
class DataCollection:
"""
A collection of dataframes and corresponding columns of interest
"""
def __init__(self, data = [], columns = []):
"""
data is a list of dataframes
columns is a list of lists of column names
... |
# 틀림
word = list(input())
left, middle, right = [], [], []
for i in word:
if i in middle:
right.append(i)
left.append(i)
middle.remove(i)
else:
middle.append(i)
if len(middle)>1:
print("I'm Sorry Hansoo")
else:
print(''.join(left)+''.join(middle)+''.join(reversed(right)... |
# -*- coding: utf-8 -*-
import os
class Node(object):
def __init__(self,obj):
self.data=obj
self.next=None
class SLinkedList(object):
def __init__(self):
self.head=None
self.tail=None
self.length=0
def add_last(self,obj):
if self.length == 0:
self.head = self.tail = Node(obj... |
from numpy import log2
def sanitized_input(prompt, input_type=None, input_min=None, input_max=None):
if input_min is not None and input_max is not None and input_max < input_min:
raise ValueError("Minimum must be less than or equal to the maximum.")
while True:
user_input = input(prompt)
... |
num = int(input('Enter number: '))
if (num >0):
print ("number is positive")
else:
print ("number is negative")
|
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
highest_candy_in_array = max(candies)
output = []
for x in range(len(candies)):
numCandies = candies[x] + extraCandies
if numCandies >= highest_candy_in_array:
output... |
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# two pointer approach
i = 0
for x in range(len(nums)):
if nums[x] != val: # if the index value is not the same as the desired value, copy nums[x] into nums[i]. This will delete the want... |
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals = sorted(intervals)
output = [intervals[0]]
for start, end in intervals[1:]:
lastValue = output[-1][1]
if start <= lastValue:
output[-1][1] ... |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# Approach 1: sorting
nums.sort()
n = len(nums)
if nums[-1] != n:
return n
elif nums[0] != 0:
return 0
for x in range(1, n):
expected_num = nums[x-1... |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
stack1 = []
stack2 = []
for x in range(len(S)):
try:
if S[x] == '#':
stack1.pop()
else:
stack1.append(S[x])
except Ind... |
# This is a comment.
from random import randint
def random_noun():
random_num = randint(0,1)
if random_num == 0:
return "sofa"
return "llama"
def random_verb():
random_verb = randint(0,1)
if random_verb == 0:
return "run"
return "kayak"
def word_transformer(word):
if word == "NOUN":
return random_noun... |
from tkinter import *
import Student_Tracker_Main
import Student_Tracker_func
def load_gui(self):
""" Define tkinter widgets and configuration, and place them. """
self.lbl_fname = Label(self.window,text='First Name:')
self.lbl_fname.grid(row=0,column=0,padx=(27,0),pady=(10,0),sticky=N+W)
self.lbl_ln... |
# Create a parent class
class Furniture:
room = ""
weight = 0
price = 0
def __init__(self, room, weight, price):
self.room = room
self.weight = weight
self.price = price
def upgrade(self, newprice):
increase = newprice - self.price
self.price = new... |
class MyExercise():
def __init__(self, number):
self.number = number
def pprint_until_number(self):
i = 0
while i < self.number:
print(i + 1)
i += 1
def print_until_number():
#write your code below this line
MyExercise(3).pprint_until_number()
if __name... |
import numpy as np
import math as math
class cell_counting:
def blob_coloring(self, image):
"""Uses the blob coloring algorithm based on 8 pixel window assign region names
takes a input:
image: binary image
return: a list of regions"""
#print("Commencing Blob coloring")
... |
import curses
import sys
import random
import numpy as np
from random import randint
from curses import wrapper
PLAYERONE_TOKEN = "\u2593"
PLAYERTWO_TOKEN = "\u2591"
EMPTY_TOKEN = "\u2592"
UPSELECTION_TOKEN = "\u253B"
DOWNSELECTION_TOKEN = "\u2533"
CURSOR_CHAR = "\u2588"
debug = open("debug.txt", "w")
class Dice(... |
"""
This module contains the required methods for automation of main page of weathershopper application
"""
def get_temperature(driver):
"""returns the temperature on the landing page"""
temp = driver.find_element_by_xpath("//span[contains(@id,'temperature')]")
# Slice only the temperature value
... |
import copy
class Employees(objects):
def __init__(self, employees_list=[]):
self.employees_list = employees_list
def __init__(self, employees_list=[]):
self.employees_list = employees_list
def get_employees_list(self):
return self.employees_list
def load_data_from_DB... |
def countChar(myString):
count = {}
for i in myString:
if i in count:
count[i] += 1
else:
count[i] = 1
print ("\n" + str(count))
countChar("aaabbddaabbcc") |
#replace spaces with %20
def spaces(string):
if len(string) == 0:
print("There is nothing")
else:
string1 = string.replace(" ", "%20")
return string1
string = "hello world mama"
print(spaces(string))
|
__author__ = 'Eutimio'
f=open("bananas.txt")
cont=0
for line in f:
index=line.find("banana")
if(index!=-1):
print("found a banana on line", index)
cont= cont +1
print("found", cont, "bananas") |
from images import *
class Character:
#"""An outline or super-class for each character's individualized class/role""""
className = 'the role of the character'
goal = 'what each character should be trying to do'
abilityDefinition = 'what the ability of the character does'
minigameName = 'the name o... |
from tkinter import *
import random
import tkinter
from tkinter import messagebox, ttk
colors = ["Red", "orange", "yellow", "green", "blue", "pink", "purple", "brown", "black", 'White']
score = 0
timeleft = 60
def startGame():
if timeleft == 60:
countdown()
nextcolour()
def countdown():
global ... |
import tkinter
import tkinter.ttk
import tkinter.messagebox
class MainWindow:
def __init__(self, n):
self.window = tkinter.Tk()
self.window.wm_title("Insert data")
self.n = n
self.widthList = []
self.lengthList = []
self.quantityList = []
self.addEntries(n... |
# 2018 - Pathing Algos, currently BFS, best first search, A* still to do dijkstra
# Also started this the 3rd day of learning python, probably going to look messy in a few months
from collections import deque
import time
import math
max_size = 20
class GridElement:
def __init__(self, x, y, prev_x, prev_y, ... |
from datetime import datetime, timedelta, date
class LastDate:
def __init__(self):
now = date.today()
self.current_year = now.year
self.current_day = now
def _most_recent_workday(self, last_day):
#.weekday returns a 0 - 4 for Monday - Friday
if last_day.weekday() <... |
from __future__ import annotations
from abc import abstractmethod
from math import sin,cos,pi,sqrt
sizeConstant = 3000
class point():
def __init__(self,xCoord:float,yCoord:float) -> None:
self.xCoord = xCoord
self.yCoord = yCoord
def add(self,p:point)->point:
return point(self.xCoor... |
def textos():
print ("Hola empezamos")
print ("1")
print ("2")
for i in range(0,10):
textos()
mylist=["Juan","Villa verde",3245678]
mylist.append("Casa 1")
mylist.insert(1,"Conjunto villa verde")
mylist.extend(["Jairo Andres","Adriana"])
mylist.remove("Juan")
#elimina el ultimo dato de la lista
mylist.pop()
... |
mytupla=("jairo","Juan",23,2,1981,13,13)
mylist=list(mytupla)
print (mytupla)
print (mylist)
mytupla=tuple(mylist)
print (mytupla)
print ("jairo" in mytupla)
print(mytupla.count(13))
print(len(mytupla))
mytupla1=("Jairo Andres","Delgado Lopez",17,2,1981)
nombre,apellido,dia,mes,año=mytupla1
print(nombre)
print(ape... |
class Node:
def __init__(self, key, val):
self.next = None
self.key = key
self.val = val
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.node_to_prev = {}
self.size = 0
dummy = Node(0, 0)
self.head = dummy
... |
from collections import deque
class Solution:
"""
@param colors: the colors of grids
@return: return the minimum step from position 0 to position n - 1
"""
# Standard BFS
# 1. Create a dict for indexes with the same num
# 2. Start standard BFS by layer, note
# a. to include indexes if ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import defaultdict, deque
class Solution:
def __init__(self):
self.index_to_nodes = defaultdict(list)
self.min_index = ... |
from collections import defaultdict
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
if not paragraph:
return []
word_count = defaultdict(int)
word = ""
banned = set(banned)
max_val = 0
max_word = ""
for i, char i... |
import collections
class Solution:
"""
@param graph: the graph
@return: the shortest path for all nodes
"""
def shortestPathLength(self, graph):
# Write your code here.
visited = [{} for _ in range(len(graph))]
full_path = (1 << len(graph)) - 1
min_distance = float('... |
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution:
"""
@param: node: A undirected graph node
@return: A undirected graph node
"""
def cloneGraph(self, node):
# write your code here
if not node:
return... |
# data represents something to search on
from collections import deque
def bfs(start):
queue = deque([start])
visited = set()
visited.add(start)
while queue:
length = len(queue)
# Level order search
for _ in range(length):
element = queue.popleft()
for ... |
# 1. DFS inroder, return if root == None
# 2. 如果first为空,first和last指向当前node
# 3. last right指向当前node, 当前left指向last,last = node
# 4. 最后更新first和last
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solu... |
class Solution:
"""
@param A: an integer array
@param V: an integer array
@param m: An integer
@return: an array
"""
def backPackIII(self, A, V, m):
# write your code here
dp = [0] * (m + 1)
modified = True
for i in range(len(A)):
cur_size = A[i]
... |
class Solution:
"""
@param arr: An integer array
@param k: An integer
@return: return the pair of movies index with the longest total duration
"""
def FlightDetails(self, arr, k):
# write your code here
if not arr:
return []
k -= 30
array = sorted(li... |
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param intervals: interval list.
@return: A new interval list.
"""
def merge(self, intervals):
# write your code here
i... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
return self.helper(root, float('inf')... |
# https://leetcode.com/discuss/interview-question/383669/
def max_min_path(matrix):
if not matrix or not matrix[0]:
return 0
n, m = len(matrix), len(matrix[0])
dp = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
if i == 0 and j == 0:
con... |
class Solution:
def findMin(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums) == 1:
return nums[0]
left = 0
right = len(nums) - 1
target = nums[right]
# Pivot value = end of array
# end is max value if array is not so... |
# python模版## Python普通BFS模版
# 创建所需数据结构
queue = collections.deque()
visited = set()
# 初始化,将初始点加入队列和visited
queue.append(0)
visited.add(0)
while queue:
now = queue.popleft()
# 找所有当前点能一步到达的点
for next_point in self.find_next(now):
# 不满足条件直接跳过
if not self.is_valid(now):
continue
... |
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return ""
longest = 0
left = 0
right = 0
for n in range(len(s)):
start, end, cur = self.find_longest_helper(s, n - 1, n + 1, 1)
if cur > longest:
longest... |
print()
course = "Python for Beginners"
print(len(course)) # This will print the length of the string
print(course.upper()) # Upper Caae
print(course.lower()) # Lower Case
print(course.find('B')) # Finds this charachter - CASE SENSITIVE
pri... |
print()
# https://docs.python.org/3/py-modindex.html
import random
for i in range(3) :
print(random.random())
print()
################################################
for i in range(3) :
print(random.randint(10,20))
print()
################################################
members = ['john', 'b... |
print()
is_hot = False
is_cold = False
if is_hot == True :
print("It's a hot day.")
elif is_cold == True :
print("It's a cold day.")
else:
print("It's a average day.")
print("Enjoy your day.")
print()
#########################################################
price = 1000000
good_credit = False
if good... |
print() # Print Blank Line
print('Hello World!') # Print Statement
print() # Print Blank Line
print('Hello World!' * 10) # This will multply the string by the number that you provide |
def bfs(graph, v):
n = len(graph)
vis = [False]*n
traversal = []
st = []
st.append(v)
vis[v-1]=True
while(st!=[]):
v = st.pop(0)
traversal.append(v)
for i in graph[v-1]:
if(not vis[i-1]):
st.append(i)
vis[i-1] = True
ret... |
'''Guessing Game
Logan Woods
Version 1.0.0.3
Guess the random number that has been selected'''
#Importing the required libraries
import random
import os
import time
#Defining variables
list_guess = [ ]
bool_playagain = True
int_lives = 3
#Defining functions
def clear(): os.system('clear')
def title():
print("**... |
import unittest
# O(N)
def find_string(pat, txt):
# Basic implementation of KMP search
# Could have used python's str.find which is probably more efficient, but it was more fun implementing that.
if len(pat) > len(txt):
return False
# Compute the prefix table
prefix_tbl = [0] * len(pat)
... |
import unittest
class BTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def validate_bst(tree):
is_bst, _ = dfs(tree)
return is_bst
def dfs(tree):
if tree is None:
return True, None
is_bst_left, max_left = dfs(tree.left)
... |
import unittest
class MultipleStack:
# Store N stacks in a single array
# The first N values of the array are used to store the position of the next value in this array.
# push increase the size of the array if necessary
# pop does not decrease the stack
def __init__(self, n):
self.N = n
... |
def find(arr, fn):
for index, item in enumerate(arr):
if fn(item):
return index, item
def balance_banks(arr, loops = 1):
arr = arr[:]
steps = 0
seen = {}
while True:
steps += 1
biggest = max(arr)
index, _ = find(arr, lambda x: x == biggest)
arr... |
def reverse_captcha(txt):
arr = [int(x) for x in list(txt)]
total = 0
previous = None
for c in arr:
if c == previous:
total += c
previous = c
if arr[0] == arr[-1]:
total += arr[0]
return total
def reverse_captcha_two(txt):
arr = [int(x) for x in list... |
from functions import open_file, cenzura0, cenzura1, cenzura2, cenzura_cont, wybór_stopnia
a0 = input('Podaj tekst do ocenzurowania: ')
b = open_file() # stworzenie listy wulgaryzmów
a2 = a0.split(' ')
while True:
choice0 = input("""W jaki sposób chcesz usunąć wulgaryzmy w tek... |
#Solicitar un número en decimal por teclado y convertirlo a binario. Si no se conoce la forma de hacerlo, localizar
#el algoritmo en internet.
n=int(input("Introduce el número decimal: ")) #pido el numero
dividendo=n #el dividendo de nuestras divisiones será el número que se ha introducido
resto=0 #inicializamos la ... |
#Reescribe el programa del cálculo del coste de un servicio, para darle 1.5 veces la tarifa horaria para todas las
#horas trabajadas que excedan de 40.
# Horas de trabajo: 45
#Coste por hora: 10
#Importe total: 475.0
horas=float(input("Escribe el numero de horas: "))
precio=float(input("Escribe el precio por horas: ")... |
#Escriba un programa que pida una cantidad de segundos y que escriba cuántos minutos y segundos son.
segundos=float(input("Escribe una cantidad de segundos "))
if segundos%60 != 0: #si el numero no es una cantidad exacta de minutos
minu=int(segundos/60) #paso la cantidad a minutos
resto=segundos%60 #guardo e... |
#Dados dos números enteros (un dividendo y un divisor distinto de 0) obtener su cociente y el resto mediante
#restas sucesivas
dividendo=int(input("Introduce el primer numero: ")) #pido dividendo
divisor=int(input("Introduce el segundo numero: ")) #pido divisor
cociente=0 #el cociente realmente es un contador de ... |
#Realizad el mismo ejercicio anterior y además hallar la suma de todos los números visualizados.
lista=[] #creo una lista
total=0 #empiezo el conador total en 0
for i in range(0,100,2): #hago un bucle que recorra el rango que hay entre el 0 y el 100 cogiendo solo los numero pares
lista.append(i)
total+=i#en ca... |
#Escriba un programa que pida una temperatura en grados Fahrenheit y que escriba esa temperatura en grados Celsius.
#Se recuerda que la relación entre grados Celsius (C) y grados Fahrenheit (F) es la siguiente: C = (F - 32) / 1,8
temperaturaenf= float(input("Escribe una temperatura en F: ")) #pido la temperatura en F
... |
#Solicitar por teclado una cantidad de dinero con decimales hasta los céntimos y calcular el cambio en billetes y
#monedas de curso legal.
dinero=float(input("Introduce una cantidad de dinero: "))
#en una lista introducire todos los valores que pueden tomar los billetes y monedas
cantidades = [500,200,100,50,20,10,5,... |
#Escribir el programa del ejercicio 1.7 usando solamente dos variables diferentes.
#LO QUE SE HACE ES SUMAR CON UN SUMATORIO, A LA VARIABLE AÑADIENDOLE ANTES EL += SE LE SUMA EL VALOR NUEVO QUE SE INTRODUCE
suma = float(input("Escribe el primer numero: "))
suma += float(input("Escribe el segundo numero: "))
suma += fl... |
#Escriba un programa que pida dos números enteros y que escriba si el mayor es múltiplo del menor.
num1=int(input("Escribe un numero: "))
num2=int(input("Escribe un numero: "))
#PRIMERO VOY A COMPARAR Y GUARDAR EN UNA VARIABLE QUE NUMERO ES MAYOR Y QUE NUMERO ES MENOR
if num1>num2:
mayor=num1
menor=num2
else:... |
#Adivinar el resultado del programa introduciendo: 3, 8 y 13. ¿Qué hace el programa?
try:
a=int(input("numero: "))
p=True
for n in range(2,a):
if not a%n:
p=False
break
if p:
print("si")
else:
print("no")
except:
print("no es un numero: ")
#3:mos... |
a,b = 0,1
if a == b or a <= b: #not =<
print(True)
if a != b:
print(False)
if a == b:
print(True)
else:
print(False)
switch = dict(
one = 1,
two = 2)
var = 'one'
print(switch[var]) #prints 1
var = 'three'
print(switch.get(var, 'default')) #prints 'default'
var = '... |
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!... |
import time
from threading import Thread
import queue
def sequential():
start = time.time()
numofbells = 5
count = 3
base = ["123","213","231","321","312","132"]
permlist = []
while count < numofbells:
##Update list to have room for new bell
for i in range(len(base... |
"""
Breadth First Placeholder Script
-Basically defines a graph that stands in the place of our main grid
"""
def from_id_width(id, width):
return (id % width, id // width)
def draw_tile(graph, id, style, width):
r = "."
if 'number' in style and id in style['number']:
r = "%d" % style['number'][id... |
"""
Cell object used to draw the background grid and define the paths of the players.
"""
import pygame
from pygame.locals import*
import time
class Cell(object):
"""Cell object defining the visualized form of a cell.
Not used structurally to define player locations, but used to visualize the game"""
def _... |
income = int(input("請輸入今年收入淨額:"))
print("付稅金額:",end="")
if(income >= 2000000):
print(income*0.3, end=" 元\n")
elif(income >= 1000000):
print(income*0.21, end=" 元\n")
elif(income >= 600000):
print(income * 0.13, end=" 元\n")
elif(income >= 300000):
print(income * 0.06, end=" 元\n")
else:
... |
'''
visualisation makes interpretation of data easier: then normal numerical values
basic plots:
- scatter plot
a set of points scattered over a 2 different variable plotted on a horizontal and vertical axes(2D)
- histogram
> graphical representation using bars of different heights
>... |
'''
Use of seaborn (which is built upon matplotlib library):
- Scatter plot
- Histogram
- Bar plot
- Box and whiskers plot
- Pairwise plot
'''
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={'figure.figsize':(5,4)})
os.chdir(r'..\data science\Npt... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 19:31:03 2021
@author: swift
"""
#words = ["This", "is", "an", "example", "of", "text", "justification."]
#words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"]
words = ["What","m... |
#C:\Users\mwhitenett\Documents\Security\Scripts\Message.txt
#============================================= File Functionality =====================================================
from string import Template
#Function to pull names and email addresses from a file.
def get_respondents(filename): ... |
import webbrowser
def main():
website = input("Paste in the URL of the site you want to visit.")
webbrowser.open(website, new=2)
def nezuko():
webbrowser.open('https://divine-bird-8888.bss.design/bamboo.html', new=2)
main()
again = int(input("Would you like to do this again? Press 1 for yes, and then... |
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
# This is basically a 3D plotter that takes the 2D
# points and the associated values to draw different
# regions using a color scheme.”
def plot_classifier(classifier, X, y):
# define ranges to plot the figure
x_min, x_ma... |
if __name__ == '__main__':
s = raw_input()
print(any(string.isalnum() for string in s))
print(any(string.isalpha() for string in s))
print(any(string.isdigit() for string in s))
print(any(string.islower() for string in s))
print(any(string.isupper() for string in s))
|
#remove function in list with while loop:
A=["A"," ","B","C"," "]
i=0
while i<len(A):
if A[i]==" ":
A.remove(A[i])
i=i+1
print(A)
#remove function in list with for loop:
B=["a"," ","y"," "]
for x in B:
if x==" ":
B.remove(x)
print(B)
#in function
def list(l):
for a in l:
if a=... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 19 12:11:04 2017
@author: Sameer
"""
"""
The function char_equivalent(p,q) accepts two numbers that defines the range.
It iterates through p to q+1 to determine character equivalents of each number.
Then it divides the each number in the range by 26 until we re... |
"""14. 대문자는 소문자로, 소문자는 대문자로 출력하고
영어가 아닌 문자가 입력 되었을 때는
'입력 형식이 잘못되었습니다' 라고 출력하는 프로그램을 작성하시오.
예시
<입력>
EAST
<출력>
east
<입력>
hello
<출력>
HELLO
<입력>
안녕
<출력>
입력 형식이 잘못되었습니다.
"""
text = input()
if not text.isalpha():
print("입력 형식이 잘못되었습니다.")
else:
for i in text:
if i.isupper():
i = i.lower()
... |
import datetime
currentDate = datetime.date.today()
daysToComplete = 0
cWeeks = 0
cDays = 0
adate = input('Enter your project deadline in format MM/DD/CCYY: ')
pdeadline = datetime.datetime.strptime(adate, "%m/%d/%Y").date()
daysToComplete = pdeadline - currentDate
cDays = daysToComplete.days
print("There are %d da... |
MonthlyPayment = 0
LoanAmount = 0
InterestRate = 0
NumberOfPayments = 0
nLoanAmount = input("What is the total loan amount? ")
LoanAmount = float(nLoanAmount)
nInterestRate = input("What is the interest rate?" )
InterestRate = float(nInterestRate)
nNumberOfPayments = input("How many monthly payments? ")
NumberOfPaymen... |
#가변 함수 *arg
def args_func(*arg):
print(*arg)
args_func("kim")
args_func("kim","park")
# kwargs
def kwargs_func (**kwargs):
print(kwargs)
kwargs_func(name1="kim", name2="park", name3="lee")
def example_mul(arg1, arg2 ,*arg, **kwargs):
print(arg1, arg2 , arg, kwargs)
example_mul("sangjun", "yujin", "sa... |
import re
# The pattern to be removed here is a numbered string named "Section"
f = 'Check_for_duplicates.txt'
pattern = re.compile('Section_[0-9]{7}') # the number has 7 digits
dict1 = dict()
openFile = open(f, 'r')
fw = open('Checked.txt', 'w')
fw.write('Duplicates Files/lines: \n')
for row in openFile.readline... |
def tabuada(n1):
cont = 1
while cont != 11:
print(n1, "X",cont, "=", (cont*n1))
cont+=1
n1 = int(input("Digite um número para saber sua tabuada\n"))
tabuada(n1) |
import matplotlib.pyplot as plt
import numpy as np
def visualizeData(width, height, px_vals):
'''Takes the 1-D list of pixel intensities, makes them
rectangular, and displays them. The px_vals variable
should be a 1-D numpy array.'''
img = np.reshape(255-px_vals, (height, width))
img_plot = plt.imshow(img, cma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.