blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ddea2dcdf682f00d0bb331022ffb9bcda2961982 | Potrik98/plab2 | /proj3/crypto/MultiplicationCipher.py | 805 | 3.65625 | 4 | from crypto.Cipher import Cipher, alphabet, alphabet_length
from crypto.SimpleCipher import SimpleCipher
from crypto.crypto_utils import modular_inverse
class MultiplicationCipher(SimpleCipher):
class Key(Cipher.Key):
def __init__(self, factor: int):
self._factor = factor
self._inve... |
ea93a608608867db9112c90d2bafd74f4f5942fc | arizpando/Hacktoberfest1 | /arbol.py | 782 | 3.75 | 4 | x=int(input("opción= "))
espacios=x+2
if espacios >= 1:
if (x%2)==0:
for i in range(0,(espacios//2)-1):
espacio=" "
espacios-=2
numEspac=(espacio*espacios)
inicEspac=espacio*i
print(inicEspac,"\\",numEspac,"/")
for i in range(... |
c17edcf8c17fae20d8072f584ecb1337e6f9cac1 | djtorel/python-crash-course | /Chapter 09/Try It/Try04/number_served.py | 2,171 | 4.59375 | 5 | # Start with your program from Exercise 9-1 (page 166). Add an attribute
# called number_served with a default value of 0. Create an instance
# called restaurant from this class. Print the number of customers the
# restaurant has served, and then change this value and print it again.
# Add a method called set_num... |
a3750ca9cc89a0a6940c6264a5bc3523c5911929 | juntwelfth/Notes | /Python/Computer Science/Algorithms/Searching/Linear Search.py | 300 | 3.890625 | 4 | def linear_search(search_list, target_value):
for idx in range(len(search_list)):
if search_list[idx] == target_value:
return idx
raise ValueError("{0} not in list".format(target_value))
print(linear_search([1, 2, 3, 4, 5], 4))
print(linear_search([1, 3, 5, 7, 9], 10))
|
00946591f304cb8f9aced866210a7f8e344a4016 | marcusshepp/dotpy | /acm_comp/pc.py | 662 | 3.875 | 4 | #!/usr/bin/python
import copy
the_in = raw_input().strip().split()
method = the_in[1]
size = int(the_in[0])
def split_list(l):
return l[len(l)/2:], l[:len(l)/2]
def merge(r, l, m):
z = []
if m == "in":
return [item for pair in zip(r, l) for item in pair]
elif m == "out":
return [item... |
2c809d3629a624d5553d91f9bb627bec88bc0556 | m-lab/bigsanity | /bigsanity/formatting.py | 1,415 | 4.0625 | 4 | # Copyright 2015 Measurement Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
fbd451ae7116eedee1d7f5b854e17946f459fd88 | devecis/learning | /Python_Workout/Exercise01/Exercise01.py | 1,372 | 4.5 | 4 | """
Write a function (guessing_game) that takes no arguments.
When run, the function chooses a random interger between 0 - 100 inclusive
Then asks the user to guess what number has been chosen
Each time the user enters a guess, the program indicates one of the following:
- Too High
- Too Low
- Just right
If the user gu... |
51bc534916cb106dad19fdba834e24a9dd15cab4 | shanuman816/project-1 | /L-11 Assignment Water Gates.py | 362 | 3.640625 | 4 | # Fuction to check
def balance(s):
stack = []
balanced = True
i = 0
c = 0
while i<len(s) and balanced:
char = s[i]
if char == '(' : stack.append(char)
else:
if stack==[]: balanced = False
else:
stack.pop()
c+=1
i+=1
if stack==[] and balanced: print(c)
else: print(-1)
# Taking Input
s = inp... |
76350336dd46c3e7d13d97bd3717748e3eea5d19 | Jyun-Neng/LeetCode_Python | /130-surrounded-regions.py | 2,720 | 3.9375 | 4 | """
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
Input:
X X X X
X O O X
X X O X
X O X X
Output:
X X X X
X X X X
X X X X
X O X X
Explanation:
Su... |
0c1f2a4bce64b04570725861e01b4813f68c3cbc | jordanmmck/cs | /alg_ds/hackerrank/python_path/07.collections/2.defaultdict.py | 566 | 3.75 | 4 | from collections import defaultdict
# d = defaultdict(list)
# d['python'].append("awesome")
# d['something-else'].append("not relevant")
# d['python'].append("language")
# for i in d.items():
# print(i)
# print(d)
n, m = map(int, input().split())
# group A
A = []
for i in range(n):
A.append(input())
# group ... |
486137f6731552af3b034e2a74b036ba8470024d | clarkngo/python-projects | /python-list-mastery/two-pointers-switch-in-place.py | 636 | 3.640625 | 4 | # Remove Duplicates from Sorted Array
# Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
class Solution:
de... |
e765039ed759174736885b56c4587ccb108d1205 | calvinterpstra/TUDelftPython | /PythonQ2/IndentationLevel.py | 1,688 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
IndentationLevel.py -- experiment whith source code indentation levels
@author: Bart Gerritsen
"""
# EXPERIMENT: try shifting any line at this level (including def's) one to
# position to the right
# EXPERIMENT: try shifting all lines at this level (consistently) to the right
p... |
f3c1853b5a640cd5abc22df26fb5affb35b2517e | karthikram003/Projects | /secretSanta/shuffle.py | 485 | 3.515625 | 4 | ##import random
##import queue
##
##q = queue.Queue()
##
##randlist = list(range(1,11))
##print(randlist)
##random.shuffle(randlist)
##print(randlist)
##
##for i in randlist:
## q.put(i)
##
##if not q.empty():
## print("hihihihihih")
##
##import itertools
##
##permlist = [i for i in range(1,4)]
##print(permlist)... |
a07daf176c8b1bcc93fe331fc45717b7cbbb82ff | dikshakurwa/learning | /wishlist.py | 183 | 3.765625 | 4 | wishList = ["takis", "new macbook", "license", "car", "vacation"]
item = str(input("please enter one of diksha's wishes: "))
if item in wishList:
print("True")
else:
print("False")
|
37e792ecfee97e1b5687c2c2fcbb4e6c28b401fc | JulianCSalazar/Python_Tutorial | /PythonIntro.py | 10,256 | 3.890625 | 4 | #############################################################
# File : PythonIntro.py
# Author: Julian Salazar
# Date: 7/21/18
# Description:
# This file is a testing platform for basic python commands
# Contents:
# 1. Print Statements
# 2. Variables and Types
# 3. Logical Operators
# 4. Mathematical Operator... |
47d7d110119490e9a81a417410e268f92b1ab3cb | lnhote/leetcode | /46_permutation.py | 1,229 | 3.71875 | 4 | class Solution(object):
"""docstring for Solution"""
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
return self.permuteResult([], nums)
def permuteResult(self, result, nums):
import copy
new_result = []
... |
1adb1b699317592682b801b011c15cf2a09cafad | o-henry-coder/python05_12_2020 | /univer/HW/chapter02/algorithmic trainer.py | 999 | 3.984375 | 4 | #Task1
height = input('please, enter your height ')
print('thank you! your height is ', height)
#Task2
color = input('Now please, enter your favourite color ')
print('thank you! your color is ', color)
#Task3
a = int(input('enter a '))
b = a + 2
a = b * 4
b = a / 3.14
a = b - 8
print(a,b)
#Task4
w = 5
x = 4
y = 8
z ... |
9c6706bae39da017aa9d24bd5e5dc424b853aa0e | jmac03/CSE310 | /client.py | 2,652 | 3.515625 | 4 | import socket
import errno
import sys
# Constants
HEADER_LENGTH = 16
FORMAT = "utf-8"
RECEIVE_COLOR = "\033[35m"
NORMAL_COLOR = "\033[32m"
ERROR_COLOR = "\033[31m"
# IP address of this computer
IP = socket.gethostbyname(socket.gethostname())
PORT = 1234
ADDR = (IP, PORT)
my_username = input("Username: ")
client_sock... |
8741c3ec2c5dba3f088820dfce94c27587c9512f | shouliang/Development | /Python/PyDS/array_sum.py | 801 | 3.8125 | 4 | # coding=utf-8
'''
数组求和
'''
# 循环遍历做法
def sum1(array):
sum = 0
for value in array:
sum += value
return sum
# 递归: 分解为最后一位+前n-1项的求和,递归终止条件:n == 1
def sum2(array):
def sumCore(array, n):
if n == 1:
return array[0]
return array[n - 1] + sumCore(array, n - 1)
return... |
37ee2ccc42bdbbb544291b2587f49a00ea4d061d | StetsenTech/rolodex-reader | /rolodex/utils/process.py | 2,320 | 3.65625 | 4 | """Module that adds methods to help with processing input"""
import re
import phonenumbers
# Regex validators for file input
VALID_ONE = re.compile((
r'(?P<last>[A-z]+),\s(?P<first>[A-z. ]+),\s'
r'(?P<phone>\([0-9]{3}\)-[0-9]{3}-[0-9]{4}),\s'
r'(?P<color>[A-z ]+),\s(?P<zip>[0-9]{5})'
))
VALID_TWO = re.com... |
7b6c9b49eff36473333993646501077b86ab7e4b | salim7ali/HackerRank | /Algorithms/Implementation/Encryption/solution.py | 907 | 4.03125 | 4 | #https://www.hackerrank.com/challenges/encryption
#!/bin/python3
import math
import os
import random
import re
import sys
from itertools import zip_longest
# Complete the encryption function below.
def encryption(text):
low = math.floor(math.sqrt(len(text)))
high = math.ceil(math.sqrt(len(text)))
newTex... |
5b5f1892d90bc5af3fea0a93d7dc44343ae65093 | cheonyeji/algorithm_study | /이코테/구현/q11_기둥과보.py | 5,241 | 3.53125 | 4 | # 2021-01-30
# 이코테 ch12 구현 문제 Q11 기둥과 보 설치
# https://programmers.co.kr/learn/courses/30/lessons/60061
# 해설
# 구현 과정이 복잡하고, 시간이 5초로 넉넉하기 때문에 m^3의 시간복잡도로 간단하게 해결하는 풀이
# 설치 및 삭제 연산을 요구할때마다 일일히 전체 구조물을 확인하며 규칙 체크
# 현재 설치된 구조물이 가능한 구조물인지 확인
def possible(answer):
for x, y, stuff in answer:
if stuff == 0: # 기둥 설... |
7fc685e7bc1be522d8416ba0f3d77131e448234c | 1bcb1/Lab06 | /Conservation of Angular Momentum.py | 1,617 | 3.625 | 4 | # Brooks Brickley & Hector Hernandez CC: 2019
from statistics import mean
from math import sqrt
before = input('What is the name of the before file? : ') + '.csv'
after = input('What is the name of the after file? : ') + '.csv'
beforeID = open(before, 'r')
data = []
firstline = beforeID.readline()
nextline = beforeID... |
164fe64755c132ef76ab8d92f9a308b2760d2002 | srclayton/Python-uDemy | /ex01.py | 167 | 4.03125 | 4 | # -*- coding: utf-8 -*-
idade = int(input("Digite sua idade: "))
if idade > 17:
print("Você é maior de idade!")
else:
print("Oh não, você é menor de idade!") |
d70045f170b1622864cf036131c038c7ea1b03bf | zhkflame/StudyCode | /BFSandDFS/mytree.py | 766 | 3.609375 | 4 | class TreeNode(object):
def __init__(self,v=None):
self.val=v
self.right=None
self.left=None
def addLeft(self,ele):
self.left=ele
def addRight(self,ele):
self.right=ele
def setValue(self,v):
self.val=v
if __name__=='__main__':
binT=TreeNode('t')
... |
c0ec3abac0da9ec860aedff8efbe9b9688797788 | hrishisd/CS170-Solver | /phase2/solver.py | 5,098 | 3.828125 | 4 | import argparse
import random
import numpy as np
from collections import defaultdict
import operator
"""
======================================================================
Complete the following function.
======================================================================
"""
def solve(num_wizards, num_const... |
232dd01c726bd37b6e46ee7221954bf112624929 | bumjin/python-essential | /18_gui-programming/gui.py | 561 | 3.53125 | 4 | #!/usr/bin/env python
import wx
def sayHello(event):
#print "hello world!"
#textArea.SetValue("hello World!")
labelValue = myLable.GetValue()
textArea.AppendText(" Hello "+labelValue)
app = wx.App()
frame = wx.Frame(None, title="hello world!", size=(400,400))
frame.Show()
helloButton = wx.Button(frame, label='s... |
65cb8faecf0cdecf2904f56145becca0093d2a01 | Nora-Wang/Leetcode_python3 | /Stack/716. Max Stack.py | 1,983 | 4.1875 | 4 | Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, a... |
048c631503e728b70329a317514a8e4621177193 | vidi-vidi/Tugas | /5a.py | 279 | 3.6875 | 4 | print("MENGECEK KELULUSAN")
jwb = "y"
while jwb.lower() == "y":
n = input("Masukan nilai =")
if int(n) > 60:
status = "Lulus"
else:
status = "Ulang"
print(status)
jwb = input("Input Lagi y/t")
if jwb.lower() == "t":
print(jwb)
break |
d00d3c1c3ef2bceaa49c2da91dc20fa16aba507a | ZhangYajun12138/buxianxian | /BuXianXian/buxianxian10.py | 1,619 | 4.53125 | 5 | # coding:utf-8
# string
def main():
str1 = "hello world!"
# 通过len函数计算字符串的长度
print(len(str1))
# 获得字符串首字母大写的拷贝
print(str1.capitalize())
# 获得字符串变大写的拷贝
print(str1.upper())
# 从字符串中查找子字符串所在位置
print(str1.find("or"))
print(str1.find("shit"))
# 与find类似但找不到子字符串时会引发异常
print(str1.in... |
5b23fd00af451fa857ac8ddbb77487e0eb83fc34 | darvid7/fit2085-notes | /algorithms/01-bubble_sort.py | 168 | 3.75 | 4 | def bubble_sort(L):
n = len(L)
for i in range(n - 1):
for j in range(n - 1):
if L[j] > L[j + 1]:
L[i], L[j] = L[j], L[i] |
334138e515e0fa63ad033f3648a67c9ad83f3361 | ridbit10/PS1-Parinati-Solutions | /DateAndTime/Date.py | 689 | 4.15625 | 4 | import datetime
#gets current date and time
datetime_object=datetime.datetime.now()
print(datetime_object)
#gets todays date
date_object=datetime.date.today()
print(date_object)
#date is a constructor
d=datetime.date(1999,10,6)
print(d)
#date from timestamp
timestamp=datetime.date.fromtimestamp(1326244364)
print("D... |
af0062ca859e0b372db17af63c7e4d618dc62f5b | alejo979/Address-Book | /ab1.py | 5,618 | 4.1875 | 4 | # Create your own command-line address-book program using which you can browse, add, modify, delete or search for your contacts
# such as friends, family and colleagues and their information such as email address and/or phone number.
# Details must be stored for later retrieval.
import pickle
from pathlib import ... |
5ce77a872ab716ca11e266d7a8c43b70bb831aa2 | satriansyahw/StudyPython | /Test2.py | 917 | 3.828125 | 4 | # string
name="kiran"
kar1=name[1]
print(kar1)
print(type(name))
print(name.capitalize())
anak=["Ara","Kiran"]
print('print pertama :' + anak[0])
print('print kedua : '+anak[1])
txt ="hai-hello-world"
txtsplit= txt.split('-')
print('Split 0 : '+txtsplit[0])
print('Split 1 : '+txtsplit[1])
print('Split 2 : '+txtsplit[... |
1778c257042176fb58c7cee607795281900c1f36 | Carmenliukang/leetcode | /算法分析和归类/动态规划/打家劫舍.py | 1,522 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上
# 被小偷闯入,系统会自动报警。
#
# 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
#
#
#
# 示例 1:
#
#
# 输入:[1,2,3,1]
# 输出:4
# 解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
# 偷窃到的最高金额 = 1 + 3 = 4 。... |
49b2a4d7ea2eee79f263366883e457fd22b478b9 | bill-ma/project-euler | /random_number_game.py | 384 | 3.96875 | 4 | import random
low = 1;
high = 100;
x = random.randrange(low,high);
#print(x);
print("I'm thinking of a number b/t", low, "and", high, end="\n\n");
count = 1;
while True:
print("Attempt #", count, end=": ");
guess = int(input());
if(guess < x):
print("Too low!");
elif(guess > x):
print("To... |
d77de5c02531a1311995a7f9c44d1212b455a8de | kenwu90/leetcode | /complement_number.py | 541 | 3.609375 | 4 | import sys
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
# find leading 1
a = num
cnt = 0
while ((a & sys.maxsize) > 0):
cnt += 1
a = a >> 1
b = 0
... |
d37766651b385108883f6094c929120d667a3e99 | TwilightStrafer/LeanCoding | /strings.py | 109 | 3.796875 | 4 | a = 'hello'
b = "hello"
c = """hello
Next Line
Third Line
"""
print(c)
name = input ("What's Your Name?\n") |
5afa4c0b90297824f949b378027a7938ff7649b7 | Ran4/stringexpand | /stringexpand/__init__.py | 1,197 | 3.953125 | 4 | #!/usr/bin/env python3
__all__ = ["expand"]
from typing import List, Tuple
from functools import wraps
def find_braces(s: str) -> Tuple:
return (s.index("{"), s.index("}"))
def string_contains_set_of_braces(s: str) -> bool:
return s.find("}") > s.find("{") >= 0
def split_brace_contents(s: str) -> List[str]:... |
d188c66ed92a38d8348da7a9de56ad36fee0ea21 | iasinDev/codinginterviewquestions | /Simple Queries/Solution.py | 258 | 3.5 | 4 | import bisect
def counts(nums, maxes):
nums.sort()
result = []
for max in maxes:
index = bisect.bisect_right(nums, max)
result.append(index)
return result
print(counts([1,4,2,4],[3,5]))
print(counts([2,10,5,4,8],[3,1,7,8])) |
718c95f8fcac9c60c5783aa11a78c2077bda7ff8 | 316060064/Taller-de-herramientas-computacionales | /Clases/Programas/Tarea4/Problema03.py | 298 | 4 | 4 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
'''
Josue Artemio Hernandez Rodriguez, 316060064
Este programa realiza la conversion de grados
centigrados a farenheit, y viceversa.
'''
def grados(x):
g = 0
if x == 1:
x = (x * 9/5.0) + 32
else:
x = (x - 32) * 5.0/9
return x
... |
83d0092762593cfbf4d7111b2c8154c8fda273e3 | smrsassa/Studying-python | /curso/PY3/funcao/funcao2/ex6.py | 263 | 3.546875 | 4 | #exercicio106
while True:
def div_texto():
print ('-='*40)
div_texto()
print ('Sistema de ajuda PyHELP')
div_texto()
opc = str(input('Digite a função aqui: '))
if opc.lower() == 'fim':
break
else:
help(opc)
|
168e854f32e1aa6626bd915aaa3b68ea18f6db68 | Jahanzaib-int/Cryptographic-Algorithms | /RSA.py | 3,590 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 10:39:35 2018
@author: Jahanzaib Malik
"""
import random
'''
Euclid's algorithm for determining the greatest common divisor
Use iteration to make it faster for larger integers
'''
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
'''
Euclid's exten... |
6802004433d0db42d6a461e6fc26d5605f5cce55 | SurajAravindB-GITAM/data_structures_using_python_lab_assignment-SurajAravind | /10_queue.py | 2,674 | 4.625 | 5 | """ Python Script to create a queue and perform various operations on it """
# Write your code from here
##from queue import Queue
##
##queue_01 = Queue(maxsize = 3)
##
##print("Number of elements in the queue: ", queue_01.qsize())
##
### Adding of element to queue
##queue_01.put('a')
##print("Number of elements in t... |
0166fafa262be33a5b252b595bddc6bdeb5ba2e6 | rcutu/pytest-framework | /dummmy.py | 314 | 3.796875 | 4 |
def add_dots(string):
new_string = ''
for i in range(0, len(string)-1):
new_string = new_string + string[i] + '.'
return new_string+string[len(string)-1]
def remove_dots(string):
new_string = ''
for c in string:
if c != '.':
new_string += c
return new_string
|
3e8701d81b2a5782ac58cd3de2fddce1a7af92c0 | p-p-m/how | /google/tasks/dijkstra-heap.py | 2,561 | 3.65625 | 4 | import functools
import heapq
@functools.total_ordering
class Vertex:
def __init__(self, index, distance):
self.index = index
self.distance = distance
self.is_invalid = False
def __ne__(self, other):
return self.index != other.index
def __lt__(self, other):
retur... |
2f1778d267cbaf2e46ab4af0bb443df99891547a | hahahayden/CPE202 | /Lab4/ordered_list.py | 8,734 | 4.375 | 4 | # Hayden Tam
# Professor Einakian-
# CPE 202-03
# Lab4: Create an ordered double linked list
#
# Design Recipe: Create a node class that creates a node which makes it easier to forming an ordered double linked list
# Data Defintion for Node Class: data= int; next=None; previous=None
class Node:
def __in... |
d0a1bb811f1936c933a919fb63af77df65396b1b | ansonmiu0214/algorithms | /2018-06-28_Score-of-Parentheses/solution.py | 655 | 3.78125 | 4 | #!/bin/python3
from collections import deque
def scoreOfParentheses(S):
total = 0
stack = deque()
while S != "":
if S[:2] == "()":
# match token, increment score, advance
total += 1
S = S[2:]
elif S[:1] == "(":
# push current total onto stack, reset and advance
stack.append(total)
total = 0... |
bf9f1b5d0fe2f1f28c3041d3ed1af49bbf0090d4 | vsdrun/lc_public | /co_ms/215_Kth_Largest_Element_in_an_Array.py | 1,497 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/kth-largest-element-in-an-array/description/
Find the kth largest element in an unsorted array.
Note that it is the kth largest element in the sorted order,
not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, retur... |
cec56f963396caf4746c6742bad16a848693e094 | DJSanti/assignment5 | /assignment5.py | 6,890 | 3.984375 | 4 | # Names: Bradford, Caleb, Sam
# Assignment #5
# Dr. Timofeyev
# CSC 450
# Dijkstra's Algorithm
# libraries used
import sys #For system input
import pandas as pd #For .csv file input
#getnum function to calculate the costs from .csv
def getnum(node, i, df):
return df.loc[node, i]
# get filename of .csv, get i... |
e4e36a73a7205364e8f7fb18033fdeff29894d5b | CatalinaYepes/parsers | /select_files.py | 1,526 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Select files inside a folder
@catalinayepes
"""
import os
def select_files(folder=".", start="", end="", contain="", include_path=False):
'''Function to select files inside a folder
:folder: folder name, by default current one
... |
a6da91a32103ed7211b4141a0ac3865b9fb41c7d | dnivanthaka/demo-programs | /Python/fileio.py | 609 | 3.640625 | 4 | #!/usr/bin/env python
reader = open( 'haiku.txt', 'r' )
data = reader.read()
reader.close()
print len(data)
reader = open( 'haiku.txt', 'r' )
data = reader.read(64)
while data != '':
print len(data)
data = reader.read(64)
print len(data)
reader.close()
reader = open( 'haiku.txt', 'r' )
contents = reader.read... |
9c20c0359c8adb2dfa43914c632a035ef98bf9b1 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4378/codes/1734_2508.py | 219 | 3.65625 | 4 | k=int(input("numero de termos: "))
a1=2
a2=3
a3=4
i=0
termo=0
if(k==1):
print("3")
else:
while(i+1<k):
sinal=(-1)**i
termo=termo+sinal*(4/(a1*a2*a3))
a1=a1+2
a2=a2+2
a3=a3+2
i=i+1
print(round(3 + termo,8)) |
621cf56dab1643b68d150b631b0ca56058234c7f | codafett/python | /uncategorised/multiply_even_numbers.py | 416 | 4.09375 | 4 | def multiply_even_numbers(values):
evens = [val for val in values if val % 2 == 0]
sum = evens[0]
for val in evens[1:]:
sum *= val
return sum
print(multiply_even_numbers([2, 3, 4, 5, 6])) # 48
def multiply_even_numbers(lst):
total = 1
for val in lst:
if val % 2 == 0:
... |
076c061216dec7e605ed25b8eb33c23e03490861 | arunkumarpatange/fib100 | /pyd/cake2.py | 1,991 | 3.53125 | 4 |
def uniq(l):
x = 0
for n in l:
x = n ^ x
return x
print uniq([1, 2, 10, 1, 2])
def has_cycle(l, head):
'''
1 - 2 - 3 - 4
| |
- - - - -
'''
next = current = head
while l.get(current) is not None:
current = l.get(current)
next = l.get(l.get(next))
print current, next
if next == current:
... |
8e24cda519daa5a0f048f5aac87c285b458bc4dc | TotumRevolutum/Control_HW_2 | /classes.py | 1,559 | 3.53125 | 4 | import csv
def write_file(products):
with open('products.csv', 'w', encoding="utf8") as csvfile:
writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=['price', 'name', 'q_left'])
writer.writeheader()
for i in products:
writer.writerow({'price': products[i].price, 'name': ... |
4baa9659924ea96fc6cf144cf0c1231424a7807d | brmonitor/PythonMentee | /Level1/Ex8.py | 353 | 3.765625 | 4 | # Python Mentee - Level 1 - Exercises
# https://bairesdev.atlassian.net/servicedesk/customer/article/2101576225
# 8 - Write a Python function to remove an item from a tuple.
def tuple_remove_item(tup, i):
lis = list(tup)
lis.remove(i)
print(tuple(lis))
if __name__ == '__main__':
tup = ('a', 'b', 'c')... |
5e4ea86c14decd951d3b7c363fa742ada0c56d83 | Sahil4UI/PythonJuly2020Reg2 | /F_handeling/csv_IO.py | 439 | 3.640625 | 4 | import csv
'''
data = [
{"name":"ram","id":101},
{"name":"shyam","id":102},
{"name":"radhey","id":103},
{"name":"samay","id":104},
{"name":"amar","id":105}
]
with open('data1.csv','w',newline='') as file:
writer = csv.writer(file)
for item in data:
writer.writerow(item.values())... |
8dc11df66534147f761a083f5ebb0b8fe9ac9718 | happinessbaby/Project_Euler | /sum_primes.py | 1,008 | 3.796875 | 4 | #summation of all primes below 2 million
import time
def calc_time(func):
def inner(*args, **kwargs):
begin = time.time()
returned_val = func(*args, **kwargs)
end = time.time()
print("time: ", end-begin)
return returned_val
return inner
@calc_time
def sum... |
7bde23e27255f8ba31951e46cbfa6a558dc609d3 | LautaroRuggieri/newbie-cow | /basic mouse capturer in canvas.py | 3,903 | 3.875 | 4 | #last version: 10 may 2020 (aprox. 2.5 months into programming)
#author: Lautaro Ruggieri (https://github.com/LautaroRuggieri)
#desc: bored, quarantined cow presents a basic mouse activity responder:
#1-it draws a circle each time you left click, alternatig between red and blue color.
#2-it draws a text if ... |
f849bb74a78838c65ae9e1fad12ccc7a2095b19c | bhalder/python-datastructures | /tree/check_largest.py | 380 | 3.796875 | 4 | from bst import BST, Node
def get_maximum( root ):
if not root:
return False
else :
cur = root
while cur.right:
cur = cur.right
return cur.item
if __name__=="__main__":
bst = BST()
l = [ 6, 2, 9, 8, 7, 3, 1 ]
for i in l:
bst._add( i )... |
d5ed336d8cc75e634bb3be34c9e88252fdf06893 | YuanShisong/pythonstudy | /day3/01set.py | 2,973 | 4.3125 | 4 | '''
鸡汤:
《追风筝的人》
《白鹿原》
《琳达看美国》
'''
# 列表 元组(不可变列表) 集合 字符串:不可修改
list1 = [1,9,2,3,2,4,5,3]
print(list1)
list1 = set(list1)
# 集合是有序的??? 官方文档:A set object is an unordered collection of distinct hashable objects.
print(list1)
set1 = set(['2','2','1','4','9','5'])
print(set1)
'''
无序的,不重复的,可哈希的对象集合,但为什么放数字就是有序的??... |
de10bc49264d8268e0b3b773f12009f40914178b | jainharshit27/C7_AA2_T | /C7 AA2 reference.py | 204 | 3.65625 | 4 | # WHILE LOOP
import random
ring = random.randint(1,18)
print(ring)
i = 1
while i<=18:
if i == ring:
print(i)
break
else:
print(i)
i+=1
|
e39b07186f6c021fc728700ca44caa494a4328db | jparrieta/nk | /python_versions/levinthal_create_landscape.py | 14,481 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Tutorial on Creating Rugged Landscapes
#
# In this tutorial, you will be introduced to a simple model to create NK landscapes following Levinthal (1997). The tutorial does not include search in rugged landscapes, just the creation of the landscapes. You can find a code with t... |
701783cbf3c341b7343750d7d8e8325c021e8d47 | cckhatgt/untitled | /bagWord.py | 756 | 3.53125 | 4 | import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer();
docs = np.array([
"The sun is shining",
"The weather is sweet",
"The sun is shining and the weather is sweet" ])
bag = count.fit_transform(docs)
print(count.vocabulary)
print("##")
print(count.vocabul... |
a130ea3a0fd9adf1ec5c12cf6fc23f4ec0bb73e1 | calvindajoseph/patternrecognition | /FakenewsPreProcessing.py | 2,833 | 3.65625 | 4 | """
Preprocess the initial dataset.
Includes dropping columns and encoding the target class.
Partition the dataset into smaller datasets in the end.
"""
# Import re for regex
import re
# Import LabelEncoder
from sklearn.preprocessing import LabelEncoder
# Import FileManager and DatasetPartitioner
from FileManager ... |
3a6108745226f7528a9a426209fa84f01d76767f | nrutkowski1/AI-Projects | /Project 2/Rutkowski_ANN.py | 9,516 | 3.6875 | 4 |
import numpy as np
import sklearn
import matplotlib as mpl
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, InputLayer, Dropout
import keras
import tensorflow as tf
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_score
f... |
543512c95ce791129d9229521f546a66a2cd2438 | haydenjeune/patterns | /behavioural/visitor.py | 2,028 | 3.984375 | 4 | """Allows the separation of algorithms from the objects on which they operate"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Optional
@dataclass
class BaseNode(ABC):
value: Any
left: Optional[BaseNode] = None
right: Opti... |
f6bc94e10b34ba8262a655aa1e5093b3aaa9578f | Indiana3/python_exercises | /wb_chapter3/exercise74.py | 419 | 4.15625 | 4 | ##
# Implement Newton's method to compute the square root
# of an x number
#
GOOD_APPROXIMATION = 1e-12
# Read x from the user
x = float(input("Please, enter a number: "))
# Compute the good approximation
guess = x/2
while abs(guess ** 2 - x) > GOOD_APPROXIMATION:
guess = (guess + x/guess) / 2
# Display the appr... |
5437d6fb2a92a614be8450a4dee64b5c4111ad4c | MarsWilliams/algos | /25_12_2020_single_number.py | 667 | 3.578125 | 4 | from typing import List
from collections import Counter
def single_number(nums: List[int]) -> int:
return (k for k, v in Counter(nums).items() if v == 1).__next__()
assert single_number([4, 1, 2, 1, 2, 2]) == 4
def single_number_set(nums: List[int]) -> int:
singles = {}
for i in nums:
if i in ... |
ec9b61c1ac8453294bca14b903e021fc3aa3e775 | mveselov/CodeWars | /tests/kyu_7_tests/test_area_of_a_circle.py | 498 | 3.5625 | 4 | import unittest
from katas.kyu_7.area_of_a_circle import circleArea
class CircleAreaTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(circleArea(43.2673), 5881.25)
def test_equals_2(self):
self.assertEqual(circleArea(68), 14526.72)
def test_false(self):
self.a... |
f3db1273e8aa1462a043b3329f0a9f91e7d7bfa8 | ruanhq/Leetcode | /Algorithm/69.py | 444 | 3.75 | 4 | #69. Sqrt(x):
class Solution(object):
def mySqrt(self, x):
if x < 2:
return x
if x == 2:
return 1
low = 1
high = x
while low <= high:
med = (low + high) // 2
num = med * med
if num > x:
high = med -... |
53768d5bff7a0315fee0c0388a9e345bd522912d | shashankkarthik/CSE | /CSE 231/Computer Projects/project06/proj06a.py | 1,613 | 3.953125 | 4 | #############################################################################
# Computer project 6a
#
# Algorithm
# try
# prompt user for file name
# open file object
# initialize count variable
# intialize lists for years and temps
# iterate through each line in file
# increase count by 1
# ... |
c051f09e451bc9a7dd40e1c298e88c996556b289 | natandias/Python_CursoEmVideo | /Fase_17_Lista_part1.py | 2,403 | 4.34375 | 4 | # Listas podem ser alteradas diferentemente das tuplas
lanche = ['hamburguer', 'suco', 'pizza', 'pudim']
print(lanche)
''' Pode-se trocar um elemento realizando atribuição '''
lanche[3] = 'goiabada'
print(lanche)
''' Adicionando valor à lista '''
lanche.append('biscoito')
print(lanche)
''' Adicionando valor entre el... |
8a9abcc24e93b87d2221871be0cbf1d7d50a600b | nyroro/leetcode | /LC501.py | 947 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
table = ... |
6b1533e953bc6217a9b0d0ec04acdc7c38b4f07c | Stanshiki246/Introduction-to-Programming---Lab | /ATM class.py | 4,481 | 4.28125 | 4 | # Define a class for ATM.
class ATM:
# Define a function to initialize ATM class.
def __init__(self,balance,wallet,another):
self.balance = float(balance) # Variable for my balance.
self.wallet = float(wallet) # Variable for my wallet.
self.another = float(another) # Variable for a... |
e7adb157f497204bbffda1bf560638d62b00b38d | Brekkjern/SudokuSolver | /SudokuSolver/cell.py | 3,325 | 4.1875 | 4 | import math
from typing import Union
class Cell(object):
"""
The cell object.
The x and y are the respective coordinates.
neighbours is a list of all cells that impact the current cell.
value is the current value of the cell, or None if there is no value set.
possibilities is a list of curren... |
8666fd1ebec5f5ce91af1e4d34bd76268928ed21 | f0lie/basic_python_workshop | /part_oop_3.py | 562 | 3.796875 | 4 | class Point():
def __init__(self, x, velo):
self.x = x
self.velo = velo
def move(self):
self.x += self.velo
def print(self):
print(self.x, self.velo)
line = 10*[' ']
point_1 = Point(0,1)
point_2 = Point(9,-1)
for i in range(10):
line[point_1.x] = '*'
line[point_2... |
f9cc881df450647eb781156158c3b1277388ab4e | Tulip4attoo/coding-dojo | /geeky.vn/problem1_2.py | 4,078 | 3.5 | 4 | import sys
import time
def convert_input(s_input):
adj_input = s_input.splitlines()
encrypted_text = adj_input[0].split(' ')
dictionary = adj_input[1]
pre_table = adj_input[2 :]
return encrypted_text, dictionary, pre_table
def split_pre_table(pre_table):
simple_pre_table = []
... |
2d158728e71a0f47a775f4f9a3309fc17820d9c7 | TheGoop/learnWebDev | /test.py | 5,045 | 3.75 | 4 | class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
#could approach in a sort of dfs manner
#start at a 1, search neighboring nodes
# when searching these adjacent nodes, mar... |
f3249db436c706be90505c3be7a0cff3c36a427b | srithanrudrangi/PythonCoding | /5_2_SalesTaxProgramRefactoring.py | 513 | 3.953125 | 4 | def sales():
number = int(input(" How many items did you purchase? "))
subTotal = 0
for i in range(number):
price = int(input("Enter price of item: "))
subTotal = price + subTotal
stateSalesTax = subTotal*0.05
countySalesTax = subTotal*0.025
print("Your Sub total:", subTotal)... |
0dbd40eca7efc0f8c31ec7ba814691966acff9df | SomethingRandom0768/PythonBeginnerProgramming2021 | /Chapter 6 ( Dictionaries )/Exercises/6-10favorite_numbers2.py | 421 | 3.828125 | 4 |
favorite_numbers = {'r': [12, 6],
'c': [9, 3],
's': [13, 1],
'coo': [6, 8],
'e': [9, 2],
'd': [5, 8],
'f': [25, 1],
}
for name, values in favorite_numbers.items():
print(f... |
c49b33f614578a174b5009b418b525930f6def8c | htmlprogrammist/kege-2021 | /tasks_22/homework/task_22.10.py | 1,476 | 3.8125 | 4 | """
Задание 22 (№834).
Ниже на четырёх языках программирования записан алгоритм.
Получив на вход число x, этот алгоритм печатает два числа: L и M.
Укажите наибольшее число x, не содержащее нулей,
при вводе которого алгоритм печатает сначала 14, а потом 3.
"""
# x = int(input())
# L, M, R = 0, 0, 0
# while x > 0:
# ... |
92550e32dbfff20120c56734d1c6501bb22faa86 | merissab44/superHero | /hero.py | 5,141 | 3.84375 | 4 | import random
from ability import Ability
from armor import Armor
from weapon import Weapon
class Hero:
# We want out hero to have a default "starting health"
# we set that in the finction header
def __init__(self, name, starting_health=100):
# abilities and armors dont have starting values
... |
1ba80b3cf0672689d966aaf3dfef53b44f6c0969 | ChangxingJiang/LeetCode | /0101-0200/0105/0105_Python_2.py | 1,009 | 3.78125 | 4 | from typing import List
from toolkit import TreeNode
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def recursor(p_left, p_right, i_left, i_right):
if p_left < p_right and i_left < i_right:
# 寻找当前二叉树的根节点
val = preorder... |
4483ca3c37dc9164404bed8f67703a506a3bad2b | jgabdiaz/mycode | /lab_input/iptaker02.py | 390 | 3.625 | 4 | #!/usr/bin/env python3
user_input = input("Please enter an IPv4 IP address:")
print("You told me the IPv4 address is:", user_input)
VendorID = input("Please enter the vendor name: ")
print("You told me the vendor name is:", VendorID)
User_Name = input("tell me your user_name: ")
DayWeek = input("What day of the week is... |
7e75cb00a531cc35bfb23a39d73192924e00da4e | nawendusingh/leetcode | /20validparentheses.py | 717 | 3.890625 | 4 | def vp(str):
paren = {'[': ']', '(': ')', '{': '}'}
stk = []
for i in str:
if i not in paren:
if not stk or i != paren[stk[-1]]:
return False
else:
stk.pop()
else:
stk.append(i)
return stk == []
# imagine... |
636f6308d26f9712c2a9bbfe902e9ed1e033bc48 | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/Osiddiquee/lesson08/test_circle.py | 808 | 3.8125 | 4 | '''
This is the test program for circle.py
'''
from circle import *
def test_init():
c = Circle(5)
assert c.radius == 5
assert c.diameter == 10
def test_change_diameter():
c = Circle(5)
c.diameter = 8
assert c.radius == 4
def test_area():
c = Circle(2)
assert round(c.area, 2) == 12.... |
a6cea0616d279fb67fac02d7182e7be8c6833739 | Nadezhda-Sokolova/Practice-and-Home-work | /practice_2nd_episode.py | 732 | 3.703125 | 4 | # First excercise
a = 2
b = 3
a1 = str (a)
b1 = str (b)
c = a1 + b1
print (c)
d = int (a1 + b1)
print (d)
d1 = a + b
print (str(d1))
c1 = c * 2
print (c1)
# Second exercise
line = 'ABCDCDC'
sub = 'CDC'
n = line.count(sub)
print (n)
import re
print (len (re.findall('(?=CDC)', line)))
#Third exercise
text = 'It w... |
970861d1c278970e0fef6d706ffd18a4e8c50586 | Lzffancy/Aid_study | /fancy_month01/day12_fancy/12homework/stuff_manager_sys.py | 3,444 | 3.5625 | 4 | #公司员工管理系统
'''作业
1. 三合一
2. 当天练习独立完成
3. 员工信息管理系统
(1)录入员工信息
(2)显示员工信息
(3)删除员工信息
(4)修改员工信息
class Employee:
def __init__(self, eid, did, name, money):
self.eid = eid # 员工编号
self.did = did # 部门编号
self.name = name # 姓名
self.money = money # 薪资'''
class Employee_Model:
d... |
dcdf726e087b77002e0d8ed1769e7b7725547412 | ji-cc/MyPython | /函数/案例 控制终端.py | 142 | 3.828125 | 4 | endstr = "end"
str = ""
for line in iter(input, endstr):
str += line + "\n"
print(str) #在后台输入字符串,打印end结束程序 |
ba8fd1f5cd890944b47038ad489b34495f811e48 | ghoshorn/leetcode | /leet260.py | 2,512 | 3.984375 | 4 | # encoding: utf8
'''
Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not import... |
4e2f1456b6cf4eb1412b3fe12b1a140780321912 | HeywoodKing/mytest | /MyHello/person.py | 690 | 3.8125 | 4 | # -*- coding: utf-8 -*-
class Person(object):
def __init__(self, name, gender):
self.__name = name
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self, gender):
# if gender.strip() != '':
# self.__gender = gender
... |
86304c58328b019f82bcd9f20a0ab4a6c4997400 | Paula-Bean/PaulaWords | /crosswords-guardian/cleanup.py | 1,142 | 3.640625 | 4 | #!/usr/bin/env python3
#
# Reads the file 'guardian-puzzlewords-withsees.txt' and removes unwanted
# material from it, combines clues when multiple clues for a word are
# present, and writes the result to 'guardian-puzzlewords.txt'.
#
# Words can have one or more clues:
#
# ACCREDITATION
# Granting of recognition (13... |
247700ef4892d112a3be6b2fb6cd7b2acf116032 | Artur-STN/Curso-de-python | /ExerciciosCursoEmVideo/ex059 - Criando um Menu de opções.py | 1,718 | 3.65625 | 4 | from time import sleep
print('\033[31;1m▲▼\033[m'*10)
n1 = int(input('{}Primeiro valor: {}'.format('\033[32;1m', '\033[m')))
n2 = int(input('{}Segundo valor: {}'.format('\033[33;1m', '\033[m')))
print('\033[31;1m▲▼\033[m'*10)
sair = 0
maior = [n1, n2]
while sair != 5:
print('''{} [ 1 ] Somar{}
{}[ 2 ] Mul... |
606d3ff1deb1fd76008077ae2a63824d97a5454f | vladGriguta/leetcode | /AugustChallenge/longest-palindrome.py | 732 | 3.703125 | 4 | # Day 14 - August Challenge
class Solution:
def longestPalindrome(self, s: str) -> int:
# idea: maximum palindrome is the size of the string minus the number of characters
# that appear an odd number of times plus 1
# if all characters with an even number of appearances, max palind... |
74e169a12769df77c2745d831596d16eccb2cebf | amogchandrashekar/Leetcode | /Medium/Last Stone Weight II.py | 1,575 | 3.8125 | 4 | """
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x and y with x <= y.
The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed... |
3c33a83270457d165f7d36c2c34938028969a89b | denistsiupka/PythonLab1 | /Tsuipka__lab1_8.py | 926 | 4 | 4 | print(
"Програма, яка визначає значення цілої змінної number - від 1 до 7, в залежності від того,\nна який день тижня (від понеділка до неділі) припадає день (ціла змінна day) "
"невисокосного року, в якому 1 січня - понеділок (1 ≤ day ≤ 365). ")
day = int(input("Введіть номер вашого дня = "))
if day <= 0 or da... |
a40ea79502f8ca49349f41b693c8fe0f65d490e5 | JMoVS/JUMP | /UserInput.py | 12,944 | 4.0625 | 4 | __author__ = 'Justin Scholz'
__copyright__ = "Copyright 2015 - 2017, Justin Scholz"
def recognize_user_input_yes_or_no(user_choice: str, default: bool):
user_input_understood = False
yes = str
no = str
user_choice_answer = "x"
if default:
yes = ""
no = "no"
elif not default:
... |
b66f4d4715286e19a184b0458cae819c01423168 | angelajiang/TensorFlow-Tutorials | /show_results.py | 3,304 | 3.75 | 4 | # Import a function from sklearn to calculate the confusion-matrix.
from sklearn.metrics import confusion_matrix
## HELPER FUNCTIONS FOR SHOWING RESULTS
def plot_confusion_matrix(cls_pred):
# This is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.