text stringlengths 37 1.41M |
|---|
# In this program, we will use three datasets to answer some questions.
import pandas as pd
import numpy as np
pd.options.mode.chained_assignment = None
# Energyy file.
def energy():
# Loading the first file and omitting some rows from the top and bottom.
energy = pd.read_excel('energy.xls', skip... |
import os
disk=input("Введите путь, который вы хотите отскранировать: ")
folder=[]
for i in os.walk(disk):
folder.append(i)
files=[]
sum=0
for address, dirs, files in folder:
for file in files:
sum+=os.path.getsize(address+'\\'+file)
print(sum,'- Б')
print(sum/1024,'- КБ')
print(sum/1024/1024,'- М... |
# names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# usernames = []
#
# # write your for loop here
# for name in names:
# usernames.append(name.replace(' ', '_').lower())
#
# print(usernames)
# names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
#
# for name ... |
name= "America"
print(name)
favFoods= ["banku","konkonte","waakye","beans","tuozaafi"]
print(favFoods)
print(favFoods[-1])
print(favFoods[0:4])
print("My favourite foods are "+ favFoods[0] + " " + favFoods[1] + " ")
string1= "We are"
string2= " here to study"
string3=" cloud computing"
print(string1 + string2 + s... |
import random
from Score import Score
class Player:
def __init__(self, name, order):
self.name = name
self.order = order
"""There are two type of turns, open and closed
You start closed, once you score 1000 in a turn
You become open, meaning you can score less
that 1000 points"""
self... |
import unittest
def insertion_sort(list):
for i in range(2, len(list)):
index = i
while index > 0 and list[index - 1] > list[index]:
list[index - 1], list[index] = list[index], list[index - 1]
index -=1
return list
class UnitTest(unittest.TestCase):
def test(self)... |
# Задание 6
# Напишите функцию, которая считает количество
# цифр в числе. Число передаётся в качестве параметра. Из
# функции нужно вернуть полученное количество цифр.
# Например, если передали 3456, количество цифр будет 4.
def number_of_digits (num:int):
count=0
while num>0:
num//=10
count=c... |
# 2. Що таке map(), filter(), lambda x: x ** 2
#
# map() - это функция, которая принимает два аргумента: функцию и аргумент составного типа данных,
# например, список. map применяет к каждому элементу списка переданную функцию.
# Например, вы прочитали из файла список чисел, изначально все эти числа имеют строковый тип... |
def GetAnswerWithUnderscores(answer, letters_guessed):
result = ''
for char in answer:
if char in letters_guessed:
result += char
else:
result += '_'
return result
answer = GetAnswerWithUnderscores('welcome', 'mel')
print('GetAnswerWithUnderscores #1: expected _el__... |
class object:
def __init__(self,Name,Health,Speed,Power):
self.Name = Name
self.Health = Health
self.Speed = Speed
self.Power = Power
self.Luck = 0
def update_luck(self,num):
self.Luck = num
def add_luck(self,num):
self.Luck += num
def show_stats(... |
li = ["Improve","Problem","Solving","Skills"]
li.sort()
print(li)
print("These tips are very good")
li.reverse()
print(li)
print(len(li))
wonderOftheWorld = ["Great Wall of China","Christ The Reedemer","Machu Picchu","Chichen Itza","Roman Colosseum","Taj Mahal","Petra"]
print(len(wonderOftheWorld))
... |
#https://leetcode.com/problems/guess-number-higher-or-lower/description/
"""
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(in... |
# Write a function that takes a string in prefix notation (operator and two numbers)
# Parse output and produce appropriate output
# Assume only valid arguments
# Implement each operation as a separate function; don't use an if statement
from operator import add, sub, mul, truediv, mod, pow
def calc(s):
opmap = ... |
# Write function that takes a string and translates it into Pig Latin
def pig_latin(s):
if s[0] in 'aeiou':
return s + 'way'
else:
return s[1:] + s[0] + 'ay'
#else if begins with other letter
#take first letter, put at end, and add "ay"
# Things we could have done better
# No ne... |
# Write a version BigBowl that inherits from Bowl and takes more scoops
class Scoop:
def __init__(self, _flavor):
self.flavor = _flavor
class Bowl:
max_scoops = 3
def __init__(self, _scoops):
self.scoops = []
self.add_scoops(*_scoops)
def __repr__(self):
return "\n"... |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib import patches
#import pylab
import time
import math
class KalmanFilter:
"""
Class to keep track of the estimate of the robots current state using the
Kalman Filter
"""
def __init__... |
# -*- coding: utf-8 -*-
# @Author: KeyangZhang
# @Date: 2019-12-04 17:28:17
# @LastEditTime: 2020-04-29 18:10:26
# @LastEditors: Keyangzhang
import warnings
def _mid(a,b,c):
"""return the middle value of three numbers"""
if a<=b<=c or c<=b<=a:
return b
elif b<=a<=c or c<=a<=b:
... |
c = input('please enter ciuseuis: ')
c = float(c)
f = c * 9 / 5 + 32
print('ferenheit:', f) |
"""
Create a dictionary, using the List items as keys. This will automatically remove any duplicates
because dictionaries cannot have duplicate keys.
Then, convert the dictionary back into a list:
"""
MyList = ["a", "b", "a", "c", "c"]
MyList = list(dict.fromkeys(MyList))
print(MyList)
# Convert it into Set
MyLis... |
# This will generate Fibonacci Series
def fibo_series(n):
a = 0
b = 1
for i in range(n+1):
print(a)
c = a + b
a = b
b = c
fibo_series(10)
|
# Selection Sort
MyList = [5, 3, 8, 6, 7, 2]
for i in range(len(MyList)):
minpos = i
for j in range(i, len(MyList), 1):
if MyList[j] < MyList[minpos]:
minpos = j
tmp = MyList[i]
MyList[i] = MyList[minpos]
MyList[minpos] = tmp
print(MyList)
|
# Linear Search
MyList = [5, 3, 8, 6, 7, 2]
for i in range(len(MyList)):
if MyList[i] == 8:
print("Element is found @Position ", i)
break
else:
print("Element is Not Found in List")
|
import sys
sys.setrecursionlimit(200) # This will set Recursion limit
print(sys.getrecursionlimit()) # this will print recursion limit
# This will calculate Factorial of Given Number
def fact(n):
if n == 1:
return 1
else:
return n * fact(n-1)
print("Factorial = ", fact(5))
|
"""
String concatenation,
..lets print a string "Welcome to_________ "
"""
# place = "himachal"
# print("Welcome to " + place)
# print("Welcome to {}".format(place))
# print(f"Welcome to {place} ")
adjective = input("Adjective :")
verb1 = input("verb1 : ")
verb2 = input("verb 2 : ")
famous_place = input(... |
from random import randint as alea
def quizz_table():
a = alea(1, 10)
b = alea(1, 10)
ab = str(a * b)
c = alea(1, 10)
d = alea(1, 10)
cd = str(c * d)
e = alea(1, 10)
f = alea(1, 10)
ef = str(e * f)
g = alea(1, 10)
h = alea(1, 10)
gh = str(g * h)
i = alea(1, 10)
... |
"""
Class Book: stores individual book information and returns it
"""
class Book(object):
def __init__(self, name, writer, ISBN):
self.name = name.strip()
self.writer = writer.strip()
self.ISBN = ISBN.strip()
def print_info(self):
print("{:<30} {:<30} {:<30}" .format(self.... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
user_input = str(input("Enter a Phrase: "))
text = user_input.split()
a = " "
for i in text:
a = a+str(i[0]).upper()
print(a)
# In[ ]:
|
import bs4
import requests
import urllib
url = "https://www.nytimes.com/2014/09/21/arts/design/ai-weiwei-takes-his-work-to-a-prison.html"
html = requests.get(url).text
#it creates a BeautifulSoup object that parsing the html
soup = bs4.BeautifulSoup(html,'html.parser')
#the css select that we inspected before
conten... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if r... |
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def reverse(head):
cur = head
p = None
while cur:
q = cur.next
cur.next = p
p = cur
cur = q
return p
def merge(node1, node2):
dummy = Node(0)
p = dummy
p1, p2 = ... |
fibonacci_numbers = [0, 1]
# Uses memoization for previously calculated fibonacci numbers
def nth_fibonacci_number(n):
if n < 0:
print(f'Błąd - liczba n: {n} < 0')
else:
if n >= len(fibonacci_numbers):
for i in range(2, n + 1):
if i >= len(fibonacci_numbers):
... |
# DONE
user_quit_flag = 1
list_of_strings = []
user_input = ''
string_found_flag = 0
while user_quit_flag == 1:
user_input = raw_input("Enter string to be inserted into a list of strings, enter q to terminate: ")
if user_input != 'q':
list_of_strings.append(user_input)
user_input = ''
elif user_input == 'q':... |
class RSA:
def __init__(self, p, q):
self.phi = (p - 1) * (q - 1)
self.n = p*q
self.e = RSA.find_e(self.phi)
self.d = self.find_d(self.e, self.phi, self.n)
self.public_key = self.e, self.n
self.private_key = self.d, self.n
print(f"Private key is: '{self.priva... |
"""
https://leetcode-cn.com/problems/group-anagrams/submissions/
https://leetcode-cn.com/problems/group-anagrams/solution/python-4xing-dai-ma-duo-chong-jie-fa-by-x62e3/
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
strs_dict = {}
strs_list = []
n = 0
... |
"""
https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/
"""
# 1
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
if len(nums) < 2:
return []
nums = sorted(nums)
nums_len = len(nums)
i = 0
for j in range(1, nums_len)... |
"""
https://leetcode-cn.com/problems/validate-binary-search-tree/
https://leetcode-cn.com/problems/validate-binary-search-tree/solution/yan-zheng-er-cha-sou-suo-shu-by-leetcode-solution/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# ... |
"""
https://leetcode-cn.com/problems/word-ladder/description/
https://leetcode-cn.com/problems/word-ladder/solution/python3-bfshe-shuang-xiang-bfsshi-xian-dan-ci-jie-/
https://leetcode-cn.com/problems/word-ladder/solution/python-shen-du-jiang-jie-bfsde-jie-gou-by-allen-23/
"""
class Solution:
def ladder... |
def find_sum_pair(l,sum,s):
for i in range(len(l)):
temp = sum - l[i]
if temp>=0 and temp in s:
print "pairs with given sum is :"+str(l[i])+" "+str(temp)
break
l = map(int,raw_input().split())
sum = input()
s = set()
for i in range(len(l)):
s.add(l[i])
find_sum_pair(l,s... |
#!/usr/bin/env python3
"""Solution for: https://www.hackerrank.com/challenges/primsmstsub
"""
from collections import defaultdict, namedtuple
from queue import PriorityQueue
from typing import Dict, List
Edge = namedtuple("Edge", ['weight', 'src', 'dest'])
Graph = Dict[int, List[Edge]]
def prims_mst(graph: Graph, s... |
#!/usr/bin/env python3
"""Solution for: https://www.hackerrank.com/contests/gs-codesprint/challenges/buy-maximum-stocks"""
from collections import namedtuple
from typing import List
Stock = namedtuple('Stock', ['price', 'count'])
def buy_max_stocks(dollars: int, stock_prices: List[int]) -> int:
"""Calculate ...... |
import sys
import os
def is_leap(year):
leap = False
# Write your logic here
# By doing year and modulo 4, it will check if it evenly divides by 4
# At the same time, it will check if it evenly divides by 400.
# An or comparison statement is in place incase if a year is does not evenl... |
#METODO DE LA BISECCIÓN
import numpy as np
import matplotlib.pyplot as plt
from math import*
def f(x):
return x+cos(x)
def biseccion(a,b,tol):
m=a
c=b
k=0
if(f(a)*f(b)>0):
print("\nLa función no cambia de signo")
print()
while(abs(m-c)>tol):
m=c
c=(a+b)/2
... |
print('今、何歳?')
age = int(input('you > '))
print('初恋はいくつのときだった?')
first_love = int(input('you > '))
print('あれから' + str(age - first_love) + '年経ったね')
|
import bisect
import random
SIZE = 7
random.seed(1729)
my_list = []
'''
bisect is a library that calculates insertion index when adding a certain value to any list.
bisect is as same as bitsect_right.
'''
print('---< bisect.insort >---')
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
bisect.inso... |
"""
A multi-dimensional ``Vector`` class, take 3
"""
from array import array
import reprlib
import math
import numbers
print(__doc__)
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._co... |
n1=int("22")
n2=int("17")
n3=int("56")
if(n1>n2)and(n1>n3):
largest number=1
elif(n2>n1)and(n2>n3):
largest number=2
else(n3):
largest number=3
print("largest number")
|
# Time Complexity: O(N) +O(M) where O(N) time taken to traverse left side of array and O(M) is time taken to traverse right side of array
# Space Complexity: O(1) as Output array result is not considered as extra space in single array calculation is done
class Solution(object):
def productExceptSelf(self, nums):
... |
"""
PRACTICE Test 3.
This problem provides practice at:
*** LOOPS WITHIN LOOPS, SEQUENCES and MUTATION ***
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and Dave Fisher.
""" # TO DO: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST fun... |
""" Credit to : https://stackoverflow.com/a/7392364 """
class Bin(object):
""" Container for items that keeps a running sum """
def __init__(self):
self.items = []
self.sum = 0
def append(self, item):
self.items.append(item)
self.sum += item
def __str__(self):
... |
""" generateMap.py
This Python program loads a set of map-generation parameters from a given
named module, and then generates a map using those parameters.
This program is provided as an extended example of the "shapeToMap.py"
program used in Chapter 4 of the book Python Geospatial Analysis.
"""
impor... |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = self.right = None
def print_level_order(root):
h = _height(root)
for i in range(1, h + 1):
print_given_level(root, i)
def print_given_level(root, level):
if root is None:
return
elif level == 1:
... |
import collections
"""
Shortest Word Distance
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", return 1.
"""
class Solution:
def distance(self, input, word1, word2):
dict ... |
from algos import STRATEGIES
from algos.searching import UNSUCCESSFUL
def iinterpolation_search(arr, target):
"""Iterative implementation of interpolation search.
:param arr: input list
:param target: search item
:return: index of item if found `-1` otherwise
"""
result = UNSUCCESSFUL
len... |
from algos import STRATEGIES
from algos.sorting import ASCENDING, GREATER_THAN, SORTING_OPERATORS
def iinsertion_sort(arr, order=ASCENDING):
"""Iterative implementation of insertion sort.
:param arr: input list
:param order: sorting order i.e "asc" or "desc"
:return: list sorted in the order defined
... |
from algos import STRATEGIES
from algos.searching.binary_search.search import binary_search
def exponential_search(arr, target, strategy=STRATEGIES.ITERATIVE):
"""Implementation of exponential search.
:param arr: input list
:param target: search item
:param strategy: search strategy i.e "iterative" o... |
days = "Mon Tue Wed Thus Fri Sat Sun"
months = "Jan\n Feb\n Mar\n Apr\n May\n Jun\n Jul\n Aug\n Sep\n Oct\n Nov\n Dec\n"
print "Here are days: ", days
print "Here are months: ", months
print """
There's something going on here.
With three double quotes.
We'll be able to type as much as we like.
Even 4 lines if we wan... |
file_name_input = raw_input("Please enter file path: ")
file_name = open(file_name_input)
def print_all(file_name_in):
print file_name_in.read()
def revind(file_name_in):
file_name_in.seek(0)
def print_a_line(line_number,file_name_in):
print line_number,file_name_in.readline()
print_all(file_name)
rev... |
__author__ = 'chris'
"""
Lab 16, Objective 1:
This project tests your understanding of analyzing the structure of code, and your ability to mercilessly refactor.
1. Create a new Python source file named refactory.py.
2. Copy the code below into the refactory.py file.
3. Run the program. If you copied it correctly, no ... |
__author__ = 'chris'
#Python 1: Lesson 4: Iteration: For and While Loops
"""Program to locate the first space in the input string."""
s = input("Enter any string: ")
pos = 0
for c in s:
if c == " ":
print("First space occurred at position ", pos)
break
pos += 1
else:
#Python loops come with ... |
__author__ = 'chris'
"""
Lab 12, Objective 1:
This project tests your ability to use modules and imports.
1.Create a new Python source file named guessing_game.py.
2.Import the random module.
3.Use the help() function on the random module to determine how to generate a random number between 1 and 99 inclusive.
4.Gener... |
__author__ = 'chris'
"""Write a GUI-based program that provides two Entry fields, a button
and a label. When the button is clicked, the value of each Entry
should (if possible) be converted into a float. If both conversions succeed,
the label should change to the sum of the two numbers. Otherwise it should
read "***ERR... |
__author__ = 'chris'
#Pyton 1: Lesson 4: Lab 4, Quiz 1
"""Create a new Python source file named guess.py.
Write a program that uses a while loop to ask the user to guess a number. Each guess should be checked against a
number stored in the "secret" variable, to which a value between 1 and 20 should be assigned at the s... |
import random
name = input("give me everybody's name spearated by coma")
names = name.split(" , ")
num_items = len(names)
random.randint = len(names)
random_choice = random.randint(0, num_items - 1)
person_will_pay = names[random_choice]
print((person_will_pay + "is going to buy meal today"))
|
List1 = [ "Vishu",5,10,2,"Mansi"]
for items in List1:
if str(items).isnumeric() and items>6:
print(items) |
from coding import encoding
class Client:
def __init__(self, login, psswd):
self.login = login
self.psswd = encoding(psswd)
def __str__(self):
return self.login
def __gt__(self, obj):
return self.login > obj.login
def __eq__(self, obj):
return self.login == obj.login
def check_pssw... |
######################
## Merge Sort ##
######################
data = list(map(int, open("input.txt","r").read().split(" ")))
n = len(data)
print(data)
def Merge(A,p,q,r):
n1 = q-p+1
n2 = r-q
L = []
R = []
for i in range(1,n1+1):
L.append(A[p+i-1])
for j in r... |
#!/usr/bin/env python3
import json
import yaml
from sys import argv
from os import path
if len(argv) < 2:
print("You have to provide a path to the file you want to convert. Exiting.")
elif not path.isfile(argv[1]):
print(f"File {argv[1]} doesn't exist. Exiting.")
else:
file_path = argv[1]
try:
... |
class Tree:
def __init__(self, name="root", children=None):
self.name = name
self.children = []
if children is not None:
for child in children:
self.add_child(child)
def __repr__(self):
return self.name + (str(self.children) if self.children else "")
... |
#Escriba el codigo necesario para que al ejecutar
#python ejercicio1.py se impriman los enteros del 10 al 1 en cuenta regresiva.
import numpy as np
nume=10
for i in range(0,nume+1):
print(nume-i)
print("Hasta la vista, Baby") |
from tkinter import *
# allows the use of the UI
# importing global variables
label_text = ''
not_breaking_equals = False
not_breaking_equals_2 = False
root = Tk()
label_equals = ''
# defining what happens when you press the one button
def one():
# importing global variables
global label_text... |
d = {'name':'laowang','age':18}
'''
d1 = {}
'''
d2 = {}
for k,v in d.items():
d[v]=k
print(d)
print(d2)
'''
d1=([v,k] for k,v in d.items())
print(d)
print(d1)
'''
|
class Dog():
def __init__(self):
self.name = ''
self.__age = 0
def setAge(self,age):
if age >15 and age < 1:
print('不符和实际')
else:
self.__age = age
def getAge(self):
return self.__age
ly = Dog()
ly.setAge(12)
print(ly.getAge())
|
def Tool(a,b,c):
if c == '+':
return a+b
elif c == '-':
return a-b
elif c == '*':
return a*b
elif c == '/':
if b != 0:
return a/b
else:
print('输入有误')
class Test():
pass
|
class Student():
count = 0
@staticmethod
def listen():
print('上课学习')
def __init__(self,name):
self.name = name
Student.count += 1
s1 = Student('小李')
s2 = Student('小张')
s3 = Student('小刘')
print(Student.count)
|
s1 = set(input("Enter a set1").split())
s2 = set(input("Enter a set2").split())
if(s1.issuperset(s2) and len(s1)>len(s2)):
print("Yes")
else:
print("No")
|
n = int(input("Enter no"))
nums = list(input().split(" "))
for i in range(n):
for j in range(n-1-i):
if nums[j] > nums[j+1]:
nums[i], nums[j]=nums[j], nums[i];
print(nums)
|
#
d ={'x':1}
d1 = {'y':3}
result = filter(lambda s: 0 in s.items(),[d,d1])
print(list(result))
#
# """
# It is better to return result because if we want to add element because we can add in empty and if we write None this will create an exception.
# nums =[1,2,3,4,5,6,7]
# Implementing filter
# def my_filter(func,iter... |
"""
filter remove something
and accept something
"1 2 3 4 5 6"
[1,2,3,4,5,6]
numbers =[int(x) for x in input("enter nos").split()]
int(x):act as map(for ke phele)
numbers =[int(x) for x in input("eneter nos").split()filter if ]
filter after for loop
"""
"""
input ="1 2 3 4 5"
string
list of string
even_numbers = [int... |
main_string = input("Enter string")
sub_string = input("ENter string")
print(main_string.count(sub_string))
pos = 0
start = 0
count = 0
while pos !=-1:
pos = main_string.find(sub_string,start)
if(pos!=-1):
count+=1
start=pos+len(sub_string)
print(count)
|
initial = int(input("Enter initial range"))
final = int(input("Enter final range"))
if initial == 1:
initial += 1
for i in range(initial,final+1):
flag = True
for j in range(2, i):
if i % j == 0:
flag = False
break
if flag:
print(i) |
"""z = "abc"
dct = {"x":2,"y":4,"z":5}
for x in dict.items():
print(x)
x is tuple(key,pair)
for x in dict:
print(x)
x would be keys
print(dict[x])-->value
list = ["hi","ok","Hm"]
coll =dict(data)
All are collections of length @2
first element becomes the Key
Second element becomes the Value
INput of dict:
raw... |
x = int(input("Enter 1st positive number"))
temp = x
sum = 0
product =1
reverse = 0
while temp != 0:
d = int( temp % 10)
sum += d
product *= d
reverse = reverse*10+d
temp = int(temp/10)
print(f'sum of digits {sum}')
print("product of dits is", product)
|
# # # Constructor:
# #
# #
# #
# #
# # class Sample:
# # def __call__(self, *args, **kwargs):
# # obj = self.__new__()
# # self.__init__(obj)
# # return obj
# # def __new__(cls, *args, **kwargs):
# # print("I am creating that obj")
# # return super(Sample, cls).__new__(cl... |
#!/usr/bin/env python3
# Anagrama
# dada una palabra busca anagramas de la misma
print('Ingrese una palabra para buscar:')
palabra = input()
listapalabras = "palabras.txt"
f = open(listapalabras, 'r')
lines = f.readlines()
for line in lines:
if sorted(list(line)[:-1]) == sorted(palabra):
print(line.replace... |
import matplotlib.pyplot as plt
import numpy as np
def f(x):
f = eval(function)
return f
print('''
#########################################################
#########################################################
#### ####
#### Método de Secante ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# fibonacci.py
def fib_iter(n):
"""Wylicza n-ty wyraz ciągu Fibonacciego
F(0)= 0
F(1)= 1
F(n)= F(n-2) + F(n-1) """
if n == 0:
return 0
elif n == 1:
return 1
a, b = (0, 1)
print(a)
for i in range(1, n):
... |
#textprobar
import time
scale = 51
print ("执行开始".center (scale // 1 , "="))
for i in range (scale) :
time.sleep(0.1)
str1 = "*" * i
str2 = "." * (scale -1 - i)
print ("\r{:^3}% [{}->{}]".format (i *2 , str1 , str2) , end = "")
print ("\n" + "执行结束".center (20 , "="))
cc = input ("请输入任何字符以结束程序")
|
import math
a=eval(input('请输入第一个边长值'))
b=eval(input('请输入第二个边长值'))
c=eval(input('请输入两边长的夹角角度值'))
third=math.sqrt(math.pow(a,2)+math.pow(b,2)-2*a*b*math.cos(c*math.pi/180))
print('第三边长为:',third)
|
import sys
moves = input()
index = 1
for i in moves:
if (i == 'A' and index != 3):
index = 2 if index == 1 else 1
elif (i == 'B' and index != 1):
index = 3 if index == 2 else 2
elif (i == 'C' and index != 2):
index = 1 if index == 3 else 3
print(index) |
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
print 'Transpose of the original array is:'
b = a.T
print b
print '\n'
print 'Sorted in C-style order:'
c = b.copy(order = 'C')
print c
for x in np.nditer(c):
print x,
print '\n'
print 'Sorted in F-style o... |
#Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
#Creatting a Tuple
#with the use of string
Tuple1 = ('Python', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
... |
import numpy as np
x = np.arange(9.).reshape(3, 3)
print 'Our array is:'
print x
# define a condition
condition = np.mod(x,2) == 0
print 'Element-wise value of condition'
print condition
print 'Extract elements using condition'
print np.extract(condition, x)
|
# Python code to demonstrate the working of isleap()
# importing calendar module for calendar operations
import calendar
year = 2017
# calling isleap() method to verify
val = calendar.isleap(year)
# checking the condition is True or not
if val == True:
# print 4th month of given leap year
calendar.prmont... |
# Python code to Reverse each word
# of a Sentence individually
# Function to Reverse words
def reverseWordSentence(Sentence):
# Splitting the Sentence into list of words.
words = Sentence.split(" ")
# Reversing each word and creating
# a new list of words
# List Comprehension Technique
newWords = [w... |
# Calenndar Module
# First Weekday
# Calendar.firstweekday()
# Returns the current setting for the weekday that starts each week.
# default is Monday i.e '0'
import calendar
print(calendar.firstweekday())
# Leap year
# calendar.isleap(year)
# returns true if the year is ;eap year, else false
year = 2020
print("Is 20... |
# filter the selection by
# using the "WHERE" statement
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address ='Park Lane 38'"
mycursor.execute(sql)
... |
# Python program to
# demonstrate time class
from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute = 12)
print("\nTime with one argument", my_time)
# Calling constructor with
# 0 argumen... |
import numpy as np
a = np.array([10,100,1000])
print 'Our array is:'
print a
print '\n'
print 'Applying power function:'
print np.power(a,2)
print '\n'
print 'Second array:'
b = np.array([1,2,3])
print b
print '\n'
print 'Applying power function again:'
print np.power(a,b)
|
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
def pairSum(n,input_array):
input_array.sort()
if input_array[0]>n:
print("no such elements")
else:
... |
class Problema(object):
def __init__(self, inicio, objetivo=None, acao=None):
self.inicio = inicio
self.objetivo = objetivo
self.acao = acao
def test_objetivo(self, estadoNo):
return estadoNo == self.objetivo
def acoes(self,estadoNo):
return list(self.acao[estadoNo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.