blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
87c81a7b3e7797bada95933f433016d2b81aaa44 | BenThomas33/practice | /python/crack_interview/ch11/sort.py | 696 | 3.546875 | 4 |
import copy
dic1 = {}
for c in "abcdefghijklmnopqrstufwxyz":
dic1[c] = 0
def v(str1):
global dic1
dic2 = copy.copy(dic1)
res = ""
for i in str1:
if i.lower() in dic2:
dic2[i.lower()] += 1
for c in "abcdefghijklmnopqrstufwxyz":
if dic2[c] > 0:
res += c... |
606bdb4aa1e37eae5b4001246b02b093890d1d39 | ctnormand1/active_learning_demonstration | /code/st-app.py | 4,622 | 3.6875 | 4 | import streamlit as st
import pandas as pd
import sqlite3
import plotly.graph_objects as go
import plotly as py
import numpy as np
from sqlalchemy import create_engine
def main():
st.title('Active Learning for AI')
st.markdown(
"""
This is a demonstration of active learning applied to a convolutional
... |
dca325135ed210e7b0180cede1f885ec8fa1be57 | GusW/python_main | /study/concurrency/threads_concurrent_futures.py | 1,069 | 3.53125 | 4 | import concurrent.futures
from datetime import datetime
from time import perf_counter, sleep
def _sync_sec(seconds: float) -> None:
sleep(seconds)
return f'{datetime.now()} - dummy sleep {seconds}s'
if __name__ == "__main__":
time_init = perf_counter()
with concurrent.futures.ThreadPoolExecutor() as... |
a9b508fe2073e966fe3cc3016bbe22dcdf3f723f | JorgeLuisCampos/Python-Course | /Python101 GitHub/Mis Ejercicios/Objetos_Baraja.py | 720 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import random
class Baraja(object):
def __init__(self):
self.palos = ["Espadas", "Corazones", "Tréboles", "Diamantes"]
self.rangos = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "As"]
self.maso = []
for palo in self.palos:
... |
50371d4da016af406987835b389afc4b92c34640 | himnsuk/Python-Practice | /Interview/Array/rearrange.py | 210 | 3.84375 | 4 |
def rearrange(A):
for i in range(len(A)):
A[i:i+2] = sorted(A[i:i+2], reverse = i%2)
return A
A = [i for i in range(1,11)]
print(rearrange(A))
# Output => [1, 3, 2, 5, 4, 7, 6, 9, 8, 10] |
6950477c0a04b6cf7861496e7fbfbfa0b850bab2 | arinablake/python | /homework1.py | 4,301 | 4.375 | 4 | # Ask for the total price of the bill, then ask how many diners there are.
# Divide the total bill by the number of diners and show how much each person must pay.
bill_total = float(input('What is a bill total?'))
diners = int(input('How many diners are?'))
each_person_pays = bill_total / diners
print(f'Each person ha... |
f1556a2e3331538d6c657002a40bf558694ad319 | Allen-C-Guan/Leetcode-Answer | /python_part/Leetcode/Data Structure/BinaryTree/Medium/114. Flatten Binary Tree to Linked List/Solution.py | 895 | 4 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
题中没有说要求,但是要求是用pre-order来展开。所以我们就用preorder。
思路为:
1. 我们把right subtree 放在left subtree的最右下角的位置
2. 把left subtree 放在 right subtree的位置
3. left subtree 清零。
'''
class So... |
0b9bbac65d96a6263739322dccb5adda2286fc70 | kiettran95/Wallbreakers_Summer2019 | /week2/python/NumberOfAtoms_726.py | 1,482 | 3.59375 | 4 | class Solution:
def countOfAtoms(self, formula: str) -> str:
stack = []
i = 0
while i<len(formula):
atom=formula[i]
i += 1
if atom == ("("):
stack+="("
elif atom == (")"):
num = ""
while ... |
1db011f86bf6951518d716c9ce450bc1816edfcd | DakEnviy/om-lab1 | /algo/find_min_golden_ratio.py | 904 | 3.6875 | 4 | from math import sqrt
def find_min_golden_ratio(func, left, right, epsilon):
x1 = left + ((3 - sqrt(5)) / 2) * (right - left)
x2 = right - ((3 - sqrt(5)) / 2) * (right - left)
val1 = func(x1)
val2 = func(x2)
while (right - left) > epsilon:
if val1 == val2:
left = x1
... |
0b310149a136736f59e734e2d95c9dd6681813f8 | Prempatrick/Python-Projects | /Machine Learning/predictive2.py | 1,457 | 3.765625 | 4 | import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
fruits=pd.read_csv("https://raw.githubusercontent.com/susanli2016/Machine-Learning-with-Python/master/fruit_data_with_colors.txt", delimiter="\t")
#There ... |
40ec3c29b9b9d9a0192e88ff80070245809eadf2 | CarlosG4rc/CursoPy | /Curso Python/Diccionarios.py/diccionarios.py | 1,066 | 3.96875 | 4 | colores = {'amarillo':'yellow','azul':'blue','verde':'green'}
print(colores)
print(colores['azul'])
numeros = {10:'diez',20:'veinte'}
print(numeros[10])
colores['amarillo'] = 'white'
print(colores)
del(colores['amarillo'])
print(colores)
edades = {'Hector':27, 'Juan':45, 'Maria':34}
print(edades)
eda... |
ef89ad9f4303df3eec45b521bb904d0785bcfeb7 | MarHakopian/Intro-to-Python-HTI-3-Group-2-Marine-Hakobyan | /Homework_5/is_palindrome2.py | 308 | 4.1875 | 4 | def is_palindrome(text):
if len(text) <= 1:
return True
elif len(text) > 1 and text[0] == text[-1]:
text = text[1:-1]
return is_palindrome(text)
else:
return False
input_text = input("Please enter the text: ")
print("Yes" if is_palindrome(input_text) else "No")
|
6898cbe0127f0154f89f42e45c0f2ad8a6a095b1 | IgorEM/Estudos-Sobre-Python | /operadores.py | 104 | 3.703125 | 4 | x = 2
y = 3
soma = x + y
print ( x == y)
print ( x < y)
print (soma > y)
print (soma == (y + x)) |
e7eeee22a1e5e38d645ad982b2dfe6aca7d07ab4 | vismantic-ohtuprojekti/qualipy | /qualipy/filters/multiple_salient_regions.py | 4,637 | 3.859375 | 4 | """
Filter for detecting multiple salient regions.
The detection works by first extracting the full saliency map
using an object extraction algorithm. The saliency map is binarized
using a threshold which is calculated individually for each image
as the weighted average of 3/4 of the biggest saliency values.
Using thi... |
72e842199274cb7619b28a598cc2f9dd6c8ad469 | 770120041/DataMiningWebsite | /polls/logic/Classification/DT.py | 1,877 | 3.71875 | 4 | # Descision Tree Algorithm
import pandas as pd
# Function importing Dataset
def importdata():
balance_data = pd.read_csv(
'https://archive.ics.uci.edu/ml/machine-learning-' +
'databases/balance-scale/balance-scale.data',
sep=',', header=None)
# Printing the dataswet shape
print("Da... |
4feb8447bcad93bf28b8f66657937d95bed03b8b | sahlamina/oop_calculator | /calc2.py | 895 | 4.15625 | 4 | import operators2
class Calc2:
def calc(self):
num1 = int(input("Please enter your first number "))
num2 = int(input("Please enter your second number "))
operator = input("Which operation will you like to perform +, -, *, /? ")
if operator == "+":
print(str(num1) + " ... |
4746e1b74810176d4c0687406fbe7fe954cf8e8e | Fandresena380095/Some-Projects-in-python | /recursion fonctionnel.py | 178 | 3.9375 | 4 | a = int(input("First number : "))
b = int(input("Second number : "))
x = int(input("maximum number : "))
c = a+b
while c<x:
a=b
b=c
print(b)
c = a+b
|
e271047cb2e83cf45f676e5fb8c017ccf28e9b1b | dorianbenitez/Homework2_CS4395 | /Homework2_drb160130.py | 5,726 | 3.9375 | 4 | #######
# File: Homework2_drb160130.py
# Author: Dorian Benitez (drb160130)
# Date: 9/6/2020
# Purpose: CS 4395.001 - Homework 2 (Word Guessing Game)
#######
import sys
import nltk
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
import random
# Function to pr... |
aefe35f5176ef9f984fe703f2bcc82cd5e578a44 | maybemichael/sudoku | /leetcode.py | 6,460 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode2:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
new_list = ListNode()
current = new_list
# value1 = 0
# val... |
e92ac6ffc4b95c08f7b142981e298cbb0586778c | nishaagrawal16/Datastructure | /Tree/simple_tree/sum_of_precedence_nodes.py | 1,376 | 3.78125 | 4 | # Date: 13-Dec-2019
# Sum of precedence of Nodes
# 10(120)
# / \
# 20(90) 30(30)
# / \
# 40(40) 50(50)
# O(n)
# TODO
class Node:
def __init__(self, value):
self.info = value
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
de... |
56fafa70d945a08fca789249729e155fbc8e5139 | javedinfinite/practice_questions | /no_equal_pair_indices.py | 566 | 3.703125 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def getCount(A,val):
c = 0
for i, v in enumerate(A):
if(val==v):
c+=1
return c
def solution(A):
# write your code in Python 3.6
c = 0
original_list = A.copy()
unique_list = list... |
84370f5d7a00c09ec8ad5208955a780236158e1a | UdhaikumarMohan/Strings-and-Pattern | /Remove/dirty_1.py | 522 | 4.125 | 4 | # Write code to remove the all occurrence of a dirty word from a given sentence.
def dirty_1(String,word):
str =""
li = String.lower().split()
for a in li:
if not (a==word or a[:-1]==word):
str+=a+" "
return str
String = """Indian Goverment cancelled the special status of jamm... |
d4e6dd4094689ca754b37094de8709a36ec9bdd5 | Vinicius-de-Morais/Exercicios | /Desafios/Desafio_1.py | 944 | 3.8125 | 4 | import random as r
funcionarios = []
def adiciona_funcionario():
contador = 0
while len(funcionarios) <= 9:
funcionario = input('Qual o nome do Funcionario?\n')
salario = float(input('Qual o salario?\n'))
combo = [funcionario,salario]
funcionarios.append(combo)
contador ... |
d42d871a9ec36f3cca1ff020f1d43f254f514ac0 | deepika-jaiswal/hands_on_python | /checkeoro.py | 92 | 4.0625 | 4 | num=int(input())
if (num%2==0):
print("no is even")
else:
print("no is odd")
|
fd70132321f3270561c8a17fc34e95a3ba0ab4e9 | jf20541/Multi-LinearRegressionModel | /src/MR_data.py | 587 | 3.546875 | 4 | import pandas as pd
import MR_config
def clean_data(data):
"""Clean xlsx file, set index, replace NaN values,
convert to csv file
Args:
data [float]: set data as pandas dataframe
"""
data = data.set_index("Year")
data = data.astype(float)
if data.isnull().values.any() == False... |
c9f973c4afd9c7ac5283dad3d88ab52879382303 | StechAnurag/python_basics | /28_for_loop.py | 910 | 4.3125 | 4 | # FOR Loop
# Iterables in python - Lists, Tuples, Sets, Dictionary, Strings
for item in 'Zero to mastery':
print(item)
# with lists
for el in [1, 2, 3, 4, 5]:
print(el)
# with sets
for el in {1, 2, 3, 4}:
print(el)
# with tuples
for i in (1, 2, 4):
print(i)
# Nested for loops
for item in [1, 2, 3]:
for ... |
87928877afe839b0a8cc13281273a86e3611ca13 | trojanosall/Python_Practice | /Basic_Part_1/Solved/Exercise_79.py | 676 | 4.25 | 4 | # Write a Python program to get the size of an object in bytes.
import sys
str1 = "one"
str2 = "four"
str3 = "three"
str4 = "THREE"
myint = 1698
myfloat = 1896.36983
print()
print("Memory size of " + str1 + " = " + str(sys.getsizeof(str1)) + " bytes")
print("Memory size of " + str2 + " = " + str(sys.getsizeof(str2)... |
9a5d70da3a61889d9c0b69f03f33bd7d54205a0a | adipixel/conding-questions | /DataStructures/Tree/level_order_traversal.py | 478 | 3.984375 | 4 | """
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)
"""
def levelOrder(root):
if root == None:
return
queue = []
queue.append(root)
while(len(queue) > 0):
print queue[0].data,
node = queue.p... |
9b450808fa1cf936782f3af43d557c2287df09f5 | EvgeniyBudaev/python_learn | /options/deep_and_shallow_copy.py | 1,592 | 4.4375 | 4 | import copy
list1 = [1, 2, 3, [4, 5, 6]]
copied_list = list1.copy()
copied_list[3].append(7)
print(list1) # [1, 2, 3, [4, 5, 6, 7]]
print(copied_list) # [1, 2, 3, [4, 5, 6, 7]]
# Поверхностная копия
shallow_copy = copy.copy(list1)
shallow_copy[3].append(8)
print(list1) # [1, 2, 3, [4, 5, 6, 7, 8]]
print(copied_list... |
4b2a17b97cdc77b61f7e42c8d7418db3ac1daaec | shentong-hbu/Coronary-Artery-Tracking-via-3D-CNN-Classification | /infer_tools_tree/tree.py | 609 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
# @Time : 04/08/2020 15:38
# @Author : QYD
# @FileName: tree.py
# @Software: PyCharm
class TreeNode(object):
def __init__(self, value, start_point_index, rad=None):
self.value = value
if rad is not None:
self.rad = [[i] for i in rad]
else:
... |
afe46128a79ec9bf4b20e3ae7943e3120d48f74f | gutucristian/examples | /ctci/python/Dijkstra/main.py | 1,304 | 3.984375 | 4 | from min_heap import MinHeap
from node import Node
from graph import Graph
heap = MinHeap()
graph = Graph()
A = Node("A", 0)
B = Node("B")
C = Node("C")
D = Node("D")
E = Node("E")
F = Node("F")
A.add_neighbors(B=3, C=1)
B.add_neighbors(A=3, C=1, D=5)
C.add_neighbors(A=1, B=1, D=2, E=4)
D.add_neighbors(B=5, C=2, E=1... |
38b8e3011a60e86db8958e18116cc73a30318cf3 | Chewie23/fury-train | /PyProjects/HW_3.py | 8,575 | 3.828125 | 4 | def num_to_str(num):
"""
6.8
convert numeric value to read as string
ex. 89 -> "eighty-nine"
"""
ones_db = {1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine"}
teens_db = {10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen",
... |
5c67e6d276e6c8887a7f822fbc9c6638b19805b2 | ZenTauro/telematicos | /python_back/ServTelemBack/sensor.py | 1,242 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint
from typing import Dict
def get_sensors():
tmp = temperature()
hum = humidity()
noi = sound()
bri = light()
mov = motion()
return {
"temp": tmp.get(),
"humid": hum.get(),
"noise": noi.get(),
"b... |
bc173d7d456ef68301e042137287161d2f72d663 | FabioLeonam/exercises | /hacker_rank/linked_list/sorted_insert.py | 1,547 | 3.796875 | 4 | # Complete the sortedInsert function below.
#
# For your reference:
#
# DoublyLinkedListNode:
# int data
# DoublyLinkedListNode next
# DoublyLinkedListNode prev
#
#
def sortedInsert(head, data):
new_node = DoublyLinkedListNode(data)
# Case 1: empty list
if head == None:
head = new_node
... |
b05e97000eed3c4abc636492aae3fff52892acc4 | sulemanmahmoodsparta/Data24Repo | /Football_Game/Game Code/a_Players.py | 1,855 | 3.96875 | 4 | import random # for player generation
from abc import ABC, abstractmethod
PlayerPositions = ["Goalkeeper","Defender","Midfielder","Attacker"]
# An Abstract class that cannot be initialised
class Players(ABC):
@abstractmethod
def __init__(self, fname, lname, value, position):
self.id = 0
self.f... |
3ce8e95e0cdf849d2c434197aaffc427177505a5 | DeltaDeutsch/3.-Python-Homework-Deutsch | /Pypoll Deutsch May 3 2021.py | 2,349 | 3.828125 | 4 | #Pypoll Deutsch
#Define Variables
total_votes = 0
Candidates_votes = {}
list_of_candidates = []
winning_candidate = ""
winning_count = 0
"""
The total number of votes cast ()
* A complete list of candidates who received votes
* The percentage of votes each candidate won
* The total number of votes each candid... |
d9bd5a54cb829d172ef1e2848af16bc0b5acfe13 | rashmierande/practice | /strings/Palindrome.py | 310 | 3.78125 | 4 | def is_Palin(str1):
return str1[::-1]== str1
print(is_Palin("hello"))
print(is_Palin("123"))
print(is_Palin("111"))
print(is_Palin("aba"))
def is_pal(str1):
r=str1[::-1]
for i in range(0,len(str1)+1//2):
if str1[i]!=r[i]:
return False
return True
print(is_pal("aabac17")) |
1a95ec6308ef19d7573f3ff1eda184941cfad8b2 | Jack2ee-dev/NKLCB_homework | /programmersSkillCheckLevel1/no2/solution.py | 267 | 3.59375 | 4 | def solution(array, commands):
answer = []
for command in commands:
start = command[0]
end = command[1]
order = command[2]
temp = array[start-1:end]
temp.sort()
answer.append(temp[order-1])
return answer
|
c9b30321bde82b1a80ec64b3a7ce0e5b6465a50f | gau-nernst/search-algos | /search.py | 9,761 | 3.546875 | 4 | class Search():
valid_strat = {'bfs', 'dfs', 'ldfs', 'ids', 'ucs', 'greedy', 'a_star'}
def __init__(self, strategy):
assert strategy in self.valid_strat
self.strat = strategy
def __call__(self, start, end, adj_list, max_depth=3, heuristic=None):
print("Strategy:", self.... |
eb0f7b3c30d4540680feb8ea0a2a77aa5e402240 | tech-vin/tkinter-Exercies | /2.py | 193 | 3.75 | 4 | # create title to widjet and label
from tkinter import *
root = Tk()
root.title('This is the title of the window')
label = Label(root, text="Representing Label")
label.pack()
root.mainloop() |
c3613d1209e07c7f4c04d43d3159b530c884dbc7 | jaadyyah/APSCP | /2017_jaadyyahshearrion_4.02a.py | 984 | 4.5 | 4 | # description of function goes here
# input: user sees list of not plural fruit
# output: the function returns the plural of the fruits
def fruit_pluralizer(list_of_strings):
new_fruits = []
for item in list_of_strings:
if item == '':
item = 'No item'
new_fruits.append(item)
... |
fb1efbb8d885e116c665ee9c351f9247a649a719 | gallofb/Python_linux | /py_test/栈与队列/push_and_pop.py | 906 | 3.6875 | 4 | # -*- coding:utf-8 -*-
#栈的压如弹出序列
class Solution:
def IsPopOrder(self, pushV, popV):
if pushV != None and popV != None and len(pushV) == len(popV):
stack = []
i = 0
while popV:
p = popV.pop(0)
while i < len(pushV):
stack.... |
20aacc63fbe22210095ee0d8e49b1f3fd7749ba0 | FranckCHAMBON/ClasseVirtuelle | /Term_NSI/devoirs/4-dm2/Corrigé/PROF/E6.py | 535 | 3.5 | 4 | """
auteur : Franck CHAMBON
https://prologin.org/train/2003/semifinal/nombres_impairs
"""
def nombres_impairs(n: int, m: int) -> list:
"""Renvoie la liste des nombres impairs entre `n` et `m` inclus.
>>> nombres_impairs(42, 51)
[43, 45, 47, 49, 51]
"""
liste = []
i = n
if i % 2 == 0:
... |
07b40e151845f33384e1f58a4d4af77917705f9f | Rahelsc/forHezi | /get_anastasia_to_ariel.py | 2,234 | 3.703125 | 4 | import math
# code complexity: |V|
def Dijkstra_init(graph, vertex):
for key in graph.keys():
graph[key]['d'] = 0 if key == vertex else math.inf
graph[key]['p'] = None
# relax gets 2 vertices (neighbor and current)- when e is (current,neighbor)
def relax(graph, neighbor, current, e):
# if (d... |
606c28434e0552b5dfce957ab837d3d911cfcbd8 | yaelRashlin/checkio-solutions | /home/backward_string_by_word.py | 694 | 4.03125 | 4 | def backward_string_by_word(text: str) -> str:
import re
return "".join([y[::-1] for x in re.findall("(\w+)(\s+)?", text) for y in x])
if __name__ == '__main__':
print("Example:")
print(backward_string_by_word(''))
# These "asserts" are used for self-checking and not for an auto-testing
asser... |
8c2b8a5f76d4d2cd7470512761bdaca5e15a975e | arnabid/QA | /sortsearch/divide2Integers.py | 977 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 15 20:50:05 2017
@author: arnab
"""
def divide(dividend, divisor):
maxintp = 2147483647
maxintn = -2147483648
if divisor == 0:
raise ValueError("divisor is 0")
if dividend == 0:
return 0
if divisor == 1:
return min(max(... |
fd48edd5c45535b2f425d600a62972b84297b59a | EwanThomas0o/Self_teaching | /bin_tree_traversal.py | 7,333 | 4.25 | 4 |
#A binary tree is a structure where each node has at most two children
# root node
# / \
# / \
# left child right child
# The depth of a node is how many nodes it is away from the root
# The dead ends of the tree are called leaves, and the height of a node is how many nodes another node ... |
e6324c17afec834dfe495f816981810e91396aa9 | QilinGu/price_watcher | /commodity.py | 1,126 | 3.921875 | 4 | # File for a class Commodity
# Each Commodity has three data members
# url_address: a string containing the weblink url address
# original_price: a float of the original price of the item
# current_price: a float of the real-time price of the item
class Commodity:
#constructor
def __init__(self, url, firs... |
d826e79efb91623d68fe30ad73109aa98ea0bfbe | kailvin7/kailvin-python | /learn/file_io.py | 672 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
"""
#raw_input 函数
str = raw_input("plz input:")
print "your inputing is ",str
#input函数 // input函数和raw_input函数类似,但是它可以接受一个Python表达式作为输入,并将运算结果返回
str = input("请输入:")
print "你输入的内容是:",str
"""
#open函数
test_name = r"E:\pycharm\learn\for range.py"
test_fo = open(test_name,"a+")
... |
b10927893e7c1b1cc16c9b89dd3470799e8a98a7 | TurnUpTheMike/CamouflagePuzzle | /camo/solution/puzzleutility.py | 1,256 | 3.90625 | 4 |
class PuzzleUtility:
"""
These are common functions that multiple classes use
"""
def __init__(self, properties):
self.properties = properties
# which column of the puzzle row grid that the "chosen letter" will appear
self.chosen_letter_index = self.properties.puzzle_row_lengt... |
5d9a2a002e45e4027042c070fdc70b9dadffbbe5 | zhulei2017/Python-Offer | /sword-to-offer/43.1.py | 731 | 3.5625 | 4 | def print_probability(nums):
if nums < 1:
return []
data1 = [0] + [1] * 6 + [0] * 6 * (nums-1)
data2 = [0] + [0] * 6 * nums
flag = 0
for v in range(2, nums+1):
if flag:
for k in range(v, 6*v+1):
data1[k] = sum([data2[k-j] for j in range(1, 7) if k > j])
... |
434b8d0d1cf5cdc6b515012054a8f4babdf42bd1 | JacksonMike/python_exercise | /python练习/老王开枪/Test1.py | 584 | 3.609375 | 4 | a = "Jim"
b = "Jack"
c = "Mike"
d = "Hard"
name_list = [a,b,c]
name_list.append(d)
e = name_list.count(b)
print(e)
print(name_list)
for a in name_list:
print(a)
infor_tuple = ("Jim",12,12)
print(infor_tuple)
print(infor_tuple.count("Jim"))
for item in infor_tuple:
print(item)
o = {"name":"Jim","age":15,"job":"... |
67a53c73107f77bc2cf3c17b114bd92f6c317be8 | blue2525989/caesar | /caesar.py | 1,016 | 3.9375 | 4 | import string
def alphabet_position(char):
bet = string.ascii_letters
pos = bet.find(char)
if pos > 25:
new_pos = pos - 26
return new_pos
else:
return pos
def rotate_letter(letter, n):
if letter.isupper():
start = ord('A')
elif letter.islower():
start ... |
6500131604b6ab13a1074ab4a2710feb846558ca | Aasthaengg/IBMdataset | /Python_codes/p03108/s474201214.py | 1,535 | 3.515625 | 4 | import math
def P(n, r):
return math.factorial(n)//math.factorial(n-r)
def C(n, r):
return P(n, r)//math.factorial(r)
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
... |
7c7e3e6fa35ca4d0a5b41c290fa8dfdbf2f1daeb | GustavoGarciaPereira/Topicos-Avancados-em-Informatica-I | /exercicios_strings/exe1.py | 326 | 4 | 4 | '''
Escreva um programa que leia uma palavra
qualquer e conte o número de vogais
'''
print("exe1")
string = input("escreva a palavra: ")
cont = 0
for i in string:
if i.upper() == 'A' or i.upper() == 'E' or i.upper() == 'I' or i.upper() == 'O' or i.upper() == 'U':
cont +=1
print("quantidade de vogais", ... |
de1908cd3e2aa667336bc749d431aeab6353b996 | amitturare/Basic-Python-Problems | /Calculator.py | 1,818 | 4.25 | 4 | '''
a = float(input("Enter one number"))
b = float(input("Enter another number"))
print("Print 1 for Addition")
print("Print 2 for Substraction")
print("Print 3 for Multiplication")
print("Print 4 for Division")
print("Print 5 for Modulus")
try:
c = int(input("Enter your choice: "))
if(c == ... |
f771cf234d4d7a26c160fae5cef4bc3740007eea | gitfernandojmm/devcode_python_notas | /cap04/4_break-continue.py | 433 | 3.859375 | 4 | # /usr/bin/env python
# coding=utf-8
# break
x = 0
while True:
if x == 10:
break
x += 1
print('Salio del bucle infinito')
lista_enteros = [1, 2, 3, 4, 5]
for x in lista_enteros:
if x == 3:
break
print(x)
# continue
x = 0
while x < 10:
if x == 4:
continue
x += 1
... |
7aa6affd0c2ee4e979b7bfef6067dc5a77782ebe | SJmdy/PythonForLeetCode | /src/stack_or_queue.py | 4,209 | 3.640625 | 4 | # 使用栈或队列解决的问题
# 1047. 删除字符串中的所有相邻重复项
#
# 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。在 S 上反复执行重复项删除操作,直到无法继续删除。在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
#
# LC: [1047. 删除字符串中的所有相邻重复项](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/)
def remove_duplicates(s: str) -> str:
if len(s) == 0:
... |
746cc6d9d51df422ec1634c629adb4afd90d031d | fstoltz/schoolwork | /Datastructures and algorithms/DSALibrary_fredriks/test_Queue.py | 951 | 3.65625 | 4 | import unittest
from Queue import Queue
"""
Things are working fine as of 1/12-2017
"""
class TestQueue(unittest.TestCase):
def test_01_create_queue(self):
q = Queue()
q.enqueue(50)
q.enqueue(100)
q.enqueue(150)
value = q.dequeue()
self.assertEqual(value, 50... |
3a44379c89fd057e1d6934f2bf215d305f8c43e8 | python-practice-b02-927/volkova | /lab2/task_11.py | 224 | 3.921875 | 4 | def circle(r):
for i in range (50):
t.forward(math.pi *r / 50)
t.left(360 / 50)
import turtle
t = turtle.Turtle()
import math
for i in range(8):
circle(100+20*i)
t.left(180)
circle(100+20*i) |
299a909e0454f6350072ff968328a2881773d927 | brunasimaens/pubele2020 | /exercicios_completos/ex2-2.py | 439 | 3.828125 | 4 | import sys
import re
# neste programa apenas contamos o numero de ocorrencias da palavra "".
def search(word):
with open("dicionario_medico.txt", "r") as f:
content = f.readlines()
ocorrencia = 0
linhas = []
for i, line in enumerate(content):
matches = findall(word ,line)
if matches:
ocorrencia +=... |
2f3eb07894e37386429f634774e40d6e84216df0 | emilianocasijr/Reviewer | /common_voice_recognition.py | 980 | 3.578125 | 4 | # This program is used to store the common voice recognition of various commands in the program
import speech_recognition as sr
import csv
r = sr.Recognizer()
data = {}
key = ""
while(1):
key = input("Enter key: ")
if key == "end":
break
print("Say " + key)
for i in range(50):
print(... |
6111e391ac32a1781a0981d7fc16bff283e01f13 | Pattadon7642/100-Days-Python | /Rock Paper Scissors.py | 1,019 | 3.984375 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
_... |
0892399580ec60774d623692662040c9d077d650 | Computer-engineering-FICT/Computer-engineering-FICT | /I семестр/Програмування (Python)/Лабораторні/Лисенко 6116/Python/Презентації/ex23/Ex25.py | 184 | 3.515625 | 4 | class MyClass:
def __init__ (self, y):
self.x = y
def hash (self) :
return hash(self.x)
m = MyClass(10)
d = {}
d[m] = "Значення"
print(d[m])
|
d77765cd57f7594bbe6da9a3ea975b6e9239c04d | livolleyball/python_smart | /python_cookbook/DataStructuresAndAlgorithms.py | 894 | 4.09375 | 4 | # coding:utf8
# 1.1 将list或者tuple分割成变量
p = (4, 5)
x, y = p
print("x:", x, "y:", y)
data = ["a", "b", "c", "d"]
A, B, C, D = data
print(A, B, C, D)
s = 'hello'
a, b, c, d, e = s
print(a, b, c, d, e)
# a,b,c,d,e,f=s
# ValueError: not enough values to unpack (expected 6, got 5)
data = [12.1, "b", "c", 5, (3, 4, 5)]
_, ... |
e5d9e90dc394684518809add8ba7473b3959d0a5 | LucasLima337/CEV_Python_Exercises | /exercicios/ex090.py | 945 | 3.8125 | 4 | # Dicionário em Python
# condição de aprovamento >= 7
aluno = dict()
grupo = []
cont = 0
while True:
aluno['nome'] = str(input(f'\nNome do {cont + 1}º aluno: ')).strip().title()
aluno['media'] = float(input(f'Média de {aluno["nome"]}: '))
if aluno['media'] >= 7:
aluno['situacao'] = 'Aprovado'
e... |
b2613302caa6a6a333e32f9bbf9bcc1ca9c180bb | sasa33k/PSCourse | /_02_PyFunctionsFilesYieldLambda.py | 2,712 | 3.703125 | 4 | students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase.append(student["name"].title())
return students_titlecase
def print_students_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_stud... |
fd03ae6217f18d3c15f7af01ee1646aeba7651c7 | B05611003/108-2_python_hw | /1081.py | 67 | 3.671875 | 4 | a = int(input())
if a%2 == 0:
print("Tom")
else:
print("Jerry")
|
c43b9f4a739bf2c36a735143fbabda49d34c4c53 | 810Teams/pre-programming-2018-solutions | /Online/0057-Bedtime.py | 376 | 3.828125 | 4 | """
Pre-Programming 61 Solution
By Teerapat Kraisrisirikul
"""
def main():
""" Main function """
sleep = int(input())*60 + int(input())
awake = int(input())*60 + int(input())
if awake <= sleep:
awake += 24*60
if awake - sleep < 7*60:
print('Not enough')
elif awake - sleep < 10... |
e2a7c955c6a223bb52d2c6aea54c49ec072afbbe | blancasserna/Mo3 | /python/Preu_a_pagar1.py | 121 | 3.640625 | 4 | edat = int(input("Indica la teva edat:"))
if (edat < 5) or (edat >= 65) :
print ("Gratis")
else:
print ("No gratis")
|
5a7aa39bbcdf7abd69ff8d5f896699679aa73ef7 | banma12956/banma-leetcode | /lc77.py | 193 | 3.609375 | 4 | import itertools
n=5
k=3
comb = list(itertools.combinations(range(1, n+1), k))
print(comb)
answer = []
answer_temp = []
for i in range(len(comb)):
answer.append(list(comb[i]))
print(answer) |
9cc4fef03af193b716ea06b7fa2db28a031c7192 | mikooh/learnsite | /learnsite/views.py | 2,121 | 3.546875 | 4 | from django.http import HttpResponse # this is basically just some django code, that allows us to very simply return back, some information as HTTP response. we can essentially send back the 'hello' below.
from django.shortcuts import render
import operator
# def home(request):
# return HttpResponse('Hello') # ... |
fa6078a33ff4099f307a2b793537f66e59f6a2f5 | boddachappu/interviewnotes | /DataStructures/DataStructures.py | 2,018 | 3.84375 | 4 | class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
def getPointer(self):
return self.pointer
def setPointer(self, new):
self.pointer = new
class LL:
def __init__(self):
self.head = None
def insertEnd(self, v... |
9438e05943ea8fd5c6f77190eff68ab6870bc560 | MFTECH-code/Exercicios-logicos-python-02 | /ex07.py | 213 | 4.125 | 4 | num = int(input("Digite um número inteiro: "))
if (num % 5 == 0 and num % 10 == 0):
print(f'{num} é divisivel por 5 e 10 ao mesmo tempo')
else:
print(f'{num} não é divisivel por 5 e 10 ao mesmo tempo') |
090d66834f6cb0d83987c8eba18403765c28cbb3 | Fixer38/University-Notes | /semester-1/progra-ex/manip2/ex2-null.py | 101 | 3.8125 | 4 | nb = int(input("Entrez un nombre: "))
if nb == 0:
print("nb nul")
else:
print("nb non nul")
|
a1ad701ae83f3ff436c1ca2a0cc2b05d8c5b9d5e | Javigner/Bootcamp-Python-for-Machine-Learning | /Day00/ex02/whois.py | 200 | 3.734375 | 4 | import sys
if sys.argv[1].isnumeric() == False or len(sys.argv) != 2:
print("ERROR")
else:
if (int(sys.argv[1]) % 2 == 0):
print("I'm Even.")
else:
print("I'm Odd.")
|
4c1c5203335d2ff52ed91f17ede55a507cf617a6 | mikkosoi/Python-programming | /13.py | 618 | 4 | 4 | '''
Write multiple functions that print the following information when called:
'''
def dog_sleeps(name, time): #prints: X sleeps Y hours
print name, " sleeps ", time, " hours"
def dog_walks(name, speed): #prints: X walks Y speed
print name, " walks ", speed, " speed"
def dog_runs(name, speed): #prints: X runs... |
0b896b503be27ca339d51e0ab79a146356a2b7e9 | jasapozne/Project-Euler | /euler_problem25.py | 285 | 3.71875 | 4 | def fibonacci(n):
a = 0
b = 1
while a <= n:
a, b = b, a + b
return a
def fibonacci_1000_stevk():
k = 11
while True:
k += 1
fib = fibonacci(k)
if len(str(fib)) > 999:
break
return k
print(fibonacci_1000_stevk()) |
6349fcb5aad610888dd2b773ca448cbd0bb02b41 | SolomonLake/Scheduling-Python | /make_output.py | 925 | 3.78125 | 4 | def make_output(out_dict,output_name):
"""
Given an output dictionary that looks like {course_number : [Room, Teacher, Time, students]} makes an a file at output_name that is essentially a .tsv
"""
with open(output_name,'w') as f:
output = ["Course\tRoom\tTeacher\tTime\tStudents"]
for course in out_dict:
lin... |
0c605019e96ad3ad9b0c00af35f42e5042f52ac6 | sirkibsirkib/python_tut | /tasks/task1_converter/converter.py | 434 | 4.15625 | 4 | """
TODO
"""
lb_per_kg = 2.204
km_per_mi = 1.6
print('Input your value:')
string_value = input()
value = float(string_value)
print('Input your unit:')
unit = input()
if unit == 'kg':
print(str(value*lb_per_kg) + ' lb')
elif unit == 'lb':
print(str(value/lb_per_kg) + ' kg')
elif unit == 'mi':
print(str(valu... |
c895a94a2b0c2e12f428bb956a990cb5e5ed2a10 | garyalex/pythonpractice | /pybites/107.py | 341 | 4.03125 | 4 | def filter_positive_even_numbers(numbers):
"""Receives a list of numbers, and filters out numbers that
are both positive and even (divisible by 2), try to use a
list comprehension"""
return list(i for i in numbers if (i % 2 == 0 and i > 0))
nums = [1, 2, 4, -1, 11, 6, 0, 8]
print(filter_positive... |
f6a61a83db50b18147d2e11bfe224dd0be674409 | anish531213/Interesting-Python-problems | /InsertionSort.py | 229 | 4.125 | 4 | def InsertionSort(arr):
for i in range(1, len(arr)):
for j in range(i, 0, -1):
if l[j] < l[j-1]:
l[j], l[j-1] = l[j-1], l[j]
l = [3, 9, 7, 1, 3, 4, 8, 2, -1, -5]
InsertionSort(l)
print(l)
|
ca284c839f4116d24825b68eafbc0b78e14892ed | basnetroshan/Python-Revision | /strings.py | 1,561 | 3.796875 | 4 | a = "Double Hello" #double quote
b = 'Single Hello' #single quote
print(a)
print(b)
#Multi line String in double quote
c = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(c)
#Multi line String in single quote
d= '''\nLorem ipsum d... |
e96767e093d5acfd072a689f8f7757fb672b2fba | annh3/coding_practice | /alien_dictionary_2.py | 1,777 | 4.1875 | 4 |
def alien_dictionary(words):
# Here's how you do a double for loop list comprehension
reverse_adj_list = {c: [] for word in words for c in word}
# add edges to the adjacency list
"""
I think the structure that you need to understand here is that information is only useful up to the “first difference”
That’... |
08c48354f15d42c6fbdd4f9c060c1a0fe0a3e494 | itsdeepakverma/anu_repo | /day1_CC.py | 5,421 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 11:24:40 2018
@author: sharm
"""
#Challenge 1
n=input("Enter a number ")
import math
x=math.factorial(int(n))
print("factorial of number is:",x)
#challenge 2
r=input("enter radius of the circle :")
from math import pi
area= pi* int(r)*int(r)
circum=2*pi*int(r)
print... |
726979fb4c9e10fde0292a0a4a415bf29a3bdbaa | wakafengfan/Leetcode | /dp/rabbit.py | 1,234 | 4.03125 | 4 | """
小兔的叔叔从外面旅游回来给她带来了一个礼物,小兔高兴地跑回自己的房间,拆开一看是一个棋盘,小兔有所失望。不
过没过几天发现了棋盘的好玩之处。从起点(0,0)走到终点(n,n)的最短路径数是C(2n,n),现在小兔又想如果不穿越对角线(但可接触对角线上的格点),
这样的路径数有多少?小兔想了很长时间都没想出来,现在想请你帮助小兔解决这个问题,对于你来说应该不难吧!
Input
每次输入一个数n(1<=n<=35),当n等于-1时结束输入。
Output
对于每个输入数据输出路径数,具体格式看Sample。
Sample Input
1
3
12
-1
Sample Output
1 1 2
2 3 10
3 12 4160... |
ea5312aa8e072f20adc94cdc3d90562c824f0320 | Lusius045/LucioRP | /Estructuras repetitivas/TP2.py | 564 | 4.0625 | 4 | print("-------------------------------------------------------")
print("SUMA DE DIVISORES:")
print("-------------------------------------------------------")
print("Ingrese números aleatorios, para concluir, ingrese un número negativo")
num = int(input())
while (num > 0):
suma = 0
for i in range ... |
e2a0eb9ec199bf83ec8051a52791eb5e22aa0e75 | ntkawasaki/complete-python-masterclass | /13: Using Databases/Exception Handling/intro.py | 353 | 4 | 4 | # wrap code in try and except to prevent a crash
def factorial(n):
"""Calculate n! recursively."""
if n <= 1:
return 1
else:
return n * factorial(n - 1)
try:
print(factorial(1000))
except (RecursionError, ZeroDivisionError):
print("[Factorial Error/Zero Division Error]")
print(... |
68400430d4d414579210550d5f8faee661520201 | zequequiel/ramda.py | /ramda/remove.py | 354 | 3.640625 | 4 | from toolz import curry
@curry
def remove(index, length, list):
"""Removes the sub-list of list starting at index start and containing
count elements. Note that this is not destructive: it returns a copy of
the list with the changes.
No lists have been harmed in the application of this function"""
return list... |
88df94d1422b7adf5b7ce7a5fdda352e65aa1ccd | chriswtanner/lectures | /lecture12/scope_example.py | 233 | 4.03125 | 4 | def main():
names = ["malik", "stephanie", "ellie", "rico"]
for name in names:
print(name)
i = 3
print(i)
# this is the main entry point of our entire Python program
if __name__ == "__main__":
main()
|
a32ada2d856b88e755dac19228fde49293694acf | VTBEST12/turtle-art-design | /I dont know what to name it.py | 3,049 | 3.609375 | 4 | import turtle
turtle.colormode(255)
bob=turtle.Turtle()
turtle.bgcolor("black")
bob.width(5)
bob.speed(500)
c = (217,98,175)
for times in range(40):
c = ("lime")
bob.color(c)
bob.circle(100)
bob.right(7000)
for times in range(30):
c = ("orange")
bob.color(c)
bob.circle(100... |
e662c85702ae36deaeaadd037884ded7dd2d8cbc | rybakovas/Python | /Python/Exercises/exerc5.py | 239 | 3.796875 | 4 | # Remove the duplicate itens in a list
numbers = [1, 4, 3, 2, 1, 5, 4, 10]
unique =[]
for number in numbers:
if number not in unique:
unique.append(number)
print(unique)
# By Victor Rybakovas Sep 2019 - http://bit.ly/linkedin-victor
|
a40f0fc3d628501d01e2bd7fdcef1c31bb1aa3ab | tangneng/study_python | /files_to_folder.py | 1,243 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/25 9:12
# @Author : superyang713
# @File : file_folder.py
# @desc: 把相同文件类型的文件移动到一个文件夹中
import os
import shutil
def main():
dest_folder = 'E:\\N迈外迪'
sort_files(dest_folder)
def sort_files(dest_folder):
"""
parameters:
des... |
f6d46195b9961d7108b27a2e71e2a52b542c8950 | KaranKaur/Leetcode | /458 - PoorPigs.py | 2,073 | 4.125 | 4 | """
There are 1000 buckets, one and only one of them contains poison,
the rest are filled with water. They all look the same. If a pig drinks that poison it
will die within 15 minutes. What is the minimum amount of pigs you need to figure out
which bucket contains the poison within one hour.
Answer this question, and... |
4c1c3597e7301190c6b4182c0b51f03d9b1db38e | rishabht1219/software-engineering | /services/Interfaces/ICharacter.py | 369 | 3.578125 | 4 | from abc import ABCMeta, abstractmethod
class ICharacter(metaclass=ABCMeta):
"""interface for the player and bear class"""
@abstractmethod
def move_up(self, position): pass
@abstractmethod
def move_down(self, position): pass
@abstractmethod
def move_left(self, position): pass
@abstra... |
583bf829ba9fdc2a64f0ad9d1dae1f90cf1e4b3a | qixiaobo/navi-misc | /python/menu.py | 798 | 3.78125 | 4 | #!/usr/bin/env python
import sys
def menu(title, items):
while True:
print title
itemNumber = 0
itemMap = {}
for item, value in items.iteritems():
itemNumber += 1
print "%d. %s" % (itemNumber, item)
itemMap[itemNumber] = value
try:
... |
2fb821d3432b5012844939ef9021407a6d54332a | dqureshiumar/competitive-coding-python | /xor-operation-in-an-array.py | 377 | 3.625 | 4 | #Author : Umar Qureshi
#Leetcode's XOR Operation in an Array Python3 Solution
# Problem Link : https://leetcode.com/problems/xor-operation-in-an-array/
class Solution:
def xorOperation(self, n: int, start: int) -> int:
nums = []
for i in range(n):
nums.append(start + 2 * i)
x = ... |
1797ef75ac808b8ef5e2163150656f2d527d46b0 | Leahxuliu/Data-Structure-And-Algorithm | /Python/巨硬/C19.找下标值与值相同的点.py | 451 | 3.625 | 4 | '''
有序数组找到num[i] == i的那个,进阶:数组有可能有重复值
1. 无
'''
def find(nums):
if nums == []:
return -1
l = 0
r = len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if mid == nums[mid]:
return mid
elif mid < nums[mid]:
r = mid - 1
else:
l... |
8550fecf338ea66c6a9b1d59cbeb4ba982006e6f | sdmgill/python | /Learning/Chapter10/10.3-Exceptions.py | 940 | 4.1875 | 4 | # generate an error - can't divide by 0
print(5/0)
# use try/except block to handle to error
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by 0 dumbass.")
# add to this
print("Give me two numbers and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nF... |
00b0690298e4322de5c9d28507ae0ecb67497ad7 | arpitp07/UChicago_MScA_RTIS | /Week 6/Week_6_distance.py | 6,655 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
import time
random.seed(123)
k_bit = 32
#
# Complete the Node and CircularLinkedList class below.
#
class Node:
# implement here. see case1 below for required attributes
def __init__(self, data, k=k_bit):
self.id = random.getra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.