blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1e3a6f2c2c5b0b6c7aa6d55de8535b3a4ec57bd5 | JOINYYz/jianzhiOffer | /code/Mirror.py | 774 | 3.84375 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
'''
和先根遍历相似,将打印根值部分替换成“交换左右节点”
'''
# write code here
cur = root
stack = []
... |
82e3f08268807f309792cf47af86f9fa3d8bc935 | WalczRobert/Module_11 | /employee_class.py | 743 | 4.03125 | 4 | """
Robert Walczak
program to get and return employee personal information
:param phone_number - Employee's phone number
:param address_street - Employee's street address
:param last_name - Employee's last name
:param address_city - Employee's city and state
:param first_name - Employee's first name
:return Employee's ... |
83d05406dfba446047280c393bb7fa027ae0fd97 | rajeshchangdar/Python-Introduction | /PyFunction/HighOrderFuncDemo.py | 1,332 | 4.625 | 5 | """
#Introduction to Doc String in Python
import math
def longest_side(num1,num2):
Function to find the length of the longest side of the right triangle
:arg num1: side a of the triangle
:arg num2: side b of the triangle
:return: Length of the longest side num3 as the Floot
... |
06cfb1c87c21bbae0d65be630d2a422fc03f68e1 | Sankalp-Tiwari/Python-Tutorials | /Python Problems/PythonProblem3.py | 745 | 4.28125 | 4 | '''
Author : Sankalp
Date : 23 January 2021
Purpose : Practise Problem
'''
mylist = []
no_of_items = int(input("Enter the size of the list\n"))
for i in range(no_of_items):
list_item = input("Enter the item of the list\n")
mylist.append(list_item)
reverseList1 = mylist.copy()
reverseList1.reverse()
print(f"The... |
0779109964afd8233e2a0a0435e820c027732e11 | nithinreddykommidi/pythonProject | /PYTHON_WORLD/1_PYTHON/1_DATA_TYPES/1_Define_datatypes/1_number.py | 492 | 4.21875 | 4 | '''
1. Number data type is used to store integer values(0-9).
2. Number is a immutable object
Example :- N = 123
1. 'N' is a Variable
2. '=' is a assignment operator
3. '123' is a value
4. 'N' Data type is number(int)
3. type() function is used to know type of object.
'''
# To Create a variable... |
44fb78bff28402cf2731393700adf565ae30c1c3 | RookieRick/AdventOfCode | /AoC2019/day11.py | 3,477 | 3.5 | 4 | from AoC2019.inputs import get_input
from AoC2019.intcode import IntCodeComputer
from collections import defaultdict
import queue
import math
# initial thoughts..
# build a hash of (x, y) -> color [default black = 0] to represent hull.
# don't really care where the robot starts..
# assume x, y standard cartesian coords... |
57c8e95dad69edd7e52efcd57670092ecb499a9a | santuchidura/NUMPY | /palindrome.py | 322 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 8 16:27:49 2019
@author: Santosh
"""
def reverse(s):
return s[::-1]
def isPalindrome(s):
# Calling reverse function
rev = reverse(s)
# Checking if both string are equal or not
if (s == rev):
return True
return Fal... |
af91e3f292913a16cda479df2b785f0a54868b35 | jimmybasketball/Python | /untitled/day10_extend.py | 1,249 | 4.125 | 4 | #!D:\Python\python27
# -*- coding:utf-8 -*-
__metaclass__=type
#构造方法__init__(self),当一个对象被创建后,会立即调用构造方法
#继承,方法重写
class A:
def hello(self):
print 'hello he is A'
class B(A):
def hello(self):
print 'he is B'
a=A()
b=B()
a.hello()
b.hello()
class Bird:
def __init__(self):
self.hungry=... |
dae4396e8747a0fc70301be8f24f7bf7f7b27639 | zhyordanova/Python-Advanced | /05-Functions-Advanced/Exercise/04_negative_vs_positive.py | 450 | 3.890625 | 4 | def print_stronger_sum_nums(iters):
positive_sum = sum(filter(lambda x: x > 0, iters))
negative_sum = sum(filter(lambda x: x < 0, iters))
print(negative_sum, positive_sum, sep='\n')
if positive_sum > abs(negative_sum):
print(f"The positives are stronger than the negatives")
else:
pri... |
072b1da641b7d0f8a9e907b531b74cd6acb89fd9 | prattita/AirportDatabase | /make_tables.py | 5,443 | 3.53125 | 4 | import psycopg2
def drop_tables():
try:
conn = psycopg2.connect("dbname='AirlineDB' user='postgres' host='localhost' password='Nintendo_20'")
cur = conn.cursor()
cur.execute("""DROP TABLE earnsMileage;
DROP TABLE costs;
DROP TA... |
bd7938f70e7217c7090f576e9a421cb69d2bd390 | Cheater115/acmp | /Python/0892.py | 347 | 3.515625 | 4 | seasons = {
1: 'Winter',
2: 'Winter',
3: 'Spring',
4: 'Spring',
5: 'Spring',
6: 'Summer',
7: 'Summer',
8: 'Summer',
9: 'Autumn',
10: 'Autumn',
11: 'Autumn',
12: 'Winter',
}
nMonth = int(input())
season = seasons.get(nMonth, None)
if season is not None:
print(season... |
226d492878b61ef29da0ebc9aa19f3e0d4a31df9 | vikramlance/Python-Programming | /codeChef/OCT20B/covid_run.py | 1,968 | 3.9375 | 4 | """
Covid-19 is spreading fast! There are N cities, numbered from 0 to (N−1), arranged in a circular manner. City 0 is connected to city 1, 1 to 2, …, city (N−2) to city (N−1), and city (N−1) to city 0.
The virus is currently at city X. Each day, it jumps from its current city, to the city K to its right, i.e., from c... |
2634a9b891c68b355c54b03e2fae432dc6862044 | natal20-meet/meetyl1201819 | /lab2.py | 591 | 3.75 | 4 | import tkinter as tk
from tkinter import simpledialog
a = [1,2,3,4,5]
def make_list ():
x = [a[0], a[4]]
print (x)
#make_list()
b = [-2,-1,0,1,2,3,4,5,6,7,8,9]
def values_less_5(x):
for number in b:
if number <=5:
print(number)
num_list2 = []
#values_less_5(b)
c = [2,4,6,8,10,12,14,16,18]
d = [2,6,10,14,1... |
6714cbb4451a14486c9c7d0cb9362d14d16c0a8b | OliverTarrant17/CMEECourseWork | /Week2/Code/control_flow.py | 2,452 | 4.03125 | 4 | #! /usr/bin/python
""" Author - Oliver Tarrant
Some functions exemplfying the use of control statements"""
#docstrings are considered part of the running code (normal comments are
#stripped) . Hence you can access your docstrings at run time.
__author__ = 'Oliver Tarrant (oit16@ic.ac.uk)'
__version__ = '0.0.1'
# imp... |
e7ac3a2ed0deae84e3f564c786ab44003d791d4f | Satily/leetcode_python_solution | /solutions/solution950.py | 523 | 3.65625 | 4 | from queue import Queue
class Solution:
def deckRevealedIncreasing(self, deck: 'List[int]') -> 'List[int]':
deck.sort(reverse=True)
q = Queue()
q.put(deck[0])
for card in deck[1:]:
q.put(q.get())
q.put(card)
result = []
while not q.empty():
... |
a03a000cd2c58876e69ae1e69d2c8dad01e4f120 | Katherinaxxx/leetcode | /20.valid-parentheses.py | 740 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/10/18 上午10:58
@Author : Catherinexxx
@Site :
@File : 20.valid-parentheses.py
@Software: PyCharm
"""
# 1、暴力:不断replace匹配的括号 O(n^2)
# 2、栈 左括号入栈 右括号与栈定元素匹配
class Solution:
def isValid(self, s: str) -> bool:
dic = {")": "(", "]": "[", "}": "{"} ... |
cce2e003f7cc825bfced7948aba1d12997a0ed5d | lazumbra/script-Learning | /Matplot_Tutorial_Series/legends_titles.py | 545 | 3.921875 | 4 | import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [5, 7, 4]
x2 = [1, 2, 3]
y2 = [10, 14, 12]
#A gente só usa label quando queremos imprimir legandas na
#figura.
plt.plot(x, y, label='First Line')
plt.plot(x2, y2, label='Second Line')
#Legendas e titulos devem ser colocados antes de plt.show()
#E depois de plt.plot(... |
97fcad5230366d2e7441a7f5dc520be917651590 | smbren/Data-Structures | /linked_list/linked_list.py | 1,461 | 3.71875 | 4 | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
retu... |
83271ca60a8a705d7fd7f940f16164dee62c188b | sanjayait/core-python | /03-Chapter 3/else_statement.py | 137 | 3.953125 | 4 | age=input("enter your age: ")
age=int(age)
if age>= 14:
print("you are verified")
else:
print("sorry,you cannot verified")
|
3a0bace41b9c5f45443538116a78b7d5782454a1 | cp1372/Project-Euler-Solutions | /problem 357.py | 1,269 | 3.734375 | 4 | '''Consider the divisors of 30: 1,2,3,5,6,10,15,30.
It can be seen that for every divisor d of 30, d+30/d is prime.
Find the sum of all positive integers n not exceeding 100 000 000
such that for every divisor d of n, d+n/d is prime.'''
threshold = 100000000
#Dynamic programming since if x div y then y has all... |
bd1b4ddc019f3afaf24a96747626a1fe0a2a3608 | Emmy1997/agglomerative_clustering | /sample.py | 655 | 3.6875 | 4 |
class Sample:
def __init__(self, s_id, genes, label):
"""
This constructor initiates sample
@:param s_id: sample's id
@:param genes: sample's list of genes
@:param label: sample's label
"""
self.id = s_id
self.genes = [x for x in genes]
... |
78905c74de5c53c4d574135e79896098209822da | kstseng/Algorithm_DataStructure_using_Python | /ch4_Recursion/towerOfHanoi.py | 642 | 3.828125 | 4 | def moveTower(height, fromPole, toPole, withPole):
if height >= 1:
moveTower(height - 1, fromPole, withPole, toPole)
moveDisk(fromPole, toPole)
moveTower(height - 1, withPole, toPole, fromPole)
def moveDisk(fp, tp):
print("moving disk from {} to {}".format(fp, tp))
moveTower(3, "A", "B... |
5d4a453bcf40220430355a3b862099193076cf48 | camohe90/-mision_tic_G1 | /s14/14.5.1_count_vocales.py | 292 | 3.640625 | 4 | vocales = "aeiou"
resultado = []
frase = input("Por favor ingrese la frase que desea que verifiquemos: ")
for vocal in vocales:
conteo_vocales = frase.count(vocal)
mensaje = f"En la frase hay {conteo_vocales} letras {vocal}"
resultado.append(mensaje)
print(resultado) |
56b486db6c1387d96e9fd560e03770372d3688f4 | Y0lan/Solid-Library-Kata | /menus.py | 3,601 | 3.546875 | 4 | from authentification import login
from library import show_all_books, search_book_by_title, search_book_by_author
from member import Member
from usertypes import UserTypes
def main_menu():
current_user = None
choice = 0
while choice not in [1, 2, 3, 4]:
print("\t1. Login")
print("\t2. Sig... |
3a9ab48eda2ac343f252ebca8c0d62b92308876a | TareqJudehGithub/coffee-machine | /main.py | 3,354 | 3.71875 | 4 | from time import sleep
MENU = {
1: {
# espresso
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
2: {
# latte
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
... |
d7221afc22f73208224786b8d6975ec4fdca2ffe | MarizzaM/QA-Architect-Python-Exercise_5 | /ex_16.py | 361 | 3.65625 | 4 | id = int(input('Please enter ID number of the Person: '))
name = input('Please enter Name and Last Name of the Person: ')
archive = {}
while id != 1:
archive.setdefault(id, name)
id = int(input('Please enter ID number of the Person: '))
if id == 1:
break
name = input('Please enter Name and Las... |
0db722a9a62484dbc135c85f7c7b12e903c89903 | ntamurejocolorado/Coursera | /Machine-Learning-with-Python/Week_2/Labs/Regression/MultipleLinearRegression.py | 3,005 | 3.703125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
from sklearn import linear_model
from sklearn.metrics import r2_score
class MultipleLinearRegression(object):
def __init__(self,df,cdf,train,test):
self.__number_of_rows = 9
self.__df = df
self.__cd... |
3672c1b03253c7ca4e47f3124c8363ed61a477f5 | qqqlllyyyy/LintCode-Python | /03-Binary-Tree-Divide-Conquer/17 Binary Tree Zigzag Level Order Traversal Show result.py | 2,241 | 4.21875 | 4 | # Binary Tree Zigzag Level Order Traversal
# Given a binary tree, return the zigzag level order traversal of its
# nodes' values. (ie, from left to right, then right to left for the next
# level and alternate between).
#
# Example
# Given binary tree:
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level ... |
0d2ff011b892bfb9e373023d46a2f886515bdf01 | madeibao/PythonAlgorithm | /PartA/PyDictAndZip.py | 136 | 4.03125 | 4 |
# 通过zip函数来创建一个字典的python方法。
dic = dict(zip('abc', [1, 2, 3]))
print(dic)
# {'a': 1, 'b': 2, 'c': 3} |
e15edc0aa6a8fe717cefb459c6cfe2a0b7480a81 | rock-feller/Python_Challenge_DSI_Program | /Python_Challenge_DSI_Program/Solutions/challenge7.py | 622 | 3.640625 | 4 | """author = Rockefeller""""
#the word is "congratulations"
#Here is the code:
from string import ascii_lowercase
def ceasar_cipher(size_of_alphabet , correct_shift):
encrypted_word= 'htslwfyzqfyntsx'
James_BagOfWords = []
for shift in range(size_of_alphabet+1):
counter = 0
... |
94d2b2946c0c2a2314f20e34999d19e74d60f9d0 | mikejaron1/zipfian | /12-interview-week/2-bfs-dfs/tree.py | 1,343 | 3.9375 | 4 | from Queue import Queue, LifoQueue
class Node:
def __init__(self, name):
self.name = name
self.children = []
def __str__(self):
return self.name
def bfs(root):
q = Queue()
q.put(root)
while not q.empty():
node = q.get()
print node
for child in node... |
63bfdba32719cd95b0fea90db4835109aba47a52 | enrico-kaack/JoogleDotLaw | /backend/funktion.py | 980 | 3.921875 | 4 | def einzelwortsuche(Text, Schlagwort):
Anzahl = -1 #da while Schleife immer mind. einmal durchlaufen wird
position = 0
#ende = len(Text)
while -1 != position:
position = Text.find(Schlagwort, position+1)
Anzahl += 1
return Anzahl
# Funktion, die ein Urteil (Suchergebnis) nach vord... |
f23501b6aafd1bf6fab805e840efb682a314c363 | Raubzeug/pugalo | /5pugalo.py | 1,519 | 3.765625 | 4 | #!/usr/bin/env python3
def get_data(filename):
numbers = []
try:
with open(filename) as fh:
for i in fh:
line=i.split(' ')
numbers.append(line)
return numbers
except EnvironmentError as err:
print(err)
class MyException(Exception):
... |
73d2afb98798da44d2f1b97a979993b74ccc5149 | knzh/Python | /py/while-if-break.py | 80 | 3.5 | 4 | n=1
while n<=100:
if n>50:
break
print(n)
n+=1
print('END')
|
adcb11e46fe97bbfcef039b5028a75ee516cb494 | MisMatRey/CodigoCursoPython | /Sesion 1/proyecto_S1.py | 1,062 | 4.15625 | 4 | print(" = = = Calculadora de interes = = = ")
#Ingreso de datos Variables
print("Ingresa el Nombre de la Tarjeta : ")
str_NombreTj = input()
print("Ingresa la Tasa de Interes : ")
str_Interes = input()
flo_Interes = float(str_Interes)
print("Ingresa la Deuda : ")
str_Deuda = input()
flo_Deuda = float(str_Deuda)
... |
357acc85c7f94a0b590f53745ed75ffa483fb770 | FLINKBLINK/arquivos-de-python-aleatorios | /Exercicios/Exercicio016.py | 148 | 4.15625 | 4 | import math
numero = float(input('Digite um numero quebrado: '))
print('A porção inteira do numero {} é {}!'.format(numero, math.trunc(numero)))
|
26ca9926f70904dbde2689d810b066820a29a616 | saumyajit2000/recursion | /recursion.py | 3,532 | 4.34375 | 4 | import random
import time
#FUNCTION FOR USING MERGE SORT------------
def mergeSort(numbers):
if len(numbers) > 1:
mid = len(numbers) // 2
left = numbers[:mid]
right = numbers[mid:]
# Recursive call on each half
mergeSort(left)
mergeSort(right)
#... |
3a8f656395c62b36c8ab1adb49b54d706c9ab097 | cnelsonsic/pyPetAndroid | /pet/nodes.py | 3,832 | 3.75 | 4 |
import pygame
class Node(object):
'''Node objects will only draw their children, and not themselves.
Child nodes will be drawn on top of the parent node.
There is no such thing as local coordinates.
'''
def __init__(self, name=""):
self.children = []
self.name = name
def draw(... |
f0917c4c257e27ce66d4d176d88700399387026e | john-maluki/singlylistinpython | /main.py | 1,686 | 4 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
self.tail = self.head
self.length = 1
def append(self, value):
new_head = Node(value)
self.tail.next = new_head
self.tail = new_hea... |
3740af793bf2c19234cabfb2b38883f84157277f | xymjeek/python | /python-7-day-Basics/4序列的应用/2列表/page9.py | 419 | 3.640625 | 4 | '''
verse = [['千','山','鸟','飞','绝'],['万','径','人','踪','灭'],
['孤','舟','蓑','笠','翁'],['独','钓','寒','江','雪']]
'''
arr = [] #创建一个空列表
for i in range(4):
arr.append([]) #在空列表中再添加一个空列表
for j in range(5):
arr[i].append(j) #为内层列表添加元素
print(arr)
arr = [[j for j in range(5)] for i in range(4)]
print(arr)... |
a5fa71490605fd7aa021813f096bf4732a7a8a94 | mimipeshy/pramp-solutions | /code/shortest_word_edit_path.py | 1,295 | 4 | 4 | """
Shortest Word Edit Path
Given two words source and target, and a list of words words, find the length of the shortest series of edits that transforms source to target.
Each edit must change exactly one letter at a time, and each intermediate word (and the final target word) must exist in words.
If the task is im... |
273a5cadfd8dd55329aa4c4db9e4d88188b282bb | DanielaZabaleta/programacion2021 | /Talleres/TallerClasesyObjetos.py | 2,438 | 4.03125 | 4 | #-----Punto 1-----#
print ('Punto 1')
class Torta ():
def __init__ (self, saborEntrada, alturaEntrada, formaEntrada):
self.sabor = saborEntrada
self.altura = alturaEntrada
self.forma = formaEntrada
def mostrarAtributos (self):
print (f''' Atributos de la torta
Su sabor e... |
8d59a8a81debc606d138847bb6fe3dadf02fe09b | TesterCC/Python3Scripts | /python_cookbook/ch01/1_9_find_dict_similarity.py | 1,259 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/8/3 10:37'
"""
1.9 查找两字典的相同点
问题:
怎么在两个字典中寻找相同点(如相同的值,相同的键)
解决方案:
在两字典的keys()或items()方法返回的结果上执行集合操作
字典keys()方法返回一个展现键集合的键视图对象。键视图支持集合操作,如集合并、交、差运算。
字典items()方法返回一个包含(键,值)对元素视图对象。
字典values()方法并不支持集合操作。如果非要操作则先将集合转换成set,然后再执行集合运算就行了。
"""
... |
922ed4a52c4d50be3b5768503e07a22228c814cb | Robbot/w3resourcesPython | /Basic/1_20/Ex18.py | 521 | 3.921875 | 4 | '''
Created on 2 kwi 2018
Write a Python program to calculate the sum of three given numbers, if the values are equal then return
thrice of their sum. So, for unequal numbers just a sum, but for equal number return a sum multiplied by three.
'''
x = int(input("Input the number : "))
y = int(input("Input the number : "... |
c00f64c879a41c4d65c70543d21cc7da501685b5 | Insua/python-learn | /004/006.py | 263 | 3.65625 | 4 | print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
f = lambda x: x * x
print(f)
print(f(5))
def build(x, y):
return lambda: x * x + y * y
print(build(8, 9))
print(build(8, 9)())
L = list(filter(lambda x: x % 2 == 1, range(1, 20)))
print(L)
|
b5f04aa905fdb97133430c8a0dd70b21c97e4e64 | SanjananSantosh/C106 | /correlation.py | 705 | 3.53125 | 4 | import csv
import pandas as pd
import plotly.express as px
import numpy as np
def getDataSource(data_path):
icecream_sales=[]
temperature=[]
df = pd.read_csv(data_path)
for row in df:
print(row["Ice-cream Sales( ₹ )"])
icecream_sales.append(float(row["Ice-cream Sales( ₹ )"])... |
ad1ee4bd4839afbdf09fed9148dda9c27b304921 | weiweizhang/tutorial | /L3/random_circle.py | 700 | 3.703125 | 4 | from turtle import *
from random import *
from time import *
setup(1.0, 1.0, 0, 0) # 画布大小
speed(0) # 最快速度画画
hideturtle() # 隐藏小海龟
bgcolor("black") # 画布背景
colormode(255) # 颜色模式RGB
def draw_circle():
# 设置随机的颜色
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
color((r, g, b))
# 随机的半径
... |
af243a672aec647e470783faf4d0edf34c9bcd7b | JuliaLes/gdi-intro-python | /class3.py | 2,845 | 4.40625 | 4 | # GDI Intro Python Class 3
# 7/26/16
# url for slides: http://byssystems.com/gdi/#/
def bostonize(word):
return('Wicked ' + word)
# Write a function that a bar could use to check to see if a customer is of drinking age.
def isDrinkingAge(age):
if age >= 21:
print("This customer is of drinking age.")... |
2ff522828614bcca47a5ad9bef3e27e2a3ab3adb | Isaac-Lee/Python-Projects | /lab7/projecy1_ver2.py | 5,875 | 3.90625 | 4 | import turtle
import random
# 사각형을 그리는 함수
def draw_sq(t, distance=400):
t.penup()
t.goto(-200, 200)
t.pendown()
t.pencolor('green')
for i in range(4):
t.forward(distance)
t.right(90)
t.penup()
t.goto(0, 0)
# 삼각형 터틀을 만들고 랜덤한 위치,랜덤한 방향으로 설정해 l_tri의 리스트에 저장하... |
43fe43a3655b0d520dc9777a5186b012f5ff093e | soaresdominic/ElevatorSearch | /hotel.py | 24,908 | 3.5625 | 4 | from elevator import elevator
from person import person
from floor import floor
from KnowledgeBase import KnowledgeBase
import heapq
import copy
class hotel:
def __init__(self,numFloors,numElevators,numPeople):
#floors are a list of 2 lists that contains 0-n elevators, 0-n people, secure boolean
#... |
650f9ecefe1b61520f9240a1f6a3fce23d395b56 | HOPExxp/QZ | /dayajichu/2019-7-1 文件 。。。.py | 3,445 | 3.90625 | 4 | #文件的操作,文件的写操作、open有三种打开方式,r-w-a,默认就是r-只能读,w--写的方式,
# a--叫做附加方式,进行文件的追歼,
# 添加文件内容的方式---有文件直接添加---没文件当前目录创建
class File1():
def __init__(self,filename):
self.filename = filename
with open(self.filename,'a') as file1:
for i in range(100):
file1.write("I am a Daya teacher,my C... |
901a7544dd11b0577ed81a02a1e6782293814c69 | OseiasBeu/data_visualization_matplotlib | /boxplot.py | 366 | 3.671875 | 4 | #Boxplot - Diagrama de caixas
#Visualização que mostra o quão dispersos estão os meus dados.
import matplotlib.pyplot as plt
import random #Gerar dados aleatórios
#vetor = [1,2,3,4,6,12,551,12,2]
vetor = []
for i in range(10):
numero_aleatorio = random.randint(0,5)
vetor.append(numero_aleatorio)
plt.boxplo... |
72d94b052f9e849319a3d6a2cca534957ceb5029 | creamboy/LeetCode | /Climbing Stairs/Climbing Stairs.py | 281 | 3.5 | 4 | class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
if n<0:
return 0
s=[0 for i in range(n+1)]
s[0]=1
s[1]=1
for i in range(2,n+1):
s[i]=s[i-1]+s[i-2]
return s[n]
|
1a61f46c6f12c58a5876322984965d6fcb3326ff | Digikids/App-Development-with-Python | /GUI/tempCodeRunnerFile.py | 157 | 3.90625 | 4 | def addation(num1, num2):
add = int(num1) + int(num2)
print("The sum of "+str(num1)+" and "+str(num2)+ " is "+str(add))
addation(2,3)
addation(56,4) |
4ad297b7b665e90e43accb9949ace3ecad17ad77 | kellyj40/textAnalytics | /TextAnalytics/Tutorials/tutorial5/Sorensen_dice_coeff.py | 1,014 | 3.578125 | 4 | base = ["storm ophelia hits ireland and schools close",
"hurricane ophelia hits ireland and schools close",
"hurricane ophelia misses england and work",
"hurricane ophelia hits cork and houses destroyed",
"tornado sarah hits usa and colleges close",
"there was a hurricane in Irel... |
2ea165f32b304c5973eb57b0698f324e98a06747 | kqg13/LeetCode | /Graphs/numIslandsReview.py | 1,933 | 3.578125 | 4 | # Graph problem 200: Number of Islands
# Given an m x n 2d grid map of '1's (land) and '0's (water),
# return the number of islands.
#
# An island is surrounded by water and is formed by connecting adjacent lands
# horizontally or vertically. You may assume all 4 edges of the grid are all
# surrounded by water.
clas... |
284b3629cec3f53ba646a7132bc81dc35e775226 | palakbaphna/pyprac | /Strings/10countMethod.py | 258 | 4.28125 | 4 | #This method counts the number of occurrences of one string within another string. The simplest form is this one: s.count(substring).
# Only non-overlapping occurrences are taken into account.
print('Abracadabra'.count('a'))
print('aaaaaaaaaa'.count('aa')) |
248f7c6745706ae333df30b68cdc96659847500d | sreedevik29/to-do-list | /to-do-script.py | 745 | 3.890625 | 4 | data = {}
active = True
while active:
activity = raw_input("Add an activity: ")
category = raw_input("What type of activity is this? ")
if data.keys().__contains__(category.title()):
data[category.title()].append(activity.title())
else:
data[category.title()] = [activity.title()]
... |
35f96df639c08601887284e1f85badc6d31046d9 | poojamalviya/ds-algo | /180_que/powerOfTwo.py | 394 | 3.703125 | 4 | def isPowerOfTwo(n):
_binary = getBinary(n)
# print str(binary)
binary = str(_binary)
for i in len(binary)-1:
if binary[-1] == 0:
return False
if i == 1:
return False
return True
def getBinary(n):
res = ''
while n>1:
rem = n%2
res = res... |
b05648226dada2840a390b547f77de331c266da7 | jodr5786/Python-Crash-Course | /Chapter 3/Ch3_testing.py | 58 | 3.5 | 4 | cars = ['bmw', 'audi', 'toyota','subaru']
print(cars[-1]) |
e4c14eba8a82d86f4a97b1afb74db014415c67b3 | gness1804/python-playground | /players.py | 280 | 3.8125 | 4 | titles = {
'Lebron James': 3,
'Dak Prescott': 0,
'Tom Brady': 6,
'Anthony Davis': 0,
}
def findWinless(obj):
'''Shows each player who has not yet won a title.'''
res = []
for player in titles:
if titles[player] == 0:
res.append(player)
return res
print(findWinless(titles))
|
c4a91a468b3c96852d1365870230b15433f8007c | RoshaniPatel10994/ITCS1140---Python- | /Quiz's/quiz 2/chips.py | 989 | 4.15625 | 4 | # Roshani Patel
# 2/10/20
# Chips
# This program Calculate the cost of an order of chips.
# Display program that will ask user how many bags of chips they want to buy.
#In addition ask the user what size of bag.
#If the bag is 8 oz the cost is 1.29 dollar if the bag is 16 oz then the cost is 3.59 dollars.
#If ... |
e53daa6175ff639249d8ff205da5097c06d0ce3e | ChrisMiller83/Functions | /smallest_num.py | 451 | 4.125 | 4 | # Write a function smallest that accepts a List of numbers as an argument.
# It should return the smallest number in the List.
def smallest_num(e):
return (e)
list1 = [200, 12, 33, 56, 7, 890, 0.1, -100]
list2 = [3, 22, 45, 2, 435, 67, 5, 89, -20]
final_list = list1 + list2
final_list.sort(key=smallest_num)
pri... |
922009af423e5bbec436f87afc3ae7056689b2be | shinchanaashi123/phython-1 | /introduction.py | 295 | 4.125 | 4 | introString=input("enter sentence")
characterCount=0
wordCount=1
for i in introString:
characterCount=characterCount+1
if(i==' '):
wordCount=wordCount+1
print("name of the word in sentence")
print(wordCount)
print("name of letters in sentence")
print(characterCount)
|
4f4651910424d636b2d8e3c92d683aaba6ef1970 | rdsguliani/python | /count_words/main.py | 1,702 | 3.84375 | 4 |
input = 'My name is raman and i am 24 years of age.'
dict = {};
vowel_dict = {};
def count_chars():
f = open("demo.txt", "r")
content = f.read();
#print(f.read())
for item in content:
if(item.isalpha()):
if item in dict:
dict[item] = dict[item] + 1;
... |
0a5b3884cb7c9a2e82568cbb8f500b0db0b6342e | roblivesinottawa/INT-Python | /map/main.py | 134 | 3.75 | 4 | list_ = [10,20,30,40,50]
# define a lambda function to every element in the list
list_ = list(map(lambda x: x**2, list_))
print(list_) |
f592c528cc556343c2b21f862735066411159b57 | evinpinar/competitive_python | /leetcode/72.py | 1,595 | 3.984375 | 4 |
def minDistance(word1, word2):
'''
This algo is known as "levenshtein" distance, used in spelling correction or
bioinformatics. We build up a matrix which represents the number of corrections
between each character of the word. Last element of this matrix gives the result.
'''
n, m = len(word... |
43bedbb5a8e6e51d36fac1259cbc63e8d0a5b87b | max180643/Pre-Programming-61 | /Onsite/Week-3/Thursday/Just Insert.py | 253 | 3.796875 | 4 | """Just Insert"""
def main():
"""Main Function"""
num = int(input())
box = []
for _ in range(num):
box.append(input())
insert = int(input())
text = input()
box.insert(insert, text)
print(box)
main()
|
d2adf7dd83a5d4f1fddad6d4be4b8afd7fac6b98 | SebastianAthul/pythonprog | /files/ques/objcreation.py | 368 | 3.609375 | 4 | class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def print(self):
print("name=",self.name)
print("age=",self.age)
def __str__(self):
return self.name
f1=open('athul','r')
for i in f1:
line=i.split(",")
name=line[0]
age=line[1]
obj... |
371690781ca8da4c270956210938efb0c69a5fca | yanshit/c-110 | /main.py | 453 | 3.515625 | 4 |
import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df=pd.read_csv("data.csv")
data=df["temp"].tolist()
dataset=[]
for i in range(0,100):
random_index=random.randint(0,len(data))
value=data[random_index]
d... |
a6f7bf9ca90764567c549ed83c112e4702bc50e4 | DanielBarcenas97/Python | /1.PythonBasico/2.VariablesyTipoDeDatos/OperadoresLogicosyRelacionales.py | 798 | 3.8125 | 4 | """
Creado por Edgar Daniel Barcenas Martinez
Proteco Gen 34. FI UNAM
Diciembre 23, 2017
"Operadores Relacionales y Logicos"
"""
#Operadores Relacionales
print (True == True)
print (False != True)
print (True == False)
print (False != True)
print (True > False)
print (True < False)
print(True * 3)
#Operadores Logi... |
11d79920bbf262c4b9b410a66ff1849712fe729a | victorchu/algorithms | /python3/string_array/valid_ip.py | 3,391 | 4.15625 | 4 | #!/usr/bin/env python3
"""
TASK:
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal
numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
Be... |
e715e68a88338ff054a9bdcdfc1af3c6f643fd74 | aprilyichenwang/small_projects | /coding_exercise/binarytree.py | 275 | 3.796875 | 4 | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
# given root node of a binary tree, evaluate whether tree or not
curr=root.data
|
cda8c59198050e83cde8102dcc0c775c9cbdd40e | mazoko/python | /06_文字列操作/test6-8.py | 713 | 4.15625 | 4 | # (8)クォート文字を含む文字列を作成
stringQ = "クォート(\")を含む文字列はこう作る!\r\nクォート(\")の前にバックスラッシュ(\\)!\r\nちなみに改行は「\\r\\n」!"
print(stringQ)
# (9)文字列を連結
string = "three"
string1 = "three" + "three" + "three"
string2 = "three" * 3
print("string1:" + string1 + "\r\nstring2:" + string2)
# (10)文字列をスライス
stringBfr = "四月の晴れた寒い日で、時計がどれも十三時を打っていた。"
... |
aeeee40a460bc9bc61c6eadbd34cf7ef20e784c2 | edwardmasih/Python-School-Level | /Class 11/11-Programs/edward (real and img root).py | 444 | 4.09375 | 4 | a=int(input("enter coefficient of x square "))
b=int(input("enter coefficient of x "))
c=int(input("enter constant value "))
r1=-b+(b**2-4*a*c)**1/2
if((in r1,(b**2-4*a*c)<0):
print("The Root is Imaginary")
else:
print("The Root is Real")
r2=-b-(b**2-4*a*c)**1/2
if((in r2,(b**2-4*a*c)<0):
pr... |
73f881da5cd426f52d76a024fd520c1ebca40b51 | Bennables/bensiri | /dictionary.py | 2,884 | 4.65625 | 5 | o#Dictonary's
#What is a Dictionary??
#Now let's go ahead a create one :)
# name_of_dictionary = {key : value, key : value, key : value, ...}
car_information = {"brand" : "Honda", "Model": "Civic", "year": 2017, "Color" : "red"}
print(car_information)
#How do we access specific items in our dictionary?
brand = c... |
5d6ac13c944736b609aec457ddea29687291246f | MarioCuCa/Programas-Basicos | /edad.py | 277 | 3.859375 | 4 | name = input("Hola, como te llamas? ")
print("Un gusto " + name.capitalize())
edad = input("Que edad tienes? ")
print("Genial, ya tienes "+edad)
nueva_edad = int(edad) + 2
print("Que rapido se pasa el tiempo")
print("Entonces tu edad en el 2021 sera de",nueva_edad) |
10a6f8b25df49c6a812393824c1c081f83364575 | defufna/UrbanKombat | /template_utils.py | 865 | 3.8125 | 4 | _num_names = ["one", "two", "three", "four", "five"]
def count(i):
if i < 1:
raise ValueError("only numbers greater than zero are supported")
if i > len(_num_names):
return str(i)
return _num_names[i-1]
collective_nouns = (
(5, "group"),
(10, "mob"),
(25, "horde")
)
def collec... |
1e7146dc1f7400cb66ae368c242d10b15bd429c9 | AlexanderKornev/Public | /self_made/kanobu.py | 1,834 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import random
while True:
user_input = input('Введите: камень, ножницы или бумагу: ')
list = ['камень', 'ножницы', 'бумага']
x = random.randint(0, 2)
# TODO, на подумать. Предлагаю вывод результата произвести в самом конце. Пример шаблона вывода и заполнения.
# таким образо... |
0c4888bbde12585013af3cba5157da134ee1023c | shen-huang/selfteaching-python-camp | /exercises/1901010092/1001s02e05_array.py | 404 | 3.515625 | 4 | #翻转数组
a=[0,1,2,3,4,5,6,7,8,9]
a.reverse()
print(a)
#拼接字符串
b=''.join(str (i) for i in a)
print(b)
#用字符串切片的方式取出第3到第8个字符(包含第3和第8字符)
c=b[3:9]
print(c)
#将获得的字符串翻转
print(c[::-1])
#将结果转换为int类型
d=int(c)
print(d)
#分别转换为二进制、八进制、十六进制
print(bin(d))
print(oct(d))
print(hex(d))
|
54fabfb377ba9528a0188c34db92bb8ce586e455 | TrainingByPackt/Python-Fundamentals-eLearning | /Lesson07/sentenceAnalyzer.py | 934 | 3.515625 | 4 | text = """
The programming language Python was conceived in the late 1980s, and its implementation was started in December 1989
by Guido van Rossum at CWI in the Netherlands as a successor to ABC capable of exception handling and interfacing with
the Amoeba operating system. Van Rossum is Python's principal author, an... |
926a2f8dcd1e1e77573a720e724a4e55282a443d | wasifsarwar/python-exercises | /small exercises /prep23.py | 222 | 3.546875 | 4 | import string
def every_other(text):
text_split = text.split()
index = 0
result = ""
while index < len(text_split):
result += text_split[index] + " "
index += 2
return result.lstrip()
|
e9d90eb1da063603d11769bd992319b008a033c6 | PavelVdovinKZN/python-project-lvl1 | /brain_games/games/brain_calc.py | 642 | 3.984375 | 4 | #!/usr/bin/env python
from random import randint, choice
import operator
TASK_DESCRIPTION = 'What is the result of the expression?'
FIRST_NUMBER = 1
SECOND_NUMBER = 10
operators = {
'+': operator.add,
'*': operator.mul,
"-": operator.sub,
}
operator_symbols = list(operators.keys())
def get_game_round():... |
d6159b54ca186ae27f3c3bd2773bcc0851c02072 | JardelBrandon/Algoritmos_e_Programacao | /Atividades/Roteiro 5 - While/Programas/Roteiro 5 Questão 1 a).py | 711 | 3.9375 | 4 | #1. Analise o algoritmo abaixo e informe quais resultados serão exibidos na saída padrão (para cada
#algoritmo acompanhe os valores das variáveis usando umatabela tal como no exemplo abaixo):
# a)
#cont = 0
#soma = 0
#while (cont < 10):
#soma = soma + 2
#cont = cont + 1
#print(“Valor de soma é:\n ”, soma)
#iteração... |
71632dddc0e59eb8ec953e2ec8c07b4c077fe5d0 | Vinaypatil-Ev/DataStructure-and-Algorithms | /4.Queue/Python/queue.py | 1,121 | 4.0625 | 4 | class Queue:
def __init__(self, size):
self.size = size
self.front = -1
self.rear = -1
self.arr = [None] * size
# check if queue is full
def is_full(self):
return self.rear == self.size
# check if queue is empty
def is_empty(self):
return self.fro... |
30dddf2a27873a84b51f451cd4dcc43c202bf414 | kammitama5/Distracting_KATAS | /bigfactorial.py | 208 | 3.9375 | 4 | def factorial(n):
total = 1
if n < 0:
return None
if n == 0:
return 1
else:
for i in range(2, n+1):
total = total * i
return total
|
b682beb91557c195909f4f9043cc43e9b2105694 | Tarun-coder/Data-science- | /functionq 2.py | 427 | 4.21875 | 4 |
print("----------------------------Multiply all num in list--------------------------")
def mullist():
a=int(input("Enter the size of the list: "))
li=[]
for i in range(a):
nub=int(input("Enter the Element: "))
li.append(nub)
print("The sample list is:",li)
mul=1
for i in li:
... |
788f2b9896444c21bacf7151c09fcbe25e4fcfe4 | hsubox/algorithm-design-analysis | /week_6/assignment6-1.py | 1,062 | 3.75 | 4 | def load_file(file_to_open):
file = open(file_to_open)
lines = file.read().split('\n')
hash_table = set();
for line in lines[:-1]: # file ends with line break
number = int(line)
hash_table.add(number)
file.close()
return hash_table
file = "algo1-programming_prob-2sum.txt"
hash_t... |
5f829c131dcfc9273bf2458950bea4ef008ee5d2 | andyzhangyn/Secret-Garden | /thresholding.py | 406 | 3.53125 | 4 | from PIL import Image, ImageFilter
def thresholding(image_name):
im = Image.open(image_name)
pix = im.load()
for w in range(im.width):
for h in range(im.height):
if pix[w, h][0] > 191:
pix[w, h] = (255, 255, 255)
else:
pix[w, h] = (0, 0, 0)
... |
b7d8013fa738f9df8f1cfe1345f19e39dfdb25e6 | juanrobayo97/Proyecto1 | /main.py | 1,083 | 3.953125 | 4 | # This is a sample Python script.
# Press Mayús+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
import math
import random
def mcd(n1, n2):
if (n1 > n2)... |
8ae47c293ca413d9af992cb5809e8a331c6cceab | dhmk083/l-systems | /draw.py | 4,023 | 3.640625 | 4 | import tkinter as tk
from turtle import RawTurtle, TurtleScreen, ScrolledCanvas
from functools import partial
def get_turtle():
class MyTurtle(RawTurtle):
def __init__(self, canvas):
super().__init__(canvas)
self.bbox = [0, 0, 0, 0]
def _update_bbox(self):
pos ... |
aba3dc7f2d8d7ba3afc75490f7bfc7c244c70e19 | karolow/geocoder | /geocoder/fuzzymatching/fuzzymatching.py | 480 | 3.5625 | 4 | import fuzzyset
def build_fuzzyset(collection: dict):
"""Prepare a fuzzy set based on provided mapping"""
keys = {x for x in collection.keys()}
return fuzzyset.FuzzySet(keys, use_levenshtein=False)
def find_match(phrase: str, fuzzy_set, return_top_match=True):
"""Find match(es) between the search ph... |
b7997cda85be38699220e30e1b950db641d799ca | niranjan-nagaraju/Development | /python/algorithms/dynamic_programming/max_nonadjacent_subarray_sum/max_nonadjacent_subarray_sum_bruteforce.py | 2,830 | 3.765625 | 4 | #encoding: utf-8
'''
https://www.hackerrank.com/challenges/max-array-sum/problem
Max Array Sum
Given an array of integers, find the subset of non-adjacent elements with the maximum sum. Calculate the sum of that subset.
For example, given an array arr = [-2,1,3,-4,5], we have the following possible subsets:
Subset... |
f176190644a5250d39533c80f02efc0fded82840 | zzz136454872/leetcode | /maxLevelSum.py | 877 | 3.546875 | 4 | from typing import Optional
from pytree import TreeNode
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
nxt = [root]
maxSum = -10**10 - 1
maxLevel = 0
level = 0
while len(nxt) > 0:
level += 1
tmp = nxt
nxt = []
... |
1ae6216d0bbaa0e0ee522d5f6e8130e99bb0478e | chunjiw/rabbit-coding | /reverseStr.py | 749 | 3.6875 | 4 | class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
if not s or len(s) == 1:
return s
s = list(s)
start = 0
while start + 2 * k <= len(s):
self.reverse(s, start, start + k)
... |
16d0a246562824568215be7b9503dfa518a25852 | WallaceCheny/pyann | /tests/perceptronDemo.py | 1,085 | 3.640625 | 4 | from network.perceptron import perceptron
from matplotlib.pylab import *
#predict data label just a joke,and we do not use unittest module to do it.
print 'test 1: predict data label'
p = perceptron(1)
p.init()
p.train([[-0.4, 0.9, 1], [-0.5, 0, 1], [0.6, 0.1, -1]])
print 'predict label of the data is:%d'% p.expected(... |
b5afeb931c28203c4afe089ef01c0a669695e7be | zzz136454872/leetcode | /Trie.py | 1,687 | 3.703125 | 4 | class TreeNode:
def __init__(self):
self.has = False
self.sons = [None] * 26
def l2n(a):
return ord(a) - ord('a')
class Trie:
def __init__(self):
self.root = TreeNode()
def insert(self, word: str) -> None:
p = self.root
for letter in word:
n = l2... |
c88ef4a21afafcca8432640ec16f0a4e2d82d5c1 | omar16100/tendies | /full_functionality/LayerInjector.py | 8,654 | 3.734375 | 4 | import math
import tensorflow as tf
class LayerInjector:
""" Contains layer injection functions for ServerBuilder. These layers
are used for preprocessing and postprocessing.
Each preprocessing function must take as arguments serving input
(usually an image bitstring), channels and *args,... |
e5fce391f619049cbcc2b96006f044d265f0b7d1 | mayank2004-m/Library-Managment-System-in-Python-using-OOPS | /index.py | 4,211 | 4.15625 | 4 | # This a library managment system
# In This Library Managment System will return ,lend , borrow books
# Also data will be added in a seperate file
# First I will discuss the logic of the code I'll write below
# Here we will make a class library that will take two arguments the booklist and name
# of the library
# Fu... |
405d1b80d6839e500889d7065cb14da5b15ba564 | inergoul/boostcamp_peer_session | /coding_test/64065_튜플/solution_anna.py | 438 | 3.71875 | 4 | def solution(s):
answer = []
arrays = []
arr = []
si = 1
for i in range(1, len(s) - 1):
if s[i] == '{':
si = i
if s[i] == '}':
arr.append(s[si + 1:i])
for a in arr:
arrays.append([int(num) for num in a.split(',')])
arrays.sort(key = len)
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.