text stringlengths 37 1.41M |
|---|
calendar_years = int(input("Enter calendar years: "))
if calendar_years < 0:
raise Exception("Please enter positive value")
if calendar_years <= 2:
dog_years = calendar_years * 10.5
elif calendar_years > 2:
dog_years = 10.5 * 2 + (calendar_years - 2) * 4
print("Dog years =", dog_years)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 15:35:32 2019
@author: C.R.C
"""
from tkinter import *
# create window object
window = Tk()
def printName():
print('Hello there!')
## placing a button (widget)
# creating the button
# can also use b1.pack() but doesnt give options for positioning
## placing ... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
## Import the dependencies.
import pandas as pd
import gmaps
import requests
# Import the API key.
from config import g_key
# %%
# Store the CSV you saved created in part one into a DataFrame.
city_data_df = pd.read_csv("weathe... |
# Python Program to find the greatest common divisor(GCD) of a the given set of numbers.
# Function
def getgcd(x, y):
while (y):
x, y = y, x % y
return x
lst = []
n = int(input("Enter number of elements in the array : "))
for i in range(0, n):
element = int(input())
l... |
colors = ["red", "orange", "green", "violet", "blue", "yellow"]
def how_many_colors(color_list, n):
return color_list[:n]
for i in range(1, len(colors) + 1):
print(how_many_colors(colors, i))
definition = 'Korporacja (z łac. corpo – ciało, ratus – szczur; pol. ciało szczura) – organizacja'
print(definitio... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 14:23:54 2020
@author: Jasper Dijkstra
This script:
1. creates monthly file of data within specified location using (splitted) csv files
2. splits this monthly file into individual daily csv files
"""
import os
import csv
from datetime impo... |
def isPossible(sides):
a, b, c = sides
return a+b > c and b+c > a and c+a > b
puzzleInput = open('day 3 input.txt', 'r').read()
triangles = puzzleInput.split('\n')
impossibleTriangles = [isPossible((int(side) for side in t.split())) for t in triangles]
from collections import Counter
print(Counter(impossibleT... |
myLocation = (0, 0, 0)
def calculateDirection(direction, turnDirection):
# turnDirection should be 0 (left) or 1 (right)
direction = direction + 1 if turnDirection else direction - 1
if (direction == -1):
direction = 3
if (direction == 4):
direction = 0
return direction
def fwd(x... |
"""
Tic Tac Toe Player
"""
import math
import copy
# Initialize Global variables
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
... |
class Customer():
def __init__(self,cname):
self.customername=cname
def __str__(self):
return "raja"
def __add__(self,other):
totalcoustomer=self.customername+other.customername
customerfinaldata=Customer(totalcoustomer)
return c... |
class Outer():
y=10 # class name
def __init__(self):
print("outer class constructor")
class Inner():
x=5 # class name
def __init__(self):
print("Inner class constructor")
def show1(self):
print("In Inner class -Show met... |
a=2 # global
b=5 # global
def outer(): # enclosed function
global b
b=b+6 #UnboundLocalError: local variable 'b' referenced before assignment
b=6 # enclosed variable
print(b) # b=6
def inner(): # nested function or inner function
c=5 # local variable
print(a) # 2
... |
#print(a) #NameError:
#ZeroDivisionError: division by zero
a=5
#result=a/0
#print(result)
#KeyError: 3
d={
1:'one',
2:'two'
}
print(d[3])
try
else
except
finally
raise
if
else
try
except
else
age = 26
'raja' |
# in - lookup
# for iterationvariable in Seqence/map:
# print(iterationvariable)
employee=['A',1,True,'Hello'] # 0123
print(employee)
# don't singe letter
for emp in employee:
print(emp)
tuplex=(2,3,4)
for tup in tuplex:
print(tup+2)
setx={1,4,5,5,5,5,5,5,9}
for iter in setx:
print(iter)
... |
litsex=['one','two','three','one']
print(litsex)
numbers=[1,2,3,3,4,4,4,99,65,78]
print(numbers)
person=['john',45,200.45,['French','Spanish','English','English'],True]
# 0 - john
# 1- 45
# 2- 200.45
# 3 - ['French','Spanish','English','English']
# 4 - True
print(person)
# string -- hello - 01234
# 0 -John, ... |
from functools import reduce
listx=[1,2,3,4,5]
listsum=sum(listx)
print(listsum)
j=0
for i in listx:
j=j+i
print(j)
#reduce
result=reduce(lambda x,y: x+y,listx)
print(result)
map --apply on each element
filter -condition
reduce - sum, avg, mean, mode, meadian
first param - function
second param - sequence... |
#arg 1 must be a string, bytes or code object
age=45
print(eval('age+15'))
b=bytes(51) # int - bytes
d=bytes('hi',encoding='utf-8') # str, encoding
print(b)
print(d)
#print(eval(b))
x=2
y=bytes(2)
#z=int(y)
#print(x,y,z)
listx=[1,2,3]
print(eval('listx'))
name='2+1'
e=eval(name)
print(e)
#print(sqrt(9))
# 8/2... |
#Anonymous or lamda
lambda parameter_list: expression
addingtwo=lambda x:x+2
print(addingtwo(5))
addxy=lambda x,y: x+y
print(addxy(1,2))
def addingTwoVar(x,y):
result=x+y
print(result)
addingTwoVar(1+2,4+5)
# areaofcube=lambda X,Y,Z,*K: X*Y*Z*tuple(K.values())
# print(areaofcube(1,2,3,a=2,b=5))
x=3
... |
# isinstance - True when
class A :
pass
class B(A):
pass
a=A()
b=B()
print(isinstance(a,B))
print(issubclass(B,A)) # child, parent
print(issubclass(A,B)) # parent child
print(issubclass(int,bool))
print(issubclass(bool,float)) |
# Copyright (c) 2020 Evan
import tkinter
from tkinter import *
from reader import reader
reader = reader("alt1")
root = tkinter.Tk() # Create new Tkinter window
root.title("Testing Program") # Set the title of the window
def setLabel(): # Create new command for the button to execute
want = entry.get() # Get want ... |
#!/usr/bin/env python3
# Write a program that compares two files of names to find:
# Names unique to file 1
# Names unique to file 2
# Names shared in both files
import argparse
parser = argparse.ArgumentParser(
description='Brief description of program.')
parser.add_argument('--file1', required=True, type=str,
me... |
#!/usr/bin/env python3
# Move the triple quotes downward to uncover each segment of code
"""
# -------------------- ZIP FUNCTION --------------------
# The zip() function lets you loop through iterables in parallel
# The zip() ends when the first container ends
names = ('Nigel', 'David', 'Derek') # tuple
ages = [5... |
#!/usr/bin/env python3
import math
# Move the triple quotes downward to uncover each segment of code
"""
# We have been using functions for a while, such as print(list)
# Sometimes the variable preceeds the function, such as list.append()
# In this section, we will learn how to write new functions, like print()
# ... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Single Number 284ms
"""
/**
* Given an array of integers,
* every element appears twice except for one. Find that single one.
* Note:
* Your algorithm should have a linear runtime complexity.
* Could you implement it without using extra memory?
*/
"""
"""
/*
* @... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Spiral Matrix II 348ms
"""
/**
* Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
* For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
"""
"""
/*
* @au... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Two Sum 172ms
"""
/**
* Given an array of integers, find two numbers such that they add up to a specific target number.
* The function twoSum should return indices of the two numbers such that they add up to the target,
* where index1 must be less than index2. Please... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Excel Sheet Column Number 142ms
"""
/**
* Related to question Excel Sheet Column Title
* Given a column title as appear in an Excel sheet,
* return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Credits:
Spe... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Min Stack 232ms
"""
/**
* Min Stack
* Total Accepted: 15688 Total Submissions: 101910 My Submissions Question Solution
* Design a stack that supports push, pop, top,
* and retrieving the minimum element in constant time.
* push(x) -- Push element x onto stack.
* p... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from math import floor
size = int(input())
numbers = sorted(list(map(int, input().split())))
middle = int(size/2)
even = True if (size % 2 == 0) else False
if even:
median = round((numbers[middle] + numbers[middle-1])/2.0, 1)
else:
media... |
# Time Complexity - O(n)
# 1. Get the sum of numbers, eg: total = n*(n+1)/2
# 2. Subtract all the numbers from sum and you will get the missing number
def get_missing_number(list):
n = len(list)
total = (n+1)*(n+2)/2
sum_of_list = sum(list)
return total - sum_of_list
list = [1, 2, 4, 5, 6]
missi... |
print("5.6 koch")
import turtle
def draw(t, length, angle):
if length >= 3:
t.fd(length / 3)
t.lt(angle)
t.fd(length / 3)
t.rt(angle)
t.fd(length / 3)
t.lt(angle)
t.fd(length / 3)
else:
t.fd(length)
def snowflake(t, length,... |
#This code implements the k-means clustering algorithm of Machine Learning
#import libraries
import matplotlib.pyplot as plt
import numpy as np
import math
import csv
import random
#defining function to calculate distance
def distance (point_a, point_b):
dist = math.sqrt((point_a[0]-point_b[0])**2 + (point_a[1]... |
#对象:id、数据域、方法。类描述对象。
import math
from GeometricObject import GeometricObject
class Circle(GeometricObject):
__slots__ = 'radius'
def __init__(self,radius=1):
super().__init__()
self.__radius = radius
def get_radius(self):
return self.__radius
def get_perimeter(self):
return 2*self.__radius*mat... |
#!/usr/bin/env python
import argparse
def hotpo(n):
"""Divide by 2 if even, otherwise triple and add 1
Keyword arguments:
n -- the number to check
"""
return n / 2 if n % 2 == 0 else 3 * n + 1
def collatz(n, acc = 0, print_steps = False):
"""This function will return the number of HOTPO s... |
"""Comparison operations"""
print(1 < 1)
print(1<=1)
print(1==1)
print(1>=1)
print(1!=1)
name = input("What is your name")
if(name=='jess'):
print('Hi I am Jess')
elif name == "Bob":
print("Hi I am Bob")
else:
print('Thanks for entering your name'+name)
name = input("Enter your name please")
if name ==... |
"""
Monty Hall simulation with diagrams
Author: kupp1
"""
from matplotlib import pyplot as plt
from randompy.randompy.randompy import RandomPy
import sys
try:
doors_number = int(input('Enter number of doors (>= 3): '))
attempts_number = int(input('Enter the number of attempts: '))
if doors_number < 3:
... |
"""
All functions in Python are first class objects (FCO)
It means that all of them has all the properties of FCO:
- can assign to variables;
- store FCO in data structures;
- pass FCO as arguments to other functions;
- return FCO as a value from other function.
It's a key to understanding how decorators can work
"""
... |
def multipliers():
"""
if you will not bind i, then the result will be
The output of the above code will be [6, 6, 6, 6] (not [0, 2, 4, 6])
The reason of it is late binding.
It means that the values of variables used in closures are looked up
at the time the inner function is called.
You c... |
# creating the list for vowels
vowels = ['a', 'e', 'i', 'o', 'u']
# creating an object for user input
word = str (input ("Please enter a word: "))
# creating a empty set for vowels to be placed in when found
found = []
# for loop for finding vowels in user input based on list of vowels
for letter in word:
... |
import sqlite3
connection = sqlite3.connect("hr.db")
cursor = connection.cursor()
class CliInterface:
def __init__(self):
pass
def start(self):
print("Welcome! You're the last HR :(")
while True:
command = input("Enter command > ")
try:
self.... |
import sqlite3
db = sqlite3.connect("company.db")
db.row_factory = sqlite3.Row
cursor = db.cursor()
def lsit_employees():
result = cursor.execute("SELECT id, name, position FROM employees")
db.commit()
for row in result.fetchall():
print(row["id"], row["name"], row["position"])
def monthly_spe... |
import unittest
from bankacc import BankAccount
class BankAccountTest(unittest.TestCase):
def setUp(self):
self.bankacc = BankAccount("vlado", 100, "$")
def test_parameter_constructor_working_properly(self):
self.assertEqual(self.bankacc.getname(), 'vlado')
self.assertEqual(self.bank... |
# import the class that allows us to have abstract classes
from abc import ABCMeta, abstractmethod
# import the needed classes:
# NavigableMenuOption : The mother class
# newsMenu : The news menu
# settingsMenu : The settings menu
# joniConfig : general file containing configuration values
from navigableMen... |
#-*- coding: utf-8 -*-
import sys
def decompoe_numero(numero):
counter = 1
while (numero > 1):
if int(numero) % 2 == 0:
numero = numero/2
else:
numero = (3 * numero) + 1
counter = counter + 1
return counter
def execute(numero):
larger_sequence_numero = 0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 4.fib斐波那契数列.py
# Author: HuXianyong
# Date : 2019/5/24 11:01
# 自己写的
class Fib:
def __init__(self):
self.a = 0
self.b = 1
self.i = 0
def __call__(self, n, **kwargs):
while self.i <n-2:
self.a ,self.b = self.b,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 2.双向链表新增insert方法.py
# Author: HuXianyong
# Date : 2019/5/30 14:21
'''
当加入第一个node节点的时候,会有几个值,(这里的self.tail.next 其实就是node.next)
head = item = tail = Node(object element1 memory)
item = head = tail = Node(object element1 memory)
next = None
tail = item = head = N... |
'''
一个列表,先对其跑徐输出新链表.
分别尝试插入20,40,41到这个新序列中找到合适的位置,保证其有序.
思路:
排序后二分法找到适当的位置插入数值.
排序使用sorted解决,假设升序输出.
查找插入点,使用二分法查找完成,
假设全场为n,首先在大致的重点元素开始和待插入数比较,如果大,则和右边区域的的额重点继续比较,如果小,就和左边区域的重点进行比较,以此类推.
直到找到适合的位置
'''
# from random import randint
# l = [randint(10,100) for _ in range(10)]
# print(l)
# lst = [86, 40, 22, 71, 80, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 10.方法的调用.py
# Author: HuXianyong
# Mail: mghxy123@163.com
# Date : 2019/5/16 0016
# class Person:
# def method(self):
# print("{}'s method".format(self))
#
# @classmethod
# def class_method(cls):
# print('class = {0.__name__} ({0})'.f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 1.1随机整数生成类.py
# Author: HuXianyong
# Mail: mghxy123@163.com
# Date : 2019/5/18 0018
#同样使用生成器实现,我们之前的思路是用生成器一个一个的生成然后去去取值,
# 现在我们的实现方法修改为,生成一批值,然后去获取:
from random import randint
class RandomGen:
def __init__(self,start=1,end=100,count=10):
self.start... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 12.私有属性.py
# Author: HuXianyong
# Mail: mghxy123@163.com
# Date : 2019/5/17 0017
'''
私有属性:
使用双下划线开头的属性名
'''
class Person:
def __init__(self,name,age=18):
self.name = name
self.__age = age
def growup(self,i=1):
if 0 < self.__ag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 5.可迭代的斐波那契数列.py
# Author: HuXianyong
# Date : 2019/5/25 22:23
class Fib:
def __init__(self):
self.items = [0,1,1]
def __call__(self,index):
return self[index] #直接调用实例的索引,也就是直接调用getitem然后来计算出结果,返回
def __iter__(self):
return ite... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 6.一切皆对象.py
# Author: HuXianyong
# Mail: mghxy123@163.com
# Date : 2019/5/16 0016
class Person:
age = 3
def __init__(self,name):
self.name = name
print('----class----')
print(Person.__class__,type(Person))
print(Person.__class__ == type(Person))#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 7.set_name方法.py
# Author: HuXianyong
# Date : 2019/5/28 15:12
class A:
def __init__(self):
self.b = 'b'
def __get__(self, instance, owner):
print('get______',self,instance,owner)
print(self.__dict__)
return self
def __... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 4.单词统计和排除.py
# Author: HuXianyong
# Mail: mghxy123@163.com
# Date : 2019/5/2 0002
import re
def ignore_worlds():
top_worlds = {}
worlds= input('''
请输出你不想看到的单词
例如: a b c d
然后按回车确认后开始统计
请输入:
''')
ignore_list = worl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 求两个字串的公共子串.py
# Author: HuXianyong
# Mail: mghxy123@163.com
# Date : 2019/5/8 0008
# '''
# 思路:
# 先把两个字符串转化为列表
#
# '''
# str1 = 'abfghplf'
# str2 = 'abfgfghp'
# a = set('p')
#
# com1 = [i for i in str1 if i in str2]
# # print(str1[1:8])
# # for i,s in enumer... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 1.bool判断.py
# Author: HuXianyong
# Date : 2019/5/25 16:53
class A:pass
print(bool(A))
print(bool(A()))
# 都是True
################################################
# class B:
# def __bool__(self):
# print('in bool')
# return bool(1)
#
# prin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 5.理解as字句.py
# Author: HuXianyong
# Date : 2019/5/26 10:04
class Point:
def __init__(self):
print('init')
def __enter__(self):
print('enter')
return self #增加返回值
def __exit__(self, exc_type, exc_val, exc_tb):
print('e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 3.相同的类实例.py
# Author: HuXianyong
# Date : 2019/5/25 15:47
class Person:
def __init__(self,name,age=18):
self.name = name
self.age = age
def __hash__(self):
return 1
def __eq__(self, other):
return self.name == other... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : 1.两个实例相减.py
# Author: HuXianyong
# Date : 2019/5/25 17:23
class A:
def __init__(self,name,age=19):
self.name = name
self.age = age
def __sub__(self, other):
return self.age - other.age
def __isub__(self, other): #如果没有定义__isub... |
#!/usr/bin/env python3
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# © 2016 Lev Maximov
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Задание wordcount
Функция main() уже реализована и не требует и... |
students = [
{
"firstName" : "Alan",
"lastName" : "Gonzalez",
"id" : 123,
"hobbies": ["read", "write", "sing"]
},
{
"firstName" : "Julieta",
"lastName" : "Salazar",
"id" : 456,
"hobbies": ["read", "program"]
},
{
"firstName" : ... |
def main():
print('**********北京话生成器**********')
Putonghua = input('请输入普通话:')
Beijinghua = ''
for index in range(len(Putonghua)):
Beijinghua += Putonghua[index]+'儿'
print(Beijinghua)
pass
if __name__ == '__main__':
main() |
#!/usr/local/anaconda3/bin/python
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# Exercise 1 - rewrite the above example code using list comprehension syntax.
# Make a variable named uppercased_fr... |
def print_n_recursive(s, n, prompt):
if prompt > 0:
print("recursive function, " + str(n) + " iterations:")
prompt -= 1
if n <= 0:
return
print(s)
print_n_recursive(s, n-1, prompt)
def print_n_whileloop(s, n):
print("while loop, " + str(n) + " iterations:")
wh... |
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
# Connect to the database
conn = psycopg2.connect(database="postgres", user="postgres", password="pass", host="localhost", port="5432")
#Create the Database
try:
# CREATE DATABASE can't run inside a transaction
conn.set_isolation_leve... |
#import pygame and other necessary libraries
from pathlib import Path
import contextlib
with contextlib.redirect_stdout(None):
import pygame, sys
from pygame.locals import *
from globalvariables import GlobalVariables, gvar
import numpy as np
import time
#initialize the source for global variables from import
... |
my_map = [[],[],[]]
def replace_pixel(replacement_character, original_character, x, y):
if x == -1 or y == -1: #
return
if x >= len(my_map[0]): # horizontal check
return
if y >= len(my_map): # vertical check
return
if my_map[x][y] = original_character: # list of lists
... |
def gas_master():
gas = input(" ######################\n"
" Crap-Ton-O-Conversions!\n"
" ######################\n\n"
"Type a number representing gallons of gas you want to convert: ")
# eval(gas)
# ~~~~~~~~~~~~~~~~~~~~~~~~
... |
# Author: Chase Karlen
# Email: chase.karlen@uky.edu
# Section: 002
"""
Purpose: To calculate the resistance and current from series and parallel circuits
Pre-conditions: The inputs will be the 3 resistors in ohms
Post-conditions: The outputs will be the resistance and current from the pre-conditions
"""
# Import sqrt ... |
# Author: Chase Karlen
# Email: chase@uky.edu
# Section: 002
"""
Purpose: To calculate payroll based on employee, hourly rate, and hours worked
Preconditions: The inputs are employee name, hourly rate, and hours worked
Postconditions: The outputs are total payroll, employee name, and pay based on rate*hours worked
"""
... |
def get_choice():
print("\nMain Menu\n\n1. Load database\n2. Save database\n"
"3. Enter new record\n4. Delete existing record\n"
"5. Search database\n6. Sort by key (ID) field\n7. Display database\nQ. Quit\n")
choice = input("> ")
while choice != "1" and choice != "2" and choice != "3" ... |
class TreeNode():
def __init__(self,data):
self._lnode = None
self._rnode = None
self._data = data
def get_data(self):
return( self._data )
def set_data(self):
self._data = data
def add_right(self, data = None):
self._rnode = TreeNode(data)
def ad... |
#
#
#
import os
import unittest
def analyze_text(filename):
"""calculate number of lines, words, chars in file
Args:
filename: name of file to analyze
Raises:
IOError: if filename can not be read
"""
with open(filename, mode='r') as f:
lines = 0
words = 0
... |
l = "show how to index into sequences".split()
print(l, len(l))
for i in range(len(l)):
print( i, i-len(l), l[i] )
#can index going from the start using 0
print(l[0])
# can index from the end using -1 as the first locatoin
print(l[-1])
print(l[1:4]) # start and end, but not including the final index
print(l... |
def calcVolume(l, w, h):
return l * w * h
def calcSmallestPerimeter(*args):
d1, d2 = sorted(args)[0:2]
return 2 * d1 + 2 * d2
length = 0
for line in open("input").readlines():
(l, w, h) = list(map(int, line.strip().split("x")))
length += calcVolume(l, w, h) + calcSmallestPerimeter(l... |
#!/bin/python3.9
# Вывести первое число в строке
user_input = int(input('введите число: '))
a = user_input
print(a // 10)
|
print('输出1到100内的所有质数:')
for i in range(1,101):
s = 1 #s为判断是否为质数的标志
if i>3 :
for j in range(2,i):
if i%j==0 :
s=0
if s==1:
print(i)
else :
print(i)
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object): # hash table approach / 192ms, Faster than 80% solutions / O(m+n) time, O(m) or O(n) space complexity
def getIntersectionNode(self, headA, headB):
... |
# Credits: https://www.geeksforgeeks.org/find-a-sorted-subsequence-of-size-3-in-linear-time/
# Python program to fund a sorted subsequence of size 3
class Solution:
def increasingTriplet(self, arr):
if len(arr) < 3: return False
n = len(arr)
max = n-1 # Index of maximum element ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution: # 40ms
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
queue = deque([(root, 0... |
class Solution: # 36ms
def isValid(self, s: str) -> bool:
stack = []
closing = [']','}',')']
opening = ['[','{','(']
for i in s:
if i in closing:
if stack != [] and opening[closing.index(i)] == stack[-1]:
stack.pop()
els... |
class Solution: # 164ms, same as my prev solution to simpler problem, faster than 90% solutions
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
queue = [(root, 0)]
leveld = {}
while queue != []:
el, level = queue[0]
que... |
from collections import defaultdict # 28ms, faster than 99% solutions
class Solution:
def countOfAtoms(self, formula: str) -> str:
if not formula:
return ''
stack = [defaultdict(int)]
i = 0
count = {}
while(i < len(formula)-1):
name = formula[i]
... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
if not ... |
# Credits LeetCode, 104ms
class Solution(object):
def shortestBridge(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
startingPoint=None
for row in range(len(A)):
for col in range(len(A[0])):
#print row
#print col
... |
import heapq
class Solution: # 44ms
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# idea is to populate a min heap of capacity k
heap = []
for i in range(len(nums)):
if len(heap) == k and... |
import numpy as np
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Method 1 - 208 ms
# x = np.argsort(nums)
# for i in range(len(nums)):
# for j in list(reversed(range... |
T = input()
#iterate through the cases 1 by 1
for t in range(T):
number = input()
original_number = float(number)
i = 0
while number:
# get the digit
digit = number % 10
number /= 10
if digit != 0:
if (original_number/float(digit))%1 == 0:
i = i+1
print i
|
import largestPrimeNum
total = 1
prime = []
for n in range(1,21):
prime = largestPrimeNum.prime_factors(n) + prime
print prime
print set(prime)
for num in prime:
total = num*total
print total
# find the smallest number thats divisble by all nums from 1 to 20
# if its divisble by 20 - then its divisble by 10, 5, 2... |
list_of_nums = list(raw_input())
total = 0
# add up each number
for num in list_of_nums:
total = list_of_nums
total = total + int(num)
tot = 0
|
from collections import Counter
n = input()
arr = input().split()
keyList = list(Counter(arr).keys())
keyList = [ int(x) for x in keyList ]
newList = sorted(keyList, reverse=True)
print(newList[1]) |
from collections import Counter
"""
Print the three most common characters along with their occurrence count.
Sort in descending order of occurrence count.
If the occurrence count is the same, sort the characters in alphabetical order.
"""
s = input()
letters = []
outp = []
countnum = []
for i in range(... |
data = input("Enter Dimentions: ").split()
n = int(data[0])
m = int(data[1])
fillerLines = int(n/2)
patternFill = 3
for i in range(1, fillerLines+1):
lineOutput = ""
dashSeg = int((m - patternFill) / 2)
lineOutput = lineOutput + ("-" * dashSeg )
lineOutput = lineOutput + (".|." * (int(pattern... |
def capitalize(string):
string=string.split(' ')
return ' '.join(char.capitalize()for char in string)
if __name__ == '__main__':
string = input()
capitalized_string = capitalize(string)
print(capitalized_string)
|
"""
You are given two singly linked lists. The lists intersect at some node. Find, and return the node.
Note: the lists are non-cyclical.
Example:
A = 1 -> 2 -> 3 -> 4
B = 6 -> 3 -> 4
This should return 3 (you may assume that any nodes with the same value are the same node).
Here is a starting point:
""... |
# Project 05 part b
# A program that opens a file based on user entered filename.
# Prompts the user for a year and region then finds each line
# that has an equal year and region. Using the result set calculate
# total population, average population, lowest population and highest.
# It will also count the number of re... |
celsius = float(input('Qual a temperatura em ºC: '))
f = (9 * celsius / 5) + 32
print(f'A temperatura de {celsius} ºC corresponde a {f}ºF ') |
from random import choice
nome1 = str(input('Digite o primeiro aluno: '))
nome2 = str(input('Digite o segundo aluno: '))
nome3 = str(input('Digite o terceiro aluno: '))
nome4 = str(input('Digite o quarto aluno: '))
lista = [nome1,nome2,nome3,nome4]
sorteio = choice(lista)
print(f'Dentre os alunos {nome1}, {nome2},... |
from datetime import date
ano = int(input('Que ano quer analizar? Coloque 0 para analizar o ano atual.'))
if ano == 0:
date.today().year
if (ano % 4 == 0 and ano % 100 != 0) or (ano % 400 == 0):
print('Bissexto!')
else:
print('Não bissexto') |
nome = input('Digite seu nome completo: ')
a = 'silva' in nome.lower()
print(f'Seu nome tem Silva? {a}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.