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 |
|---|---|---|---|---|---|---|
b4ffa96061bdc9b4208aad44f320b783a4cdd4f4 | banginji/algorithms_sot | /datastructures/LinkedList.py | 4,843 | 3.828125 | 4 | class DoublyLinkedListNode:
def __init__(self, data, next=None, prev=None):
self.data = data
self.prev = prev
self.next = next
class SingleLinkedListNode:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):... |
0b5f413593a7a31d747605f012096e3092e23c98 | banginji/algorithms_sot | /chapter4/check_subtree.py | 1,720 | 3.78125 | 4 | class BTNode():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def create_bt1():
node_minus_one = BTNode(-1)
node_zero = BTNode(0)
node_one = BTNode(1)
node_two = BTNode(2)
node_three = BTNode(3)
node_four = BTNode(4)
node_five = BTNo... |
688a5fbab6922aa2fc49e629adb98e5c3d97a0e8 | banginji/algorithms_sot | /datastructures/stack.py | 615 | 3.75 | 4 | class Stack:
def __init__(self):
self.stack_data = []
def push(self, data):
self.stack_data = [data] + self.stack_data
def pop(self):
popped_data = self.stack_data[0]
self.stack_data = self.stack_data[1:]
return popped_data
def peek(self):
return self.s... |
4cf77972aff2917e716a3f3311a4e6d89ea91f61 | itbc-bin/1920-owe1a-afvinkopdracht2-DavidvanEersel | /Weektaak_2.py | 285 | 3.5 | 4 | x = input("Wat is de sequentie? ")
print("Totaal",str((len(x)))+" Nucleotiden")
totaal = len(x)
totaal_G = x.count("G")
totaal_C = x.count("C")
totaal_GC = totaal_C+totaal_G
GC =(totaal_G+totaal_C)/totaal*100
print("Totaal GC basen is", totaal_GC)
print("Het GC% is "+str(GC)+"%")
|
7bc7cadf8187f1a96f98dc4e76dab01b94776362 | archeranimesh/fantastic-waffle | /SRC/December-Batch/02_class/02_list_ops.py | 377 | 3.609375 | 4 | from typing import List
a = [10, 20, 33, 44, 52]
sum = 0
for i in range(len(a)):
sum += a[i]
print(sum)
# in operator implementation.
def is_present(a: List[int], item: int) -> bool:
"""
in operator implementation
"""
for i in range(len(a)):
if a[i] == item:
return True
r... |
60aecb02488499138bbee29575ed6c2b3138617e | archeranimesh/fantastic-waffle | /SRC/easy/leetcode-direct/01_nextGreatestLetter.py | 358 | 3.5 | 4 | from typing import List
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
print(letters, ord(target))
print(ord("a"))
print(ord("z"))
if __name__ == "__main__":
letters = ["c", "f", "j"]
target = "k"
solution = Solution()
print(solution... |
f86ab5b6216b03350e80d221da4e09c6295c4291 | archeranimesh/fantastic-waffle | /SRC/December-Batch/02_class/03_bubble_sort.py | 614 | 3.984375 | 4 | from typing import List
a = [10, 20, 54, 44, 52]
def bubble_sort(a: List[int]):
"""
docstring
"""
# Outer loop
for i in range(len(a)):
# inner loop, carefull
for j in range(len(a) - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
# Oprimized v... |
b1189fb8bb27a5ea03cfb834c376c30eae5c152d | Dyn0402/QGP_Scripts | /poisson_vs_binomial.py | 523 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on May 14 10:47 AM 2020
Created in PyCharm
Created as QGP_Scripts/poisson_vs_binomial
@author: Dylan Neff, Dylan
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binom, poisson
def main():
n = 60
p = 0.5
x = np.aran... |
4c0929363bd0cc6bc0ce47d08445756949d2f4e0 | soph714/6.00.1xFall2017 | /FingerExercises/week5/student and grade combined example.py | 5,268 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 20:58:25 2018
@author: Ted
"""
import datetime
class Person(object):
def __init__(self, name):
"""create a person called name"""
self.name = name
self.birthday = None
self.lastName = name.split(' ')[-1]
d... |
447d237ea3c7da2132ac1382b16a78d002fa44f3 | soph714/6.00.1xFall2017 | /ProblemSets/ProblemSet4/pset4.1.py | 1,665 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 18:36:41 2017
@author: Ted
"""
def getWordScore(word, n):
"""
code by: tjs on 11/1/2017 for MITx edX 6.00.1x pset4.1
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the poi... |
063bb9b06914cd4b62c12cde40f9bb5c54c61b2f | soph714/6.00.1xFall2017 | /Midterm/midterm_4.py | 479 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 15 14:21:19 2017
@author: Ted
"""
def getSublists(L, n):
'''
code by theosopher 10/15/2017
6.00.1x MITx edX miterm problem 4
assume L is not empty
assume 0 < n <= len(L)
'''
sublists = []
for char i... |
02b18fc26f899ce4fc75b652d16cebc9a2c77451 | andrewjton/codingPractice | /completed/lruCache.py | 2,100 | 3.78125 | 4 | #https://leetcode.com/problems/lru-cache/description/
class LRUCache:
#use a dictionary to store the Nodes you're using
#use a linkedlist to order the Nodes from first accessed to last accessed.
#get: check your cache dict for key
#if it exists, remove & add it back to the LL. return the node'... |
078eaf2890dc0d87dedce8fe5e0e6a0dc7e03923 | andrewjton/codingPractice | /pythonLanguagePrep.py | 5,040 | 4.0625 | 4 | #Python Preparation
#BIT MANIPULATION -----------------------------------------------------------
# -integers have arbitrary precision (infinite range) in python 3 --> no overflow issues, unless your machine runs out of memory
# -sys.maxsize refers to the word size on a system but you can exceed that
# - -16 >> 2 = -4... |
78d0f11ae198c5115cee65f7646a1cc00472b497 | piotrbelda/PythonAlgorithms | /SpiralTraverse.py | 1,280 | 4.1875 | 4 | # Write a function that takes in an n x m two-dimensional array
# (that can be square-shaped when n==m) and returns a one-dimensional array of all the array's
# elements in spiral order; Spiral order starts at the top left corner of the two-dimensional array, goes
# to the right, and proceeds in a spiral pattern all th... |
209019237804db02fcb51e4001df53aaff1e45b0 | kleutzinger/dotfiles | /scripts/magic.py | 2,524 | 4.25 | 4 | #!/usr/bin/env python3
"""invoke magic spells from magic words inside a file
magic words are defined thusly: (must be all caps)
#__MAGICWORD__# echo 'followed by a shell command'
put something of that format inside a file to set up running that command
additionally, #__file__# will be substituted with the path of t... |
6369192c8d069bc4fd9f3b49e1e0cc94b1cc124a | nihaal-gill/Example-Coding-Projects | /Egyption Fractions/EgyptianFractions.py | 1,000 | 4.28125 | 4 | #Language: Python
#Description: This program is a function that uses the greedy strategy to determine a set of distinct (i.e. all different) Egyptian
#fractions that sum to numerator/denominator. The assumptions in this program are that the numerator and denominator are positive integers
#as well as the numerator is... |
9c02b3d2b766e3579349acfec777674e29fb8a69 | bitomann/functions | /ActivitiesForKids.py | 860 | 3.890625 | 4 | # Define four Python functions named run, swing, slide, and hide_and_seek.
# Each function should take varying number of children's names as the argument.
running_kids = ["Pam", "Sam", "Andrea", "Will"]
swinging_kids = ["Marybeth", "Ariel", "Kevin", "Courtney"]
sliding_kids = ["Mike", "Jack", "Jennifer", "Earl"]
hidin... |
8db973f94f7c6f7a6e35c70b5783333246487fae | vishalV96/term-tube | /src/video_player.py | 15,017 | 3.5 | 4 | """A video player class."""
import random
from .video_library import VideoLibrary
from .video import Video
from .video_playlist import Playlist
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
self._currently_playing ... |
9a41f0eb7d1b2b7191c75154f92bcf5724b87d32 | aganashcse/ciscoassignment | /Problem1/geometric_figure.py | 939 | 3.59375 | 4 | """
This python code will show a picture of combined geometric shapes.
"""
import numpy as np
import cv2
def imageProcessing():
image = np.zeros((512, 512, 3), np.uint8)
cv2.circle(image, (250, 250), 50, (0, 255, 0), 5)
cv2.line(image, (250, 220), (280, 250), (255, 0, 0), 5)
cv2.line(image, (280, 25... |
21721b96ca208c93dda43c064c5ba9238f12018b | Void-TK-57/Drift | /maplib.py | 1,906 | 3.8125 | 4 | import pygame
from graphics import *
class Map:
def __init__(self, lines, color = (255, 255, 255)):
self.lines = lines
self.color = color
# method to draw the line of the map
def draw(self, screen, collisions = True):
# for each line
for line in self.lines:
pyg... |
63b3ede97d2cdb4f1aaa6b902e3a104caffe60b9 | machacek/diplomka | /experiments/compare_translations.py | 3,903 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from difflib import SequenceMatcher
from termcolor import colored
import random
def parse_args():
parser = argparse.ArgumentParser(
description="""This script is used to manually evaluate machine
translation. It randomly select given cou... |
ce29078af93fde2e448f8e26063e97d7111aee85 | freddyloorcosta/Tarea_1_logica_de_programacion | /tareaE-11.py | 440 | 3.765625 | 4 | #11.Una escuela aplica dos exámenes a sus aspirantes, por lo que cada uno de ellos
# obtiene dos calificaciones denotadas como C1 y C2. El aspirante que obtenga una
# calificación mayor que 90 en cualquiera de los exámenes es aceptado; en caso contrario es rechazado.
def run():
c1=input('c1->')
c2=inpu... |
8de246bfb0239fdbcfd9f80c04d7365ad10ffba9 | freddyloorcosta/Tarea_1_logica_de_programacion | /tareaE-5.py | 581 | 3.859375 | 4 | #5-Dado como dato la calificación de un alumno en un examen,escriba “aprobado” si
# su calificación es mayor o igual que 7 y “Reprobado” en caso contrario.
def calificacion(cal):
cal= int(input("ingrese una calificacion: "))
if cal >7:
print("__usted_esta:")
print('aprobado')
... |
431b63d4efe95ece96ba5e41035011517a596044 | poLLiAziatka/Super-Gaame | /board.py | 4,050 | 3.921875 | 4 | import random
class Board:
def __init__(self, x_size, y_size):
self.field = [[0] * y_size for _ in range(x_size)]
self.x_size = x_size
self.y_size = y_size
self.status_move = 0
def add(self, hero, x, y):
if x >= self.x_size or x < 0 or y > self.y_size < 0:
... |
89121f93c54886606dbdba6b269e07de1f1a906b | Jane620/CSDN | /Python100/Day1/turtle_learn.py | 790 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/7/13 下午1:43
# @Author : Jane
# @Site :
# @File : turtle_learn.py
# @Software: PyCharm
# @Describe:
import turtle as t
def demo(x,y):
init()
#t.colormode(111)
'''
t.setx(-100)
t.sety(100)
t.fd(100)
t.seth(80)
#t.right(90) # x轴向上偏角度
... |
57060973638e77b4247be650fc3f065b3a06070c | BloodyInspirations/VSA2018 | /proj01.py | 2,321 | 4.375 | 4 | # Name:
# Date:
# proj01: A Simple Program
# Part I:
# This program asks the user for his/her name and grade.
#Then, it prints out a sentence that says the number of years until they graduate.
# Part II:
# This program asks the user for his/her name and birth month.
# Then, it prints a sentence that says the number ... |
65fb4afd1c43749106c02ed065d530e8bf3782b3 | KeerthanaPravallika/DSA | /Patterns/Xpattern.py | 558 | 4.28125 | 4 | '''
Write a program to take String if the length of String is odd print X pattern otherwise print INVALID.
Input Format:
Take a String as input from stdin.
Output Format:
print the desired Pattern or INVALID.
Example Input:
edyst
Output:
e t
d s
y
d s
e t
'''
word = input()
if len(word) % 2 == 0:
... |
31011721639a1860057d2be97224ee38f4676c08 | KeerthanaPravallika/DSA | /Recursion/RecursiveDigitSum.py | 1,788 | 4.0625 | 4 | '''
We define super digit of an integer x using the following rules:
Given an integer, we need to find the super digit of the integer.
• If z has only 1 digit, then its super digit is z.
• Otherwise, the super digit of x is equal to the super digit of the sum of the digits of z.
For example, the super digit of 9875... |
68c5a16b3a0fcc32c64fc02284c26b7fd0497c8a | akuelker/intermediate_python_class | /Exercise 6/Exercise6_4.py | 250 | 3.796875 | 4 | even = lambda x: x%2 ==0
evenList = []
for i in range(1, 21):
if(even(i)):
evenList.append(i)
print(evenList)
#option 2
numberList = []
for i in range(1,21):
numberList.append(i)
evens = list(filter(even, numberList))
print(evens)
|
46570a75d27e9c7ff46d8e90f7a13d46a19bb7fb | akuelker/intermediate_python_class | /Exercise 2/Exercise2_1.py | 252 | 4.0625 | 4 | import re
#spaces not allowed. Appears to work. Haven't explained string match
word = input("Enter a word with only letters and numbers: ")
if (re.search(r'^[\w]*$', word)) and not(re.search(r'_', word)):
print("good")
else:
print("bad")
|
3a5e1b7ade252d9acc549f3d1177580ff9d9fd89 | akuelker/intermediate_python_class | /Exercise 7/Exercise7_3.py | 279 | 4.3125 | 4 | import datetime
year = int(input("Enter your Church Year: " ))
today = datetime.date(year,1,1) # January 1st
today += datetime.timedelta(days = 6 - today.weekday()) # First Sunday
while today.year == year:
print(today)
today+= datetime.timedelta(days = 7)
|
6dba82f500e04e4b895f23af4bc70e13aa71bca6 | noircir/ppp | /params.py | 890 | 3.53125 | 4 | import requests
import random
from pyfiglet import figlet_format
from termcolor import colored
count = 0
ascii_art = figlet_format("Dad Joke 3000")
colored_ascii = colored(ascii_art, color="green")
print(colored_ascii)
url = "https://icanhazdadjoke.com/search"
topic = input("Let me tell you a joke! Give me a topic: ... |
556546782189dce0b48c166f0b9b74c57f3e1a88 | notmatthancock/notmatthancock.github.io | /code/py/base_b_expansion.py | 1,011 | 3.796875 | 4 | import numpy as np
def expand_base_b(x, b, N):
"""
Expand `x` in base, `b`, to `N` digits.
Returns:
approx_x: the truncated base-b expansion.
string_x: the string of base-b digits with appropriately
placed decimal point.
"""
assert isinstance(b, int)
assert is... |
6fa49ee49f7b891599fbbf8140e796be7bc45691 | SunqiSteven/DataStructure | /搜索算法/二分查找/BinarySearch.py | 1,455 | 4 | 4 | def binary_search(array, element):
low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) / 2
if array[mid] == element:
return mid, mid
if array[mid] > element:
if mid == low or \
array[mid - 1] < element:
return m... |
92ce9b0448c92f73eb1b62ce21082550a7aad8c3 | SunqiSteven/DataStructure | /分支限界算法/shortest_path.py | 3,548 | 3.640625 | 4 | # coding: utf8
# 最小堆
class MinHeap:
get_parent = lambda self, ind: (ind - 1) / 2
get_left_child = lambda self, ind: 2 * ind + 1
get_right_child = lambda self, ind: 2 * ind + 2
def __init__(self):
self._queue = []
def _adjust(self, heap, start=None, end=None):
if start == None:
... |
1852801e9bfc353709e8be9a57b96a59e0febc5a | SunqiSteven/DataStructure | /排序算法/希尔排序/shell_sort.py | 888 | 3.640625 | 4 | class ShellSort:
@staticmethod
def group_sort(array, gap):
n = len(array)
for i in range(n - gap):
j = 1
while (i + gap * j) < n:
for p in range(j):
if array[i + gap * j] >= array[i + gap * p]:
continue
... |
c82e59572509da4b8daf5291e27eed4b1c25e8f3 | paezdavid/python-journey | /Week 1/ZigZag.py | 717 | 3.78125 | 4 | import time, sys
indent = 0 # how many spaces to indent
indentIncreasing = True # whether the indentation is increasing or not
try:
while True:
# 1 - by multiplying the space to a number we aument the number of spaces.
print(' ' * indent, end='')
# 2 - print eight asterisks
print('***... |
a283fdada45eefeb8f24c24a52148cfab49d4f1b | paezdavid/python-journey | /Week 1/listExercise.py | 1,275 | 3.953125 | 4 | from collections import Counter
# Initial inventory
inventory = {
'sword': 2,
'axe': 1,
'cold milk': 10,
'stormwind pie': 2,
'bow': 1,
'helmet': 4,
'bags': 6,
'shirt': 2
}
# Items we want to add to the initial inventory
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'dagger', 'gold... |
3b5f8d01f266d3eba90dfecf87764a638671df14 | sdanjie/DungeonsAndDragonsNameGenerator | /GenerateName.py | 1,441 | 3.78125 | 4 | # This program demonstrates using python to read and write with files.
# sdanjie
# create: 10/25/2016
# last update: 12/05/2018
import random
def main():
# Get the lists
nameList = loadFile("names.txt")
titleList = loadFile("titles.txt")
descrList = loadFile("descriptors.txt")
... |
488adf142b4eea5c71f5f3381b80935a33e47ebb | kayodeomotoye/Code_Snippets | /import csv.py | 848 | 4.1875 | 4 | import csv
from io import StringIO
def split_words_and_quoted_text(text):
"""Split string text by space unless it is
wrapped inside double quotes, returning a list
of the elements.
For example
if text =
'Should give "3 elements only"'
the resulting list would be:
... |
fc90ca47208680c805b85b6d9a103be8a4b6471f | kayodeomotoye/Code_Snippets | /hundred_days.py | 952 | 3.53125 | 4 | from datetime import date, datetime
from months import START_DATE
from dateutil.rrule import *
TODAY = date(year=2018, month=11, day=29)
def get_hundred_weekdays(start_date=TODAY):
"""Return a list of hundred date objects starting from
start_date up till 100 weekdays later, so +100 days
skipping Sa... |
6135e11b9a7179eed5d6e083142122858b72f0b8 | kayodeomotoye/Code_Snippets | /pascal.py | 707 | 3.984375 | 4 | from typing import List
def pascal(N: int) -> List[int]:
"""
Return the Nth row of Pascal triangle
"""
if N == 0: return []
N = N - 1
line = [1]
for k in range(max(N ,0)):
line.append(int(line[k]*(N-k)/(k+1)))
return line
#pybites
from math import factorial
# Solution 1
d... |
a29a74255df46a2d0944a8389558cc294ed2eacb | kayodeomotoye/Code_Snippets | /running_mean.py | 1,227 | 4.3125 | 4 | from itertools import islice
import statistics
def running_mean(sequence):
"""Calculate the running mean of the sequence passed in,
returns a sequence of same length with the averages.
You can assume all items in sequence are numeric."""
avg_list=[]
new_list = []
for num in sequence:
... |
50766b92c2d95d7f53ebac929c0efa6cab85fa96 | kayodeomotoye/Code_Snippets | /orders.py | 2,696 | 3.578125 | 4 | import os
from urllib.request import urlretrieve
import pandas as pd
TMP = os.getenv("TMP", "/tmp")
EXCEL = os.path.join(TMP, "order_data.xlsx")
if not os.path.isfile(EXCEL):
urlretrieve("https://bites-data.s3.us-east-2.amazonaws.com/order_data.xlsx", EXCEL)
def load_excel_into_dataframe(excel=EXCEL):
"""Lo... |
f0cc8d422cf5c8f333979ed4ad4906ae627b2263 | kayodeomotoye/Code_Snippets | /fizzbuzz.py | 520 | 3.84375 | 4 | def fizzbuzz(num):
if num % 15 == 0:
return 'Fizz Buzz'
elif num % 5 == 0:
return 'Buzz'
elif num % 3 == 0:
return 'Fizz'
else:
return num
fizzbuzz(2)
fizzbuzz(30)
fizzbuzz(10)
import string
def remove_punctuation(input_string):
"""Retur... |
81ca101123db74af6eafc21b06a94cef0e78bdbb | kayodeomotoye/Code_Snippets | /mday.py | 774 | 3.578125 | 4 | from datetime import date, datetime
from dateutil.rrule import rrule, YEARLY, SU
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta, SU
def get_mothers_day_date(year):
"""Given the passed in year int, return the date Mother's Day
is celebrated assuming it's the 2nd Sunday of ... |
44e2e6ebda6edf51dd89856fb2c118c3fed984e7 | huikinglam02/Guided_Project_Transforming_data_with_Python | /time_dq.py | 810 | 3.59375 | 4 | import dateutil
import read
def hours(x):
y = dateutil.parser.parse(x)
return y.hour
def days(x):
y = dateutil.parser.parse(x)
return y.day
def years(x):
y = dateutil.parser.parse(x)
return y.year
def weekdays(x):
y = dateutil.parser.parse(x)
return y.weekday()
def get_time():
#... |
a73631e8460daca760fa217efa0dc9c9b5c0ef25 | lftys2021/github-landing | /myvenv/Chapter5/07.리스트실습문제5.2.1.py | 634 | 3.59375 | 4 | result=[33,40,12,63,52]
# 1. 6번의 팔굽혀펴기 개수는 9개
# 리스트의 마지막에 추가하자.
print("1. 리스트 마지막에 추가하기")
result.append(9)
print(result)
print("\n")
# 2. 2번은 재측정하여 50개를 하였다.
# 2번의 데이터를 변경해 보자
print("2. 리스트 데이터 변경")
result[1] = 50
print(result[1])
print("\n")
# 3. 3번부터 6번까지의 데이터를 슬라이싱하기.
print("3. 데이터 슬라이싱")
print(result[2:6])
print... |
e12ec0d529f890f1f46ead8feb24ce5ba1bef83a | rinoSantoso/Python-thingy | /Sorting.py | 1,256 | 4.21875 | 4 | def sort(unsorted):
sorted = []
sorted.append(unsorted[0])
i = 1
while i < len(unsorted):
for j in range(len(sorted)):
if unsorted[i] < sorted[j]:
sorted.insert(j, unsorted[i])
break
elif j == len(sorted) - 1:
sort... |
5efc917d77416bf5066136d3521ff56e83957b78 | buseorak/ITU-ACM-21-22-Python-Programming-Course | /Week3/Assignment/plurality.py | 1,707 | 3.921875 | 4 | #global değişken, bu sözlük adayların oy sayımlarını tutmak için oluşturulmuştur.
candidateDict = {}
def vote():
#Seçmen adaylardan herhangi birine oy vermiyorsa tekrar seçim yapması istenir.
#doğru giriş yaptıysa seçtiği adayın oy sayımı 1 arttırılır
candidate_name = input("Vote: ")
if candidate_... |
d889add40f111deff202d1cae95694222da49b3e | swapnilmayekar/TestGitRepo | /fibonnaci.py | 329 | 3.875 | 4 | #fibonacci algorith
#algorith is for number only
#code added to support this
def fibo(number):
imf number < 1:
raise Exception
elif number==1 or number==2:
return number-1
else:
return fibo(number-1)+fibo(number-2)
count=1
while count <= 9:
print(f'{fibo(count)}',end=' ')
... |
8c289337bdc27bb15963cf1ab6c78e1471f0a0aa | abhinavsoti/practice | /ObjectOrientedHomeWork.py | 524 | 3.953125 | 4 |
class Line:
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1, y1 = self.coor1
x2, y2 = self.coor2
dist = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
return dist
def slope(self):
x1, y1 = self.coor1
... |
deecb07167227cdac2ccd23ddf6bdd688b5ca024 | abhinavsoti/practice | /methodAndFunctions.py | 926 | 3.609375 | 4 | ######################################################################################
# Script Name: methodAndFunctions #
# Description: This script will print the user executing the program and will also #
# keep checking the current system processes running at the momen... |
037ed9844747010a9a2d8da79c8ca973b6b278c2 | DtjiAppDev/Python-Recursion-Tutorial | /recursive_fibonacci.py | 406 | 4.28125 | 4 | """
This file contains implementation of calculating the nth Fibonacci number using recursion
Author: CreativeCloudAppDev2020
"""
def fibonacci(n: int) -> int:
if n < 0:
return 0
elif n == 0 or n == 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Tes... |
a4b13f890d9a6aa4947879fcea48e50f3ab6c363 | san250240/projects | /Number guessing game.py | 889 | 4.03125 | 4 | # This is a number guessing game.
import random
print ("What is your name?")
name = input()
print ("Well " + name + ", I'm thinking of a number between 1 and 10. Take a guess.")
secretnum = random.randint(1, 10)
for guessestaken in range(1, 7):
try:
print ("Take a guess!")
guess = inp... |
4e3f87c1150c9491969534e9d03061742fea2127 | lmbaeza/aes-128 | /main.py | 1,236 | 3.625 | 4 | from aes import *
def AES_CBC(KEY, TXT, IV, DEBUG=False):
key_aes = plaintext_to_hex(KEY)
crypt = AES(key_aes)
plaintext = plaintext_to_block(TXT, DEBUG=True)
print(plaintext)
ciphertext = crypt.encryptCBC(plaintext, IV)
if DEBUG: print()
if DEBUG: print("Cipher Text: ", ciphertext)
... |
5d05efc97462518dff00b83cd1c21d38024dc1ac | Adam-Katz/set-solver | /solver_advanced.py | 4,278 | 3.546875 | 4 | # downloaded from: http://code.activestate.com/recipes/578508-finding-sets-in-the-card-game-set/
import random
class Table:
# a random table of n different cards
def __init__(self, n=12):
self.cards = random.sample(Card.allcards(), n)
###############################################
# four d... |
83ffbc501322048cdaa422835958bb80cbdeeafb | senpa1/1331 | /forloop1.py | 446 | 3.90625 | 4 |
############################################
#
# Name: Newsom
# Course: 1331
# Origin Date: 8/31/2016
# Description: Hello World
# This program outputs "Hello World" when run
#
############################################
# The next line should print "Hello World" when the program is run
##i=0
##print("The " + "End"... |
e1da70824235e8a5f7ad841ec3e7111cd19009d0 | senpa1/1331 | /michael0x2agrid2.py | 816 | 3.640625 | 4 | import turtle
rat = turtle.Turtle()
dot_distance = 50
width = 5
height = 1
rat.penup()
def draw_octogon():
rat.pd()
num_sides = 6
side_length = 20
angle = 360.0 / num_sides
for i in range(num_sides):
rat.forward(side_length)
rat.right(angle)
rat.pu()
def draw_a_grid():
... |
e1656bf31c4cc20fe0a1365acff493ab0fd905ea | jwalter2020/Python | /walter2a.py | 2,428 | 3.96875 | 4 | class Rectangle:
def __init__(self,length,width):
self.length=length
self.width=width
def getLength(self):
return self.length
def setLength(self,length):
self.length=length
... |
4abaa1f1e2df0cf557d8f1419b6e8cf951885499 | UMBC-CMSC-Hamilton/CMSC201-Spring2020 | /function_examples.py | 896 | 3.875 | 4 | def capitalize(my_string):
capitalized = my_string[0].upper()
for i in range(1, len(my_string)):
capitalized += my_string[i]
return capitalized
def even_or_odd(x):
if x % 2:
return 'odd'
else:
return 'even'
def is_friendly(x):
the_sum = 0
for i in range(1, x)... |
dcdbfbda673a248eff39ff8a5a4d55260132f359 | UMBC-CMSC-Hamilton/CMSC201-Spring2020 | /TestingProjects/pac_man_project.py | 851 | 3.625 | 4 | """
Everyone wants to know about testing.
"""
class PacMan:
def __init__(self):
self.the_board = []
self.baddies = []
print('Pac Man Constructor Running')
def load_map(self, map_file):
"""
:param map_file: file name as string
:return: board, 2d list which is t... |
88843df9c7155d053223b91bf5953bd16ff9d280 | UMBC-CMSC-Hamilton/CMSC201-Spring2020 | /Lecture 11/dictionary_day.py | 860 | 3.96875 | 4 | def count_words(file_name):
word_dict = {}
with open(file_name) as the_file:
for word in the_file.read().split():
if word.upper() != word:
word = word.lower()
if word in word_dict:
word_dict[word] += 1
else:
... |
c0842c0917df268ba89c1d1fac5c46154ce24960 | twhorley/twho | /matplotlib_tests.py | 1,540 | 4.34375 | 4 | """
Script to play around with how to make a variety of plots using matplotlib and
numpy. I'll be using object-oriented interface instead of the pyplot interface to
make plots because these are far more customizable.
"""
import matplotlib.pyplot as plt
import numpy as np
# Create a figure with 2 axes, both same scal... |
fd5b72446f6c1aac97f790e491c3ae3d37f4c6f0 | jonathanronen/ml101-biebola | /code/preprocessing.py | 2,608 | 3.640625 | 4 | """
For Intro to Data Science, NYU 2014.
Reads raw csv file, cleans texts and counts words in dictionary.
@auth jonathanronen
"""
import string
from collections import defaultdict
# available on https://github.com/SMAPPNYU/smappPy
from smappPy.unicode_csv import UnicodeReader, UnicodeWriter
from nltk.corpus import s... |
5d6ae2ade619b7a743aa366185c8b95f986247dd | viniciusdotto/criptografiaUFMT | /T3-CRIPTOGRAFIA-201611310010-VINICIUS_DOTTO_FIGUEIREDO.py | 1,236 | 3.5625 | 4 | """
Aluno: VINICIUS DOTTO DE ARRUDA FIGUEIREDO
RGA: 201611310010
"""
#coding=UTF-8
def stringPbin (text): #Transforma o texto em binario
textoBin = ""
tam = len(text)
for i in range (tam):
textoBin = textoBin + str(bin(ord(text[i]))[2:].zfill(8))
return textoBin
def completaZero(text): #Completa o ultimo con... |
df49ae6baac33d8a7a82b258d6e7828c9eb34201 | arunrathore45/Linear-Regression-from-Scratch-with-NumPy | /Linear Regression.py | 658 | 3.546875 | 4 | import numpy as np
a=[i for i in range(1,6)]
b=[i for i in range(2,7) ]
x1=np.array(a).reshape(1,len(a))
y=np.array(b).reshape(1,len(b))
theta=np.random.randint(-2,high=2,size=2).reshape(1,2)
def train(x,y,alpha,m):
global theta
prediction=np.matmul(theta,x)
error=y-prediction
gradient=(alpha/m)*np.matmul((pred... |
b6c5eb4ac8da4ef2ec71f2646e66f0d8e8b43996 | johannesmik/wipro | /sheet0/examples/sheet4_ratespiel.py | 585 | 3.671875 | 4 | #!/usr/bin/python
__author__ = 'johannes'
import math
import random
# Erzeuge Zufallszahl zwischen 0 und 100
zahl_cpu = int(random.random()*100)
# Geht auch:
#zahl_cpu = random.randint(0,100)
zahl_spieler = -1
versuche = 0
print "Errate meine Zahl! (Zwischen 0 und 100)"
while zahl_spieler != zahl_cpu:
versuch... |
bcf2f73481722379e5472d1262b1271ed290c80a | bassil/1803applets | /matrix_vector/test_matrix_vector.py | 475 | 3.6875 | 4 | from matrix_vector import *
## Define your variables here:
# Matrix A:
a11 = 1
a12 = 1
a21 = 1
a22 = 0
A = np.array([[a11, a12],[a21, a22]])
# Vector v:
x = 1
y = 1
v = np.array([x,y])
## Define the plot interval [-bounds, bounds]
# (bounds>15 and the graphics start to look wonky)
bounds = 10
## Create a "matr... |
f8ab35dfa6775ea5b9eaf7eea415cd485c4a2966 | alberturria/kata-bowling | /src/test_game.py | 1,376 | 3.796875 | 4 | import unittest
from src.game import Game
class GameTestCase(unittest.TestCase):
def setUp(self):
self.game = Game()
def test_when_rolling_without_a_spare_then_the_score_is_updated_by_the_number_of_knocked_pins(self):
expected_score = 5
self.game.roll(5)
self.... |
f5d246d38acbfcaf616967a01c7d869c3fe92fe7 | huochezaodian/python-learning | /python/example-100/example018.py | 298 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
num = raw_input('please enter a number:')
count = int(raw_input('please enter the number of times:'))
sum = []
for i in range(count):
v = num * (i+1)
print v
sum.append(int(v))
s = reduce(lambda x,y:x+y , sum)
print '计算和是:\t%d' % s |
2313cb9e2639ae7d797a64f81015126ff9099dc9 | huochezaodian/python-learning | /python/example-100/example011.py | 383 | 3.8125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def rabbit(m):
if m == 1 :
return [1]
if m == 2 :
return [1, 1]
count = [1, 1]
for i in range(2, m+1):
count.append(count[-1] + count[-2])
return count
def printCount(m):
arr = rabbit(m)
for i in range(0, m):
print '... |
b7dbde400107ffbc5664b3f6d05a2c90e8a06e5d | huochezaodian/python-learning | /python/example-100/example001.py | 291 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
count = 1
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if i != j != k:
count += 1
print i, j, k
print("能组成%d个互不相同且无重复数字的三位数" % count) |
60a5f16475043b84d86291d682741dc632c44c8c | deacsah/picoCTF2013 | /ReadTheManual/decipher.py | 919 | 3.609375 | 4 | #!/usr/bin/env python
import string
import re
steps = 16
def decipherChar(c):
if c.istitle():
return string.uppercase[(string.uppercase.index(c) - steps) % 26]
else:
return string.lowercase[(string.lowercase.index(c) - steps) % 26]
newfile = open('deciphered.txt','w')
with open('caesar.txt'... |
7713a3b3df95c0d26af4d39b6ee595dbcd2eaa39 | AB95/ProjectEulerPython | /Euler006.py | 242 | 3.546875 | 4 | def euler6(n):
return abs(square_of_sums(n) - sum_of_squares(n))
def sum_of_squares(n):
return sum([i**2 for i in xrange(n+1)])
def square_of_sums(n):
return sum([i for i in xrange(n+1)]) ** 2
print euler6(100)
|
c155dcf62d0416422eb23c2f581ebd05b353dc0c | AB95/ProjectEulerPython | /Euler005.py | 319 | 3.65625 | 4 | def euler5(n):
if n == 1:
return 1
elif n > 1:
num = n * (n - 1)
while not is_divisible(n, num):
num += n * (n - 1)
return num
def is_divisible(n, num):
for i in xrange(1, n+1):
if num % i != 0:
return False
return True
|
7e4431679fc53501878fda291e3127fa943d80b7 | rocioluct/ex_8.4 | /ex_8.4.py | 154 | 3.59375 | 4 | fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
lstline = line.split()
lst = lst + lstline
lst.sort()
print(lst)
|
2851661c52be4d4cb5baa880b57634471ab6a286 | MoisesFreitas1/EstruturasDeDecisao | /Q1.py | 235 | 3.765625 | 4 | custoF = float(input("Custo da Festa: R$"))
pConvite = float(input("Valor do convite: R$"))
nconvites = round(custoF/pConvite)
multi = nconvites * pConvite
if multi < custoF:
nconvites = nconvites + 1
print(nconvites," convites") |
a98813061b478d0d7be602d6ba503f33ed228863 | LaKeshiaJohnson/python-fizz-buzz | /challenge.py | 664 | 4.3125 | 4 | number = int(raw_input("Please enter a number: "))
# values should be stored in booleans
# If the number is divisible by 3, print "is a Fizz number"
# If the number is divisible by 5, print "is a Buzz number"
# If the number is divisible by both 3 and 5, print is a FizzBuzz number"
# Otherwise, print "is neither a fiz... |
b94d821e88ec726c0fd25801f48358aa7ca10f08 | MartynaRe/Zadania1 | /quiz.py | 797 | 3.984375 | 4 | quest1 = "Poland is in Europe.\na.yes\nb.no"
quest2 = "The longest river in Poland is:\na.Wisła\nb.Odra\nc.Wieprz"
quest3 = "National language in Poland is:\na.English\nb.French\nc.Polish"
print("Welcome to our Quiz. Answer this 3 questions!")
print(" ")
print(quest1)
ans1 = input("Your answer is: ")
score =... |
7c6a4ba9c744ff237b8cc5ea4a4734dd000724ed | MartynaRe/Zadania1 | /modules.py | 694 | 3.53125 | 4 | from delta import delta
from generator import generator
from fibbonacci import fib
# 2
def calculate_delta(a=3, b=4, c=1):
return delta(a, b, c)
# 6
def longest_sequence(string):
start_index = 0
start_index_tmp = 0
seq_len = 1
seq_len_tmp = 1
for i in range(1, len(string)):
... |
31345ce89c6ebed82295734f7e391b83e31ec4ae | ohmuraken/udacity_python_lesson | /test2.py | 211 | 3.5 | 4 | def inc(n):
return n+1
print inc(1)
def square(num):
return num*num
print square(square(2))
def sum3(a,b,c):
return a+b+c
print sum3(1,2,3)
def abbaize(a,b):
return a+b+b+a
print abbaize("cat","dog") |
e11dc77444f46c44e4aa495528b3e930c01c886d | ohmuraken/udacity_python_lesson | /test3.py | 122 | 3.640625 | 4 | # 渡した数まで数える
def print_nubers(num):
i = 1
while i <= num:
print i
i = i+1
print print_nubers(3) |
a6b7095bdf942c083324dc7d49dc2835d651bdb9 | RileyMathews/nss-python-exercises-classes | /employees.py | 1,597 | 4.1875 | 4 | class Company(object):
"""This represents a company in which people work"""
def __init__(self, company_name, date_founded):
self.company_name = company_name
self.date_founded = date_founded
self.employees = set()
def get_company_name(self):
"""Returns the name of the compan... |
7bb05a191d977b80760a880bf31fb85d3adfc635 | mksaini026/Python_Learning_Programs | /src/dict/SumOfDictionary.py | 203 | 3.6875 | 4 | d = eval(input('Enter dict key value'))
# sum = 0
# for item in d.items():
# sum = sum + int(item[1])
# print(sum)
#
# for k, v in d.items():
# sum = sum + v
# print(sum)
print(sum(d.values()))
|
fbdeaa3a1d75928f862d8453ea34739e24dfcfdd | zihao-chen/projecteuler | /problems/problem_52.py | 825 | 4.0625 | 4 | """
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
"""
def rearrange_digits(d):
return "".join(sorted(str(d)))
if __name__ == '__main__':... |
a49f87f30a760b15854f40a196ac0805af10499b | Chethanr2/pro1 | /Classes_ex/Methods.py | 388 | 3.5 | 4 | class Students:
School = 'NEC'
def __init__(self,m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
@classmethod
def info(cls):
return cls.School
@staticmethod
def Clg_Info():
print("NEC technologies")
s1 = Students(28,49,50)
s2 = Students(33,69,90)
p... |
7e54b54161b0b49fcffa91315a8d7bb41b8293bd | Chethanr2/pro1 | /Python_Automation/Error_handling/Box_printing.py | 636 | 4.03125 | 4 | # This program will give the box printing
'''
**************
* *
* *
* *
* *
* *
**************
'''
def BoxPrinting (symbole, width, hieght):
if len(symbole) != 1:
raise Exception('"Symbol" needs to be string of 1 not more than that')
if (width)... |
eb53eaf3195f48b6185f8130fc901a12714d3a66 | arturbr97/Python-Exercicios | /Lista 2/Exercicios Python/q13.py | 395 | 3.5 | 4 | import sys
import random
import os
valor = input('Valor: ')
if(valor=='1'):
print('Domingo')
elif(valor=='2'):
print('Segunda-Feira')
elif(valor=='3'):
print('Terça-Feira')
elif(valor=='4'):
print('Quarta-Feira')
elif(valor=='5'):
print('Quinta-Feira')
elif(valor=='6'):
print('Sexta-Feira')
elif(valor=='7... |
36531ca7d49794a0d374f107ac6de48ee9a58038 | arturbr97/Python-Exercicios | /Lista 3/questao8/fumante.py | 293 | 3.78125 | 4 |
anos=int(input(print('informe a quantidade de anos que fuma:')))
quant=int(input(print('informe a quantidade de cigarros que fuma por dia:')))
preco=float(input(print('informe o preço da carteira de cigarros:')))
print('Quantidade de dinheiro gasto: ', anos * 360 * quant * preco / 20)
|
f93bcce675db057b918c06dbca8e1ac4bc3aaa38 | arturbr97/Python-Exercicios | /Lista 1/Lista 1/Q13.py | 346 | 3.84375 | 4 | dia = input('Digite o Dia da Semana ')
if dia == 1:
print('1- Domingo')
elif dia == 2:
print('2- Segunda')
elif dia == 3:
print('3- Terça')
elif dia == 4:
print('4- Quarta')
elif dia == 5:
print('5- Quinta')
elif dia == 6:
print('6- Sexta')
elif dia == 7:
print('7- Sabado')
else:
... |
4cbf6d0c5f34d61ef79d7228174f28f2fb9f5014 | arturbr97/Python-Exercicios | /Lista 2/Exercicios Python/q11.py | 962 | 3.796875 | 4 | import sys
import random
import os
salario = float(input('Valor do Salario: '))
if(salario<=280):
print('Salario antes do reajuste: R$ ', salario)
print('Aumento de 20%')
print('Valor do aumento: R$ ', (salario*0.20))
print('Salario com Reajuste: R$ ', (salario*0.20)+salario)
elif((salario>280)and(salario<=700))... |
06cc508052e5651d5d9b031fd5b17e16e42925da | peterjoking/Nuevo | /expresionesregulares.py | 620 | 3.875 | 4 | import re
def buscar (palabra, texto):
resultado = re.search(palabra,texto)
return resultado
texto = "Este es un texto donde escribo algo para después probar un programa en el cual voy a buscar una palabra"
palabra = input('coloque la palabra que quiere buscar: \n')
resultado = buscar(palabra,texto)
if (res... |
eec5d6c8cb0b850addb2f043eb56b93787cb123f | peterjoking/Nuevo | /Ejercicios_de_internet/Ejercicio_22_Readfile.py | 897 | 4.53125 | 5 | """
Opening a file for reading is the same as opening for writing, just using a different flag:
with open('file_to_read.txt', 'r') as open_file:
all_text = open_file.read()
Note how the 'r' flag stands for “read”. The code sample from above
reads the entire open_file all at once into the all_text variable.
Bu... |
eb7e036e7e92a9da145eeee84005014fd446db55 | peterjoking/Nuevo | /basededatos.py | 480 | 3.640625 | 4 | import sqlite3
conexion = sqlite3.connect("basedatos1.db")
cursor = conexion.cursor()
cursor.execute ("CREATE TABLE PERSONAS2(nombre TEXT, apellido TEXT, edad INTEGER)" )
cursor.execute("INSERT INTO PERSONAS2 VALUES('Pedro', 'Lopez', 44)")
lista_varios = [('Pablo', 'Alvares', 32), ('Gimena', 'Rodriguez', 21), ('Michel... |
a0bb5ec6d46848a6be9046c58cd7b5b580134f59 | peterjoking/Nuevo | /tkinterejemplo1.py | 1,358 | 4 | 4 | import tkinter
raiz = tkinter.Tk()
raiz.title("Mi primer programa de tkinter")
#creamos el componente frame.
#creamos el componente label
texto = "Etiqueta Label"
etiqueta = tkinter.Label(raiz, text=texto)
etiqueta.config(fg='red', bg='pink', font=('Arial', 30))
etiqueta.pack()
#creando el metodo entrada junto con l... |
1add1a753b6fe229c64d5a734d34aecfd1f411eb | yawaramin/lambdak | /lambdak.py | 3,678 | 4.03125 | 4 | # lambdak.py - functional programming with continuations in Python
from __future__ import print_function
class lambdak(object):
'''A lambda with a continuation, to allow extended calculations.'''
def __init__(self, k, x = ()):
self.k = k
self.x = x if x == () else (x,)
def __call__(self, *args, **kwargs... |
74653dc226c6e40512231a02cbc6968f3040d881 | hackto-dev/APS-2020 | /insertion_sort.py | 386 | 3.84375 | 4 | def insertion_sort(arr):
for i in range(1,len(arr)):
k = i-1
if(arr[i] < arr[k]):
temp = arr[i]
while(temp < arr[k]):
arr[k+1] = arr[k]
k -= 1
if k == -1:
break
arr[k+1] = temp
return arr... |
59821f3d51588cdd16c60c460a5dc2def3350cf1 | Zalasyu/Linear-Regression | /Hmk8BME147/hmk8.py | 9,102 | 3.796875 | 4 | """
Problem 1
The amounts m of a chemical compound that dissolved in 100 grams of water at
various temperatures T were recorded as in Table 1.
a. Using the formulas in your textbook (page 149), calculate the intercept and slope of
the regression line for the sample. (10 points)
b. Graph the line o... |
f7f797fb97aacdbfb96154ebb5fc8b42ccaeb2dc | Sohaib76/Full-Stack-Django-Udemy-1-2 | /Full Stack Django/python_lectures/lists.py | 1,834 | 3.8125 | 4 | '''
VERY IMP
'''
l = [1,2,3,4]
def xyz(l):
c = [l[0]] + [l[3]] + [l[2]]
return c
#to print 0th 3rd and 2nd index of list with this order
#output >>> [1,4,3]
newList = list1 + list2
list = string.split() #>>> string with spaces become list
if 'a' not in list:
print "noo"
for i in list:
print ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.