blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
9fe2f6b65dd997183979558e6a035ad40b393da6 | kpanag-ynwa/da-test | /Package/insured.py | 1,356 | 3.78125 | 4 | # Design a data structure that
#- Contains aggregated metrics for all insured people
# - Total covered amount for all claims
# - Claims per year
# - Average age of insured
import pandas as pd
import numpy as np
import uuid
# The Insured class allows to store the attributes of an Insured in an insured objec... |
63f4bff3a3132ec2bddb3b8cce6bddb14033054a | cguldner/PythonReplace | /replace.py | 4,194 | 4.46875 | 4 | #!/usr/bin/env python3
import re
import sys
import argparse
if sys.version_info[0] != 3:
print("This script requires Python version > 3.0")
sys.exit(1)
# The delimiter that separates the entries in the regex file
DELIMITER = "~"
FILE_ENCODING = "utf-8"
def replace_from_file(content_filename, replace_filena... |
e141d27ddd608997abb5304149501a242715e7d8 | El-Mohr/Stegano | /src/LSBMain.py | 3,437 | 3.515625 | 4 | import os,sys
from PIL import Image
import numpy
import math
import subprocess
import datetime
def divideData(image,rawData,numberBits):
if(numberBits > 8):
print "Error: Number of bits should not be larger than 8"
div = int(math.ceil(len(rawData) / (len(image)*numberBits*3.0)))
blockedData = [[[b'0' for x in ran... |
bb2d826dd1bf2d9afb50d79d6cdedc96a4262309 | Rashika258/Myaudiobook | /audiobook.py | 1,397 | 3.765625 | 4 | #python text to speech conversion
import pyttsx3
#pdf lib
import PyPDF2
#select your book open in read binary mode
book = open('CN.pdf', 'rb')
#create pdfReader object
pdfReader = PyPDF2.PdfFileReader(book)
#count the total pages
total_pages = pdfReader.numPages
print("Total number of pages " +str(total_pages... |
520108eaa27e3864ab84624df04fe5810ce74be1 | mikhail-dvorkin/competitions | /hackerrank/weekofcode27/zero-move-nim.py | 350 | 3.59375 | 4 | #!/usr/bin/env python3
def solve(a):
xor = 0
for x in a:
xor ^= ((x - 1) ^ 1) + 1
return "W" if xor else "L"
def test():
assert solve([1, 2]) == "W"
assert solve([2, 2]) == "L"
def read_ints():
return list(map(int, input().split()))
if __name__ == '__main__':
test()
for _ in range(int(input())):
input(... |
2c6075e9584c6d21f3d4010ff4480aa08cd53899 | vivianlorenaortiz/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 441 | 4.03125 | 4 | #!/usr/bin/python3
def append_after(filename="", search_string="", new_string=""):
""" inserts a line of text to file after each line containing a string """
with open(filename, 'r+', encoding='utf-8') as f:
lines = []
for line in f:
lines.append(line)
if search_string ... |
868be30cf661c231a4ca0175f0eb1c1b8488a9d9 | vivianlorenaortiz/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 1,229 | 4.09375 | 4 | #!/usr/bin/python3
"""
creating “Interactive tests”. For this exercise, you will add Unittests.
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""
unittest for the function max integer function.
"""
def test_basic_case(self):
... |
949b939ef934fb793119900d36b377d7069c1916 | vivianlorenaortiz/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 345 | 4.3125 | 4 | #!/usr/bin/python3
"""
Funtion that prints a square with the character #.
"""
def print_square(size):
"""
Function print square.
"""
if type(size) is not int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
for i in range(size):
... |
4a0527d5b5fae707c8fb21b006fcdfdaad6776eb | miao906612/python_learn | /03python/dynamicTyping.py | 3,170 | 3.84375 | 4 | # -*- coding: utf-8 -*-
#########################################################################
# File Name: dynamicTyping.py
# Author: Shuo Miao
# mail: miao906612@163.com
# Created Time: 2015年11月24日 13:09:03
#########################################################################
#Dynamic Typing Model
#In python... |
6252a2da6e3c857b6966580fdb6e8f028040c55b | CharlieZheng/LearningPython | /NumPy/Arrays.py | 3,481 | 3.6875 | 4 | from numpy import *
import numpy as np
a1 = array([1, 1, 1])
a2 = array([2,2,2])
print(a1+a2)
print(a1*2)
e =np.random.random((3,2,2)) *20
print(e)
'修改数组操作'
arr = np.arange(10)*3
out=np.where(arr%2==1, -1, arr)
print(arr)
arr = arr[arr%2==1] # 取index满足条件的item组成新的数组
print(arr)
print(out)
'把1行10列的数组变成2行5列的数组'
out =... |
0ebb8cb51fc117d53c7c652eb366c2cbecb540d1 | knitendra5371/Python | /DSA/linked list/ReverseDLL.py | 1,088 | 3.734375 | 4 | class Node:
def __init__(self, d):
self.data = d
self.prev = None
self.next = None
class DLL:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
if self.head is not None:
se... |
b7817e01ba1aaae1e739c7fe808308b6329d5e4b | martinchristen/pyRT | /pyrt/renderer/renderer.py | 543 | 3.5625 | 4 | """
This is the abstract Renderer.
If you override if you implement your own.
"""
from abc import abstractmethod
from ..scene import Scene
class Renderer(object):
def __init__(self, name="UNKNOWN RENDERER"):
self.name = name
print("# Creating Renderer: " + self.name)
@abstractmethod
def... |
42b3c176483c9a5b7143fa51a88a0ffe2522b4ae | martinchristen/pyRT | /pyrt/geometry/triangle.py | 10,928 | 3.65625 | 4 | """
This is the geometric object triangle
(renderable object)
"""
from ..geometry import Shape, Vertex
from ..material import PhongMaterial, TextureMaterial, NormalMappedMaterial
from ..math import *
class Triangle(Shape):
"""Triangle class for raytracing"""
def __init__(self, a: Vertex, b: Vertex, c: Ver... |
a2362127d8c7d383370debab8bd048b9f24de73c | martinchristen/pyRT | /examples/00_drawpoints.py | 452 | 3.828125 | 4 | # Example 1: **Introduction to the image class**
# This example draws 5000 points and stores the image using PIL
from pyrt.renderer import RGBImage
from pyrt.math import Vec2, Vec3
import random
w = 320
h = 240
image = RGBImage(w, h)
for i in range(5000):
image.drawPoint(Vec2(random.randint(0, w - 1), random.ran... |
9035e9d46ddbd176336315b757870fb81c93fed8 | QuentinAndre11/D10-WoD-Probabilities | /rolls.py | 8,453 | 4 | 4 | import random
"""
The goal of this code is to get the probability of success when you roll your dices with the World of Darkness roleplaying system.
Brief reminder of the WoD system :
- Roll as many D10 (dices with 10 faces) as your character score in attribute + skill
(example : you want to give a sword... |
894956d2946bd4dafa6f7cfa985b0f34f590b04b | Ninedeadeyes/WoodsofYpres | /items.py | 3,501 | 4.0625 | 4 | class Weapon:
def __init__(self):
raise NotImplementedError("Do not create raw Weapon Objects.")
def __str__(self):
return "{}+{} STR ".format(self.name, self.damage)
class Rock(Weapon):
def __init__(self):
self.name="Rock"
self.description= "A fis... |
0a840da01b6d20c3ce6e266be57be3cf83757c4d | zackcode123/Basic_Python_Exercises | /Ex3_Raio.py | 202 | 4 | 4 | '''Faça um programa que peça o raio de um círculo,
calcule e mostre sua área.'''
pi = 3.14
n1 = int(input('Digite a area do circulo:'))
soma = pi*(n1*n1)
print('A area do circulo é:', soma, 'm²') |
809e7e3a4be9be995241c67909ae61fc5796d98d | drummerevans/Vector_Multiply | /cross_input.py | 564 | 4.125 | 4 | import numpy as np
items = []
max = 3
while len(items) < max:
item = input("Add an element to the list: ")
items.append(int(item))
print("The length of the list is now increased to {:d}." .format(len(items)))
print(items)
things = []
values = 3
for i in range(0, values):
thing = input("Add an eleme... |
630fcaf6cdae8276f74bea51e69da73b7f27138a | Catheryna1/Final | /BankAccount.oy.py | 13,707 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 04:50:35 2021
@author: Catheryna
"""
import random
import csv
import matplotlib.pyplot as plt
class Bank():
def __init__(self):
pass
class Accounts(Bank):
def __init__(self, first_name, last_name, account_ID = "", active = 1, balance = ... |
c62a24d22dc6ed3846ca0d00d802eab58391455f | leosiqueira/uwhpsc_leo | /homework3/newton.py | 1,947 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 26 10:08:35 2014
@author: leosiqueira
"""
def solve(fvals, x0, debug = False):
""" Estimate the zero of f(x) using Newton's method.
*Input*
fvals: tuple containing the function to find a root of
and its derivative (f, f').
x0: the ini... |
148b89137dcc89452f5cc9a23f58f3228875e529 | sayannandi/interviewbit | /arrays/max_distance.py | 648 | 3.5 | 4 | class Solution:
# @param A : tuple of integers
# @return an integer
def maximumGap(self, A):
n = len(A)
if n == 1:
return -1
for i, num in enumerate(A):
A[i] = (num, i)
A.sort()
max_so_far = -1
max_arr = [-1 for i in range(n)]
f... |
63e60ee629985c2d2751c668fc2265eea88985b2 | KevinLaam/-EDD-Tarea1_201403888 | /Tarea1.py | 2,908 | 4.03125 | 4 |
class node_list:
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class linked_list:
def __init__ (self):
self.head= None
def insertar(self,data):
if not self.head:
self.head=node_list(data=data)
return
x=self.head
while x.next :
x=x.next
x.next=node_list(data=dat... |
2ab414ed542eb8ce8acf15474cd3c5d06abbf144 | macks2008/theobot | /theobot/timey.py | 5,854 | 4.15625 | 4 | #! /usr/bin/env python
import re
import time
# CC-BY-SA Theopolisme
def ordinal(value):
"""
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1,13):
... ordinal(i)
...
u'1st'
u'2nd'
u'3rd'
u'4th'
u'5th'... |
8e4d6287bc73c492a896d3d5ec390cfea9866231 | p-brcn/pig | /dice.py | 417 | 3.859375 | 4 | """The die of the game :^)."""
import random
class Dice():
"""Create a six-sided dice."""
def __init__(self):
"""Initiate the dice."""
self._sides = 6
random.seed()
def roll(self):
"""Roll the dice and return the number."""
return random.randint(1, self._sides)
... |
95d25e15de2e4a225dea05f91c991463c53d8db1 | p-brcn/pig | /game_test.py | 6,073 | 4.09375 | 4 | """Unit test for the game logic."""
from unittest.mock import patch
from unittest import mock
import unittest
import game
import player
class TestGameClass(unittest.TestCase):
"""Test game class."""
def test_init_default_object(self):
"""Test initiating the game."""
the_game = game.Game()
... |
64613835c929b1ac62c8bdce72e6cb0ddc439189 | seun-beta/Unit-Testing | /fish/test_fish.py | 1,070 | 3.671875 | 4 | import unittest
import fish
class TestFish(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('setUpClass')
@classmethod
def tearDownClass(cls):
print('tearDownClass')
def setUp(self):
print('setUp')
self.fish_1 = fish.Fish('Jake')
self.fish_2 = ... |
82bdcc6068afdf6b3cf8d25d011477427efdd6a5 | Endrju00/History-of-Olympics | /family.py | 1,123 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
if __name__ == '__main__':
athlete_events = pd.read_csv('athlete_events.csv')
participants = athlete_events.drop_duplicates('ID')['Name'] # to count gender the objects have to be unique
# Prepare data
d = {'Firstname': [], 'Surname':[]}
for pers... |
8c24401b4f528b6443f8463bbd53b32661028cd0 | HaydenHartley/Sandbox | /oddName.py | 177 | 3.84375 | 4 | name_input = input("enter your name: ")
while len(name_input) < 1:
name_input = input("enter your name: ")
name_length = len(name_input)
print (name_input[1:name_length:2])
|
e4c866e60c92d3713121b35b0492a06a07a72e4b | Athenian-ComputerScience-Fall2020/mad-libs-yesak1 | /my_code.py | 596 | 3.890625 | 4 | # Collaborators (including web sites where you got help: (enter none if you didn't need help)
# none
personname= input("enter a person's name")
verb=input('enter a verb')
adverb=input('enter an adverb')
food=input('enter a food')
personname2=input("enter a person's name")
verb2=input('enter a verb')
adverb2=input('ent... |
bf97eaf66c4402ca38a0a936c43fceaa0ba26351 | alexolmedo/ComputacionDistribuida | /2018.01.04.cuentas.py | 1,516 | 3.5 | 4 | class Cuenta:
tipo = ""
numero = ""
saldo = 0.0
def __init__(self, argTipo, argNumero, argSaldo):
self.tipo=argTipo
self.numero=argNumero
self.saldo=argSaldo
def debito (self, monto):
self.saldo -= monto
def credito (self, monto):
self.saldo += monto
... |
b68e9ef0f7ac561544d0c87c516c20a8a6261dab | saikumarballu/PythonPrograms | /palindrom.py | 363 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 14:59:11 2019
@author: saib
org=a.lower().split(",")
print(org)
b=a.lower().split(",")
print(b)
c=''
for s in b:
c=c+s
print(c[::-1])
"""
a="A man, a plan, a canal; Panama"
b=list(a.lower())
alphas = list(filter(lambda x:x.isalpha(),b))
print(alphas)
print("T... |
1868740c233aab72a24aedb0b3b2fb3014f14118 | saikumarballu/PythonPrograms | /RegularExp.py | 2,058 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 10:14:04 2019
@author: saib
^ - Begining of String or expression
$ - Ending of String or an Expression
+ - One or more occurance of previous character
* -
import re
pat1 = re.compile('^Hello')
mystr = "Hi Hello World"
if pat1.search(mystr):
print("Matched")
... |
aa1d0cc8b6e7b6f0ecb3ca5921ae75026901a9ea | Paul-Cl-ark/cli_games | /rock-paper-scissors.py | 2,587 | 3.96875 | 4 | from random import choice
from time import sleep
moves = ('rock', 'paper', 'scissors')
def print_winner(winner):
print('\n')
if winner == 'draw':
print('DRAW...')
elif winner == 'computer':
print('YOU LOSE THIS ROUND!')
else:
print('YOU WIN THIS ROUND!')
print('\n---------... |
44a4dda12809ebd8ba6e3c6c52c96e130a0fa7e1 | PrateekMinhas/Python | /assignment14.py | 1,555 | 4.4375 | 4 | Q.1- Write a python program to print the cube of each value of a list using list comprehension.
lst=[1,2,3,4,5]
lstc=[i**3 for i in lst]
print(lstc)
#Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension.
lst_pr= [ i for i in range(2,int(input("Enter the end input of th... |
cc1aa3c2ec38ffc869b942af0491d3c44baf9ba1 | PrateekMinhas/Python | /assignment3.py | 2,048 | 4.25 | 4 |
#Q.1- Create a list with user defined inputs.
ls=[]
x=int(input("enter the number of elements"))
for i in range (x):
m=input()
ls.append(m)
print (ls)
#Q.2- Add the following list to above created list:
#[‘google’,’apple’,’facebook’,’microsoft’,’tesla’]
ls1=['google','apple','facebook','micr... |
46e9979cd8a2425b46f7f4bf6917516fd64ca081 | dasherinuk/homework | /homework_left.py | 284 | 4 | 4 | array=[]
input_amount=int(input("Enter the amount of elements"))
for i in range (0,input_amount):
element_input=int(input("Enter your element"))
array.append(element_input)
print(array)
for i in range(len(array)-1):
array[i] = array[i+1]
array[-1]=0
print(array)
|
b07f52dcbe8954d40666807cabcf0218744d7524 | dasherinuk/homework | /homework_31.10.py | 309 | 3.9375 | 4 | array=[]
amount=int(input("Enter the amount of elements"))
for i in range (0,amount):
element_input=int(input("Enter your element"))
array.append(element_input)
print(array)
for i in range(0,amount):
if array[i] > 0:
array[i]=1
elif array[i] < 0:
array[i]=-1
print(array)
|
ec9cf19559140c672c666ad15ad01ac90169a805 | dasherinuk/homework | /change_1_2_array.py | 577 | 3.53125 | 4 | input_user=int(input())
main_array=[]
for i in range(0,input_user):
array = [int(r) for r in input().split()]
main_array.append(array)
len_array=input_user
# 1 2 3
# 4 5 6
# 7 8 9
sum_first_array=sum(main_array[0])
##for index in range(0,len_array):
## sum_first_array+=main_array[index][0]
sum_last_... |
dded39863ce76844ffa7f1e8ae79fa54a9619487 | 0xch25/Data-Structures | /2.Arrays/Problems/Height Checker.py | 769 | 4.09375 | 4 | '''Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
Current array : [1,1,4,2,1,3]
Target array : [1,... |
8ecd98ebb901cb5a26893a09b4057c6362e43f6f | 0xch25/Data-Structures | /2.Arrays/Problems/Number of Good Pairs.py | 610 | 3.6875 | 4 | '''
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed
'''
class Solution:
def numIdenticalPairs(self,nums):
... |
cef5dd3e9ca6fe8f9ce33b6e4f8aca9e35f368f4 | 0xch25/Data-Structures | /2.Arrays/Problems/Running sum of 1D Array.py | 497 | 4.21875 | 4 | '''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]'''
def runningSum(nums):
sum =0
for i in range(len(... |
7816262c0cda16be8c7d255780fba2c1203905a8 | 0xch25/Data-Structures | /3.Stacks/Palindrome using Stacks.py | 544 | 4.15625 | 4 | '''Program to check weather the given string is palindrome or not'''
class Stack:
def __init__(self):
self.items = []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
s = Stack()
str= inp... |
8cf6f4add4206848befc6559c83f207033d67529 | 0xch25/Data-Structures | /2.Arrays/Problems/Check If N and Its Double Exist.py | 590 | 4.09375 | 4 | '''
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is t... |
e3655a11ecdd6541eabc9ba2e942c8184360e79d | 0xch25/Data-Structures | /7.Graphs/Problems/Range Sum of BST.py | 668 | 3.9375 | 4 | '''
https://leetcode.com/problems/range-sum-of-bst/
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
'''
def... |
532c4d70a4f5037a4a520e4ffe3a1edd92cb2ff0 | 0xch25/Data-Structures | /2.Arrays/Squares of a Sorted Array.py | 490 | 4.0625 | 4 | '''Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
One Line Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
... |
d8893f260d7836c4dae56181bee4c081b2097bd1 | 0xch25/Data-Structures | /1.Linked List/Detect Loop(2ptr).py | 1,005 | 4.0625 | 4 | '''
Given a linked list, determine if it has a cycle in it.
'''
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
newNode = Node(data)
if self.head:
... |
85d22aeebd8243443c2210b065efc2636c8bde8c | 0xch25/Data-Structures | /1.Linked List/Intersection of Two Linked Lists.py | 982 | 3.84375 | 4 | '''
Write a Function to find the node at which the intersection of two singly linked lists begins
Approach1:using Dictionaries
def getIntersectionNode(headA,headB):
dict = {}
while headA:
dict[headA] = 1
headA = headA.next
while headB:
if headB in dict:
return headB
... |
e70a83469f49d7f0dcb0ce94f8621e1b8b032836 | 0xch25/Data-Structures | /10.Strings/Problems/Shuffle String.py | 776 | 4.1875 | 4 | '''
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, ... |
8488bf556555ef239437cef6f2449cc0414074b2 | 0xch25/Data-Structures | /1.Linked List/problems/Convert Binary Number in a Linked List to Integer.py | 470 | 3.875 | 4 | '''
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 =... |
79ca4e928dcab2736833269027a8209c2965d47d | 0xch25/Data-Structures | /3.Stacks/Postfix Evaluation.py | 760 | 3.84375 | 4 | def postfix_evaluation(str):
s=str.split()
n=len(s)
stack =[]
for i in range(n):
if s[i].isdigit():
stack.append(int(s[i]))
elif s[i]=="+":
a=stack.pop()
b=stack.pop()
stack.append(int(a)+int(b))
elif s[i]=="*":
a=stack.... |
933bb92720f57065456529f36a6ceb0adf3cb8da | josemigueldev/tkinter-crud | /main.py | 5,611 | 3.734375 | 4 | from tkinter import *
from tkinter import ttk
import sqlite3
class Product:
db_name = "database.db"
def __init__(self, window):
self.window = window
self.window.title("Aplicacion de productos")
# creating a frame container
frame = LabelFrame(self.window, text="Registrar un nu... |
5075c9230e0ed97262d585dc7f39079e6fe265f3 | jjefferson34/projects | /projects/dataanalysis.py | 380 | 3.71875 | 4 | import json
def findAverageAge(data):
sum = 0
for entry in data:
sum += int(entry["age"])
return sum / len(data)
def main():
file = open("allanswers.json", "r")
data = json.load(file)
print("Analyzing data...")
averageAge = findAverageAge(data)
print("Average age: ... |
fb6785fbbc7e3514f8eebc0c727c270cb3cabdba | agencer/PythonCourse_Summer2020 | /hw_gencer.py | 6,179 | 3.578125 | 4 | import random
from datetime import datetime
# Let's start with the classes for different non liquid investments.
# The question asks for inheritence. So let's create one:
class NonLiquidItems():
def __init__(self, value, name):
self.name = name
self.value = value
class Stock(NonLiquidItems):
def __init__(s... |
4f45c92ee32651269b186c7ac51ce7897ed1ab1c | memuller/bunnyscript | /Python/14-lists-index.py | 473 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
Faça um programa exatamente como o anterior,
mas que possua um for no qual a variável de controle represente o índice
de cada elemento, ao invés de o elemento em si.
for i blabla:
#aqui i deve ser o índice de cada elemento
'''
# len(lista)
# retorna a quantidade de elementos de uma li... |
e30453364c48bdf2673d717cbd4ec9e06eca6581 | memuller/bunnyscript | /Python/17-list-duplicates.py | 892 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
Escreva um programa que leia palavras fornecidas pelo usuário.
Caso a palavra não tenha sido fornecida anteriormente, a adicionamos em uma lista.
Paramos de ler palavras quando o usuário não inserir nenhuma.
Ao final do programa, imprimimos a lista das palavras não-repetidas inseridas.
'''... |
a2fb281d1a4a402573494612e7d752c5440e3f17 | jamesmili/BattleShip | /Game.py | 1,601 | 4 | 4 | from State import *
def main():
print "Rules for battleship: \n"
print "1) Each Player gets two boards, and five ships"
print "2) Objective is to sink all of your opponents ships"
print "3) Firing shots by typing coordinates 'A', 3"
print "4) You can only have one length 2 ship, two length 3 ships... |
0f0f6fcd447b17773cd930fb8b47b1e06a8f2a8a | ethyl2/Hash-Tables | /src/tk/sorting.py | 417 | 4.03125 | 4 | d = {
"foo": 12,
"bar": 17,
"qux": 2
}
# Sorting by Key:
items = list(d.items())
print(items)
items.sort()
print(items)
for i in items:
print(f'{i[0]}: {i[1]}')
print('\n')
# Sort by Value:
items = list(d.items())
print(items)
"""
def get_key(e):
return e[1]
items.sort(key=get_key)
"""
items.so... |
d1667225c113c51c6bd4bdca42a55d7c129bb348 | ethyl2/Hash-Tables | /src/tk/indexing.py | 588 | 3.640625 | 4 | records = [
("Alice", "Engineering"),
("Bob", "Sales"),
("Carol", "Sales"),
("Dave", "Engineering"),
("Erin", "Engineering"),
("Frank", "Engineering"),
("Grace", "Marketing")
]
def build_index(rec):
idx = {}
for r in rec:
name, dept = r
if dept not in idx:
... |
f37fb441250ae026c201842c0200a4e9b2734fe0 | josecgomezvazquez/SudokuSolver | /sudokuGenerator.py | 3,151 | 4.46875 | 4 |
# Used for randomizing
from random import sample
# Sudoku Generator
"""
Begin the creation of the board
"""
base = 3 # Size of the base of a 3x3 square
side = base * base # Size of the side of a sudoku board
# Pattern for a baseline solution
# r = rows
# c = columns
def pattern(r, c):
... |
b8426fb3918281d063f0d7077e1d8a3caf5cf382 | SabiulSabit/Polynomial-Equation | /B.py | 1,003 | 3.515625 | 4 | import numpy as np
print("Enter 6 ploy5 coefficients:")
number = 6
#for i in range(6):
#n = input("")
#x.append(int(n))
while (True):
arr = list(map(float, input("").split()))
if(len(arr) == 6):
break
else:
print("Wrong input. Please enter 6 ploy5 coefficients: ")
print("Enter solution:")
... |
61b3e2c81debcc3076f42b7df02e3b107b53270f | pablo-grande/Aula | /KDC-Simulator/node.py | 1,611 | 3.515625 | 4 | from aes import *
class Node(object):
""" A node is just an identifier and a hash key"""
def __init__(self, node_id):
self.__id = node_id
self.__key = create_key() # shared with KDC
self.__key_dict = {}
self.__messages = {}
# below some general functions to interact with... |
355a3568f845a02c8c3af90bf627ea2a207d7b84 | ndri/challenges | /old/33.py | 1,139 | 4.125 | 4 | #!/usr/bin/env python
# 33 - Area Calculator
import sys
try:
shape, args = sys.argv[1], ' '.join(sys.argv[2:])
except:
sys.exit('Error. Use -h for help.')
if shape == '-h':
print 'Challenge 33 - Area Calculator'
print '-h\t\t\tDisplay this help'
print '-r width height\t\tArea for a rectangle'
... |
05962d07fdeabc7d4c774d5ce609206b55813df4 | ndri/challenges | /17.py | 152 | 3.9375 | 4 | #!/usr/bin/env python
# 17 - Count the words in a string
string = 'the quick brown fox jumps over the lazy dog'
words = len(string.split())
print words
|
cb032ab3bb68230342d365afbcd3616121c65152 | hjj99m/sturpy_gamedev | /pygame_temp02.py | 4,973 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
My First Game
"""
import pygame
''' 定義物件 define class --------------------------------------------------'''
class Missile:
def __init__(self, pos):
self.pos = [pos[0], pos[1]]
def get_pos(self):
return self.pos
def set_pos(self, pos):
... |
6bfef5338d6574be09828fe4e6a250b5c831ab9e | fgrelard/ProcessMRI | /src/compleximage.py | 2,730 | 3.734375 | 4 | import numpy as np
import math
import cmath
def separate_real_imaginary(img_data):
"""
Separates the real and imaginary parts
in a complex image.
Real and imaginary parts are assumed to be
mixed in the last dimension of size n
With real contained in the first n//2 slices
and imaginary in th... |
81be275d54c77ac60482e8fd78febe61182691f7 | patrickfriedman/Sudoku-Solver | /Sudoku.py | 3,023 | 3.71875 | 4 | from random import randrange
def diff(difficulty): #players difficulty
if (difficulty == 0):
shown = 55
elif (difficulty == 1):
shown = 45
elif (difficulty == 2):
shown = 35
return shown
def newBoard(): ... |
c3d8124982c4d803f1b54d193966f3f906e59bdf | SDMR-LAB/interpeter | /lang105.py | 407 | 3.640625 | 4 | def block(code):
opened = []
blocks = {}
for i in range(len(code)):
if code[i] == '[':
opened.append(i)
elif code[i] == ']':
blocks[i] = opened[-1]
blocks[opened.pop()] = i
return blocks
def parse(code):
new = ""
for c in code:
if c in... |
5d67e0b356bf312478a940ad7d9bf965b7b751ac | bijon1161/Python-Course-from-coursera.org | /ProblemSet4.py | 5,039 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 1 20:04:57 2021
@author: Admin
"""
# - ProblemSet4.py *- coding: utf-8 -*-
"""
Problem 4_1:
Write a function that will sort an alphabetic list (or list of words) into
alphabetical order. Make it sort independently of whether the letters are
capital or lowercase. First... |
e416d465ae64dad5353d431d099ff1fab5e801cf | CodingPirates/taarnby-python | /uge1/5_lister.py | 2,203 | 4.125 | 4 | #coding=utf8
# Når vores programmer bliver lidt mere komplicerede får vi rigtig mange variable
# Det gør at de bliver mere og mere besværlige at læse
# Nogle gange så hænger flere af de variable sammen
# Så kan vi prøve at lave dem om til en enkelt variabel som gemmer på mere end én ting ad gangen
# Den mest simple he... |
691b544bfdd55701f8aa45bc3fb350f21c2a5a4d | SLrepository/dev | /partie1.py | 1,188 | 3.78125 | 4 | # -*- coding: utf-8 -*-
## 1\.Exercice 1 : Hello World
print("\nExercise Nr. #1")
print("---------------")
print("Hello World")
Macron = "hello world"
print(Macron)
## 2\.Exercice 2 : Calculs divers
print("\nExercise Nr. #2")
print("---------------")
print(3*3)
try:
12/0
except ZeroDivisionError:
print("N... |
0c96d7d80611737119321313920bd3d8005b4e70 | royabouhamad/Algorithms | /Sorting/QuickSort.py | 667 | 3.859375 | 4 | def partition(list, left, right, pivot):
while left <= right:
while list[left] < pivot:
left += 1
while list[right] > pivot:
right -= 1
if left <= right:
list[left], list[right] = list[right], list[left]
left += 1
right -= 1
ret... |
dd390f155046dceec4cbbcd0a5f9c8368a88851f | PraneshASP/COMPETITVE-PROGRAMMING | /LEETCODE/HARD/124. Binary Tree Maximum Path Sum.py | 643 | 3.671875 | 4 | # Definition for a binary tree node.
import sys
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
ans = -sys.maxsize - 1
def helper(self, root: TreeNode) -> int:
if not root:
retur... |
2b1bb143910ac13d63bf9fe1be87ca57f89cf98f | richardpon/mypractice | /leetcode/14_longest_common_prefix/longest_common_prefix.py | 421 | 3.59375 | 4 | class Solution:
def longestCommonPrefix(self, strs):
longest_prefix = ""
if len(strs) == 0:
return longest_prefix
for i in range(0, len(strs[0])):
cur_char = strs[0][i]
for s in strs[1:]:
if i >= len(s) or cur_char != s[i]:
... |
4ffc7902e78df665462fa618b65750e6b445c880 | richardpon/mypractice | /leetcode/122_best_time_to_buy_and_sell_stock_ii/best_time_to_buy_and_sell_stock_ii.py | 1,632 | 3.859375 | 4 | from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
#maybe buy on day n
#if next day cheaper, then reset and maybe buy that day
#if next day is higher, maybe sell
#if next day lower,... |
f99a6f7cba5470fee26eedbd0e6db4338bf40499 | richardpon/mypractice | /codewars/5kyu/draw_the_borders_1_simple_ascii_border/draw_borders.py | 4,437 | 3.828125 | 4 | from typing import Tuple, Set
class Solution:
def draw_borders(self, shape):
#convert each shape[] into squares and borders
# output = borders is set of tuples representing border
borders = self.get_borders(shape)
#donut detection
borders = self.remove_donut(borders)
... |
95a5bdc7784e1729fbb136e74aefd62c9da9a6e7 | microsoft/AdversarialGMM | /mliv/linear/utilities.py | 1,196 | 3.59375 | 4 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import numpy as np
from functools import reduce
def cross_product(*XS):
"""
Compute the cross product of features.
Parameters
----------
X1 : n x d1 matrix
First matrix of n samples of d1 features
(or an n-e... |
112e10fe234d7685da85c2b1ce37bd1f8f2d08e0 | PramodhMahadeshKM/OOPPythonMiniProject | /3_Implementation/telephone.py | 11,013 | 3.921875 | 4 | """This is the source file for the telephone project."""
import re
class Customer:
def __init__(self,idn=None,name=None,email=None,number=None):
"""Parent class constructor."""
self.idn=idn
self.name=name
self.email=email
self.number=number
def update_email(self,new_e... |
e27d12cf122b6bbb62491f06d9e0ac37dc001b41 | LaloGarcia91/CrackingTheCodingInterview | /Chapter_4/ListOfDepths.py | 2,584 | 3.6875 | 4 | from Chapter_4.Trees.BinaryNode import *
from Chapter_2.LinkedList import *
import math
class ListOfDepths:
def __init__(self):
self.allListsOfDepths = []
self.binaryTreeRoot = None
def add(self, root, node):
if node.value > root.value:
if root.rightNode is None:
... |
d1566aa76b394885eeb94a8bb1f730a958b5b834 | LaloGarcia91/CrackingTheCodingInterview | /Chapter_2/LoopDetection.py | 1,196 | 3.953125 | 4 | from Chapter_2.LinkedList import *
class LinkedListLoopDetect:
def FindBeginning(self, linkedList):
slow = linkedList.head
fast = linkedList.head
# find meeting point. This will be LOOP_SIZE - k steps into the linked list
while fast is not None and fast.nextNode is not None:
... |
2c69dfb001152a2017815ada26426d69925404e8 | LaloGarcia91/CrackingTheCodingInterview | /Chapter_1/OneAway.py | 1,301 | 3.734375 | 4 | class OneAway:
def __init__(self, str1, str2):
self.CheckIfWordsAre1CharAway(str1, str2)
def CheckIfWordsAre1CharAway(self, str1, str2):
check_1 = self.LoopThe2Words(str1, str2)
check_2 = self.LoopThe2Words(str2, str1)
if check_1 or check_2:
print("One Away was fou... |
42096d931802f6a0edcfa5702f2a91d0bbba2cd5 | LaloGarcia91/CrackingTheCodingInterview | /Chapter_1/CheckPermutation.py | 775 | 4.125 | 4 | class CheckPermutation:
def __init__(self, str1, str2):
self.checkIfIsPermutation(str1, str2)
def checkIfIsPermutation(self, str1, str2):
str1_len = len(str1)
str2_len = len(str2)
if str1_len == str2_len:
counterIfEqualLetters = 0
for str1_letter in str... |
2d4789ea57bf69e568774d4359be67ce3ebe8c13 | LaloGarcia91/CrackingTheCodingInterview | /Chapter_2/LinkedList.py | 8,468 | 4.03125 | 4 | import math
class Node:
data = None
nextNode = None
def __init__(self, data):
self.data = data
class LinkedList:
head = None
def append(self, data):
if self.head is None:
self.head = Node(data)
return
currentNode = self.head
while current... |
522f02bc0640964a1c2ed57d3499383a021506c2 | oaugusto256/computerscience-psu | /cs161-intro-programming-solving-problem/HW4/score.py | 814 | 4.03125 | 4 | import math
def score(distance, radius):
"""
Radius = 200
Examples:
score(0,200) - Return 10
score(4,200) - Return 10
score(19,200) - Return 10
score(20,200) - Return 9
score(45,200) - Return 8
score(49,200) - Return 8
score... |
cfaef8bea20c252652c22f58e5c0b569b46312e4 | miawich/repository_mia | /Notes/NotesB/05_sorting_miawich.py | 2,149 | 4.21875 | 4 | # sorting
import random
import time
# swapping values
a = 1
b = 2
temp = a
a = b
b = temp
print(a, b)
# pythonic way
a, b = b, a # works only in python
# selection sort
my_list = [random.randrange(1, 100) for x in range(100)]
my_list_2 = my_list[:]
my_list_3 = my_list[:]
print(my_list)
print()
for cur_pos in ra... |
175536d4e18ea3aae593a3f6f786a64582048a01 | JohnGoure/python-crash-course | /Chapter-3/places-to-visit.py | 295 | 3.953125 | 4 | places = ['monterey', 'paris', 'los angles', 'lake tahoe', 'new york city']
print(places)
print(sorted(places))
print(places)
print(sorted(places)
)
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse = True)
print(places) |
b9a5b00d8638d3134d0a3deada8b4da242ec52cc | JohnGoure/python-crash-course | /Chapter-5/ordinal-numbers.py | 352 | 4.0625 | 4 | ordinal_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for ordinal_number in ordinal_numbers:
if ordinal_number == 1:
print(str(ordinal_number) + "st")
elif ordinal_number == 2:
print(str(ordinal_number) + "nd")
elif ordinal_number == 3:
print(str(ordinal_number) + "rd")
else:
pr... |
13550a3bd2b683327b96a2676f5d006b69353b73 | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Smooth Sailing/isLucky.py | 614 | 4.21875 | 4 | """
Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
Given a ticket number n, determine if it's lucky or not.
Example
For n = 1230, the output should be
isLucky(n) = true;
For n = 239017,... |
c54226da11c55ca48ea8ea3d9231897a66bdb9bf | AndreiBratkovski/CodeFights-Solutions | /Arcade/The Core/Intro Gates/addTwoDigits.py | 268 | 4.0625 | 4 | """
You are given a two-digit integer n. Return the sum of its digits.
Example
For n = 29, the output should be
addTwoDigits(n) = 11.
"""
def addTwoDigits(n):
total = 0
n = [int(i) for i in str(n)]
for i in n:
total += i
return total |
144affbc9d46e349ee76697c0f3ef466faaa3b3f | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Island of Knowledge/isIPv4Address.py | 1,723 | 4.0625 | 4 | """
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
IPv4 addresses are repres... |
27f090cb703d12372205b7308efe17f5e0a73980 | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Smooth Sailing/commonCharacterCount.py | 718 | 4.34375 | 4 | """
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
"""
def commonCharacterCount(s1, s2):
global_count = 0
char_count1 = 0
... |
71bbd17180dddba7251a2e1822d0d6452acc87d3 | NunchakusLei/python-basic | /smart_lock.py | 246 | 3.96875 | 4 | password = input("Enter the passwrod to open the door > ")
correct_password = "123456"
if password == correct_password:
print("The password is correct. Openning the door.")
else:
print("The password is incorrect. No open the door.")
|
b7315bf9114c641c1b3493ffef65109da2dc9046 | Surenu1248/Python3 | /eighth.py | 434 | 4.15625 | 4 | # Repeat program 7 with Tuples (Take example from Tutorial)
tpl1 = (10,20,30,40,50,60,70,80,90,100,110)
tpl2 = (11,22,33,44,55,66,77,88,99)
# Printing all Elements.....
print("List Elements are: ", tpl1)
# Slicing Operations.....
print("Slicing Operation: ", tpl1[3:6])
# Repetition.....
print("Repetition of list f... |
f1e4f6da855d49216d836d7e79fe89ee69983346 | Surenu1248/Python3 | /first.py | 401 | 3.953125 | 4 | # Write a program for add, subtract, multiplication, division of two numbers.
def add(a,b):
return a + b
def sub(a,b):
return a - b
def mul(a,b):
return a * b
def div1(a,b):
return a / b
def div2(a,b):
return a // b
print(add(10, 5))
print(sub(10, 5))
print(mul(10, 5))
pri... |
54d2387d255062fe1e739f7defeb0cff1f9cf634 | Surenu1248/Python3 | /third.py | 233 | 4.375 | 4 | # Write a program to find given number is odd or Even
def even_or_odd(a):
if a % 2 == 0:
print(a, " is Even Number.....")
else:
print(a, " is Odd Number.....")
print(even_or_odd(10))
print(even_or_odd(5))
|
b70f897288430e69f488f4d79474f8f4678ddc16 | ChWeiking/PythonTutorial | /Python高级/day41(线程进程回顾)/demo/01_进程线程锁/同步.py | 356 | 3.515625 | 4 | from threading import Thread
import time
num = 0
def test1():
global num
for i in range(1000000):
num += 1
print("test1 num=%s"%num)
def test2():
global num
for i in range(1000000):
num += 1
print("test2 num=%s"%num)
p1 = Thread(target=test1)
p1.start()
#time.sleep(3)
p2... |
b451f256bb1918783542ba683f146f463c3b6276 | ChWeiking/PythonTutorial | /Python基础/day08(面向对象、类)/demo/练习/day_08.py | 3,684 | 3.75 | 4 | '''
面向对象技术简介
类(Class): 用来描述具有相同的属性和方法的对象的集合。
它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
类变量:类变量在整个实例化的对象中是公用的。
类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。
方法重写:如果从父类继承的方法不能满足子类的需求,
可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
实例变量:定义在方法中的变量,只作用于当前实例的类。
继承:即一个派生类(derived class)继承基类(base class)的字段和... |
5e1ffe216af069b7078d350af8f10421ad3e0f8b | ChWeiking/PythonTutorial | /Python高级/day36(链表、数据结构)/demo/01_引入.py | 473 | 3.75 | 4 | import time
start_time = time.time()
# 注意是三重循环
for a in range(0, 1001):
for b in range(0, 1001):
for c in range(0, 1001):
if a**2 + b**2 == c**2 and a+b+c == 1000:
print("a, b, c: %d, %d, %d" %, (a, b,c))
end_time = time.time()
print("elapsed: %f" % (end_time - start_time))
p... |
d6306fd2b306a4a534e7984a84b69c438a9b2248 | ChWeiking/PythonTutorial | /Python基础/day05(集合容器、for循环)/demo/01_list/04_列表基础操作.py | 2,101 | 4.0625 | 4 | list = [1,2,3,4,5]
# 按下标取值1
print(list[0])
# 按下标最后一个元素
print(list[-1])
search = list.index(5)
#查找对应值的下标
print(search)
list = [1,2,3,4,5,5,5]
#查找某个元素的出现次数
mynum = list.count(5)
print(mynum)
#列表长度
print(len(list))
#大小值
print(max(list))
print(min(list))
#末尾添加
list.append(8)
print(list)
#从下标插入
list.insert(0,9)
print... |
5689fb6197e042236fade0ca7724d6ce96025538 | ChWeiking/PythonTutorial | /Python高级/day33(tcp通信)/demo/01_tcp服务器端.py | 682 | 3.59375 | 4 | #1. 买个手机
#2. 插上手机卡
#3. 设计手机为正常接听状态(即能够响铃)
#4. 静静的等着别人拨打
from socket import *
# 1. socket创建一个套接字
tcpServer = socket(AF_INET,SOCK_STREAM)
tcpServer.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 2. bind绑定ip和port
tcpServer.bind(('',5678))
# 3. listen使套接字变为可以被动链接
tcpServer.listen(5)
# 4. accept等待客户端的链接
print('服务端监听中......')
#... |
e371b410dcd37608a68114fff2a56926b3efff88 | ChWeiking/PythonTutorial | /Python高级/day41(线程进程回顾)/demo/02_链表队列栈/02.单向循环链表.py | 2,925 | 3.953125 | 4 | class Node(object):
"""docstring for SinCycLinkedList"""
#初始化节点
def __init__(self,item):
self.item = item
self.next = None
class SinCycLinkedList(object):
"""docstring for SinCycLinkedList"""
def __init__(self):
self._head = None
# is_empty() 判断链表是否为空
def is_empty(self):
return self._head == None
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.