text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 31 14:17:37 2017
@author: 00mymy
"""
import math, random
from collections import Counter
from linear_algebra import distance, vector_subtract, scalar_multiply
def sum_of_squares(v):
return sum(v_i**2 for v_i in v)
def difference_quotient(f, x, h):
return (f(... |
def is_palindrome(n):
stringnum=str(n)
i=0
while i<len(stringnum):
if stringnum[i]!=stringnum[len(stringnum)-1-i]:
return False
i=i+1
return True
output = filter(is_palindrome, range(1, 1000))
print(list(output))
|
L1=[('Lili',75),('Adam',92),('Bart',66),('Lisa',68)]
def name(x):
i=0
L2=[]
while i<len(x):
L2.append(L1[i][0])
i=i+1
return L2
output=sorted(L1,key=name)
print(output) |
from dumbo_syntaxique import Node
from dumbo_lexical import variables
"""
Analyseur semantique
"""
def getVariable(node):
"""
:param node: un noeud
:return: va chercher la valeur de la variable dans le dictionnaire variable
"""
if node.p_type == "variable":
try:
return variab... |
import statistics
import string
# create matrix for animals
#Sharks, rays, amphibians
#sharks
#rays
#amphibians
#function determines the lowest element in the matrix
def minVal(animal_matrix):
minVal = 999 #start minimum with first element
for row in range(len(animal_matrix)):
for col ... |
#!/usr/bin/env python3
from math import sqrt
def get_botright_edges(location):
"""
Simply returns i as the bottom right value where the location is
and a list of squares numbers from 1 to i with a step of 2
"""
i = 1
res = [1]
while (i * i) < location:
i += 2
res.append(i*i)... |
#Hi! Thanks for viewing my code. I hope my coments are clear enough to understand...
#Reset ans to 0 for some reason
ans = 0
#We introduce the calculator and give information
def info():
print "Welcome to my simple calculator!"
print "Type 'fin' for your first or second number if you want to stop."
print ... |
students=[
{"name": "Sanskriti", "clique": "Nerd"},
{"name": "Samyak", "clique": "Coder"},
{"name": "Preetansh", "clique": "Idiot"}
]
#def f(person):
# return person["clique"]
students.sort(key=lambda person: person["clique"])
print(students) |
#Alan ve Hacim Hesaplayıcı - Area and Volume Calculator
pi=3.141592
dil=input("Türkçe İçin 1- For English 2")
if dil=="1":
print("Çeviriciye Hoşgeldin")
while(True):
print("-"*30)
secimilk = input("Alan için 1 Hacim için 2 yi tuşlayınız")
if secimilk=="1":
secimik... |
import matplotlib.pyplot as plt
import networkx as nx
# Define a function wich computes the Closeness Centrality:
def closeness(graph):
return nx.closeness_centrality(graph)
# Define a function wich plots the Closeness Centrality:
def plot_closeness(graph):
closenessDict = closeness(graph)
keyList = []
... |
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
fruits = ["Апельсин",... |
'''
* * * * *
* * * *
* * *
* *
*
when n=5
'''
n=int(input('Enter the value of n\n'))
for i in range(n,0,-1):
for sp in range(0,n-i+1):
print(" ",end="")
for j in range(0,i):
print("*",end=" ")
print()
|
x,y=0,0
increment=10
n=int(input('Enter the number\n'))
evenCount=0
oddCount=0
noOfIterations=0
# for i in range(1,n+1):
# if i%4==0:
# y=y-increment
# elif i
testvalue=0
for i in range(1,n+1):
noOfIterations+=1
if noOfIterations%2==0:
evenCount+=1
if evenCount%2==0:
... |
'''
Given a String of date of format YYYYMMDD, our task is to compute the life path number. Life Path Number is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions.
Examples:
Input : test_str = “19970314”
Output : 7
Expla... |
'''
Given a list, the task is to write a Python program to mark the duplicate occurrence of elements with progressive occurrence number.
Input : test_list = [‘gfg’, ‘is’, ‘best’, ‘gfg’, ‘best’, ‘for’, ‘all’, ‘gfg’]
Output : [‘gfg1’, ‘is’, ‘best1’, ‘gfg2’, ‘best2’, ‘for’, ‘all’, ‘gfg3’]
Explanation : gfg’s all occurr... |
'''
Python program to print all pronic numbers between 1 and 100
The pronic number is a product of two consecutive integers of the form: n(n+1).
For example:
6 = 2(2+1)= n(n+1),
72 =8(8+1) = n(n+1)
'''
def isPronic(num):
import math
#num = int(input('Enter the number\n'))
n = int(math.sqrt(num))
if ... |
def fre(ch,word):
count =0
for i in word:
if i==ch:
count+=1
return count
def max(ls):
maximum=ls[0]
for i in range(1,len(ls)):
if maximum<ls[i]:
maximum=ls[i]
return maximum
print(fre('l','lala'))
print(max([1,2,3,5,21,1,1,2]))
print(fre('',''))
|
#!/usr/bin/python
import sys
class Solution:
"""
@param: nums: an array of Integer
@param: target: target = nums[index1] + nums[index2]
@return: [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, nums, target):
# write your code here
i = 0
j = len(nums) - 1
... |
#!/usr/bin/python
import sys
# 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 findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
... |
#!/usr/bin/python
import sys
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
houses.sort()
heaters.sort()
heaters = [float('-inf')] + heaters + [float('inf')]
... |
#!/usr/bin/python
import sys
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The head of linked list.
@return: You should return the head of the sorted linked list, using cons... |
#!/usr/bin/python
import sys
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
"""
@par... |
#!/usr/bin/python
import sys
import heapq
class MaxStack(object):
def __init__(self):
""" Space O N
initialize your data structure here.
"""
self.stack = []
def push(self, x):
""" O 1
:type x: int
:rtype: void
"""
m = max(self.stack[-1... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: matrix: A list of lists of integers
@param: target: An integer you want to search in matrix
@return: An integer indicate the total occurrence of target in the given matrix
"""
def searchMatrix(self, matrix, target):
# write your c... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: n: An integer
@return: the nth prime number as description.
"""
def nthUglyNumber(self, n):
# write your code here
ugly = [1]
i2, i3, i5 = 0, 0, 0
while n > 1:
u2, u3, u5 = ugly[i2] * 2, ugly[i3] ... |
#!/usr/bin/python
import sys
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = [-1] * len(nums)
stack = []
for i in range(len(nums)) * 2:
while stack and nums[i] > nums[stack[-1]]... |
#!/usr/bin/python
import sys
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
result = ""
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
a = [[] for _ in range(len(s) + 1)]
for k in d.keys():
... |
#!/usr/bin/python
import sys
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
a = 0
l = 0
c = 0
for i in s:
if i == 'A':
a += 1
c = 0
elif i == 'L':
... |
#!/usr/bin/python
import sys
class Solution:
# @param {int} n an integer
# @param {int[][]} edges a list of undirected edges
# @return {boolean} true if it's a valid tree, or false
def validTree(self, n, edges):
if len(edges) != n - 1:
return False
neighbors = {i: [] for i ... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: reader: An instance of ArrayReader.
@param: target: An integer
@return: An integer which is the first index of target.
"""
def searchBigSortedArray(self, reader, target):
# write your code here
index = 0
while reade... |
#!/usr/bin/python
import sys
# 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 buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type p... |
#!/usr/bin/python
import sys
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
d = {'6': '9', '9': '6', '1': '1', '8': '8', '0': '0'}
if set(num) - set(d.keys()):
return False
new = []
for n in n... |
#!/usr/bin/python
import sys
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
n = 0
... |
#!/usr/bin/python
import sys
# 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 minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int... |
#!/usr/bin/python
import sys
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: the root of binary tree
@return: the root of the maximum average of subtree
"""
def findSu... |
#!/usr/bin/python
import sys
# 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 findMode(self, root):
"""
:type root: TreeNode
:rtype: List[in... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: source: source string to be scanned.
@param: target: target string containing the sequence of characters to match
@return: a index to the first occurrence of target in source, or -1 if target is not part of source.
"""
def strStr(self,... |
#!/usr/bin/python
import sys
# 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 upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rt... |
#!/usr/bin/python
import sys
# 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 isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
... |
#!/usr/bin/python
import sys
# 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 trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: i... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: s: A string
@return: Whether the string is a valid palindrome
"""
def isPalindrome(self, s):
# write your code here
i = 0
j = len(s)-1
while i<j:
if not s[i].isalnum():
i += 1
... |
#!/usr/bin/python
import sys
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
# BFS
if image[sr][sc] == newColor:... |
#!/usr/bin/python
import sys
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
self.visited = set()
result = 0
for n in range(len(M)):
if n not in self.visited:
self.dfs(M, n)
... |
#!/usr/bin/python
import sys
# 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 convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeN... |
#!/usr/bin/python
import sys
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
j = -1
for r in matrix:
... |
#!/usr/bin/python
import sys
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = sum(nums)
leftsum = 0
for i, n in enumerate(nums):
if leftsum == (s - leftsum - n):
return i
... |
#!/usr/bin/python
import sys
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
l = nums[0]
f = nums[n - 1]
li = -2
fi = -1
for i in range(len(nums)):
l = ... |
#!/usr/bin/python
import sys
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
if set([a, b]) == set([2147483647, -2147483648]):
return -1
if a < 0 or b < 0:
if a < 0:
b, a =... |
#!/usr/bin/python
import sys
# Recursive dfs
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.result = []
self.dfs(nums, [])
return self.result
def dfs(self, nums, ss):
if len(ss) == len(... |
#!/usr/bin/python
import sys
class Solution(object):
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
d = {}
for p in paths:
path = p.split(" ")[0]
files = p.split(" ")[1:]
for f in files:
... |
#!/usr/bin/python
import sys
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
s = f =... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
# write your code here
self.result = []
self.dfs(nums, [])
return self.result
def dfs(self, nums, ss):
if len... |
#!/usr/bin/python
import sys
class Solution:
"""
@param: s: a string
@param: dict: a set of n substrings
@return: the minimum length
"""
def minLength(self, s, dict):
# write your code here
if not s:
return 0
result = len(s)
h = {s}
q = [s]
... |
import math
def longest_side(a, b):
"""
Founction to find the length of the longest side of a right triangle.
:arg a : Side a of the triangle
:arg b: Side b of the triangle
:return Length of the longest side c as float
"""
return math.sqrt(a*a + b*b)
if _name_ == '_main_':
print(lon... |
'''
Created on 10 mar. 2021
@author: Ivi
'''
num1 = int(input("Dame el numero entero inicial:"))
num2 = int(input("Dime cuantos valores quieres:"))
i = 0
lista = []
if num2 >= 0:
while num2 > i:
lista.append(num1)
num1=num1+1
i=i+1
if lista.__len__()>0:
print(lista)
else:
p... |
# Rock, Paper, Scissors game.
# Import modules
import sys
import random
import time
# Scores
wins = 0
loses = 0
ties = 0
# Strikes
strikes = 0
balls = 0
fouls = 0
# Agreements
yes = ('y', 'yes')
no = ('n', 'no')
# Are we
# playing?
def Play():
global wins
global loses
global ties
# What are our op... |
__author__ = 'danbox'
from time import time
import math
import random
'''
FORMATTING CONVENTION
The convention for formatting a list of points in this program is to use
a list of lists of pairs of floating-point values. The first
element in each pair is the x coordinate of a point and the second
is its y coordinate... |
#QUESTION-1
try:
a=3
if a<4:
a=a/(a-3)
print(a)
except ZeroDivisionError:
print("no. !/0")
#QUESTION-2
try:
l=[1,2,3]
print(l[3])
except IndexError:
print("list out of index.")
#QUESTION-3
#Output will be {An exception} as "hi there" will not be found.
#QUESTION-4
#smjh nhi... |
#QUESTION-1
list1=[int(input("Enter the number:- ")) for i in range(10)]
for i in list1:
print(i)
#QUESTION-2
while(True):
print("infinite loop")
#QUESTION-3
number=int(input("Enter the number of elements:- "))
list2=[int(input("Enter number:- ")) for i in range(number)]
list3=[i**2 for i in list2]
prin... |
def DDAL(x1, y1, x2, y2, color1, color2):
dx = abs(x2 - x1)
dy = abs(y2 - y1)
steps = 0
if (dx) > (dy):
steps = (dx)
else:
steps = (dy)
xInc = float(dx / steps)
yInc = float(dy / steps)
xInc = round(xInc,1)
yInc = round(yInc,1)
fo... |
import random
from itertools import combinations
question_format = """
- {id}) {question}"""
def random_get_answer(answers, memory=None):
if memory is None:
memory = []
while True:
answer = random.choice(answers)
if answer not in memory:
memory.append(answer)
... |
def class animal(self, )
print ("Hello world")
a = 22
while a != 23:
a = int(input("Enter integer:"))
print(a)
print(type(a))
else:
print(f"You got it, the number is {a}")
print("End")
|
def ordinalFunc(x):
if not isinstance(x, int):
return "Input must be integer"
x_string = str(x)
last_digit = x_string[-1]
last_2_digits = x_string[-2:]
last_digit = int(last_digit)
last_2_digits = int(last_2_digits)
if last_2_digits in range(11,16):
return "%sth" % x
else:
if last_digit == 1:
ret... |
#Task1
#def CounttoN(num):
num = abs(num)
#num will be assigned the absoulute value of it self
#for i in range(1,num+1):
# print i
n = raw_input("enter an interger:\n")
n = int(n)
#alternative
# i = 1
# while i <=num:
# print i
# list()... |
# File: src/python/basic_mathematical_operations.py
# First, let's import the 'math' library
import math
# Declare some variables so we have data to play around with
str1 = "I am string #1"
str2 = "I am string #2"
int1 = 12
int2 = 58
float1 = 100.2
float2 = 56.3
# Addition ===========================================... |
# File: src/python/basic_control.py
# Demonstrates the use of if/elif/else statements.
# The following line is unrelated to control statements
num = int(raw_input("Input Number:"))
if num > 0:
print num, "is positive"
elif num < 0:
print num, "is negative"
else:
print num, "is zero"
|
# File: src/python/physics_numerical_euler.py
# Simulates an object being launched at a particular angle given an initial velocity using the forward Euler method.
import math
ANGLE = 30.0 #degrees
V0 = 112.0 #initial velocity, m/s
DT = 0.01
G = -9.8 #gravity, m/s
H_DAMP = 0.0 #wind, m/s
t = 0.0 #time (seconds)
x = ... |
# File: src/python/basic_arrays_multinumpy.py
# Demonstrates the use of the NumPy array library to make multidimentional arrays
# Import the NumPy library
import numpy
# Declare a 2D array
arr2D = numpy.array([
[00,01,02,03],
[10,11,12,13],
[20,21,22,23],
[30,31,32,33]
])
# Access an element
item = arr2D[1][1]... |
# Copyright 2008-2020 pydicom authors. See LICENSE file for details.
"""Code for multi-value data elements values,
or any list of items that must all be the same type.
"""
from typing import overload, Any, cast, TypeVar
from collections.abc import Iterable, Callable, MutableSequence, Iterator
from pydicom import conf... |
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n") #\n creates a new line.
print("Thank you everyone! \nThat was a great magic show!")
message = ("Those are the first 9... |
#Programmed by Chris Olszewski
#Imports
import sys
import time
#Variables
#a=2
#Methods
def yes_no(prompt, complaint='Invalid Answer'):
while True:
ok = input(prompt)
if ok in ('Y', 'y', 'yes', 'Yes'):
return True
if ok in ('N', 'n', 'no', 'No'):
return False
print(complaint)
def mutliChoice(title, an... |
n = int(input())
k = int(input())
total = 0
total += n
for i in range(1,k+1):
total += n*10**i
print(total)
|
def runFunction():
v1 = input()
v2 = input()
v3 = input()
v4 = input()
v5 = input()
v6 = input()
wins = 0
if v1 == "W":
wins+=1
if v2 == "W":
wins+=1
if v3 == "W":
wins+=1
if v4 == "W":
wins+=1
if v5 == "W":
wins+=1
if v6 == "W":
wins+=1
if wins >=5:
return (1)
elif wins >= 3:
... |
temp = int(input())
p = 5 * temp - 400
print(p)
if (p < 100):
print(1)
elif (p > 100):
print(-1)
else:
print(0) |
word = input()
Success = True
for i in range(len(word)):
if word[i] == "I" or word[i] == "O" or word[i] == "S" or word[i] == "H" or word[i] == "Z" or word[i] == "X" or word[i] == "N":
Success = True
else:
print("NO")
Success = False
break
if Success == True:
print("YES")
|
import tkinter as tk
print("Stage 5")
'''
Base 2 to Base 10
1010
1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0 = 1 * 8 + 0 * 4 + 1 * 2 + 0 * 1 = 10
'''
#This gets printed in terminal when program is opened
#This function makes program process the entered value
#*args function: when function is called, *args allows any numbe... |
# модуль для работы с текстом
def removeSymbols(string):
# список символов к замене на пробел
symbolsToReplaceWithSpace = ['\n', '\"', '/', '{', '}', '[', ']', '(', ')', '<', '>', '=', '.']
# заменяем в цикле символы на пробелы
for symbol in symbolsToReplaceWithSpace:
string = string.replace(symbol, ' ')
# спис... |
'''
-------------------------------------------------------------------------------
Name: problem1.py
Purpose: The purpose of this program is to make a conversion between the temperature in Fahrenheit to the temperature in Celsius, for my cousin visiting from the U.S
Author: Surees.A
Created: 07/12/2020
-----------... |
class Human():
def __init__(self):
self.attack = 0
def play(self,node):
print("Human turn!")
while 1:
print("Avaliable move: \n")
for col,row in enumerate(node.frontier):
if row!=None:
print(str(row)+" "+str(col)+'\n')
action = [int(x) for x in input("Your turn: ... |
import sqlite3
class menuPrincipal:
barra = lambda self,n=40,caraca='*':print(caraca*n)
def menu(self):
self.barra()
print("$ 1 -> Logar como Administrador")
print("$ 2 -> Logar como Secretario")
print("$ 3 -> Logar como Presidente")
print("$ 4 -> Logar como Mesar... |
from math import *
class Circle:
#@staticmethod
def __init__(self):
#dict=[]
#for i in range(1,21):
# dict.append(i)
#print dict
#self.radius=radius
pass
def rec(self):
y = []
while True:
l = (raw_input("enter the number"))
... |
#Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input
# and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence
class A:
def array(self):
print "hi"
b = (raw_input("Enter th... |
# 2. Write a program which can compute the factorial of a given numbers.
#The results should be printed in a comma-separated sequence on a single line.
def fact(n):
if n==0:
return False
elif n==1:
return 1
else:
prod = 1
for i in range(n):
prod=prod*n
... |
class Circle:
def rec(self,n):
print "hi"
print "wassup"
y=[1,3,2,6,4,9,7]
y1=sorted(y)
print y1
for i in y1:
#print i
if i==n:
print y1.index(i) # using the element to find the index
else:
print "ele... |
#Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
class A:
def q10(self):
b= raw_input("enter the string")
c=[]
d=[]
for i in b.split(' '):
print i
... |
#creating a bell-curve graph with mobile data
print("Hello!\nThis is a bell-curve graph which shows the average rating for amazon mobile brands.")
#importing the right libraries
import csv
import pandas as pd
import plotly.figure_factory as ff
#reading the csv file
df=pd.read_csv("mobileData.csv")
#creat... |
"""This is test file1 for list.
"""
cars = ['ww', 'subaru', 'honda', 'toyota']
print('last car brand is % s.' % cars[-1].title())
# title() function is to capitalize the first char of string
print(cars[-1].title())
# Use for loop to traverse the list elements.
# Exercise 3-1
for car in cars:
print(car)
# Exerc... |
""" This is a text file for testing Git in Pycharm!
This is a new line for 1st time edition.
End of line
"""
"""This is the 2nd time edition.
New line appended for 2nd time."""
name = "morris"
print('%s, Welcome to PyCharm' % name)
"""Exercise 2-3:
Upper case the first char of the name string
"""
# Function Casec... |
#!/usr/bin/env python
def isPrime(n):
def modulus(n,x):
if (n%x)==0:
return False
else:
if x<(n/2):
return modulus(n,x+1)
else:
return True
if n==0 or n==1:
return False
elif n==2:
return Tr... |
'''
使用lambda 表达式为槽函数传递参数
lambda 表达式:匿名函数,也就是没有名字的函数
'''
# fun=lambda :print("hello world")
#
# fun()
#
# fun1=lambda x,y:print(x,y)
#
# fun1("a","b")
from PyQt5.QtWidgets import *
import sys
class LambdaSlotArgs(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("使用lambda ... |
x = "Samyuktha"
print(x)
# Combine numbers and text
s = "My lucky number is %d, what is yours?" % 7
print(s)
# alternative method of combining numbers and text
s = "My lucky number is " + str(7) + ", what is yours?"
print(s)
# print character by index
print(x[0])
# print piece of string
print(x[0:3])
v = "Today i... |
class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
# insert at end of heap
new_index = len(self.storage)
self.storage.append(value)
self._bubble_up(new_index)
def delete(self):
if len(self.storage) == 0:
return None
... |
#!/usr/bin/python
__author__ = 'boltz_j'
import sys
from time import time
class Game():
def __init__(self, size_of_deck):
"""
At the creation of the game, we init a lookup table (shuffle_table)
to precalculate the distribution of card for a round
:param size_of_deck: Number of ca... |
class Solution:
def isMatch2(self, text, pattern):
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return (self.isMatch(text, pattern[2:]) or
first_match and se... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.root = None
def get_max(self, node: TreeNode) -> TreeNode:
if not node:
return node
... |
class Solution:
def reverse(self, x: int) -> int:
is_negative = False
if x < 0:
is_negative = True
x *= -1
x_str = str(x)
x_list = list(x_str)
x_list_reversed = x_list[::-1]
print(x_list_reversed)
x_string = ''.join([char for char in x_l... |
import tkinter as tk
from tkinter import Label,messagebox,Button,Entry,TOP,BOTTOM
import webbrowser
root = tk.Tk()
root.geometry("300x100")
root.minsize(300,100)
root.maxsize(300,100)
root.title("Multiple open URL")
labal1 = Label(text = "Enter New URL:")
labal1.pack()
E1 = Entry()
E1.pack()
def url():
webb... |
#-*-coding:utf-8-*-
# Author: GISyang_china
# 抽象工厂
# 是抽象方法的一种泛化,抽象工厂是一组工厂方法,其中每个工厂方法负责产生不同种类的对象
#
'''
工厂模式使用场景:
追踪对象的创建时
将对象的创建和使用解耦时
优化应用的性能和资源占用时
'''
class Frog:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def interact_with(self, obstacle)... |
'''
# -*- coding: utf-8-*-
esto se utiliza para validar carecteres especiales en espanol
Palabras reservadas
False, class, finally, is, return
None, continue, for, lambda, try
True, def, from, nonlocal, while
and, del, global, not, with
as, e... |
'''
Secuencia de caracteres
se puede acceder por indice
indices empiezan en cero
0 1 2 3 4 5
c a m i l o
Metodos
upper isupper lower islower find isdigit endswith startswith split join
'''
name = 'Camilo'
validar = name[0]
longitud = len(name)
ultimaLetra = name[len(name)-1]
mayuscula = name.upper()
minuscula = n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.