blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
55b00d4ec187dfd88f71584ce85af1b217af704c | frankieliu/problems | /leetcode/python/ListNode/ListNode.py | 714 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x=None):
self.val = x
self.next = None
self.label = x
self.random = None
def __repr__(self):
out = []
out.append(str(self.val))
head = self.next
while head:
out.ap... |
d5f8d17e402d580bd4e305071def1cb02cb91fad | a1exlism/HackingSecretCiphersWithPy | /Transposition/BruteForce/detectEnglish.py | 1,367 | 3.5 | 4 | import sys
def load_dictionary():
# load English dictionary alpha means all letters
w_obj = open('words_alpha.txt')
dict_eng = {}
for word in w_obj.read().split('\n'):
dict_eng[word] = None
w_obj.close()
return dict_eng
def transform_letter(msg):
UPPER_LATTER = 'ABCDEFGHIJKLMNOPQ... |
c803ba5e9859c23727d3237a03a9716d838c53f5 | PerseuSam/FATEC-MECATRONICA-0791811039-SAMUEL | /LTPC2-2020-2/Prova/exerci3.py | 938 | 4.09375 | 4 | temperaturas = []
continuar = True
while continuar == True:
temperatura = int(input("Temperatura que deseja informar: "))
temperaturas.append(temperatura)
if input("Deseja continuar (s/n)? ") == 's':
continuar = True
else:
continuar = False
valor_limiar = int(input("Digite um valor limiar(média): "))... |
a6bed297fe9e4494999191684baa3e96eec4ac46 | farhasalim/hacktoberfest2021-1 | /Python/Fractal Tree/Fractal_Tree.py | 558 | 3.59375 | 4 | import turtle
import math
import random
t = turtle.Turtle()
t.screen.bgcolor("black")
t.pensize(2)
t.color("brown")
t.penup()
t.left(90)
t.backward(250)
t.pendown()
t.speed(0)
def start(x):
if x < 10:
return
else:
t.forward(x)
t.right(30)
t.color("red")
... |
29b694500f92a03f4bbff521c65cb69ec0fd7051 | pedrovs16/PythonEx | /ex115Library/home.py | 2,208 | 3.703125 | 4 | def inicio():
print('\033[33m=' * 60)
print('MENU PRINCIPAL'.center(50))
print('=' * 60)
print('\033[34m1\033[m - \033[35mCadastrar nova pessoa\033[m')
print('\033[34m2\033[m - \033[35mVer pessoas cadastradas\033[m')
print('\033[34m3\033[m - \033[35mSair do Sistema\033[m')
print('\033[33m=\0... |
e82cc502cba9ed5151594e5a9b9248e97fa9f53d | arvakagdi/UdacityNanodegree | /LinkedLists/LinkedListModified.py | 5,858 | 3.921875 | 4 | '''
Linked lists with multiple functionality
'''
class Node:
def __init__(self,value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self,value):
if self.head is None:
self.head = Node(val... |
46e48a40dae7276ff2a04870329f2e464887f17a | igorlongoria/python-fundamentals | /03_more_datatypes/2_lists/03_09_flatten.py | 335 | 3.828125 | 4 | '''
Write a script that "flattens" a list. For example:
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
flatten_list = []
for sublist in starting_list:
for item in sublist:
flatten_list.append(item)
print... |
d2cd8e8db4cb5848cfcd74b43bb3ec68d15410fc | escm1990/PhythonProjects | /Tareas/T5_Ejercicio1.py | 355 | 3.859375 | 4 | #Ejercicios de concatenación
print("-----EJERCICIO 1-------")
cadena = "Bienvenidos al curso de Python"
cambio = "b" + cadena[1:]
print(cambio)
#############################
print("\n\n-----EJERCICIO 2-------")
cadena2 = "esto es un texto"
numero = 777
cambio2 = "Hola. E" + cadena2[1:] + " y le contateno el núm... |
991416e1a143f742350427150c6c293c87e6ead1 | Xolani96/search_base | /05_nqueens_exercise.py | 12,969 | 3.890625 | 4 | """The n queens puzzle: put down n queens on an n by n chessboard so no two
queens attack each other.
The state will be the whole chessboard in these exercises to make implementation
easier.
Implement the BT1 search first, then the two additional state spaces.
"""
from enum import Flag
import copy
from functools i... |
66301bd070f5daa788007dfc888275116155cc48 | whitefly/leetcode_python | /链表/92_reverse_linked_list_ii.py | 1,271 | 3.75 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
思入: 和反转链表差不多, 在反转链表的基础上要进行收尾连接.
先到需要反转的首节点上,反转完... |
753b86f21a1a32dc6cd70ef192082543ef71f83b | jriall/leetcode | /easy/monotonic_array.py | 801 | 4.3125 | 4 | # Monotonic Array
# An array is monotonic if it is either monotone increasing or monotone
# decreasing.
# An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
# An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
# Return true if and only if the given array nums is mono... |
750b2af56d173f32973df187e39d02de498a5005 | yungjoong/leetcode | /20.valid-parentheses.py | 1,554 | 3.890625 | 4 | #
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (38.24%)
# Likes: 4571
# Dislikes: 207
# Total Accepted: 936.3K
# Total Submissions: 2.4M
# Testcase Example: '"()"'
#
# Given a string containing just the cha... |
247cedce1dd2fe23bb90357048bf5856adc2c07d | jayantraj66041/python-calculator | /python-calculator/calculator design.py | 4,227 | 3.8125 | 4 | import tkinter
from tkinter import *
root = tkinter.Tk()
root.title("Jayant's Calculator")
root.minsize(440, 505)
root.maxsize(440, 505)
top = Frame(root, width=400, height=150, bg="black")
top.pack(fil=X)
num = IntVar()
sum = ""
def clear():
global sum
#num.set(0)
form.delete(0,END)
sum... |
da376b2371aaf992f321d37f8e83881d3b384a3a | csiggydev/crashcourse | /3-1_names.py | 193 | 3.578125 | 4 | #! /usr/bin/env python
# 3-1 Names
names = ['Mike', 'Jason', 'Matt']
print(names)
# Print Mike only
print(names[0])
# Print Jason only
print(names[1])
# Print Matt only
print(names[2]) |
763e10cbeb85e0a00e6d8bbea2c4a139845202d9 | shadowflush/my_LeetCode | /findMedianSortedArrays.py | 1,439 | 3.953125 | 4 | def median(nums1, nums2):
len1, len2 = len(nums1), len(nums2)
if len1 > len2:#make sure len(nums1)<=len(nums2)
nums1,nums2,len1,len2 = nums2,nums1,len2,len1
if len1 == 0:# if one list is empty
if len2%2:
return nums2[len2//2]
else:
return (nums2[len2//2]+nums2... |
eb101b948b5209b0e6af3757cf74d8bf92b3b18f | danilosp1/Exercicios-curso-em-video-python | /ex044.py | 476 | 4.03125 | 4 | val = float(input('Qual o valor do produto? '))
print('Digite a forma de pagamento:')
print('[1] À vista no dinheiro')
print('[2] À vista no cartão')
print('[3] Até 2x no cartão')
print('[4] 3x ou mais no cartão')
tip = int(input('Qual sua opção de pagamento? '))
if(tip == 1):
pagamento = val*0.9
elif(tip == 2):
... |
579137ee63152401b0cae5e3f564c378ad4f5d29 | EyesMcKinney/Python-Projects-CS1 | /lab08/train_run.py | 2,199 | 4.09375 | 4 | """
file: train_run.py
by: Isaac McKinney
runs a simulated train yard based off a serious of user inputted commands
"""
from command_list import *
def process_commands(command, train):
"""
process the inputted command
pre-condition: command has been passed in as an input and a train h... |
b94a4c99cfd1c0dea043afd9452ade2ef29552d6 | falcon97/wallbreakers | /Week 2/Hashmaps and Sets/word_pattern.py | 367 | 3.703125 | 4 | class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
s = str.split()
return len(set(zip(pattern, s))) == len(set(pattern)) == len(set(s)) and len(pattern) == len(s)
if __name__ == "__main__":
solution = Solution()
pattern = "abba"
str = "dog cat cat dog"
out = sol... |
21b4af045fa440a952e5b7f62e6a1b49f8cb40d4 | beidou9313/deeptest | /第二期/北京-辉色秋天/day-2/day2-convert.py | 197 | 3.71875 | 4 | # -*- coding:utf-8 -*-
if __name__ == "__main__":
x = 1.68
y = 10
print("整数为%d"%int(x))
print("浮点数为%f"%float(y))
print("复数为", end='')
print(complex(x))
|
e65dfe0b108b098789b0dd1f95ab923c7de06970 | Acc-one/vsu_programming | /3.2 .py | 236 | 4.09375 | 4 | a = int(input('Введите номер месяца: '))
if 0 < a < 3 or a == 12:
print('Зима')
elif 2 < a < 6:
print('Весна')
elif 5 < a < 9:
print('Лето')
elif 8 < a < 12:
print('Осень')
|
972214935177b10614e04d0c5928da6eded6bc28 | lvrcek/advent-of-code-2020 | /day19/1.py | 1,749 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 19, Part 1
"""
from time import time
memo = {}
def parse(f):
d = {}
for line in f:
line = line.strip()
if len(line) == 0:
return d
rule_num, rest = line.split(':')
rule_num = int(rule_num)... |
0f74f85526b5d961c800d4334ace72176b7a1853 | anoopkcn/meeseeks | /meeseeks/format.py | 1,910 | 4.59375 | 5 | def to_string(list, sep=' '):
'''returns a list without brakets[]
For using python list's in other programs
Arguments:
a {list} -- one dimensional list
Example:
>>> a = [1,2,3,4,5]
>>> print(strip(a))
>>> 1 2 4 5
'''
return f'{sep}'.join(map(str, list))
def with_commas(N... |
2a00e1e90af48761b0f676057bb355ad46533f42 | ArshSood/Codechef_Assignment | /PEC2021C/lineartime.py | 237 | 3.65625 | 4 | n = int(input())
set={""}
for i in range(0, n):
x = int(input())
set.add(x)
set.remove("")
q = int(input())
print("1")
for i in range(0, q):
x = int(input())
if x in set:
print('yes')
else:
print('no') |
9657dd8cbef2614a646d155955744ffe90e34fcd | billakantisandeep/pythonproj | /Files/file2.py | 576 | 4.09375 | 4 | #This program demonstrates the closing of the file without using the f.close()
#Using the context managers -- Which will help inclosing
#Within the context manager
with open('C:\\Users\\sbillakanti\\pythonlearning\\Files\\test.txt', 'r') as f:
f_contents = f.read()
print(f_contents)
print(f.name) #To open... |
4793cc0ff2a53bc044ca6cac1a3ab6c8629ba75e | zhaobe/splinter-dev | /quick-tut.py | 631 | 3.734375 | 4 | # creating the browser instance
from splinter import Browser
browser = Browser('chrome')
# going to google.com
browser.visit('http://google.com')
# input search for splinter - python acceptance ...
browser.fill('q', 'splinter - python acceptance testing for web applications')
# find the search button and click it
b... |
041271b7c348bf52176a78b4b64ba7f2e2d8c2d2 | liuyuzhou/ai_pre_sourcecode | /chapter4/dict_list_df_3.py | 257 | 3.703125 | 4 | import pandas as pd
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
df_1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
print(df_1)
df_2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df_2)
|
a4cdf65a3cd5f1eff76e47e29e498b911e000d58 | itsuna/Python-matplotlib-Usage | /angle_distribution_plot.py | 5,193 | 3.671875 | 4 | # モジュールをインポートする
# 数値計算を効率的に行う"numpy"というモジュールを"np"という名前でインポート
import numpy as np
# データ解析をサポートする"pandas"というモジュールを"pd"という名前でインポート
import pandas as pd
# グラフ作成に必要な"matplotlib"の中の"pyplot"を"plt"という名前でインポート
import matplotlib.pyplot as plt
# グラフにしたいデータの入っているExcelファイル("angle_distribution_ex.xlsx)の場所と名前を入れる
excel_path =... |
e2189990028d9fefc53eb4f656cba7af62e16f11 | taoranzhishang/Python_codes_for_learning | /study_code/Day_03/5多个数据输入和交互赋值数据交换.py | 210 | 3.953125 | 4 | num1, num2, num3 = input("请输入:") # 依次输入三个数,用逗号隔开
print(num1, num2, num3)
# 不引入中间变量实现交换
a, b, c = 1, 2, 3
print(a, b, c)
a, b, c = c, b, a
print(a, b, c)
|
f494735911e12b17f7b38e16312ec3989cad10f9 | fafaovo/python | /p127-tuple.py | 444 | 4.1875 | 4 | # 元组:可以存储多个数据,但是不能修改
tuple1 = (10, 20, 30)
print(tuple1)
tuple2 = (19,)
# 使用元组存储单个要在后面添加一个逗号
# 下标 index count len [通用方法]
# 元组中有列表,这个列表是可以修改的,一个列表里面有个元组,里面的元组不可修改
tl1 = list(tuple1)
tl1[0] = 30
tuple1 = tuple(tl1)
print(tuple1)
# 如果需求修改元组可以把他转换成列表进行修改
|
0355a47aba19239733d448d96063595597b18023 | anupivan/anup | /dicegame2.py | 155 | 3.875 | 4 | #dicegame
import random
while True:
i=input("enter r to roll or q to quit")
if(i=='r'):
print(random.randint(1,6))
else:
print("bye!")
exit()
|
5bfe083845d9622557f31675d25782fb7d6cc544 | knuu/competitive-programming | /hackerrank/unkoder/unkoder06_tera.py | 166 | 3.5625 | 4 | N = list(input())
flag = False
for i, n in enumerate(N):
if flag:
N[i] = '9'
elif n == '4':
flag = True
N[i] = '3'
print(''.join(N))
|
f37da08cf483fcb92d3cef28d52a510f128564ad | malaybiswal/python | /hackerrank/bigsorting.py | 211 | 3.765625 | 4 | n = int(input().strip())
unsorted = []
unsorted_i = 0
for unsorted_i in range(n):
unsorted_t = str(input().strip())
unsorted.append(unsorted_t)
unsorted.sort(key = int)
for val in unsorted:
print(val)
|
f6c418fbc9348d342328e8aba17cbd643f19e2d0 | smohamed7/pythonbasics | /passwordsettingtask.py | 426 | 4.25 | 4 | #An application that asks a user a string password
#if the characters are less than five print too short
#if the characters are greater than five show too long
password = str(input("type in your password:"))
if len(password)<5:
print("yours password is too short")
elif len(password)>15:
print("password too lo... |
db862addc2f5ed63335276eddbbf2723a46f511c | WhiskeyKoz/self.pythonCorssNave | /script/nave941.py | 1,220 | 4.28125 | 4 | from collections import Counter
def choose_word(file_path, index):
"""
the function return tuple of The number of different words in the file
that is, does not include repetitive words and word in index was the function was collected
:param file_path: path to txt file
:type: str
:param in... |
8683a4ff6f286a04f1d49df1783387580b012d97 | Samrat132/Printing_Format | /Lab3/fizz_buzz.py | 614 | 4.1875 | 4 | #Write a function called fizz_buzz that takes a number.
# If the number is divisible by 3, it should return “Fizz”.
# If it is divisible by 5, it should return “Buzz”.
# If it is divisible by both 3 and 5, it should return “FizzBuzz”.
# Otherwise, it should return the same number.
def fizz_buzz():
for fizz_buzz in... |
90f25bb9a3eee9abbc42a5acce5c254bbe634ad7 | Tonestheman95/Python | /bankaccount.py | 875 | 3.796875 | 4 | from fundamentals.oop.userswithbankaccount import Tonio
class Bankaccount:
def __init__(self,interest_rate = 0, balance = 0):
self.interest_rate = interest_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(self.balance)
re... |
b5f0082f71fa6f494151141960e495bbe402b8d6 | j471n/Hacker-Rank | /30 Days of Code/7-Arrays.py | 495 | 4.125 | 4 | if __name__ == '__main__':
n = int(input())
#initializing array/list which will take input with spaces
arr = list(map(int, input().rstrip().split()))
arr.reverse() #to reverse the array
#we are using loop to print the array
for x in range(len(arr)):
print(arr[x... |
52949e98dab2ff3210167666b56603f88b4f2565 | brdayauon/Competitive-Coding-11 | /reversePolishNotation.py | 1,212 | 3.734375 | 4 | # Time Complexity : O(N)
# Space Complexity : O(N)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
#array of strings
def getVal(arr):
if not arr:
return 0
stack = []
#assume a... |
4de56ac10a8ff41785076352726087816a520cb8 | hk1486/Python_master | /06_01_str.py | 3,501 | 4.15625 | 4 | # 문자열 함수들
# 대표적으로 문자열(str)은 많은 함수(메소드)들을 갖고 있습니다.
# str 의 대표적인 함수들 ==> split, join, replace, format
# https://docs.python.org/3/library/stdtypes.html#textseq
# upper(), lower() 대소문자 변환
str1 = 'apple'
print(str1, str1.upper(), str1.lower())
# str.join(), str.split() ---> 03_02 참조
#-------------------------------... |
5e788077cb8480207acf3bf622b3f914f7bde9f6 | r4inm4ker/Kraken | /Python/kraken/core/maths/vec3.py | 12,439 | 3.515625 | 4 | """Kraken - maths.vec3 module.
Classes:
Vec3 -- Vector 3 object.
"""
import math
from kraken.core.kraken_system import ks
from math_object import MathObject
class Vec3(MathObject):
"""Vector 3 object."""
def __init__(self, x=0.0, y=0.0, z=0.0):
"""Initializes x, y, z values for Vec3 object."""
... |
0560c4b586cb481be5999ad8aa7d2721ac9c648e | ZuoQA/secure-svm | /test/test_time.py | 183 | 3.53125 | 4 | import datetime
a = datetime.datetime.now()
for i in range(5000):
for i in range(5000):
s = i * 2
b = datetime.datetime.now() - a
print(b)
print(b.seconds, b.microseconds) |
d81fd98be32ea6951833a77a1cba685be62e9ebb | Iam-El/Random-Problems-Solved | /NEW_FINAL_SYSTEM_DESIGN/FILE_SYSTEM.py | 1,830 | 3.609375 | 4 | class Folder:
def __init__(self, name, parent=None):
self.name = name
self.path = "/" + name
self.parent = parent
def set_name(self, name):
self.name = name
def set_path(self, path):
self.path = path
def get_name(self):
return self.name
def get_pat... |
557bc4a8e2c39c22b4d12dbecd4faea5e43356f8 | Yaoaoaoao/LeetCode | /algorithms/125_valid_palindrome.py | 687 | 3.671875 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# discussion implement
# str.isalnum()
# return newS == newS[::-1]
s = filter(lambda x: 48<=ord(x)<=57 or 97<=ord(x)<=122, list(s.strip().lower()))
if... |
60ece6ba18f4212296142ad037079464947c7044 | leoCardosoDev/Python | /1-Curso-em-Video/01-Fundamentos-Python/03-Operadores-Aritimetico.py | 559 | 3.8125 | 4 | # 1 => ()
# 2 => **
# 3 => * / // %
# 4 => + -
n1 = int(input('Um valor: '))
n2 = int(input('Outro Valor: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
sb = n1 - n2
rd = n1 % n2
di = n1 // n2
ex = n1 ** n2
print('A Soma(+) vale: {}'.format(s))
print('A Multiplicação(*) vale: {}'.format(m))
print('A Divisão(/) vale: {:.... |
64990c5d8afe04cbff853e0944fe410bed0ebd20 | CHAKFI/Python | /TP3/Ex2/ex2.2.py | 230 | 3.78125 | 4 | print('Programme de resoudre l_équation de type ax+b = 0')
I = input('Veuillez entrer la valeur de a \n')
a = int(I)
L = input('Veuillez entrer la valeur de b \n')
b = int (L)
x = -b/a
print('La solution de l_équation est : ',x) |
d01b2e77f4efda8ffd277637c72c46f3f050d4bd | lhj0518/shingu | /11월3일 수업/list2.py | 471 | 3.640625 | 4 | color = ['red','blue','green']
color2 = ['orange','black','white']
print color + color2
len(color)
color[0] = 'yellow'
print color*2
'blue' in color2
total_color=color+color2
for each_color in total_color:
print each_color
color.append("white")
color.extend(["black","purple"])
color.insert(0,"orange")
print color
... |
24945c81ba140d8b6914671db114762b433b7805 | nbiadrytski-zz/python-training | /oop_coreyschafer_tutorial/decorators_getter_setter_deleter/decorator_getter_setter_deleter.py | 885 | 3.8125 | 4 | class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
# email() is defined as method, but with @property decorator
# we can access it as attribute, so
# emp_1.email is a valid call
@property
def email(self):
return "{}.{}@company.com".form... |
46df754b3ae97d2a8b766f345112681b3dd0f5a0 | IliaLiash/python_start | /code_review/code_review_1.py | 515 | 3.5625 | 4 | #Number of non-negative numbers in the sequence and their product
#Before
'''
count = 0
p = 0
for i in range(1, 10):
x = int(input())
if x > 0:
p = p * x
count = count + 1
if count > 0:
print(x)
print(p)
else:
print('NO')
'''
#After
count = 0
p = 1
for i in range(1, 11):
x... |
8d28b180e0a16f0b786001d9817aa545dae4382b | MaksimKatorgin/module17 | /task6.py | 589 | 4 | 4 | #Дан список из N целых чисел. Напишите программу, которая выполняет «сжатие списка» — переставляет все нулевые элементы
#в конец массива. При этом все ненулевые элементы располагаются в начале массива в том же порядке. Затем все нули из списка удаляются.
from random import randint as ri
l = [ri(-5, 5) for i in ran... |
99a3ab6b72dac716899ab303b3f14665f057a91b | philippezwietering/practicum-atp | /assignments/assignment1_3_1.py | 2,283 | 3.671875 | 4 | from unittest import *
import doctest
import io
from contextlib import redirect_stdout
def function_to_unittest(list):
ordered = []
for item in list:
if item < 0:
item *= -1
item += 1
if item % 2 == 1:
if not is_prime(item):
c... |
7343499cf6653e12a4e61a8fcf12b67710b67597 | JacksonYu92/basic-calculator | /main.py | 562 | 4.21875 | 4 | def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
}
num1 = int(input("What's the first number?: "))
num2 = int(input("What's... |
d8e33788ee365ff0e993400b2ad11d64e221bfaf | deval-patel/Monopoly_Deal | /Monopoly_Deal/Deck.py | 895 | 3.796875 | 4 | import math
import random
import typing
from Card import *
from collections import deque
"""
This class holds a set of cards as a Deck.
"""
class Deck:
"""
===Private Attributes===
cards:
The cards in this deck at this time.
"""
cards: deque[Card]
def __init__(... |
b557ea1fec542be6933e419f8f0c2d7a74c1d054 | wilsonfr4nco/cursopython | /Modulo_Basico/Listas_manipulando/aula25_1.py | 663 | 3.96875 | 4 | """
Split, Join, Enumerate em Python
* Split - Dividir uma string # str divide transformando em lista
* Join - Juntar uma lista # str
* Enumerate - Enumerar elementos da lista # list / para objetos iteráveis
"""
string = 'O Brasil é o o o o país do progresso, o Brasil é bom'
lista = string.split(' ') # removeu os espaç... |
b03b60fb1b230632706140814a585d1295cd5b5e | martincastro1575/python | /courseraPython/estructuraDatos/list_String.py | 587 | 4.03125 | 4 | nombre = 'Martin'
lista = list(nombre)
#La indexacion funciona para el string y la lista
nombre[0]
lista[0]
#El slicing funciona para string y lista
nombre[:4]
lista[:4]
#La funcion len funciona para ambas
len(nombre)
len(lista)
#El in funciona de igual forma
'r' in nombre
'r' in lista
#El not funciona de igual f... |
44db5bc86b423e0f75151432c3745796ac2e1d33 | bokdoll/Algorithm | /Algorithm-이것이코딩테스트다/Chapter08-다이나믹 프로그래밍/1로 만들기.py | 834 | 3.515625 | 4 | # 2020/11/27 (금)
# [Chapter08-다이나믹 프로그래밍 실전문제] 1로 만들기
def solution():
x = int(input())
# 앞서 계산된 결과를 저장하기 위한 DP 테이블 초기화
d = [0] * 30001
# 다이나믹 프로그래밍 진행 (bottom-up)
for i in range(2, x + 1):
# 현재의 수에서 1을 빼는 경우
d[i] = d[i - 1] + 1
# 현재의 수가 2로 나누어 떨어지는 경우
if i % 2 == 0... |
bac3b1060e8558c87abc0df3d89497e9ae41f872 | daniela-mejia/Python-Net-idf19- | /PhythonAssig/4-23-19Assigment3/4-23 Project6.py | 658 | 3.84375 | 4 | #This program input the number of packages, out put diacount and total
def main():
x=99
numPack= int(input(" Place enter the amount of packages purchased: "))
if 10>= numPack <=19 :
price= (x * numPack) * 0.20
elif 20>= numPack <=49 :
price=(x * numPack) * 0.30
... |
ba697db6bb8e339a539f89bdb3c63c487d0deb93 | alves-Moises/python_course_curso_em_video | /aula07_a.py | 311 | 3.75 | 4 | name = input('whats your name? ')
print(f'Nice to meet you, {name:^20}')
n = input('QUAL É SEU NOME?')
print(f'Prazer em te conhecer, {n}!') # sem espaços
print(f'Prazer em te conhecer, {n:^20}!') # com 20 espaços
a = int(input('Digite primeiro valor'))
b = int(input('Digie o segundo valor'))
print(a + b) |
f842c74c945acd59dba0f30973a5dea3a106b14b | mahtabfarrokh/SearchEngine | /Trie.py | 6,940 | 3.5625 | 4 | from tkinter import END
class Node :
def __init__(self , dWord , flag ):
self.data = dWord
self.Rc = None
self.Lc = None
self.next = None
self.flag = flag
self.address = []
class MyTrie :
def __init__(self ,fileOpen ):
self.root = Node("" ,0 )
se... |
d5f43007d908260d0a7a4597ac23ce8e31972c59 | NiumXp/Algoritmos-e-Estruturas-de-Dados | /src/python/calculate_pi.py | 553 | 4.21875 | 4 | """ Implementaço de um algoritmo de cálculo do PI """
def calculate_pi(number):
"""
Implementação de um algoritmo de cálculo do PI.
Argumentos:
number: int.
Retorna o valor de PI.
"""
denominator = 1.0
operation = 1.0
pi = 0.0
for _ in range(number):
pi += operation *... |
cc9c2990b09ca22ac296e0fdf99f9ad267873d4d | Katuri31/Problem_solving_and_programming | /Python/Lab_model_questions/q_6/using_numpy/6b_using_numpy.py | 675 | 4.21875 | 4 | # Write a program to perform addition of two square matrices(With NumPy)
import numpy as np
r1 = 3
c1 = 3
print("Enter the entries of 3*3 matrix in a single line (separated by space): ")
entries1 = list(map(int, input().split()))
matrix1 = np.array(entries1).reshape(r1, c1) #Matrix 1
... |
42eb20bc94f806b0e698f5041a6ee4249dacf2ea | kossy-inequality/Repository-of-Kossy | /mydate.py | 1,315 | 3.953125 | 4 | import datetime
import calendar
today = datetime.date.today()
todaydetail = datetime.datetime.today()
# 今日の日付
print('----------------------------------')
print(today)
print(todaydetail)
# 今日に日付:それぞれの値
print('----------------------------------')
print(today.year)
print(today.month)
print(today.day)
print(todaydet... |
511ce92179473ae2f6dcce55ab4252c8f0a04440 | khanhpdt/programming-pearls | /maximum_subarray_iterative.py | 1,090 | 3.90625 | 4 | # see [1, Exercise 4.1.5] for more details
def find_max_subarray(array):
max_subarray_low = 0
max_subarray_high = 0
max_subarray = array[0]
# sum of the elements from (max_index + 1) to the current index
max_subarray_end_at_current_index_low = 0
max_subarray_end_at_current_index = array[0]
... |
31ddf18c9a4a93476e3e2dcfd776c2b33b51f159 | anders-ahsman/advent-of-code | /2020/day11/main.py | 4,030 | 3.609375 | 4 | import sys
def read_floor():
return [list(line.rstrip()) for line in sys.stdin]
def part1(floor):
next_floor = [row[:] for row in floor]
while True:
for y in range(len(floor)):
for x in range(len(floor[y])):
count = occupied_count(floor, x, y)
if floor... |
a58caf45530fd1fabd4be9ef0414b576b08b2334 | kambehmw/algorithm_python | /atcoder/ABC/142/D_Disjoint_Set_of_Common_Divisors.py | 683 | 3.71875 | 4 | import math
def is_prime(n):
if n == 1: return True
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i !... |
a58c0ae845eba4f58b672df3c2b2536baea15c06 | AllanWong94/PythonLeetcodeSolution | /Y2017/M8/D12/Closest_BST_Value/Solution.py | 1,404 | 3.828125 | 4 | # Runtime: 69ms=>59 Beats or equals to 21%=>55%
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from Y2017.TreeNode import TreeNode
class Solution(object):
def closestValue(self, root, t... |
78b480e5c55537e1ad1b01ca836194ff504ba54c | luchev/algorithms | /maximum-subarray/max-subarray-linear.py | 1,927 | 4.03125 | 4 | def maxsubarray(list):
"""
Find a maximum subarray following this idea:
Knowing a maximum subarray of list[0..j]
find a maximum subarray of list[0..j+1] which is either
(I) the maximum subarray of list[0..j]
(II) or is a maximum subarray list[i..j+1] for some 0 <= i <= j
... |
d8caa31f84000f971cac08a78066b6a0f7ef7b1d | chewbocky/Python | /addition.py | 608 | 4.125 | 4 | print("Please enter two numbers and I will add them togeather")
print("please type 'q' to quit")
while True:
first_number = input("\nFirst Number: ")
if first_number == 'q':
break
try:
first_number = int(first_number)
except ValueError:
print("Sorry, but you must enter a number.")
second_nu... |
c45568f70f902f68f5c2d1f75a29423ef68e520c | HoangAnhNguyen269/practicals_CP1404 | /practical/prac9/sort_files_1.py | 636 | 4.03125 | 4 | """
sort these files from FilesToSort into subdirectories for each extension.
"""
import os
import shutil
def main():
"""move files into subfolders with the same name as their extension."""
os.chdir("FilesToSort")
for filename in os.listdir('.'):
if os.path.isdir(filename):
continue
... |
45a317bef2db3b77589fbcc7c12fbfe7237b0282 | AryanGanotra07/Computer-Graphics | /LabEvaluation2.py | 1,060 | 3.53125 | 4 | import time
from graphics import *
def trafficLights():
win = GraphWin()
rect = Rectangle(Point(60,20 ), Point(140,180))
rect.draw(win)
red = Circle(Point(100, 50), 20)
red.setFill("black")
red.draw(win)
yellow = Circle(Point(100, 100), 20)
yellow.setFill("black")
yellow.draw(win)
... |
423bd3e0383f6bff528649a7f6cbe4bbe9d6aca3 | Antonio-Rice/Pass-Generator | /genpass.py | 495 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: utf8 -*-
import random
import sys
for arg in sys.argv: 1
aide = """
Usage: python genpass.py <number of characters>
Example usage:
python genpass.py 8
"""
while True:
try:
int(arg)
break
except ValueError:
print(aide)
sys.exit(1)
lettre = list("abcdefghijklmnopqrstuvwxyzAB... |
3bb4efb2c30724e2ba6932e821da3ff5825936cd | rajibeee/Sample-Codes | /Algorithms/Assignment3/submission/source code/rajib dey Assignment 3.py | 5,721 | 3.703125 | 4 | from itertools import permutations
from random import randint
import numpy as np
import time
import matplotlib.pyplot as plt
LowestTimeBruteForce=[]
LowestTimeGreedy=[]
GreedyTimeList=[]
GreedyYaxis=[]
def randomTimeGenerator(number_of_campers, maximum_time = 100):
personset = set()
while number_of_camp... |
4a85d0f47bcdd05a5fc491d1c365343aea60aac9 | sljcb/leedcode | /pathSum.py | 1,096 | 3.9375 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
# def hasPathSum(self, root, sum):
# return s... |
f970ccab2492411710266f6fce74985a01f1aa0b | cja-smith/Python-scripts | /numberguessinggame.py | 2,346 | 3.9375 | 4 | from random import randint
def user_guess():
global NumberOfGuesses
while True:
print(f"You have {10-NumberOfGuesses} guesses left.")
guess = input()
try:
guess = int(guess)
if guess in range(101):
NumberOfGuesses+=1
... |
a25f5bda55ef4d859ab9591e7ec6cb2e11dcd1b9 | ZeroILumi/Projetos_de_Teste_ver_0.0.1 | /Testes_Complexos/Projetos Python/aula6_Zero_ILumi_ver_1.0.py | 2,563 | 3.734375 | 4 | if __name__ == '__main__':
conjunto1 = {1, 2, 3, 4, 5}
conjunto2 = {5, 6, 7, 8}
conjunto_uniao_1_2 = conjunto1.union(conjunto2)
print('União do conjunto 1 com o conjunto 2:\n{conjunto_uniao_1_2}'
''.format(conjunto_uniao_1_2=conjunto_uniao_1_2))
conjunto_intersccao_1_2 = con... |
771314de2d4e13f67465e8e9d6da20021689ef1f | czs108/LeetCode-Solutions | /Medium/74. Search a 2D Matrix/solution (1).py | 971 | 4.03125 | 4 | # 74. Search a 2D Matrix
# Runtime: 44 ms, faster than 66.69% of Python3 online submissions for Search a 2D Matrix.
# Memory Usage: 14.9 MB, less than 32.98% of Python3 online submissions for Search a 2D Matrix.
class Solution:
# Row Iteration & Binary Search
def searchMatrix(self, matrix: list[list[int]], ... |
75035c77724c2299c63ee674d625b84cf710df7a | Claire56/leetcode | /Sorting.py | 835 | 4.0625 | 4 | def mergeSort(a):
if len(a)>1:
mid = len(a)//2
L =a[:mid]
R =a[mid:]
mergeSort(L)
mergeSort(R)
R_index =L_index = a_index=0
while L_index < len(L) and R_index <len(R):
if R[R_index]< L[L_index]:
a[a_index]=R[R_index]
R_index +=1
else:
a[a_index]=L[L_index]
L_index +=1
a_index ... |
8aaa3c1143a12a1d5aafb48d207aa854dd18f339 | xjz1994/LeetCodeSolution | /Solution/Python/820. Short Encoding of Words.py | 627 | 3.5 | 4 | class Solution:
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
root = dict()
leaves = []
for word in set(words):
cur = root
for i in word[::-1]:
cur[i] = cur = cur.get(i, dict())
... |
7727cd72ef8d851ee11b61827178bf5040a11ff8 | leapfrogtechnology/lf-training | /Python/shresoshan/task1/store.py | 1,818 | 3.515625 | 4 | import sys
import argparse
from datetime import datetime
import csv
import operator
import os
#Convert to datetime type
def dob(value):
return datetime.strptime(value,'%d/%m/%Y')
#Calculate percentage
def calcpercentage(total, score):
return ((score/total)*100)
#Duplicate Check
def isDuplicate(args):
wit... |
6a3b9e9f8f9e50fd04fb86bcbdccde3836331996 | nairoukh-code/CIS2001-Winter2020 | /Trees/Trees.py | 1,516 | 3.65625 | 4 | class Position:
def __init__(self, item, container, parent, children):
self.item = item
self.container = container
self.parent = parent
self.children = children
def get_item(self):
return self.item
class GenericTree:
def __init__(self, item, parent = None):
... |
bf233e9fc8610167943438784e03cd9c04dcedff | vsmaxim/data-analysis-2021 | /utils.py | 6,530 | 3.765625 | 4 | import pandas as pd
from typing import Iterable
from matplotlib import pyplot as plt
import seaborn as sns
def get_stats_df(df: pd.DataFrame) -> pd.DataFrame:
"""
For given dataframe constructs new dataframe with numerical parameters as a rows,
and statitical values (such as mean, std, min, max and quarti... |
17ae84136c2e1368ffd4b5d54dfdfe61a04de1c3 | mike006322/FrobeniusNumber | /NijenhuisAlgorithm/dijkstra.py | 1,340 | 3.78125 | 4 | from graphHeap import MikesGraphHeap
def dijkstra(graph, start=1):
"""
input graph of the form {node1: {node2: distance, node3: distance, ... }, ...}
output dictionary {node: shortest path from start to node}
"""
X = {start} # Vertices passed so far
A = {start: 0} # Computed shortest path di... |
11678b8437700514831071fa243a4b990f961f05 | csouto/samplecode | /CS50x/pset7/finance/test.py | 104 | 3.671875 | 4 | n = [1, 2, 3, 4]
l = ['a', 'b', 'c', 'd']
for item in l:
print(n.item, end=" - ")
print(l.item) |
07308fddda82e20ced5c89709aad2f5c1f917ba4 | main7/station | /for_name.py | 533 | 3.640625 | 4 | # -*- unicode:utf-8 -*-
names=['Tom','Tim','Bob']
for name in names:
print(name)
#list
sum=0
for x in [1,2,3,4,5,6,7,8,9,10]:
sum=sum+x
print(sum)
#range(i)生成一个小于i的整数序列
sum=0
for x in list(range(101)):
sum+=x
print(sum)
sum=0
n=99
while n>0:
sum+=n
n-=2
print(sum)
n=1
while n<=100:
print(n... |
0b459d96dc303c0e1b34dd414f7a12772e617ca6 | Sid20-rgb/LabProject | /labfour/set_five.py | 260 | 4.0625 | 4 | '''5.Write a Python program to remove an item from a set if it is present in the set.'''
item = set([1, 2, 3, 4, 5, 6])
r = int(input("Enter a item to remove:"))
if r in item:
item.remove(r)
print(item)
else:
print("Not available in this set.") |
671550eae1ac21abec2ed4c40e1f837f79680e14 | Jinah1/lastName_pythagorean | /evenOrOddPt2.py | 155 | 4.3125 | 4 | x=int(input("Enter an integer and see if it is even or odd:"))
if x % 2 ==0:
print(x ,"is an even number")
else:
print(x ,"is not an even number")
|
a5dbdbb375ee5912dccc5369a00b4e47608eaeee | edoardochiavazza/Esempi-esame | /statistiche_comuni/statistiche_comuni.py | 3,810 | 3.96875 | 4 | # Soluzione proposta esercizio d'esame "Statistiche Comuni"
from typing import IO
FILE_COMUNI = 'elenco-comuni-italiani.csv'
FILE_REGIONI_SCELTE = 'regioni.txt'
def leggi_file():
"""
Legge gli interi dati sui comuni, e li salva in una lista di record.
Ciascun elemento della lista fa riferimento ad un com... |
4cfc10ee8fcd71d393e9ed1845c7f1487a2b17fb | arthurdamm/algorithms-practice | /leet/restore_ip_addresses.py | 1,064 | 3.875 | 4 | #!/usr/bin/env python3
"""
93. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.
Example:
Input: "25525511135"
Output: ["2... |
720852b5ae5fb0dd8a6153f524bbe8415e5d9798 | jose-brenis-lanegra/T08-Brenis.Niquen | /iteracion.py | 1,814 | 4.125 | 4 | #ejercicio01
str="jose"
for letra in str:
print(letra) #mostrar jose en forma vertical
#ejercicio02
str="antonio"
for letra in str:
print(letra) #mostrar antonio en forma vertical
#ejercicio03
str="remigio"
for letra in str:
print(letra) #mostrar remigio en forma vertical
#ejercicio04
str="breni... |
f936c87794e1aadcb9750081c7e64e7c431feb15 | Juozapaitis/100daysOfCodeUdemy | /100 days of code/day 27/main.py | 1,071 | 4 | 4 | from tkinter import *
def button_clicked():
print("I got clicked! ")
new_text = input.get()
my_label.config(text = new_text)
window = Tk()
window.title("First GUI Program")
window.minsize(width = 500, height = 300)
# Label
my_label = Label(text = "Enter a label", font = ("Arial", 24, 'bold'))
my_label.p... |
f769175237bbe70c5aebc6b6fdb6e9b7d6985022 | Shaftar/Fibonacci-Zahlen-1 | /Fibonacci-Zahlen-Rechner.py | 708 | 3.796875 | 4 | """Fibonacci Zahlem Rechner
Autor: Mohamad Shaftar
Datum: 25.09.2019
"""
f0 = 0 # Der alte Wert speichern
f1 = 1 # passt dem neuen wie alten wert ein
f2 = 1 # Der neue Wert speichern
zahl = int(input('Enter the number of output:'))
while zahl <= 0: # Eingabe überprüfen
zahl = int(input('Bitte ... |
23a08c61628f387bde57786871a905a37f517f32 | alicodermaker/public_code | /github_reminder/webclient/main/random_string.py | 299 | 4.09375 | 4 | import random
import string
def generator(stringLength):
"""Generate a random string with the combination of lowercase and uppercase letters """
letters = string.ascii_letters
return(''.join(random.choice(letters) for i in range(stringLength)))
if __name__ == '__main__':
print(generator(10)) |
92b91715166ad6beade18221771778f4a13b7c32 | esben2k/python3-basics | /list_of_numbers.py | 337 | 4.09375 | 4 | #list_of_numbers.py
# Converting numbers to list
numbers = list(range(1,6))
print(numbers)
# 2 = adding 2 up until 101
odd_numbers = list(range(1,101, 2))
print(odd_numbers)
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
digits = [1,2,3,4,5]
print... |
3b374071e4e3217255bc4f2553b2dbf389429d4f | IshteharAhamad/project | /aggregation.py | 523 | 3.828125 | 4 | class Salary:
def __init__(self,pay,reward):
self.pay = pay
self.reward = reward
def annual_salary(self):
return (self.pay*12) + self.reward
class Employee:
def __init__(self,name, position,sal):
self.name=name
self.position = position
self.sal = sal # here pa... |
a92a9a64129040ef87806de395c61e511800d9d3 | zachherington/python-challenge | /PyBank/main.py | 3,252 | 3.515625 | 4 | # PyBank Plan of Attack:
# Resource data
# Col1: Date | MMM-YY | Min: 1/1/2010 | Max: 2/1/2017 |
# Col2: Profit/Losses | +/- # | Max: 1170593 | Min: -1196225 |
# Deliverables:
# 1. The total number of months included in the dataset
# 2. The net total amount of "Profit/Losses" ove... |
54f5f265a17006f9e9891029a4a72697a9c87be7 | ericnwin/Python-Crash-Course-Lessons | /Chapter 2+3 Intro + Variables + Strings/WorkingWithLists.py | 639 | 4.3125 | 4 |
cars = ['Honda', 'BMW', 'Mercedes']
## Adding items to Lists
cars.append("Toyota") #Added Toyota to end of list w/ .append
cars.insert(0 , "Fiat") #Added Fiat to position 0 w/ .insert
print (cars)
## Removing Items from Lists
del cars[2] #del removes the value of BMW
print (cars)
recent_purchase = cars.pop() #.p... |
03ad60997106cec7efe570954f62e1acea57d15d | nyahjurado/portfolio | /shapes2.py | 1,062 | 4.78125 | 5 | from turtle import *
import math
# Name your Turtle.
Moana= Turtle()
#color is the color of the shape
#number is the number of sides
#length is the length of sides
color = input('Enter color of shape: ')
number = input('Enter the number of sides: ')
#make number an integer
number1 = int(number)
length = ... |
9f98f72c9cb8a94e09d849f5347738fbcb4d73cd | hooong/baekjoon | /leetcode/1413_minimum_value_to_get_positive_step_by_step_sum.py | 493 | 3.53125 | 4 | from itertools import accumulate
from typing import List
class Solution:
def minStartValue(self, nums: List[int]) -> int:
return -min(0, min(accumulate(nums))) + 1
def test():
solution = Solution()
assert solution.minStartValue([-3, 2, -3, 4, 2]) == 5
assert solution.minStartValue([1, 2]) =... |
976dc8f0633e108a5d06766153129140e151c6cc | nidhiatwork/Python_Coding_Practice | /GrokkingCodingInterview/SlowFastPointers/find_cycle_start.py | 768 | 3.890625 | 4 | '''Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.
'''
from collections import Counter
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def find_cycle_start(head):
slow,fast = hea... |
4337a751536c78843ae0d8293544204a7f83f2ce | pkshiu/rpi-rotary-example | /rotate.py | 1,668 | 3.640625 | 4 | import time
from gpiozero import Button
# Replace these with your GPIO pin connections.
# ...
# ... [31] [33] [35] [37] [39]
# ... .... gpio13 gpio19 gpio26 gnd
PIN_A = 19
PIN_B = 26
PIN_SELECT = 13
class App():
"""
Simple example to listen for change of pin A on the encoder, and determin... |
be25a1b95be12a9277661e7419d5e7bb7fa68e08 | MingYanWoo/Leetcode | /151. 翻转字符串里的单词.py | 1,799 | 3.96875 | 4 | # 151. 翻转字符串里的单词
# 给定一个字符串,逐个翻转字符串中的每个单词。
# 示例 1:
# 输入: "the sky is blue"
# 输出: "blue is sky the"
# 示例 2:
# 输入: " hello world! "
# 输出: "world! hello"
# 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
# 示例 3:
# 输入: "a good example"
# 输出: "example good a"
# 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
# 说明:
# 无空格字符构成一个单词。
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.