blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ef004ba5e244566e6484dd060bd442815ba211e9 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/1710.py | 934 | 3.5625 | 4 | # input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
# 3
# --+-++- 3
# +++++ 4
# -+-+-+ 4
import re
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
s = input()
(pancakes, k) = s... |
5fbdfb5aed115aa689b6808823d7b3db2716ba24 | johnsenaakoto/google_foobar_challenge_lvl1 | /reid_solution.py | 436 | 3.5 | 4 |
def solution(i):
prime_string = makePrimeString()
minion_ID = prime_string[i:i+5]
return minion_ID
def makePrimeString():
s=''
prime = 2
while len(s) < 10005:
s += str(prime)
prime += 1
while not is_prime(prime):
prime += 1
return s
def is_prime(n)... |
830887a385f1ae3920301fdba4b0426497fdb391 | lyz05/Sources | /牛客网/虾皮/23.py | 710 | 3.859375 | 4 |
#
# Note: 类名、方法名、参数名已经指定,请勿修改
#
#
#
# @param s string字符串 字符串数组
# @param n int整型 需要翻转的字符个数
# @return string字符串
#
from re import L
class Solution:
def longestPalindrome(self, s) :
# write code here
def judge(s):
return s==s[::-1]
for length in range(len(s),-1,-1):
... |
92909896fd84b8f976afdc1f212a7327c80ed54f | jakey1610/functions | /inverse.py | 449 | 3.90625 | 4 | from sympy.abc import x,y
from sympy import *
def inverse(f):
func = []
for letters in f:
if letters == "x":
func.append("y")
else:
func.append(letters)
invfunc = ""
for letters in func:
invfunc += str(letters)
invfunc += "-x"
invfunc = solve(invf... |
254505c88565873d87cae46855e69e35cbb1d129 | bhuvaneshkumar1103/talentpy | /difference_in_string.py | 1,365 | 3.90625 | 4 | '''
Create a func,on difference which takes a string S and character K. Find the difference between
first occurrence of K and last occurrence of K in string S. Convert the input to lower case before
processing.
Check for following condi,ons :
1. If K not occurred in S, return “K not found in S”.
2. If K occurred ... |
d455574b490feb3e0a9c43aeccb4cb7214b0c98e | kaidokariste/python | /08_object_oriented_programming/code-class.py | 423 | 3.734375 | 4 | class Student:
def __init__(self, studentname, grades): # init can have also parameters
self.name = studentname
self.grades = grades
def average_grade(self):
return sum(self.grades) / len(self.grades)
student = Student("Bob",(90,90,93,78,90,85))
print(student.name) # Rolf comes out
pri... |
7360184f9f63636823b28ddd6a35f45edf2ae9db | aybidi/Data-Structures | /Stacks/StackArray.py | 1,893 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 15:25:14 2018
@author: Abdullah Mobeen
"""
class Empty(Exception):
"""Error that will occur when attempting to access an element from an empty stack"""
pass
class Stack:
CAP =10
"""Implementation of Stack using an array"""
def __init__(self):
... |
80c23212d4241881165e5dae4b0ee3f40fdf3c5b | Seidmani64/SemanaTec | /io_utilities.py | 787 | 3.5625 | 4 | import pandas as pd
def read_vanilla(filepath):
with open(filepath, 'r') as fp:
data_unsorted = fp.read()
data_lines = data_unsorted.split('\n')
data = [f.split(',') for f in data_lines]
return data
def read_pandas(filepath, names):
"""
Read a csv in pandas
returns a pandas datafr... |
4f571c40c6b4b8e418ddee44432ceb4e9c41887d | devathul/prepCode | /coinArrangement.py | 2,364 | 3.59375 | 4 | """
coinArrangement
There are N piles of coins each containing Ai (1<=i<=N) coins. Now, you have to adjust the number of coins in each pile such that for any two pile,
if a be the number of coins in first pile and b is the number of coins in second pile then |a-b|<=K. In order to do that you can remove coins from
... |
850c9c94d2a4ad781558c283f01184cd4a941fae | hithamereddy/HackerRank | /Guess A Number | 504 | 3.953125 | 4 | #!/usr/bin/python3
import random
number=random.randint(1, 50)
chances = 0
print("guess a number between 1 and 50: ")
while chances <15:
guess = int(input())
if guess == number:
print("hithit approves™")
break
elif guess < number :
print ("your guess was too low, try again: ")
... |
5a8355299ac82757099f86215c86fe0673a24d42 | wchandler2020/Python-Basics-and-Data-Structures | /built_in_data_structures/lists.py | 754 | 3.6875 | 4 | # def rev_list(new_list):
# return [ele for ele in reversed(new_list)]
# print(rev_list([1, 2, 3, 4, 5]))
# names = ["Liam", "Henry", ]
#
# def remove_dup(my_list):
# new_list = []
# for i in my_list:
# if i not in new_list:
# new_list.append(i)
# return new_list
# output = remove_d... |
7067269d642682d4a1ae321042991028726294fa | anonimato404/hacker-rank-python | /exams/03_string_representation_of_objects.py | 666 | 4.1875 | 4 | """
Implement two vehicle classes:
- Car and Boat
"""
class Car:
def __init__(self, maximum_speed, notation_units):
self.maximum_speed = maximum_speed
self.notation_units = notation_units
def __str__(self):
return (
f"Car with the maximum speed of {self.maximum_speed} ... |
8f208b35c7a6fdef3d615deda47695e01d0f10a8 | uterdijon/evan_python_core | /week_04/labs/03_exception_handling/Exercise_01.py | 538 | 4.6875 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
def ask_for_int():
try:
var = input("Please enter an ... |
257a31c1f540c457cb2e8ef2fc6100f46204efbc | qpxu007/cheetah | /python/lib/streamfile_parser/LargeFile.py | 2,222 | 3.859375 | 4 | #
# Author: Dominik Michels
# Date: August 2016
#
class LargeFile:
"""
This class provides the ability to handle large text files relatively
quickly. This is achieved by storing a table containing the newline
positions in the file. Hence it is able to quickly jump to a given line
number without sca... |
d9875594347e8174e3b106f7588fe9d8990230a5 | zxcvbnm123xy/leon_python | /python1808real/day14/day14-2-decorator.py | 10,068 | 4.0625 | 4 | """
第十三章 迭代器、生成器、装饰器
三、装饰器
#使用装饰器来扩展已有函数或者已有类的功能。
"""
# 1. 闭包
# 嵌套函数
def outer():
def inner():
print("innner函数执行")
return inner()
# a=outer()
# print(a.__closure__) # 因为嵌套函数中没有形成闭包__closure__没有这个属性
# 闭包
def outer():# 在outer中有参数,参数 也算外围变量
x=1 # 外围变量
def inner():
# x=2# 不能加
print(... |
9bce9aa288b92a21e97e38c75c3b2bcbb800ee06 | AustinArrington87/NLP | /data-tools/lib/frequency.py | 4,503 | 3.53125 | 4 | import nltk
from nltk import tokenize
from nltk.corpus import stopwords
import matplotlib.pylab as plt
def wordFreq (tokens):
# remove stop words (am, at, the, for) and count frequency
sr = stopwords.words('english')
chars = ["{", "=", "-", "}", "+", "_", "--", ">", "<", "<=", ">=", "—", "var"]
conjunc... |
47cbfb55e9801c3a67d3fbce4c522a216e4d8ec6 | karendiz/ex-python | /desafio09.py | 359 | 3.96875 | 4 | # reduce() - Sua utilidade está na aplicação de uma função a todos
# os valores do conjunto, de forma a agregá-los todos em um único valor.
from functools import reduce
lista = [1, 2, 3, 4, 5, 6,7,8,9,10]
soma = reduce(lambda x,y: x + y, lista) #retorna o produto de todos os elemento de lista
print("lista = ",... |
89397c56d8c3490ba50c0bd80ec97823b97541dc | jojude/program-repo | /HackerEarth/fizzbuzz.py | 668 | 3.578125 | 4 | def fizzbuzz(n):
if n % 3 == 0 and n % 5 == 0:
return 'FizzBuzz'
elif n % 3 == 0:
return 'Fizz'
elif n % 5 == 0:
return 'Buzz'
else:
return str(n)
def print_fizzbuzz(limit):
return "\n".join(fizzbuzz(n) for n in xrange(1, limit+1))
def print_fizzbuzz_times(n,seq):
... |
512717a9a233e96a97c60ae115ea8fbc31ef5fc0 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2154/60710/271962.py | 237 | 3.625 | 4 | #判断一个数是不是回文数
def solve(num):
s=str(num)
for i in range(0,len(s)//2):
if s[i]!=s[len(s)-i-1]:
return False
return True
if __name__ == '__main__':
a=int(input())
print(solve(a)) |
44b45530f235b04699932265c9a4b44a686540ae | Ale1120/Learn-Python | /Fase3-Programacion-orientada-a-objetos/tema8-programacion-orientada-a-objetos/atributos-metodos-clases.py | 1,806 | 3.984375 | 4 | class Galleta:
pass
galleta = Galleta()
galleta.sabor = 'Salado'
galleta.color = 'Marron'
print('El sabor de una galleta es ', galleta.sabor)
class Galleta:
chocolate = False
galleta = Galleta()
g.chocolate
class Galleta:
chocolate = False
def __init__ (self):
print('Se acaba de crear un... |
2c61bdd440e5e3b6a4bac1f985d6b026c960fa94 | abhinavsoni2601/fosk_work | /day 6/ch4.py | 570 | 3.75 | 4 | from functools import reduce
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},
{'name': 'Sam'}]
#for person in people:
# if 'height' in person:
# height_total += person['height']
# height_count += 1
#def fun(x):
# height_total = 0
# height_count = 0
#... |
e338ef47cf40fd4f7bb5eeacb6f23db2a24442f0 | alex-stephens/project-euler | /euler_80.py | 528 | 3.734375 | 4 | # Project Euler
# Problem 80
# Square root digital expansion
import sys
sys.path.append('..')
from euler import isPerfectSquare
'''
Calculates the sum of the first d digits of sqrt(num)
'''
def sqrtDecimalSum(num, d):
target = num
n = 1
for i in range(d):
while (n+1)**2 < target:
... |
adca5abf440b34809fbbf436f287408f4b975bd5 | Shubhamgawle96/randstad_task | /get_data.py | 1,465 | 3.84375 | 4 | import requests
class generic_data_client:
"""
A class to get and save data from given url in .csv format.
...
Attributes
----------
url : str
url to download csv from
name : str
name to save the file with
Methods
-------
get_data():
downloads data from giv... |
6f7a8f27db414eadfd4e80a2819f703c9bdaa51a | sankalptambe/datastructures-and-algorithms | /fibonacci.py | 1,106 | 4.1875 | 4 | # fibonacci series
# find series upto n number.
import sys
n = int(input('Please provide a number: '))
# Fibonacci Series using Dynamic Programming
def fibonacci(n):
# Taking 1st two fibonacci nubers as 0 and 1
FibArray = [0, 1]
while len(FibArray) < n + 1:
FibArray.appen... |
81d61bbb0b76b8fb42cc5f3c0cc2bba807b9196a | csgear/python.for.kids | /basic2/loops/boring.py | 1,491 | 3.671875 | 4 |
def menu_is_boring(meals):
"""Given a list of meals served over some period of time, return True if the
same meal has ever been served two days in a row, and False otherwise.
"""
for i in range(1, len(meals)):
if(meals[i] == meals[i-1]):
return True
return False
def elementwi... |
9667c37df789616f9d7afbaa5ccc22133f7daec8 | xalumok/proga | /proga1.py | 902 | 3.84375 | 4 | def merge(s, l, m, r):
left = []
right = []
for i in range(l, m+1):
left.append(s[i])
for i in range (m+1, r+1):
right.append(s[i])
i = 0
j = 0
mergedArr = []
while i<len(left) and j<len(right):
if (left[i] <= right[j]):
mergedArr.append(left[i])
i += 1
else:
mergedArr.append(right[j])
j +... |
a41a499a78fc0dc44174812b5b3b7db1e12239b3 | FranVeiga/games | /Sudoku_dep/createSudokuBoard.py | 1,654 | 4.125 | 4 | '''
This creates an array of numbers for the main script to interpret as a sudoku board.
It takes input of an 81 character long string with each character being a number and
converts those numbers into a two dimensional array.
It has a board_list parameter which is a .txt file containing the sudoku boar... |
635fa70c7d04161ee6d73b32784ebe0f8f619273 | kevin115533/projects | /project4.py | 241 | 4.28125 | 4 | triangle_width = int(input("Enter the base width of the triangle: "))
triangle_height = int(input("Enter the height of the triangle: "))
area = .5 * triangle_width * triangle_height
print ("The area of the triangle is",area, "square units")
|
720226748304712f993c4c5dad0cc4185a2ea719 | fillemonn/tasks | /suchar.py | 184 | 3.984375 | 4 | def your_name():
while True:
your_name = input('Please type your name ')
if your_name == 'your name':
print('Thank you')
break
your_name() |
a583d73440744bed80ca2a7139906c4df4807dc1 | Runsheng/bioinformatics_scripts | /gbrowser_script/gff_type.py | 765 | 3.78125 | 4 | #!/usr/bin/env python
import argparse
import sys
def type_unique(gfffile):
"""
read a gff file, output the gff types to stdout
mainly used to write the conf file for Gbrowse
"""
with open(gfffile, "r") as f:
lines=f.readlines()
type_l=[]
for line in lines:
if "#"... |
33779c26df41abb716beb705099dc72fb9b67bdb | ChangxingJiang/LeetCode | /LCCI_程序员面试金典/面试16.11/面试16.11_Python_1.py | 479 | 3.65625 | 4 | from typing import List
class Solution:
def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]:
if k == 0:
return []
if shorter == longer:
return [shorter * k]
ans = []
for i in range(k + 1):
ans.append(longer * i + shorter * (k ... |
1a252020c6a5536e57eeeecdabc8dfd6684cb199 | greg008/PythonEPS | /W3R/Dictionary/6.py | 313 | 4 | 4 | """
6. Write a Python script to generate and print a dictionary
that contains a number (between 1 and n) in the form (x, x*x).
Sample Dictionary ( n = 5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
"""
x = int(input("podaj liczbe"))
dict1 = {}
for i in range(1, x+1):
dict1[i] = i*i
print(dict1)
|
bb6d6e2f0ee82c4b9c19ba3c47d98637f7ae98f4 | vijaypatha/python_sandbox | /vectorploting.py | 3,780 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
'''
TODO: Multiply Vector by Scalar and Plot Results
For this part of the lab you will be creating vector $\vec{av}$ and then adding to the plot as a dotted cyan colored vector.
Multiply vector $\vec{v}$ by scalar $a$ in the code below (see TODO 1.:).
Use the ax.arr... |
58697296468ef7df47d44fc64ad45d6caba320d7 | ligege12/dighub | /ghanalyzer/utils/datatools.py | 391 | 3.515625 | 4 | from itertools import islice
def islide(iterable, size):
iterator = iter(iterable)
window = tuple(islice(iterator, size))
if len(window) == size:
yield window
for x in iterator:
window = window[1:] + (x,)
yield window
def slide(sequence, size):
stop = len(sequence) - size ... |
61d69b34f6d2b1bc172ab4bae1a39c8901b08b2c | astavnichiy/AIAnalystStudy | /Python_algorithm/Lesson1/Чужое задание 2/les1_task6.py | 1,180 | 4.15625 | 4 | #6. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним.
a = int(input("Введите длину первого отрезка: "))
b = int(input("... |
9be0b3e7fb29a3e745c0aaa83bac6a915e84e84f | KalinaKa/Explosive-Dragon | /d4/07-range1.py | 437 | 3.75 | 4 | #tu jest inaczej, bo pokazuje nam zakres ten print. aby to wypisac, nalezy go zamienic na liste.
#w pythonie 2 mozna bylo tak robic zakres, ale spowalnialo to procesor.
#w pythonie 3 to juz generator, generuje liczby na żądanie. dlatego wstepnie generuje "range(0,4)"
# wiec musimy skonwertowac do listy. w Pythonie 2 na... |
d797bc44979edaac69d3e7da0587be9bfd9af7fa | stacybrock/advent-of-code | /2018/11/power.py | 1,707 | 3.546875 | 4 | # solution to Advent of Code 2018, day 11 part one and two
# https://adventofcode.com/2018/day/11
#
# usage: power.py [inputfile]
from collections import defaultdict
from collections import namedtuple
import fileinput
import numpy
def main():
serialnumber = int(next(fileinput.input()).strip())
# create a mul... |
214c42cdb7d1bdffde763a0fab4e48933ad87743 | limeiyang/python-study | /8.python脚本(备份文件01).py | 1,587 | 3.75 | 4 | #!/usr/bin/python
'''
文件创建备份的程序:
1. 需要备份的文件和目录由一个列表指定。
2. 备份应该保存在主备份目录中。
3. 文件备份成一个zip文件。
4. zip存档的名称是当前的日期和时间。
5. 我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使
用Info-Zip程序。注意你可以使用任何地存档命令,只要它有命令行界面就可以了,那
样的话我们可以从我们的脚本中传递参数给它。
'''
# 开始
import os
import time
import zipfile
filename = r'F:\backuptest\work'
z = zipfil... |
4e0bc2dd3986ed8c3a697f4b7fe3e0e77ed7341a | wujunhui0923/studying | /demo_2.py | 3,856 | 3.984375 | 4 | #!usr/bin/python
#-*- coding = utf-8 -*-
"""
模块:
包:
1.模块名称--标识符
a.数字、下划线、字母,不能以数字开头,不能是关键字
模块名称一般是下划线的形式命名的,
模块名称不能和python 中的内置模块名称重合,
random、time--内置模块,在命名内置模块的时候不可以使用的
"""
"""
2.模块导入
from 模块名称.import .类名、函数名、变量名.,适用于项目根目录/内置模块
"""
# from time import time
# print(time())
# from random import randint
# # randint 是函数... |
f8064a4e868abbfbdc4396cc442ee80b7ba56389 | xjchenhao/Learn | /python/循环/donesum_break.py | 315 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-05-17 00:48:03
# @Author : chenhao (wy.chenhao@qq.com)
# @Link : http://www.xjchenhao.cn
# @Version : $Id$
total=0
while True:
s=raw_input('Enter a number (or "done"): ')
if s=='done':
break
total=int(s)
print('The sum is '+ str(to... |
b8b64d8228e18302e5bd0d4eaecaba6f90aade46 | i-Xiaojun/PythonS9 | /Day10/9.Day10_作业.py | 1,067 | 4.1875 | 4 | # 1. 写函数,接收n个数字,求这些参数数字的和
# 2. 读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
# a=10
# b=20
# def test5(a,b):
# print(a,b)
# c = test5(b,a)
# print(c)
# 3. 读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
# a=10
# b=20
# def test5(a,b):
# a=3
# b=5
# print(a,b)
# c = test5(b,a)
# print(c)
###########################################... |
70b8b1248ef51c17a69df3152c3a18fc9104367d | rboulton/adventofcode | /2017/day3b.py | 1,088 | 3.546875 | 4 | import sys
num = int(sys.argv[1])
values = {}
dirs = [
(1, 0),
(0, 1),
(-1, 0),
(0, -1),
]
def set(x, y, value):
values.setdefault(x, {})[y] = value
print(x, y, value)
def get(x, y):
return values.get(x, {}).get(y, 0)
def walk():
x = 0
y = 0
set(x, y, 1)
while True:
for i ... |
6fae33b869e3d4211fb62706ff86fd590f5ae972 | wxdespair/wxdespair.github.com | /programming_language/Python/clutter/小程序(py格式)/猜数字 0.4.py | 455 | 3.828125 | 4 | import random
secret = random.randint( 1 , 10 )
print('…………我的…………')
temp = input("猜猜现在我想到的是哪个数字:")
guess = int(temp)
while guess != secret:
temp = input("再猜猜:")
guess = int(temp)
if guess == secret:
print("对了")
print("对了就对了吧")
else :
if guess > secret:
print("大了")
... |
0559783e106458eca12640381af58fade52eb57c | Alex-Padron/personal-projects | /homomorphic_encryption/multiparty_encryption/client.py | 2,980 | 3.53125 | 4 | import os
import program
import server1
import server2
import time
class client:
#inputs to the client
inputs = []
#inputs encrypted under a
encrypted_inputs = []
#outputs
outputs = []
a = []
b = []
def __init__(self, inputs):
assert (program.input_size > 0)
assert (len(inputs) == program.input_size)
... |
77e8b7ecf920e6a86bfceaa0579346ff4b9e12a0 | kelvDp/CC_python-crash_course | /chapter_4/TIY_4-7.py | 116 | 4.28125 | 4 | #to get a list of the multiples of 3:
numbers = []
for num in range(3,31):
numbers.append(num*3)
print(numbers) |
8d53c585c3219dc75a0aa298456d85df89f6cde0 | deanrivers/hackerRank | /python/libraryFine.py | 570 | 3.65625 | 4 | def fine(d1,m1,y1,d2,m2,y2):
return_date = d1
due_date = d2
fine = 0
#check year
if(y1>y2):
fine = 10000
print(fine)
return fine
#check month
elif(m1>m2 and y1==y2):
fine = 500*(m1-m2)
print(fine)
return fine
#check da... |
58ae34c3d1d18804569e799e9b9e74921a324a7f | nick-fang/pynetwork | /pynetwork/第三,四,五章-TCP和DNS/tcp_deadlock.py | 4,330 | 3.625 | 4 | """可能造成死锁的TCP服务器和客户端"""
import argparse
import socket
import sys
def server(host, port, bytecount):
"""服务器端;bytecount变量未使用,是为了配合命令行参数的统一,而被强行放在这里"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #双方四次挥手后不再等待4分钟才彻底断开连接,仅Linux下有效
sock.... |
49bc2a32682f0665fb5f0b26364329aa1191eab4 | venkatsvpr/Problems_Solved | /LC_Shortest_Distance_Calculator.py | 995 | 3.859375 | 4 | """
821. Shortest Distance to a Character
Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Example 1:
Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Approach:
========
Keep a count of the character ... |
e16f04c7cdf173a958afd9c5c22fd8e2fa98fc55 | EuniceHu/python15_api_test | /week_2/class_0219/if.py | 1,132 | 3.875 | 4 | #-*- coding:utf-8 _*-
"""
@author:小胡
@file: if.py
@time: 2019/02/19
"""
# 1:非常简单的条件语句
# if 条件:if 后面的条件运算结果是布尔值 逻辑/比较/成员 各类数据类型
# if代码 只有当if后面的条件成立的时候才会执行
# python 非零非空数据 都是True
# 零空数据 False
#
# s=[] 空数据代表False 不执行
# if s:
# print('我今年18岁!')
# 2:第二个条件语句
# if..else..
# age=55
# if age>=18:... |
7de24ff414e0f5c9970e014ecb348a4c1f6ed778 | rux65/Python-Exercises | /python-ProjectEuler/ProjEuler#3.py | 1,351 | 3.9375 | 4 | ## first define all the primes till that number
## from 3 onwards
## if number is divisible by prime, then largest prime is that number
## downside is having to go through the cases till till that number while:
## it would be less time consuming to divide by the first prime then result
# divide again and if not then n... |
ada7642287cd842dae220ebf91c3ad9aeab9c2d6 | daniel-reich/ubiquitous-fiesta | /Jm4eKTENReSiQFw9t_10.py | 117 | 3.859375 | 4 |
def invert_list(lst):
lst2=[]
if not len(lst): return []
for i in lst:
lst2.append(i * -1)
return lst2
|
a0c80ebf49b9c451af5bd7697ac9e655c5fa4cab | einnar82/python-abc | /dictionaries.py | 753 | 4 | 4 | # Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# just like JS Objects
person = {
'first_name': 'john',
'last_name': 'doe',
'age': 30
}
print(person, type(person))
# get value
print(person['first_name'])
print(person.get('last_name'))
# add key/value
person... |
c137a777fbb9c79f63926d91c7eca7cec03d6c2b | rattlesnailrick/leetcode | /src/task_10.py | 5,424 | 3.671875 | 4 | class Solution(object):
def isMatch(self, text, pattern):
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], "."}
if len(pattern) >= 2 and pattern[1] == "*":
return (
self.isMatch(text, pattern[2:])
o... |
b9b3faa5e7c2afdc2170c56fdf2c5cdad7a43efc | joedo29/Self-Taught-Python | /OOP.py | 4,452 | 4.65625 | 5 | # Author: Joe Do
# Object Oriented Programming in Python
# Create a new object type called Sample
class Sample(object): # By convention we give classes a name that starts with a capital letter.
pass
# Instances of Sample
x = Sample()
print(type(x))
# The syntax of creting an attribute is:
# self.attribute = somet... |
cc86073d570ec77e3032b7c6854107bb8c69f569 | anildoferreira/CursoPython-PyCharm | /exercicios/aula14-ex064.py | 203 | 3.8125 | 4 | soma = 0
c = 0
n = 0
while n != 999:
n = int(input('Digite seu número para soma: '))
if n != 999:
c = c + 1
soma += n
print('Foram {} digitados e a soma é {}'.format(c, soma))
|
86f0970b6082dc55bd86a8293a28caa1392ff8a3 | AndreaMorgan/Python_FinancialAnalysis | /PyPoll/main.py | 1,940 | 3.765625 | 4 | #Importing necessary libraries
import csv
import os
#Locating and reading csv source file
currentDir = os.getcwd()
#print(currentDir)
data = '../Python_Challenge/Resources/election_data.csv'
#Create lists, dictionary and populate them with column data
voter_id = []
candidates = []
totals = {}
#Open CSV file, read d... |
dc7f53c3b0ed0c188cbc847962af0125044a2fd0 | shomah4a/continuation-slide | /cps3.py | 452 | 3.640625 | 4 | #-*- coding:utf-8 -*-
def fib_cont(n, cont):
u'''
継続渡しスタイルのフィボナッチ数計算
'''
def f1_cont(n1):
# fib(n-1) の計算結果の継続
def f2_cont(n2):
# fib(n-2) の計算結果の継続
cont(n1+n2)
fib_cont(n-2, f2_cont)
if n <= 1:
cont(1)
else:
fib_cont(n-1, f1_cont)... |
d3808671bbd64f75861b78f96aa14a906c7c4c32 | shawnhank/chealion-old | /Shell/passwordGen.py | 3,920 | 3.6875 | 4 | """passwordGen.py
This program generates a simple 8 character password containing numbers, symbols, uppercase and lower case letters.
Below it will display the NATO Phonetic output as well
Usage: paswordGen.py
# Can take the following arguments:
# -l # (length of password)
# -n # (number of passwords to generate)
#... |
65f35e3396547469e84421c3462d0fec12fb9332 | BluebloodXXL/python | /pychartmprojects/OperatingSystemAlgorithm/sjfNp.py | 1,981 | 3.625 | 4 | import operator
arvTime_burstTime = {}
burstTime = []
burstTime_1 = []
arvTime = []
arvTime_1 = []
processNo = int(input("Enter number of process (Must enter the process which arrives at 0th second first)> "))
i = 0
while i < processNo:
arvTime_1.append(int(input(f"Enter arrival time for process {i + 1} >")))
... |
db3450917e419b101fb977f6f373805607351b3f | Hroque1987/Exercices_Python | /sort_method.py | 357 | 4.40625 | 4 | # sort() method = used with lists
# sort() function = used with iterables
students = ['Squidward', 'Sandy', 'Patrick', 'Spongbob', 'Mr. Krabs']
#students.sort(reverse=True) # Onlu works with lists
#for i in students:
# print(i)
sorted_students = sorted(students, reverse=True) # works with other iterabels
for i... |
888e5330d36ef558e8a3276974bbd279aea9956e | mliang810/itp115 | /Assignments/A6-LoopsLists.py | 5,438 | 4.125 | 4 | # Michelle Liang, liangmic@usc.edu
# ITP 115, Spring 2020
# Assignment 6
# Description:
# This program will assign 10 seats on a plane - first class and economy class
def main():
# TOTAL SEATS VARIABLE NOT HERE TO ACCOUNT FOR FIRST CLASS AND SECOND CLASS
# seatsLeft variable replaces total_seats and numFilled... |
83df8d7aa496a802bdf9e9f94c0fbd2dcee0ee99 | gnellany/Automate_the_boring | /Table Printer.py | 1,047 | 4.5 | 4 | '''
Automate the boring Stuff
Chapter 6 question Table Printer.
The following code can transpose a matrix or 2D list in python.
This code also spaces out the output list to be easily read.
'''
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
... |
7c62b21bfa2b0ec3c61dde61f4d9f830d1ef0af1 | moralesmaya/practicePython | /practice6.py | 370 | 4.28125 | 4 | #x = x + word ---> x += word
def reverse(string):
result = ""
for letter in range(len(string)):
result += string[len(string)-1-letter]
return result
userInput = input("Enter a word to check if it's a palindrome: ")
reversedWord = reverse(userInput)
if userInput == reversedWord:
p... |
6eb679d5db213a13d1b2141061222250f1a7579a | remichartier/002_CodingPractice | /001_Python/20211127_2311_HackerrankTheFullCountingSortMedium/theFullCountingSort_v00.py | 397 | 4.0625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'countSort' function below.
#
# The function accepts 2D_STRING_ARRAY arr as parameter.
#
def countSort(arr):
# Write your code here
if __name__ == '__main__':
n = int(input().strip())
arr = []
for _ i... |
ef3d76f402e72b78730ce5aa8be7f32afde5b89e | MariannaBeg/homework | /OOP3.py | 353 | 3.828125 | 4 | class Person:
def __init__(self,name,eyecolor,age):
self.name = name
self.eyecolor = eyecolor
self.age = age
my_person1 = Person("Jirayr MElikyan","Brown",19)
my_person2 = Person(my_person1.name, my_person1.eyecolor,my_person1.age)
print(my_person1.name)
print(my_person2.name)
my_person1.name="aaaa"
print(m... |
0ef5b9bbfe1ae8a3304af7cb75ea311d157b4096 | daniel-reich/ubiquitous-fiesta | /NJw4mENpSaMz3eqh2_10.py | 341 | 3.71875 | 4 |
def is_undulating(n):
l=len(str(n))
sn=str(n)
if (l<3) | len(set(sn))!=2:
return False
else:
for i in range(0,l-2,2):
if sn[i]==sn[i+1]:
return False
elif sn[i]==sn[i+2]:
continue
else:
return False
... |
47c1718849cb8e9a63bb9898990cdfcce1eedfaf | CruzAmbrocio/Batalla_Naval | /src/batalla_naval.py | 1,363 | 3.71875 | 4 | # To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="adela"
__date__ ="$22/01/2014 10:32:04 AM$"
import random
tablero = []
for x in range(0,5):
tablero.append(["O"] * 5)
def print_tablero(tablero):
for fila in tablero:
print " ".join(fila)
print "Juguemos... |
1ab7fb9525ec2b1872863b17e7d541163f1e3a20 | Chu66y8unny/EP59 | /code/item8.py | 1,019 | 4.1875 | 4 | matrix = [[1, 2, 3], [4, 5, 6]]
# flat matrix to a list by row
# by plain loops
vec_by_row = []
for row in matrix:
for col in row:
vec_by_row.append(col)
print(vec_by_row)
# by list comprehension
vec_by_row.clear()
vec_by_row = [x for row in matrix for x in row]
print(vec_by_row)
# flat matrix to a list b... |
924a82971e1d9d945a84a8a1c2aa9cf125941c3f | FilipeAPrado/Python | /Paradigmas de linguagem em python/TarefaVotos.py | 646 | 3.609375 | 4 | from enum import Enum
class Votes(Enum):
firstCandidate = 1
secondCandidate = 2
thirdCandidate = 3
fourthCandidate = 4
nule = 5
inwhite = 6
totalVotes = {
Votes.firstCandidate: 0,
Votes.secondCandidate:0,
Votes.thirdCandidate:0,
Votes.fourthCandidate:0,
Votes.nule:0,
Vo... |
cd97d8e83b682b76f9a7be9dd26e2fe1772716a7 | Surajit043/Python | /Python_Basic/range_object.py | 276 | 4.0625 | 4 | """
Range
range(stop)
range(start, stop)
range(start, stop, step)
step default = 1
start default = 0
stop default XXXXX
iterable object
"""
r = range(5, 10, 3)
print(r)
# print(type(r))
# print(r.start)
# print(r.stop)
# print(r.step)
for i in range(5, 10, 3):
print(i)
|
cdf43d69315d2c44e3f3661b819b57c7da60522c | chenfu2017/Algorithm | /leetcode/73.SetMatrixZeroes.py | 779 | 3.59375 | 4 | class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if len(matrix)==0:
return
row = []
col = []
m = len(matrix)
n = len(matrix[0])
... |
15ae0e5481a39dbc9bd3207b751e236736aa413b | HenryM975/Euler | /4.py | 641 | 3.578125 | 4 | #4
firstlist = []
for i in range(10,100):
for j in range(10, 100):
a = i*j
k = list(str(a))
num1 = k[0]
num2 = k[-1]
p = len(str(a))
if num1 == num2 :
if p <= 3:
firstlist.append(a)
elif p >= 4:
num3 = k[1]
... |
99cd0fbaf1c897bada7dc849fc2ac016998a5977 | SylviaJitti/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 176 | 4.28125 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
return[replace if n == search else n for n in my_list]
# ternary operator and list comprehension in python
|
9b902178a3073e520abf813483ca755e2b6dd075 | MachFour/info1110-2019 | /week12/max/times-tables.py | 460 | 3.875 | 4 |
def times_tables(n):
# this will be a list of lists
table = []
i = 1
while i <= n:
new_row = []
j = 1
while j <= n:
new_row.append(i*j)
j += 1
table.append(new_row)
i += 1
return table
def print_table(table):
for row in table:
... |
72f8ff0405420d0dbc483a22674666c95b5a6625 | Achyutha18/College_Sample_1 | /Sample1_5.py | 167 | 4.375 | 4 | #Python Program to Print Odd Numbers Within a Given Range
ran = int(input("Enter the range : "))
for i in range(1,ran,2):
print(i,end=" ") #to print in single line |
916f831e2768abc697832eba3e3f7a0e741c051b | Baistan/FirstProject | /function_tasks/Задача8.py | 292 | 3.859375 | 4 | def Quad():
import math
a = []
b = []
num = int(input())
while num != 0:
a.append(num)
num = int(input())
for digit in a:
result = math.sqrt(digit)
if (result - int(result)) == 0:
b.append(int(result))
print(a,b)
Quad()
|
61d074bbda6e9708f4058ed28123c14e6d34d648 | Nivaldotk/CalcuDelta- | /main.py | 236 | 3.921875 | 4 | def delta(a, b, c):
r = ((a ** 2) - 4 * a* c)
return r
a = int(input("Digite o valor de B"))
b = int(input("Digite o valor de A"))
c = int(input("Digite o valor de C"))
print("O resultado de Delta é ", delta(a, b, c))
|
dae214d8380a9c807b7acdd917a619a9906f7cc8 | HarmlessHarm/Heuristieken | /modules/Objects.py | 9,201 | 4.09375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import pprint
import copy
import numpy as np
class Board(object):
"""
Board object in which all data is stored
"""
def __init__(self, x_dim, y_dim, z_dim=10):
"""
Creates a Board object with certain dimensions and initializes a ... |
68c15c551dab4fdf225b50080b5592b68cee4a21 | nilesh-patil/digit-classification-fully-connected-neural-nets | /code/layer.py | 3,888 | 3.546875 | 4 | """All the layer functions go here.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
class FullyConnected(object):
"""Fully connected layer 'y = Wx + b'.
Arguments:
shape(tuple): the shape of the fully connected layer. shape[0] is the
output size an... |
969e8af5e0a089a78a6ffc9d6cefba8b4a6996f4 | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/assignments.py | 364 | 3.609375 | 4 | # x = 5
# y = 16
# z = 20
x, y, z = 5, 16, 20
# x, y = y, x
x += 5 # x = x + 5
x -= 5 # x = x - 5
x *= 5 # x = x * 5
x /= 5 # x = x / 5
x %= 5 # x = x % 5
y //= 5 # y = y // 5
y **= 5 # y = y ** 5
y *= z # y = y * z
# print(x, y, z)
values = 1, 2, 3, 4, 5
# print(values)
# print(type(values))
x, y, *... |
b051f9ac3a265b70ee53710a582e8f4f95716a4b | jeansabety/learning_python | /sumfac.py | 476 | 4.1875 | 4 | #!/usr/bin/env python3
# Write a program that computes the running sum from 1..n
# Also, have it compute the factorial of n while you're at it
# No, you may not use math.factorial()
# Use the same loop for both calculations
n = 5
sum=0
fac=1 #need to start at one or we will multiply by zero every time we go through ... |
aab2b9e8bd50e45d0a5bacc1b24ad170a26edecb | kb0008/MAE_623 | /Project1.py | 8,719 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
####Run this block first to initiate functions############
##no input needed in this block##
#import libraries
import numpy as np
import matplotlib.pyplot as plt
import time
#define implicit method function
def implicit(ini... |
d81ccd9d70373a78df994c6c33d351f6c8f4398e | KocUniversity/comp100-2021f-ps0-ekaramustafa | /main.py | 169 | 3.578125 | 4 | import math
x = int(input("Enter number x: "))
y = int(input("Enter number y: "))
myid = 76289
print("x**y = " , x ** y)
print("log(x) =" , math.log(x,2))
print(myid)
|
48ebc281704b8abe1ccefea9c558f4c7e557f358 | sabrinachen321/LeetCode | /python/0234-isPalindrome.py | 911 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
def iterative(head):
newHead... |
17402a3d88da1e771aefaa15f87842b7fdab7202 | daniel-reich/turbo-robot | /5Q2RRBNJ8KcjCkPwP_17.py | 974 | 4.125 | 4 | """
Create a function that takes a list of character inputs from a Tic Tac Toe
game. Inputs will be taken from player1 as `"X"`, player2 as `"O"`, and empty
spaces as `"#"`. The program will return the **winner** or **tie** results.
### Examples
tic_tac_toe([
["X", "O", "O"],
["O", "X", "O"],
... |
c4d46bb744b47b773e981fa1261ba997fac31199 | SeanIvy/Learning-Python | /ex17.py | 1,144 | 3.578125 | 4 | # ------------------------------------------------
# Header
# ------------------------------------------------
# http://learnpythonthehardway.org/book/ex17.html
# ------------------------------------------------
# I like to add line breaks into my output,
# these variables allow me to do that easily
# and cohesi... |
99efe65e7c55e594396cd8211f292ad214384de9 | dgehani86/PythonDS | /py1.py | 2,304 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
#-------Number data type-----
value1 = 12
value2 = 10
resultsum = value1+ value2
resultdiv = value1 / value2
resultexp = value1**value2
resultmul = value1*value2
result_float = float(v... |
c6c592ace1d15979ee5d0a5f6b13d065f0dfa44e | cvaz2021/GradebookStudentProject | /main.py | 1,593 | 4.09375 | 4 | flag=True
gradebook = {}
testGradebook = {}
while flag == True:
print ("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Add Grade
5.Get Class Average
6.Exit/Quit
""")
ans = input("What would you like to do? ")
if ans == "1":
name = input("Enter a name")
... |
f6ca106ffb9c744ad0e97e689c2bf7df62fd13b9 | gabrielbessler/EulerProblems | /EulerPr21.py | 1,556 | 4.21875 | 4 | ''' === Problem Statement ===
Let d(n) be defined as the sum of proper divisors of n (numbers less than n
which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and
each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, ... |
bccfc2c8eaf9d11742fc898904393f1efc04a148 | russpj/GolfTee | /apptest.py | 1,730 | 3.6875 | 4 | '''
apptest.py
Tests the golf tees game.
'''
from GolfTees import Rule
from GolfTees import Solve
from GolfTees import Solution
from GolfTees import CreateTriangleBoard
'''
This is the classic 10-hole triangular board
0
1 2
3 4 5
6 7 8 9
'''
def PegChar(peg):
if ... |
73a6de5e9f1a14bed2248af0a1f02ab4ac9d17a9 | rodrigocruz13/holbertonschool-interview | /0x00-lockboxes/0-lockboxes.py | 2,517 | 4.0625 | 4 | #!/usr/bin/python3
"""
Module used to add two arrays
"""
def canUnlockAll(boxes):
"""
Method that determines if all the boxes can be opened.
Args:
boxes (lst): List of all the boxes.
Returns:
True (bool): for success,
False (bool): In case of failure.
"""
if (type(box... |
f96e36117c6fcf3e6591c926b105cc27be16a9cb | michaelnutt2/cvAssignment | /cvcode.py | 3,929 | 4.4375 | 4 | # -*- coding: utf-8 -*-
'''
In this assignment:
· You learn how build a Convolution Neural Network for image classification a computer vision task using KERAS
. The image classification task is the handwritten digit classification using the MNIST dataset
Dataset
The MNIST dataset is an acronym that stan... |
dfd8bbaff55630ae7c721de9cedd0554bfae0f84 | stephalexandra/lesson7 | /problem2.py/problem2.py | 215 | 3.96875 | 4 | print ('-' * 65)
x = input ('Pick a number: ')
x = int(x)
y = input ('Pick another number: ')
y = int(y)
total = (x * y)
total = str(total)
print('When you multiply these numbers, you get ' + total)
print ('-' * 65) |
3a1b5a287dbd4b5b905517e2061fce62a35f54c7 | febacc103/febacc103 | /functions/calculator.py | 259 | 3.859375 | 4 | def calc():
n1=int(input("enter first number"))
n2=int(input("enter second number"))
add=n1+n2
sub=n1-n2
mul=n1*n2
print("enter your choice")
print("1.add")
print("2.sub")
print("3.mul")
if()
print(n1+n2)
calc()
|
b7fe479f010694f71b4dbc5df0e07cd3a3c08449 | DMRathod/_RDPython_ | /Simple_estimation_CrowdComputing.py | 894 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 12:53:40 2019
@author: Dharmraj Rathod
"""
from statistics import mean
#from scipy import stats
#let we have the bottle filled with marbels and we have to guess how many number of marbles are
#there in the bottle
"""total number of marbles in the bottle is 36"""
#imp... |
02c8ff63993add66fe8f444234bf283461999a92 | Simik31/KIP-7PYTH | /Úkol 8/main.py | 3,006 | 3.859375 | 4 | class Date:
def __init__(self, date):
self.split_sep = ["", ""]
self.date = date
self.monthNumber = 0
for sep in separators:
if sep in self.date:
self.split_sep[0] = sep
self.day = self.date.split(self.split_sep[0])[0]
self.... |
1bf6f5cbf6a326de1ec845adc6d8cb7807e34860 | binchen15/leet-python | /tree/prob1325.py | 667 | 3.6875 | 4 | class Solution:
def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
if not root:
return None
if root.val == target and self.isLeaf(root):
return None
root.left = self.removeLeafNodes(root.left, target) ... |
00c6ad5169e5f90f918de416dc288740c79ee4ca | AdamZhouSE/pythonHomework | /Code/CodeRecords/2452/59140/259780.py | 175 | 3.96875 | 4 | row=int(input())
str=''
for i in range(row):
str+=input()
str+=","
str=str[:len(str)-1].split(',')
target=input()
if str.count(target)!=0:print(True)
else:print(False) |
f1c920a5ea4182205ac4347dbefdc49382b92531 | GrantWils23/Texas_Hold_Em_Poker_Project | /tests/validators/test_two_pair_validator.py | 1,314 | 3.703125 | 4 | import unittest
from poker.card import Card
from poker.validators import TwoPairValidator
class TwoPairValidatorTest(unittest.TestCase):
def setUp(self):
self.three_of_clubs = Card(rank = "3", suit = "Clubs")
self.three_of_hearts = Card(rank = "3", suit = "Hearts")
self.nine_of_diam... |
48dcaac2b4c552aa9cfab5e641a4fc6d0cb64182 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4384/codes/1811_2567.py | 62 | 3.8125 | 4 | n=int(input("digite um valor:" ))
for i in n:
s=n+1
print(s) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.