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 |
|---|---|---|---|---|---|---|
36a9ad2d0f4ca22c5db3f2f5b8463664160b5ad7 | lucasdavid/artificial | /artificial/utils/priority_queue.py | 1,266 | 4.03125 | 4 | """Basic Priority Queue"""
# Author: Lucas David -- <ld492@drexel.edu>
# License: MIT (c) 2016
import heapq
import itertools
class PriorityQueue:
REMOVED = '<removed-e>'
def __init__(self):
self.priority_queue = []
self.map = {}
self.counter = itertools.count()
def add(self, e... |
8fb9216e58f0d05e13b35f10104d343e664d468b | sczapuchlak/PythonCapstoneLab1 | /CamelCase.py | 1,122 | 4.46875 | 4 | # this program takes a users sentence and turns it into camel case
# keeps the first letter lowercase
print('Please enter a sentence in any sort of case! I will make it camel case for you!')
# takes the users input and makes all of it lowercase, and then
# capitalizes the first letter in each word
sentence = input().lo... |
007641c44e8d61485fbf976c9e002b26e545d963 | codecherry12/Data_Structues_AND_Algorithms | /Queues/DoubleEndedQ.py | 1,008 | 4 | 4 | #double ended queue
class deq:
def __init__(self):
self.data=[]
def isempty(self):
return len(self.data)==0
def __len__(self):
return len(self.data)
def enquerear(self,ele):
self.data.append(ele)
def dequerear(self):
if self.isempty():
print('Q is ... |
7608fdc3cf812565aaa08722945b977a1064f7f5 | camano/Aprendiendo_Python | /condicionales/condicionales.py | 220 | 3.8125 | 4 | print("Progama de evaluacion")
nota_alumno=input("introdusca algo")
def evaluacion(nota):
valoracion="Aprobado"
if nota<5:
valoracion="Suspenso"
return valoracion
print(evaluacion(int(nota_alumno))) |
f2b61798ffe3030f6d56bc70616841965e85b44d | bhushankelkar/machinelearning-resources-ieee-apsit | /linear_regression/simple_linear_regression.py | 1,846 | 4.25 | 4 | # Simple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')#has only 2 columns experience and salary(index 0 and 1)
X = dataset.iloc[:, :-1].values #takes all column except la... |
266eb936ffeeb649bc916180cf6cd20e95e4a230 | Shmuco/DI_Bootcamp | /Week4/Day4/Ex_XP_Gold_dice.py | 2,099 | 4.5 | 4 | # Create a function that will simulate the rolling of a dice. Call it throw_dice. It should return an integer between 1 and 6.
# Create a function called throw_until_doubles.
# It should keep throwing 2 dice (using your throw_dice function) until they both land on the same number, ie. until we reach doubles.
# For exa... |
0de4eb030e3fd7e05c631f19f69375996da0a029 | wstam88/rofistar_php | /resources/snippets/Python3/Buildin functions/String/rpartition.py | 169 | 4.03125 | 4 | txt = "I could eat bananas all day, bananas are my favorite fruit"
# Returns a tuple where the string is parted into three parts
x = txt.rpartition("bananas")
print(x) |
1201c22b11346b91ded6f46f4dffc209ccb8ddc9 | shouliang/Development | /Python/PythonBasic/var.py | 430 | 4.25 | 4 | # 变量只需被赋予某一值,不需要声明或者定义数据类型
# 建议使用四个空格来索引
i = 5
print(i)
# 下面将发生错误,注意行首有一个空格
# print(i)
i = i + 1
print(i)
s = '''This is a multi-line string.
This is the second line.'''
print(s)
# 显示行连接: 故结果为:This is a string. This continues the string
s = 'This is a string. \
This continues the string '
print(s)
|
10593144eaefd390e91e0374e89684075e1f31ea | Kunal352000/python_adv | /18_userDefinedFunction46.py | 145 | 3.5625 | 4 | def f1():
x=10#local
print(x)#10
f1()
def f():
print(x)#error
f()
"""
output:-
10
NameError: name 'x' is not defined
"""
|
2cc4ae22ed55c44aaf7fa5521a093ef8e1757af4 | mendoza/hotcake | /Btree.py | 7,964 | 3.625 | 4 | from Node import Node
import bisect
import itertools
import operator
class BTree(object):
BRANCH = LEAF = Node
"""
Orden: como su palabra lo dice, el orden en el que basamos el arbol
"""
def __init__(self, order):
self.order = order
self._root = self._bottom = self.LEAF(self)
... |
c4fe96f3f104645abd2707bbe8a2e4865fa7e0e2 | NetUnit/Lv-527.PythonCore | /home_work_7_04_09/home_work_7_PSW/Sighn_Up_Password/2_check_psw_loop_for.py | 1,215 | 4 | 4 | import time
'''
Using loop for and range() sequence
in the main block to check whether a
password is strong and satisfy conditions
'''
# aforehand prepared answers in oreder to fill check() block
def inquiry():
return input('PLEASE PROVIDE A PASSWORD: ')
def incorrect_answer():
return print(('P... |
6f15a443d58247ea8ada1c3caa36bffac4f1d98c | ROYALBEFF/aaaaaa_arcade_game | /aaaaaa/ObstacleHandler.py | 1,604 | 3.796875 | 4 | from aaaaaa.Obstacle import Obstacle
import random
class ObstacleHandler:
def __init__(self):
pass
@staticmethod
def generate_obstacle(state):
"""
Generate a new obstacle with a probability of obstacle_prob percent.
"""
p = random.randint(0, 100)
if p < st... |
778ea996a187546e9656d515ea0cd9dc51085ddb | bjmarsh/insight-coding-practice | /daily_coding_problem/2020-07-31.py | 1,002 | 4.3125 | 4 | """
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
"""
def n_possible_de... |
bbd910ce6b14165d9e2701be9abe91b9b70b74ca | natann4755/JavaAlexRony | /Lessens/lessen 15 p/4.py | 943 | 3.734375 | 4 | class car (object):
def __init__(self,a,b=0):
self.a=a
self.b=b
def dd(self):
print("a:%s \nb: %s"% (self.a,self.b))
@staticmethod
def prin(c):
print ("a:%s \nb: %s"% (c.a,c.b))
def __ff(self):
print ("jjj")
def __cmp__(self, other):
if isinstanc... |
d1c4ccf8b930480ec1c9e0b2bd1d11c58e3ea524 | Mohan110594/Greedy-2 | /Task_scheduler.py | 1,612 | 3.75 | 4 | // Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
// Your code here along with comments explaining your approach:
In this problem we first calculate the frequency of the largest occuring element and how many times the freq has occured.Then we using the above two par... |
2b0ca4bd33ca78e4130332ee0122109f1a1194be | arpitx165/LeetCode | /LC30-2020/W2/q1.py | 529 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
#https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3290/
class Solution(object):
def middleNode(self, head):
"""
:type head:... |
16350bbdd5750887386b229f42715ae05a975983 | rtridz/pythonfirst | /07_threads_and_os_env/progs/excel/open_excel.py | 194 | 3.515625 | 4 | import xlrd
file = xlrd.open_workbook('file.xls',formatting_info=True)
sheet = file.sheet_by_index(0)
for rownum in range(sheet.nrows):
row = sheet.row_values(rownum)
for cell in row:
print cell |
92019d28127dce99c6b200df29efc25499889dc0 | hadoopaws8/home-work-files | /homework_set_element_inserttion_and_deletion_and_checking.py | 365 | 4.09375 | 4 | s=set()
n=int(input("enter the number of elements in set: "))
for i in range(n):
s.add(int(input("enter next element of set: ")))
check=int(input("enter which element you want check: "))
if check in s:
print(check,"your element in set so i am deleted from set ")
s.discard("check")
else:
print(c... |
c681d5fb9b36176e2950555b9075c4d7c79a0e16 | Jon-Ting/UH-DA-with-PY-summer-2019 | /part02-e01_integers_in_brackets/src/integers_in_brackets.py | 647 | 3.8125 | 4 | #!/usr/bin/env python3
import re
def integers_in_brackets(s):
mo1 = re.findall(r"\[\s*[+-]?\w*] *\]", s)
new_s = []
for i, strings in enumerate(mo1):
mo2 = re.search(r"[A-Za-z]", strings)
if not mo2:
new_s.append(strings.strip("[").strip("]").strip())
new_s = " ".join(new_s)... |
11ade73d572e6c943dbeaaac14e5cafdb4951200 | dskard/challenges | /correlation1/corr.py | 1,874 | 3.671875 | 4 | # https://www.hackerrank.com/challenges/correlation-and-regression-lines-6
#
# we could put columns in a dataframe and use the Series' corr() function,
# setting the 'method' parameter to 'person':
#
# r = df['History Scores'].corr(df['Physics Scores'],method='person')
#
# calculating the person correlation coefficient... |
d514bcf79015b1b51ca0c2f927be5716c5623b01 | Adarsh232001/Basic-python-scripts | /guessingNumber.py | 691 | 4.15625 | 4 | #import random package to generate a secrate number
import random
secretNumber=random.randint(1,10)
print('I am thinking of a number could you guess it between 1 and 10')
#Ask the player to guess the number 6 times
for guessesTaken in range(1,7):
print('Take a guess')
guess=int(input())
if guess<sec... |
92c4b6e43d217b07e98e82181c6603b736943517 | HouPoc/Practice | /data_structure/dt_stc.py | 6,042 | 4.25 | 4 | #
#Basic Information node
#
class Node:
#Initial the Node
def __init__(self,data):
self.data = data
self.next = None
#
#Basic Linked List
#
class Linked_List:
#Initial the Linked List with a Head Node
def __init__(self,):
self.head = Node('head')
self.length = 0
... |
36c407ccfc8e47b2242c242983899bb7ab9e7485 | Endkas/TSP | /ClassCities.py | 2,503 | 4.125 | 4 | import numpy as np
import random
class Cities(object):
def __init__(self,n,seed = 10):
"""
Parameters
----------
n : Number of cities you want to generate
seed : The seed you want to use for random.seed(seed=seed), optional.
The default is ... |
26a71c04779db981b1ace63c454f26dea6d69184 | MrLarsouille/MrLarsouille | /Exercices/createDictionaryFromClass.py | 159 | 3.65625 | 4 | #Créez unn dictonnaire via le constructeur de la classe dict.
mydict = dict()
mydict["E01"] = "Lar"
mydict["E02"] = "souille"
print("mydict:", mydict) |
0cd2d54ffdcad0cc7b1933bea479cd9f584daf53 | RomanMillan/EjerciciosBucles | /Ej_II_T_6.py | 202 | 4.0625 | 4 | total = 0
acum = 0
numero = input("Enter one number: ")
numero2 = input("Enter one number: ")
while total < int(numero):
acum = acum + int(numero2)
total += 1
print("The product is ", str(acum)) |
8089bbe67a2e7c7e2e9fca0da242e85a2c39817e | gadepall/IIT-Hyderabad-Semester-Courses | /EE2350/Coding Assignment-1/2.1.1j.py | 1,343 | 3.546875 | 4 | # code for simulating y1[n] = x[n] - 2x[n-1] + x[n-2] and y2[n] = x[n] - x[n-1]
import numpy as np
import matplotlib.pyplot as plt
s = int(input("No.of Elements in signal: ")) # Generating the input
x = np.ones(s)
time = np.arange(s)
for i in range(s):
x[i] = 0.95 ** i
def Filter(S): # Functi... |
5aa2cb13fd3e0d903bbd412d46191765fc383388 | dsocaciu/Books | /ImplementingDerivativesModels/Chapter2/figure210.py | 1,068 | 3.5 | 4 | #Implementing Derivatives Models - Clewlow and Strickland
#Chapter 2
#Figure 2.10
#valuation of a European Call in an additive tree
from math import exp,pow,sqrt
#parameters
#precompute constants
K = 100
T = 1.0
S = 100
sig = 0.2
r = 0.06
N = 3
dt = round(T/N,4) #.3333
nu = round(r-0.5*pow(sig,2),4) #.04
dxu = rou... |
90ddf339aacc7da57b18d11769b344006a65d303 | paolamariselli/Python-Problem-Sets | /Spell Checker/checker.py | 1,601 | 3.9375 | 4 | #!/usr/bin/env python
import dictionary
import sys
import time
def sanitize_word(word):
"""
1. Transforms the word to lower case
2. Removes any surrounding whitespace
3. Removes any leading or trailing punctuation
"""
word = word.lower()
word = word.strip()
punct = set("[]*()-,.:;?!/`\... |
bf9a4c841e52568473f4c09920d7169146b3cc2d | rmgard/python_deep_dive | /sixthSection/partialFn.py | 1,583 | 4.5 | 4 | ''' What if we only want to parameters in my_func()?
See how fn() uses my_func, but presets the value of a?
'''
def my_func(a, b, c):
print(a, b, c)
def fn(b, c):
return my_func(10, b, c)
''' We can also use functools.partial
With partial() you define the vars you don't want to
feed into the ... |
91caec4a8b0f6117f3e8777f61b42639cc845dfd | lzhang007/pytest | /ifstat.py | 255 | 3.515625 | 4 | #!/usr/bin/python
#Filename:ifstat.py
number=23
guess=raw_input("type a integer:")
if guess == number:
print'great,you guess it'
elif guess > number:
print'no,it little lower than number'
else:
print'no,it little big than number'
print'done'
|
c323d1e4266d6582b7733df2839c4ec40b1f54b5 | parshuramsail/PYTHON_LEARN | /paresh26/A6.py | 108 | 3.765625 | 4 | my_list=[1,2,3,4,5,6,7,8,9,10]
list_sum=2
for num in my_list:
list_sum=list_sum+num
print(list_sum)
|
1ff5e7646ce5087f30689120e3a614462938f1d5 | rajeshpg/project_euler_solutions | /python/Euler6.py | 359 | 3.671875 | 4 | """
Find the difference between the sum of the squares of the first one hundred natural numbers
and the square of the sum.
"""
square = lambda n: n * n
squareOfSumOfN = lambda n: square((n*(n+1))/2)
sumOfSquareOfN = lambda n: ((n * (n+1) * ((2*n)+1)) / 6)
def solution(num):
return squareOfSumOfN(num) - ... |
e74a5618cc78d2a6df279ec2f63f1e929e2137c4 | gadodia/Algorithms | /algorithms/Arrays/singleNumber.py | 363 | 3.875 | 4 | '''
This problem was recently asked by Facebook:
Given a list of numbers, where every number shows up twice except for one number, find that one number.
Example:
Input: [4, 3, 2, 4, 1, 3, 2]
Output: 1
Time: O(n)
'''
def singleNumber(nums):
dup = 0
for num in nums:
dup = dup ^ num
return dup
pri... |
aacd16e5c8a43394e186819af9bcfe987a95b517 | carden-code/python | /stepik/girls_only.py | 788 | 4.34375 | 4 | # The football team recruits girls from 10 to 15 years old inclusive.
# Write a program that asks for the age and gender of an applicant,
# using the gender designation m (for male) and f (for female) to determine whether the applicant is eligible to join
# the team or not. If the applicant fits, then output "YES", oth... |
53564278a4ac85ba599801dfc230de06924b3865 | ivan-yosifov/python-2019 | /4strings.py | 503 | 3.984375 | 4 | ########################
# Learn Python 2019
########################
import os
os.system('clear')
greetings = "My boss yelled \"Get back to work!\""
print(greetings)
first_name = 'Megan'
last_name = 'Fox'
print(first_name + ' ' + last_name)
print(first_name.upper())
print(first_name.lower())
print(first_name.capit... |
70a2d311d71c785f99ca9948ff0db0b919018841 | v-ivanko/QAlight_Online_G7_ | /4-if.py | 397 | 3.96875 | 4 | a = int(input("\nВведите 1 значение: "))
b = int(input("Введите 2 значение: "))
v = int(input("Введите 3 значение: "))
if a > b:
print('Свершилось!')
elif a < b:
print('Да ну!')
else:
print('А если так?')
if a + v > b - v:
print('Свершилось!')
elif a + v < b - v:
print('Да ну!') |
153040a0b454f0990925b79dd70eabe20ffd3a25 | je-suis-tm/recursion-and-dynamic-programming | /pascal triangle with memoization.py | 3,486 | 4.125 | 4 |
# coding: utf-8
# In[1]:
def pascal_triangle(n):
row=[]
#base case
if n==1:
return [1]
else:
#calculate the elements in each row
for i in range(1,n-1):
#rolling sum all the values within 2 windows from the previous row
#... |
d01b274e5e5b7bb9438b8f309f41a2f6d90de745 | frankieliu/problems | /leetcode/python/5/longest-palindromic-substring.py | 1,767 | 3.921875 | 4 | """5. Longest Palindromic Substring
Medium
2762
268
Favorite
Share
Given a string s, find the longest palindromic substring in s. You may
assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
Accepted
435,97... |
af843bbfe30f215c88755019e32b05f826127165 | MahdieRad/Assignment-3 | /5.py | 257 | 4.15625 | 4 | A=int(input('Enter a Number\n'))
B = 1
while True:
if A % B == 0:
A //= B
else:
break
B += 1
if A == 1:
print('This is a Factorial Number :)')
else:
print('Try Again,This is Not a Factorial Number!')
|
5e34d754f7e66ab486e97622e4464d460715f146 | cjx1996/vscode_Pythoncode | /Study python without teacher/202003102container0.py | 1,162 | 4.53125 | 5 | '''
In this file,we will learn the use of containers,which contain list、tuple and dictionary.
Of course,we will learn the use of method only can be use in objects.
'''
#这是对列表list一些method的尝试使用
'''定义'''
a=list()
a=[1,2,3,4]
a=[]
a=[1,2,3,4]
colors=['blue','green','yellow']
colors1=['blue','green','yellow']
colors2=['o... |
c0680fe79a8b87601c64da64e6e194b869d7de54 | AnuPriya1237/Books_Collection | /Milstone_project-02/utils/database2.py | 1,133 | 3.78125 | 4 | """concerned with storing and retrieving books from csv file.
csv file format
name,author,read
"""
book_file = 'book.txt'
def create_book_table():
with open(book_file,'w') as file:
pass #just to mark that file is there
def add_books(name, author):
with open('book.txt','a') as file:
file.write(... |
2efc0326bdbfa63e061ea17f1da1eeefc6816019 | m-e-l-u-h-a-n/Information-Technology-Workshop-I | /python assignments/assignment-2/5.py | 193 | 3.546875 | 4 | lst=[(),(),("",),('a','b'),('a','b','c'),('d',)]
x=len(lst)
l=[]
print(type(lst[x-1]))
for i in range(x):
if isinstance(lst[i], tuple) and len(lst[i]) > 0:
l.append(lst[i])
print(l) |
92ebae533d4f7e9b2c652cd10a0cf6e0cab6872c | 6dec3fb8/pycarproject | /erlthread.py | 6,102 | 3.65625 | 4 | #!/usr/bin/python3
# This module is used to simulate the behavior of Erlang threads.
# It is really convenient to handle multi-threading things.
# 8 16 24 32 40 48 56 64 72 80
# ruler:-------+-------+-------+-------+-------+-------+-------+-------+-------+
"""
Python... |
34a8abda0883a707ad73fb669e550b5773431670 | molejnik88/python_nauka | /własne pomysły/nauka_klas/electric_car.py | 1,121 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# electric_car.py
#
# Copyright 2016 Maciej Olejnik <maciej@maciej-pc>
from car import Car
class Battery():
"""Klasa reprezentująca baterię"""
def __init__(self, battery_size):
self.battery_size = battery_size
def describe_battery(self):
"""Wyświetla po... |
ad361f38a61d5af174ed3584bd67268f3b003196 | AmeyLaddad/A-Udacity | /introduction to python (3)/chapter 2/Rating_survey.py | 1,529 | 4.5625 | 5 | def convert_to_numeric(score_input):
""" Convert the score to a numerical type."""
a = float (score_input)
return a
def sum_of_middle_three(s1,s2,s3,s4,s5):
"""Find the sum of the middle three numbers out of the five given."""
add_all = s1 + s2 + s3 + s4 + s5
final = add_all - max(s1,s2,s3,s4,s... |
460c261fff6b824b1fe9eac44d3dd9bc670eb95b | xwmtp/advent-of-code-2020 | /Day23/Day23.py | 2,310 | 3.546875 | 4 | # https://adventofcode.com/2020/day/23
input = '219347865'
class Cups:
def __init__(self, init_circle, init_cup):
self.circle = init_circle
self.total_cups = len(init_circle)
self.min_cup = min(init_circle)
self.max_cup = max(init_circle)
self.current_cup = init_cup
d... |
fdb3e30f0ae14aaf00127ce3cd41dfb7c0897356 | KeepFreedomNoCare/Anonymous- | /lag.py | 712 | 3.828125 | 4 | #strings
print('Hello World')
msg = 'Hello World'
print(msg)
firstName = 'Bilal'
lastName = 'Ahmed'
fullName = firstName + ' ' + lastName
print(fullName)
#lists
bikes = ['trek', 'redline', 'gaint']
firstBike = bikes[0]
lastBike = bikes[-1]
for bike in bikes:
print(bike)
square = []
for x in ran... |
3d1671f924a38ad78eec3e91acb974e5e5becfe4 | luohuaizhi/test | /Questions/testFrog.py | 529 | 3.640625 | 4 | # -*-encoding:utf-8-*-
import sys
end = 0 # 终点
cnt = 0 # 统计组合方式
def jump(start):
global cnt
for i in [1,2]:
cur = start+i
if cur >= end:
print start
print cur
cnt += 1
continue
jump(cur)
def main(n):
"""
一只青蛙一次可以跳1阶或者2阶,n阶,有多少种到... |
c608bd85114516f69c294bb707a3668b92d59424 | Kakashi-93/word-guessing | /wordGuessing2.py | 5,416 | 4.15625 | 4 | import random
wordList = ['cat', 'car', 'rat', 'dog', 'pan', 'pen', 'fox', 'gun', 'wax']
word = random.choice(wordList)
var1 = "_"
var2 = "_"
var3 = "_"
guess = 0
guessCharacter = ""
print("""
*******************************************************************
* WELCOME! To t... |
144b2feb52c917d62433f6ceb38c5237165934f1 | ronj1901/ICS_32 | /ICS 32 midterm/midterm-practice (1).py | 3,788 | 4.25 | 4 | ### If you want to run the code, you should comment out the problems you haven't
### done yet so you can't see the answers for them.
### Hints for each problem are at the bottom of this file
##
### 1. What's the output of the following code?
##try:
## try:
## a = 5
## b = 7
## ... |
80be5ec102ef20c78ebbde2f94dabb79949b0ccc | decy20002002/MyPythonCourse | /Ch09/class_inheritance.py | 554 | 4.09375 | 4 |
class Parent:
def __init__(self, last_name):
self.last_name = last_name
def print_info(self):
print('I am in the ' + self.last_name + ' family')
class Child(Parent):
pass #use pass if dont want any new properties
mom = Parent('Smith')
mom.print_info()
#--------Ch03 Lab 2 Inherit... |
51322c427e4a29eaba7ff9d6d52ddcccdb1ad5ef | maci2233/Competitive_programming | /CodeForces/A/610a.py | 128 | 3.625 | 4 | n = int(input())
if n % 2 != 0 or n <= 4:
print('0')
else:
half = n // 2 - 1
quart = n // 4
print(half - quart)
|
b2ba405bfd170f058379750586bf357bef4d0de5 | amymhaddad/exercises_for_programmers_2019 | /product_search/main.py | 1,336 | 3.90625 | 4 | """Return the inventory details for an item in the product inventory"""
import sys
from product_search import (
validate_item,
inventory_details_for_user_item,
style_dictionary_items_for_output,
return_product_details,
)
from data_management import access_json_data
from user_input import get_item_name... |
ad36f72bd45295257c3250755a58822d425620cd | henrypj/HackerRank | /Strings/TwoCharacters.py | 2,082 | 4.375 | 4 | #!/bin/python3
import sys
"""
# Description
# Difficulty: Easy
#
# String t always consists of two distinct alternating characters. For example,
# if string t's two distinct characters are x and y, then t could be xyxyx or
# yxyxy but not xxyy or xyyx.
#
# You can convert some string s to string t by deleting charac... |
987195962ee506d2fa25cce58f3275218138cbf0 | DavidStoilkovski/python-advanced | /comprehension-advanced/even_matrix.py | 317 | 3.75 | 4 | def read_input():
n = int(input())
matrix = []
matrix = [map(int, input().split(', ')) for _ in range(n)]
return matrix
def find_even(matrix):
find_even = [[el for el in row if el % 2 == 0] for row in matrix]
return find_even
matrix = read_input()
even = find_even(matrix)
print(even)
|
976bc15345b03a17cad2b859840e65158985d875 | wrayta/Python-Coding-Bat | /big_diff.py | 761 | 4.09375 | 4 | """
Given an array length 1 or more of ints, return the difference between the
largest and smallest values in the array. Note: the built-in min(v1, v2) and
max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8
"""
def big_... |
4de67534f03ae6ebe4cac6573bdd92f538ba9b15 | cuiods/Coding | /Python/mooctest/19_twouniform.py | 857 | 3.515625 | 4 | #-*- coding:utf-8 -*-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def uniform_distribution():
fig = plt.figure()
#add a 3d subplot
ax = fig.gca(projection='3d')
#set X,Y,Z
X = np.arange(-1, 1, 0.02)
Y = np.arange(-1, 1, 0.02)
#create coordinate... |
765793a7f9128b8d6a2f87fb1d323e8887f76133 | maiwen/LeetCode | /Python/337. House Robber III.py | 1,990 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on 2018/7/22 20:43
@author: vincent
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in... |
e757c68767dc5bcf60fb29fafb5d905bd04d555b | CopyOfA/reddit_api_analytics | /some_queries.py | 1,169 | 3.625 | 4 | ##which user(s) post in more than 1 subreddit?
SQL = "SELECT reddit_authors.author, COUNT(*) FROM reddit_authors JOIN reddit_title_authors USING(author_id) "
SQL += "JOIN reddit_titles USING(title_id)"
SQL += "GROUP BY reddit_authors.author, reddit_titles.subreddit_id HAVING COUNT(*)>1 ORDER BY COUNT(*) DESC "
out = p... |
6a598333a6553cd359fe508d7be75a64fc182c5f | DenizSka/CodingNomads | /labs/01_python_fundamentals/01_02_seconds_years.py | 405 | 4.0625 | 4 | '''
Write the code to calculate how many seconds are in a year in this file,
so you can execute it as a script and receive the output to your console.
'''
def seconds(days):
seconds_in_hour = 60 * 60
total_hours_in_year = days * 24
total_seconds = seconds_in_hour * total_hours_in_year
return total_s... |
4dc2a5a6e47622c4365284c6299f2b702841f2d6 | ameernormie/100-days-of-python | /2. Python Fundamentals/Collections/dictionaries.py | 919 | 3.9375 | 4 | """
Basic idea of dictionaries in python
Key-value pair
Keys must be immutable i.e. strings, numbers and tuples
Values can be mutable
Never rely on order of items in the dictionary
"""
# Make from other iterables
names_and_ages = [('Alice', 32), ('Ameer', 25), ('Bob', 45)]
d = dict(names_and_ages)
d ... |
f12297bd038fd403d3d73bac92448a0c2e4830c6 | Zzzzz-art/Informatika | /Py charm shool/2.32.py | 138 | 3.546875 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
N = int(input())
print((a + b + c + d) * 3)
print((a + b + c + d) * N) |
12e741535a6e2bcbdb61664e7b4e09d94404e690 | seen2/Python | /StringHandling/inputOutputStr.py | 165 | 3.75 | 4 | def main():
# take string as input
s = input("Enter your name:")
# printing string
print(f"you entered:{s}")
if __name__ == "__main__":
main()
|
4a8ad260a9309c94342dace8eff8d70156a841e7 | saumya470/python_assignments | /.vscode/OOPs basics/ClassExample.py | 453 | 3.796875 | 4 | class Employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + last + '@company.com'
def fullname(self):
return print(self.first + ' ' + self.last)
emp1 = Employee('Co... |
a532e185dfe70beeb5cfbf6b5350ecbf05b7c7b3 | deweysasser/training-example-code | /code/testing/Basic.py | 666 | 3.75 | 4 | # A basic python class
class Basic(object):
def __init__(self):
pass;
def fact(self, i):
if i < 0: raise Exception("Can't compute factorials of negatives!")
if i < 0:
raise Exception("Can't compute factorials of negatives!")
if i is 1: return 1
... |
9df5baa60d20a77cfe9c969bb78812c1654a4e49 | BrettMcGregor/w3resource | /dict1.py | 380 | 4.15625 | 4 | # Write a Python script to sort (ascending and descending) a dictionary by value.
import random
def create_multiple_lists(name, number):
master_dict = {}
for i in range(number):
master_dict.update({name+str(i): random.randint(0, 1000)})
return master_dict
def sort_dict(master_dict):
print((... |
4a255c0c790db09a487c09510ac19d6cb83cd301 | verdi07/crypto | /ataqueDiccionarioSustSimple.py | 2,101 | 3.625 | 4 | # Ataque de diccionario a la cifra de sustitución simple
import pyperclip, sustitucionSimple, detectarEspanol
MODO = False
def main():
criptograma = input('Criptograma > ')
textoLlano = ataque(criptograma)
if textoLlano == None:
# ataque() devuelve None si no ha encontrado la clave
... |
3f21aebc8d357987061ea0ebde328a0b3e88466f | matchallenges/PythonLearning | /PythonTutDocumentation/IntroductionToPython/3.1.3._Lists.py | 1,139 | 4.3125 | 4 | # this code was created while reading the 3.1.3. Lists documentation on the tutorial page
# python knows a variety of compound data types, used to group variables together
# one of the most versatile is a list
squares = [1, 4, 9, 16, 25]
print (squares)
print (4 * squares) # you can also concatenate lists into one b... |
baae0078cd322fd2b3c22a46d8a60a13381f2491 | virajPatil11/Skill-India-AI-ML-Scholarship | /solving problems in python/2.readFile.py | 329 | 3.59375 | 4 | #opening input file
fin = open("in.txt", "rt")
#output file to write the result to
fout = open("out.txt", "wt")
for line in fin:
#read replace the string and write to output file
fout.write(line.replace('Today', '01-05-2021').replace('tomorrow','02-05-2021'))
#close input and output files
fin.close()
fou... |
9f7ca5cddb40450c6b309c135e9fc228a1f8511c | mengsince1986/coding_bat_python | /logic-1/love6.py | 447 | 4.03125 | 4 | def love6(a, b):
"""
The number 6 is a truly great number. Given two int values, a and b, return
True if either one is 6. Or if their sum or difference is 6. Note: the
function abs(num) computes the absolute value of a number.
>>> love6(6, 4)
True
>>> love6(4, 5)
False
>>> love6(1, ... |
1abf4f5341e0dfa3569729c4edb4a078fb9f20f8 | Prasad-Medisetti/STT | /My Python Scripts/VALID STRING.py | 1,739 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 14:11:50 2020
@author: hp
"""
'''
check if a string has all characters with same frequency with one variation allowed..
given a string of lowercase alphabets , find if it can be converted to a valid string by removing 1 or 0 characters . A "valid" string is a string... |
6467208f291239013d00bf05ea8bfdd9b22814d7 | rafaxtd/URI-Judge | /AC3/secondChance.py | 862 | 3.6875 | 4 | def getGrades(list, x):
for i in range(x):
n = float(input())
list.append(n)
return list
n = int(input())
grades = []
activityGrades = []
lastGrade = []
cont = 0
getGrades(grades, n)
getGrades(activityGrades, n)
for i in range(n):
if grades[i] == 10 or activityGrades[i] < 10:
... |
8abac6f77a60e073a38bceef9a8155c184ec6139 | maximile/chess | /chess.py | 33,710 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Chess! Squares are identified by tuples of ints, 0-7. Y axis is up from white's
point of view:
7 [ ][ ][ ][ ][ ][ ][ ][ ]
6 [ ][ ][ ][ ][ ][ ][ ][ ] Black's starting side
5 [ ][ ][ ][ ][ ][ ][ ][ ]
4 [ ][ ][ ][ ][ ][ ][ ][ ]
3 [ ][ ][ ][ ][ ][ ][ ][ ]
2 [ ][ ][ ][ ][*... |
5acc2d5fb97ddbaac0ff180869e5a252244cf702 | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-14/binarysearch.py | 1,002 | 4.125 | 4 | def find(arr,a,b,x):
while(a<=b):#while left index is less than right index
mid=int(a+ (b-a)/2)#finding middle index for the number
if(arr[mid] < x):#if number is less than middle element, then look in the first half of sorted array
a=mid+1
elif(arr[mid] > x):#if number is greate... |
635a89221b0dd475f9daf41b214c2050b281cdec | Csatapathy/Employee-Scheduler | /assign.py | 4,415 | 4.03125 | 4 | import pandas as pd
import collections
import csv
class people:
def __init__(self,personID,skillID,name):
"""
Defining the class for ppl that includes the 3 parameters
@params:
personID : the ID associated with the person
skillID : the array of skills that th... |
b8c25e1e26cfaceefa54cf0e62af13f22e2cfcaf | nancyya/Cortica | /Q2/main.py | 5,571 | 3.734375 | 4 | """ Rush Hour - home assignment"""
'''
Created on Mar 22, 2016
@author: nancy yacovzada
'''
"""
############################ IMPORTS ############################
"""
from time import sleep
import numpy as np
from datetime import datetime as time
"""
################### GLOBAL VARIABLES ##########################... |
35f8a3c3727abc1cd3342ee717ac3f45debabf2d | rohitjoshi6/CP-Practice | /Codeforces-practice/Word-capitalization.py | 106 | 3.8125 | 4 | str = input()
if(len(str)>0 and str[0].islower()):
print(str[0].upper()+str[1:])
else:
print(str) |
1bb13378b1571efd8712f69256c5226eac1ae36f | GreenhillTeacher/Python2021 | /multip_input.py | 1,104 | 4.53125 | 5 | #Maria Suarez
#6/4/2021
# We are going to print multiplacation tables
# Using print statements and a variable
# input ---> variable is container that will hold data and an address is assigned to it
# variables need to have valid name
base = 2
numberBase = "multiplication"
base3= 3.5
#print(base + base3)
print(1 * base... |
de315e153698c8c0726e5ae026c303a5350651a1 | zhuanganmin/python-study | /Http/urllib1.py | 1,021 | 3.671875 | 4 | #! /usr/bin/python
# encoding=utf-8
# -*- coding: UTF-8 -*-
import urllib.request
import json
#import urllib2 在python3中没有urllib2用urllib.request代替
url="https://httpbin.org"
#get请求
def get(url):
#发送请求
response=urllib.request.urlopen(url,None,timeout=3)
data=response.read().decode()
jsondata=json.loads(... |
d25b4ee8fe7db0f0402412807f10b6989c2e2994 | alexisechano/Artificial-Intelligence-1 | /searches/GraphLabs/depth_extra.py | 2,228 | 3.796875 | 4 | # Alexis Echano
from collections import deque
def swap(state, i, j): #swaps two characters in a string
str = state[:i] + state[j] + state[i+1:j] + state[i] + state[j+1:]
return str
def generate_children(state):
# creates new list to return later
children = []
# finds index of the blank
... |
29f119d059163e957546e87c7d34f5dbbea01983 | ZQ774747876/AID1904 | /untitled/day01/linklist.py | 1,326 | 4.28125 | 4 | """
linklist链表程序实现
重点代码
思路分析:
1.创建节点类,生成节点对象,包含数据和下一个节点的引用
2.链表类,可以生成链表对象,可以对脸表进行数据操作
"""
#节点类
class Node():
def __init__(self,data,next):
self.data=data
self.next=next
class Linklist():
"""
建立链表模型
进行链表操作
"""
def __init__(self):
#初始化一个链表,生成一个头结点,表示链表开始节点
self.head=Node(None)... |
1e40509a7a0c2b270289dffda9c2c5e330fff69f | erikvader/dotfiles | /python_utils/.pythonlibs/tabulate.py | 2,154 | 3.8125 | 4 | #!/bin/python
from itertools import zip_longest
import re
LEFT = 0
RIGHT = 1
IGNORE = 2
def _transpose(fields):
return [list(x) for x in zip_longest(*fields, fillvalue=None)]
def _repeat(x):
it = iter(x)
last = None
while True:
try:
last = next(it)
except StopIteration:
pas... |
c9c5622a7cfbcd71286ebf9f26302fd79a60522c | pinkumbrella14/ThinkfulBootcamp | /Unit1_Lesson5_dictionaries.py | 3,107 | 4.875 | 5 | #dictionaries have different performance implications than working
#with lists. This has to do with calling data by key vs calling
#data by index......
print("A dictionary in Python is a key: value pair.")
print('''
This is an example of setting up a dictionary.
stock = {
apples: 5,
oranges: 2,
pears... |
cbdc85cab09a2bbc4ca48de62eec8431f153e1eb | brasqo/pythoncrashcourse | /41.py | 429 | 3.828125 | 4 | #4-1
pizzas = ['cheese', 'spinach', 'pepperoni']
dots = "..."
for pizza in pizzas:
print("I love " + pizza + " on my pizza.")
print("I really love me some muh-fuckin' pizza!")
print(dots)
#4-2
animals = ['cat', 'dog', 'bird']
for animal in animals:
print(animal)
print(dots)
for animal in animals:
print("A "... |
fe3a3e0d8c18ce36f2aa7220569a6bd15e8edb23 | arisend/epam_python_autumn_2020 | /lecture_04_test/hw/task_2_mock_input.py | 847 | 3.875 | 4 | """
Write a function that accepts an URL as input
and count how many letters `i` are present in the HTML by this URL.
Write a test that check that your function works.
Test should use Mock instead of real network interactions.
You can use urlopen* or any other network libraries.
In case of any network error raise Val... |
d0b6da8636642404981e736f1dbda5f1ba61974f | obs145628/py-softmax-regression | /softmaxreg.py | 3,082 | 3.53125 | 4 | '''
Softmax regression implementation
More informations:
- http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/
- https://medium.com/@awjuliani/simple-softmax-in-python-tutorial-d6b4c4ed5c16
'''
import numpy as np
import dataset_mnist
'''
Compute matrix version of softmax
compute the sofmax functon for... |
8364d5713f956006da4ffa81702120c1d9a7ac71 | heeseoj/homecoming1 | /3주차_과제.py | 599 | 3.765625 | 4 | #1330
A,B=input().split()
A=int(A)
B=int(B)
if A > B:
print(">")
elif A < B:
print("<")
else:
print("==")
#9498
score = int(input())
if 90<=score<=100:
print("A")
elif 80<=score<90:
print("B")
elif 70<=score<80:
print("C")
elif 60<=score<70:
print("D")
else:
print("F")
#2753
year = int... |
7745d4950fa371cfc7e0920c623119d8e365fa72 | luxwarp/pygtk-playground | /01-hello-world/hello-world.py | 1,257 | 3.890625 | 4 | #!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0") # require gtk version 3.0
from gi.repository import Gtk
class MainWindow(Gtk.Window):
'''
The MainWindow class that inherit Gtk.Window
'''
def __init__(self):
# initialize the window and set a title
Gtk.Window.__init_... |
a8d9ed160164caede2030a735cbb905936fdc3ad | Vistril/pyproj | /06-counter/counter.py | 446 | 3.984375 | 4 | #Seth Camomile
#Period 7
def count(start, end, step):
rep = ''
for i in range(start, end + (-1 if step < 0 else 1), step):
rep += str(i) + ' ' #you still have to add a space at the end just because of the tests
return rep
def main():
start = int(input("What is the starting number? "))
en... |
7e1fda60da8e590d08681d9302b83e5ec84ccdeb | whiplashzhao/pyrhon | /testing_groupby_1.py | 370 | 3.53125 | 4 | import pandas as pd
import numpy as np
df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'], 'key2': ['one', 'two', 'one', 'two', 'one'], 'data1': np.random.randn(5), 'data2': np.random.randn(5)})
print(df)
grouped = df['data1'].groupby(df['key1'])
print(grouped.mean())
means = df['data1'].groupby([df['key2'], df['ke... |
b7428f082a28a09ab7487f42b91f3cfd4a66788a | AnakinCNX/PythonChallenges | /challenge_24.py | 422 | 3.59375 | 4 | # There are no comments, so I don't know what you are trying to do.
def drawline(p, x):
for i in range(0, p):
print(" ", end=" "),
for i in range(0, x):
print(".", end=" "),
print()
return
def drawpicture():
drawline(1, 3)
drawline(1, 5)
drawline(1, 6)
drawline(1, 3)
... |
08be68b0a4ddd0e99b867bf5bef62da84e32872a | GopichandJangili/Python | /general_python.py | 1,018 | 3.515625 | 4 | '''
1. Currently the most widely used multi-purpose, high-level programming language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
3. Python programs generally are smaller than other programming languages like Java.
4. Programmers have to type relatively less and indentation requirement... |
62c2ff9db360ead0904ad5b43773d316315772cb | kaushik2000/python_programs | /ex_09/counts.py | 1,064 | 4.34375 | 4 | # Counting the no. of words in a line and the most occuring word
while True:
if input('Word frequency counter:\n(Enter "Exit" to quit) or (Press Enter to continue): ').lower() == 'exit' :
print("Exiting....")
break
counts = dict()
line = input("Enter a line: ")
words = line.split()
... |
3fd30f6343754e3b36675058c1222b6a5a2c1ffe | marturoch/Fundamentos-Informatica | /Pandas/Practica 8 - pandas/3.py | 366 | 4.25 | 4 | #Ejercicio 3
#Realizá un programa que agregue datos a un DataFrame vacío.
import pandas as pd
#vamos a agregar esto:
# {1: [1, 4, 3, 4, 5], 2: [4, 5, 6, 7, 8], 3: [7, 8, 9, 0, 1]}
df = pd.DataFrame()
df[1] = [1, 4, 3, 4, 5]
df[2] = [4, 5, 6, 7, 8]
df[3] = [7, 8, 9, 0, 1]
print(df)
#Devuelve:
# 1 2 3
#0 1 4 7
#1 ... |
e9677922dc02e67f65ac7008c9b96bde62fbe8a6 | felipeAraujo/cryptopals-solutions | /Python/Set 01/challenge03.py | 1,212 | 3.5 | 4 | #-*- coding: utf-8 -*-
from Crypto.Util.strxor import strxor_c
import re
def cg03_single_byte_xor_cipher(value):
result = get_more_scored_text(value)
return result
def get_more_scored_text(value):
maximum_score = 0
text_with_maximum_score = '';
text_decoded = value.decode('hex')
for code in... |
b5f3f0fbf437baa51baf9408c8dd18666cd049f5 | lp2016/New_Algorithm | /newcode_fibonacci.py | 459 | 3.859375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
if n==1 or n ==2 :
return 1
return self.Fibonacci(n-1)+self.Fibonacci(n-2)
def Fibonacci2(self,n):
if n==0:
return 0
if n==1 or n ==2 :
return 1
f=[0]
f.append(1)
... |
338f7ed50a0c744093ef49715ba611d36146359f | BillRozy/algorithms | /sort_by_merge.py | 2,608 | 3.609375 | 4 | import numpy as np
from collections import deque
acc = 0
def inversions(it, array):
result, count = merge_count_inversion(array)
return count
def merge(left, right):
result = []
i1 = 0
i2 = 0
count = 0
left_len = len(left)
while i1 < left_len and i2 < len(right):
if left[i1] > ... |
4ebaef825cd6e6d13a7d6b7939e667c5ea01474c | hustlrr/leetcode | /accepted/Word Search II.py | 2,432 | 3.890625 | 4 | # coding=utf-8
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.childs = {}
self.isword = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a... |
b21266c36d4afe466044b9c5c7271063d37ce125 | linkian209/rps-tourney | /classes/game.py | 3,902 | 3.890625 | 4 | """classes.game
This module contains the Game class.
"""
from classes.player import Player
class Game():
"""
This class represents a single game in a match. It takes an ID and two
players and then determines the winner of the game.
Attributes:
game_id (int): The ID of the game
player... |
9de5cbf4f8d3f323b051f7b81cd0630397657a67 | shrikantnarvekar/Algorithims-and-Data-Structures | /binary tree.py | 1,664 | 3.796875 | 4 | class Treenode:
def __init__(self,d):
self.data=d
self.lchild=None
self.rchild=None
class Mytree:
def __init__(self,t):
self.root=t
def preorder(self,t):
if t is not None:
print(t.data)
self.preorder(t.lchild)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.