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 |
|---|---|---|---|---|---|---|
6f6baad65328395fc7a61d1dbf7f0e981ff9ec9a | caoxiang104/DataStructuresOfPython | /Chapter3_Searching_Sorting_and_Complexity_Analysis/example4.py | 745 | 4.21875 | 4 | # coding=utf-8
"""
expo函数的一个可替代的策略是,使用如下的递归定义:
expo(number, exponent)
=1, 当exponent=0
=number*expo(number, exponent-1) 当exponent是基数的时候
=(expo(number,exponent/2))^2, 当exponent是偶数的时候
使用这一策略定义一个递归的expo函数,并且使用大O表示法表示其复杂度。
"""
# O(nlogn)
def expo(number, exponent):
if exponent == 0:
return 1
elif exponent ... |
b8eab454743400d9e4f2e1bbb942e472ce2dcace | caoxiang104/DataStructuresOfPython | /Chapter3_Searching_Sorting_and_Complexity_Analysis/example3.py | 637 | 3.96875 | 4 | # coding=utf-8
"""
Python的pow函数返回了计算一个数的给定指数所得到的结果。定义一个expo函数
来执行这个任务,并且使用大O表示法来表示其复杂度。该函数的第一个参数是数字,
第二个参数时指数(只能是非负的数字)。在你的实现中,可以使用循环或递归函数。
"""
# O(n)
def expo(num, times):
if times == 0:
return 1
else:
return num * expo(num, times - 1)
def main():
num = 2
times = 5
out = expo(nu... |
176dd75274e9f0ac22eeaec6a8bafe296fdffd72 | caoxiang104/DataStructuresOfPython | /Chapter1_Programming_Basics/stats.py | 1,741 | 3.84375 | 4 | # coding=utf-8
"""
统计学家想要用一组函数计算一列数字的中位数(median)和众数(mode)。
中位数是将一个列表排序后出现在中间位置的数。众数是在列表中出现最频
繁的数。在名为stats.py的模块中定义这些函数。还要包括一个名为mean
的函数,它计算一组数字的平均数。每个函数都接受一个列表作为参数,并
且返回单个的数字。
"""
class Stats(object):
def __init__(self, list_):
list_.sort()
self.list_ = list_
def __str__(self):
return... |
787f852dd458b854945dd7e5fc9da154c0f3351d | caoxiang104/DataStructuresOfPython | /Chapter11_Sets_and_Dicts/item.py | 614 | 4.125 | 4 | class Item(object):
"""Represents a dictionary item."""
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return str(self.key) + ":" + str(self.value)
def __eq__(self, other):
if type(self) != type(other):
return False
... |
c5e8cae725d3955a17405ff5b267deae198ffd12 | Mario263/Hacktoberfest-python-code-bunch | /square_root.py | 130 | 4.21875 | 4 | number = float(input('Enter a number: '))
num_sqrt = number ** 0.5
print('The square root of %0.3f is %0.3f'%(number ,num_sqrt))
|
f628dc8ec7c71138078ea9d60ca08c60d950484c | Mario263/Hacktoberfest-python-code-bunch | /Basic problems/17_Fibonacci.py | 116 | 3.84375 | 4 | n=int(input("Enter number of terms\n"))
a=0
b=1
print(a, b,end=' ')
for j in range(1,n-1):
c = a+b
print(c)
a,b=b,c
|
84f3d61551f50d523bd50ed95f4805880e7a2069 | Mario263/Hacktoberfest-python-code-bunch | /random_number.py | 117 | 3.78125 | 4 |
import random
a=int(input("enter the lowest no."))
b=int(input("enter the highest no."))
print(random.randint(a,b))
|
49cbe43bb29116981d7912b86d48923c9c37a32e | timemerry/fifa19PlayerData | /bestplayer.py | 216 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
data = pd.read_csv('data.csv')
print (data.loc[[11200,11201,11206,11226,11239],['Name','Age','Overall','Potential','Value']])
#print (data.loc[11206]) |
a32b8873194fdae37f82ffaf68668be65d5eb128 | Kolobayeva/python_language | /students/km61/Kolobayeva_Kateryna/homework_3.py | 3,990 | 4.1875 | 4 | Series - 1
"""
Given two integers A and B (A ≤ B). Print all numbers from A to B inclusively.
"""
# Read an integer:
# a = int(input())
a=int(input())
# b = int(input())
b=int(input())
# Print a value:
for i in range(a,b+1):
# print(i)
print(i)
Series - 2
"""
Given two integers A and B. Print all numbers from A to B... |
631973f55701bf390a5e6b3e8d7372c07b71cf31 | enjrolas/roboscoop | /brainstem/motor.py | 2,469 | 3.515625 | 4 | import serial
import time
'''
To use this class, you'd create a motor object:
myMotor=motor()
To tell the motor to move to a position target (i.e. 'go 200 clicks'),
'''
class motor:
def __init__(self,port):
self.ser=serial.Serial( port ,9600,timeout=0)
print("serial port open")
#initialized pos... |
f91801cf456bced653f8b5ef0dde01124605e0a3 | tuannguyendang/montypython | /ebook/Chapter08/string_formatting.py | 552 | 3.90625 | 4 | s = "hello world"
print(s.count('l'))
print(s.find('l'))
# print(s.rindex('m'))
s = "hello world, how are you"
s2 = s.split(' ')
print(s2)
print('#'.join(s2))
print(s.replace(' ', '**'))
print(s.partition(' '))
name = "Dusty"
activity = "writing"
formatted = f"Hello {name}, you are currently {activity}."
print(format... |
b7e69bd1a5468c25c376e3b837fb4ba00f596ca5 | tuannguyendang/montypython | /services/abstract/assignment_abstract_service.py | 411 | 3.515625 | 4 | import abc
class Assignment(metaclass=abc.ABCMeta):
@abc.abstractmethod
def lesson(self, student):
pass
@abc.abstractmethod
def check(self, code):
pass
@classmethod
def __subclasshook__(cls, C):
if cls is Assignment:
attrs = set(dir(C))
if set(c... |
c9edd541c68a693e72eb35e48e24701e862a23a4 | IfWell/MSG-Algorithm | /p1-3.py | 464 | 4.1875 | 4 | #문제(1) ppt의 문제 3번
# """로 둘러싸인 코드들은 없는 걸로 처리됨. 지우고 사용할 것
#for을 이용한 풀이
"""
for i in range(1, 10):
for j in range(1, 10):
print("{0} x {1} = {2}".format(i, j, i*j))
"""
#while을 이용한 풀이
"""
i,j = 1,1
while(i <= 9):
j = 1 #j를 다시 1로 초기화
while(j <= 9):
print("{0} x {1} = {2}"... |
f3a8719119f89807f9b0a9200dc14fc1f404f57b | joeghodsi/interview-questions | /skiena/8.24-fewest-coins.py | 2,157 | 3.578125 | 4 | '''
Problem: Given a set of coin denominations, find the minimum number of coins to make a certain
amount of change
Solution: Started with recursive DP solution which technically seemed to work but was very expensive
and ultimately has the same failure as the iterative solution I came up with after
- Turns ... |
f9889fe47906fe5d38f6390899316528bc6c1976 | joeghodsi/interview-questions | /cracking-the-coding-interview/ch2-linked-lists/2.2-kth-to-last-element.py | 1,032 | 3.828125 | 4 | '''
Problem: find the kth to last element of a linked list
Solution: will assume k=1 means return the last element. use two pointers where p1 is k steps ahead
of p2. iterate both pointers until p1 is null. return p2
- linear time, constant space
total time: 20min
mistakes:
- originally was off by one beca... |
7303e55ad997fdd195c896f37469511801132203 | joeghodsi/interview-questions | /cracking-the-coding-interview/ch9-recursion-and-dynamic-programming/9.1-step-hops.py | 1,520 | 3.84375 | 4 | '''
Problem: Given a staircase with n steps, compute the count of all possible ways you could reach the
top assuming you can take either 1, 2, or 3 steps in one go
Solution: recursive solution - each step recurse with 1, 2, and 3 steps. Each time you hit n,
increment count. DP solution - same except cache each ... |
a671e7ee31d397a1539b039c703d483c0ef365b7 | joeghodsi/interview-questions | /cracking-the-coding-interview/ch4-trees-and-graphs/4.2-has-path.py | 1,023 | 3.90625 | 4 | '''
Problem: Given a directed graph, find whether there is a path between two nodes
Solution: BFS for target including visited set to avoid cycle infinit loops
- linear time, linear space
total time: 10 min
struggles:
- assumed list.push(*array) was a thing. push isn't even a thing. append works for single
... |
4f72a247daf41a82f4137f29ec371bb1d8cbd05c | joeghodsi/interview-questions | /reverse_linked_list.py | 437 | 4.0625 | 4 | '''
Problem description:
Write a function that reverses a linked list
'''
class Node(object):
def __init__(self, value=None):
self.value = value
self.next = None
def reverse_linked_list(head):
'''
runtime: O(n)
space : O(1)
'''
prev = None
curr = head
while curr is ... |
ceaa4c59a4ff1df16b2f02baf313a3d72d8bc6fa | Anonymous1846/PyExperiments | /Calculator/Calculator.py | 4,474 | 4.03125 | 4 | #a simple gui calculator made with tkinter and python !
import tkinter as tk
from tkinter import *
from tkinter.ttk import Button,Label
main=tk.Tk()
num1=num2=ans=operator=None
answered=False
#the geomtery stands for the width and the height later we have given the title
main.geometry('400x350')
main.title('Calculator ... |
9556d48e74ace8902e01e2a3057debaa5424084b | RougeTech21/Hangman_Game | /hangman_v01.py | 902 | 3.828125 | 4 | import random
import os
PATH = os.path.join(os.path.dirname(__file__), "words.txt")
with open(PATH, mode='r') as file:
words = file.readlines()
word = random.choice(words)[:-1]
allowed_guesses = 8
guesses = []
play = True
while play:
print(word)
for letter in word:
if letter.lower() not i... |
4eb7bb3b77de7d9a9b3b98149ed21bb2c9622e45 | jimboy911/guestList | /guestList.py | 547 | 3.953125 | 4 | #guestList.py
import csv #import the csv module into the program
def main():
with open("GuestList.txt", "r") as guestList: #opens GuestList.txt file, saves it as guestList, then closes the file
guests = csv.reader(guestList) #goes through the entire guestList and seperates each entry with a comma
... |
d26b7c70f3dc60a7283fe04e2acf8cfa7714234e | Jin-SukKim/Algorithm | /Problem_Solving/leetcode/linear_data_structure/Arrangement/42_Trapping_Rain_Winter/rain_drop_v2.py | 955 | 3.5 | 4 | # stack을 활용한 풀이
def trap(self, height: List[int]) -> int:
stack = []
volume = 0
for i in range(len(height)):
# 현재 높이가 이전 높이보다 높을 떄,
# 즉 꺽이는 부분 변곡점(Inflection Point)을 기준으로
# 격차만큼 물 높이(volume)를 채운다.
while stack and height [i] > height[[stack[-1]]]:
# 변곡점을 만나면 ... |
d226d223829643caf35dc09b8f08de0f294c5b65 | Jin-SukKim/Algorithm | /Problem_Solving/Kakao_2017_08/4_Shuttle_Bus/shuttleBus.py | 1,442 | 3.5 | 4 | # 입력값 전처리 및 대기 시각 처리
def solution(n: int, t: int, m: int, timeTable: List[str]) -> str:
# 입력값 분 단위 전처리
# 문자형으로 들어오는 입력값을 쉽게 계산 가능향 형태로 변경해준다.
# Epoch Time으로 변경하면 좋으나 여긴 시/분만 있는 형태이기에 간단히 분 단위로 변경해준다.
timeTable = [
int(time[:2]) * 60 + int(time[3:])
for time in timeTable
]
timeTab... |
98cb21075402e24205bf6fe924184d2804408074 | Jin-SukKim/Algorithm | /Problem_Solving/leetcode/Sequential(Non-Linear)_data_structure/BFS/BFS.py | 762 | 3.671875 | 4 | # 큐를 이용한 반복 구조
# 모든 인접 Edge를 추출하고 도착점인 Vertex를 큐에 삽입
def iterative_bfs(start_v):
discovered = [start_v]
queue = [start_v] # 최적화는 위해 dequeue도괜찮다.
while queue:
v = queue.pop(0)
# 인접 Edge를 추출해 다음 도착 Vertex 삽입
for w in graph[v]:
# 가본적이 없는 vertex라면
if w not in d... |
8919f70d45a824c020c3bf045354943b1e73e6d2 | Jin-SukKim/Algorithm | /Problem_Solving/leetcode/Algorithm/Bit_Operator(important)/191_Number_of_1_Bits/hammingWeight.py | 259 | 3.84375 | 4 |
def hammingWeight(n: int) -> int:
count = 0
while n:
# 1을 뺸 값과 AND 연산 횟수 측정
n &= n -1
count += 1
return count
# 파이썬 방식
def hammingWeight2(n: int) -> int:
return bin(n).count('1') |
62bb93e57f3c058e17ce937fdeecb3fcde1bb3d4 | jrod006/sp-trivial-purfruit | /tp_database.py | 3,771 | 3.53125 | 4 | import pandas as pd
import csv
import os
class Database:
df = pd.read_csv('./res/trivial_purfruit_questions.csv')
#categories = {
# 'White': 'Events',
# 'Blue': 'Places',
# 'Green': 'Independence Day',
# 'Red': 'People... |
674452164f8510e27b16e34c774d5ef4c462e57c | pixelcode009/codiation_assignment | /codiation assignment.py | 1,539 | 3.59375 | 4 | def nextGen(grid,m,n):
future[m][n]=grid[m][n]
for l in range (1,m-1):
for m in range(1,n-1):
aliveneighbor=0
for i in range[-1,1]:
for j in range[-1,1]:
aliveneighbor+=grid[l+i]
aliveneighbor-=grid[l][... |
ecbbeb44a18954527817ea4747af9df3e6c3642e | marta12121/Marta_Tyzhnyk | /Tasks_les6.py | 5,520 | 4.1875 | 4 | #################################################
#1.Написати функцію, яка знаходить середнє арифметичне значення довільної кількості чисел.
def find_arithmetic_mean( *args):
""" This function can find
arithmetic_mean."""
sum = 0
for value in args:
sum += value
return sum/len(args)
pr... |
58570055c8f9b5bbdd606ee3814c6de617f91196 | marta12121/Marta_Tyzhnyk | /date.py | 305 | 3.78125 | 4 | def shorten_to_date(long_date):
a = long_date.split()
s = a[2][0]
s2 = a[2][1]
if s2 == ',':
short = ' '.join(a[0:2]) + ' ' + s
elif int(a[2][0]+a[2][1])>9:
short = ' '.join(a[0:2]) + ' ' + s + s2
return short
print(shorten_to_date("Monday February 29, 8pm"))
|
82b89d95fe730d176fd954a5ce74c96047e8f7a9 | WhiteNew/pythonData | /PYstudy/a1.py | 520 | 3.578125 | 4 | # -*- coding: utf-8 -*-
L=[]
n=1
while n<99:
L.append(n)
n+=2
print(L)
print(len(L))
r = []
n = 3
for i in range(n):
r.append(L[i])
print(r)
print(L[-10:-3])
str='abcdefghijklmn'
print(str[::3])
#递归调用
def trim(s):
if len(s)==0:
return s
elif s[-1]==' ':
return trim(s[:-1])
elif... |
4dbd156acd668c70d2c6b1426c9a80a2843dbfdc | Struggling10000/try | /Hw_1.py | 525 | 4.125 | 4 | import string
'''
题目:有这么一串字符串 str = “my Name is alex”想要将每一个单词首字母大写,其他不变str = “My Name Is Alex”
'''
s = 'my Name is alex.'
print('原字符串:s='+s)
print('直接调用函数结果:'+string.capwords(s))
s1=s.split(' ')
print('切分后的字符串列表是:')
print(s1)
def normallize(name):
return name.capitalize()
s2=list(map(normallize,s1))
print('处理后的列表是:')
... |
51a2ec2f9393fdd6b31a64c15fb51df937018179 | sithart/python_examples | /Python3-CA/class_dunder_maethod.py | 949 | 3.984375 | 4 | class Color:
def __init__(self, red, blue, green):
self.red = red
self.blue = blue
self.green = green
def __repr__(self):
# return "Color with RGB = ({red}, {blue}, {green})".format(red=self.red, blue=self.blue, green=self.green)
return f"Color with RGB = ({self.red}, {self.blue}, {self.green})... |
07ed19483ce4f603ba24db28c3d75efd02947738 | sithart/python_examples | /Python3-CA/reverse_list.py | 159 | 4.125 | 4 | def reversed_list(lst1,lst2):
lst2.reverse()
return lst1 == lst2
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))
|
e3e7917db075662da23aeaf82eda334eaa856f9e | sithart/python_examples | /Python3-CA/Scrabble.py | 1,006 | 3.609375 | 4 | letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
letters_to_point = dict(zip(letters, points))
letters_to_point[" "] = 0
# print(le... |
e7c83990733626c1f927502d38eecbd16bd63465 | sithart/python_examples | /Python3-CA/class_grade.py | 1,141 | 3.875 | 4 | class Student:
def __init__(self,name,year):
self.name = name
self.year = year
self.grades = []
def add_grade(self,grade):
if type(grade) == Grade:
self.grades.append(grade)
else:
return
def get_average(self):
class Grade:
minimum_passing = 65
d... |
1ee8539bb2f404133719ce8c970e0d579acfbb85 | Playfloor/Educational | /Python/HackerRank_Algorithms_Mini_Max_Sum.py | 919 | 4.03125 | 4 | # Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
# Input Format
# A single line of five space-separated integers.
# Const... |
81b19b6bf13c2776cb7a8435242c490d4f44cb0d | Playfloor/Educational | /Python/Codewars_Beeramid.py | 1,358 | 3.890625 | 4 | # Codewars - Beeramid
# https://www.codewars.com/kata/51e04f6b544cf3f6550000c1
# Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome!
# To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy,
# and build, the la... |
58f39da57a5c075d17bad9cca0920807b1fc7813 | Playfloor/Educational | /Python/ProjectEuler_035_Circular_Primes.py | 1,798 | 3.640625 | 4 | #https://projecteuler.net/problem=35
#The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
#There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#How many circular primes are there below one million?
from math... |
597653d108f0c38033a862126f529a959c0afd2d | OlegMeleshin/Lubanovic-Exercises | /Chapter 3/Chapter_3_part_4.py | 836 | 4.5 | 4 | # 10. Create an English-French dictionary called "e2f" and print it.
# Here are your words: dog/chien, cat/chat and walrus/morse.
e2f = {'dog' : 'chien', 'cat' : 'chat', 'walrus' : 'morse'}
print(f'''English to French Dictionary
{e2f}\n''')
# 11. Print french for walrus using your dictionary.
print(f"Fr... |
0f498dc435ba20d7cace60400c5439d12a0546e4 | OlegMeleshin/Lubanovic-Exercises | /Chapter_4/Chapter_4_part_6.py | 270 | 4.28125 | 4 | '''6. Use Set comprehension to create the 'odd' set containing even numbers in range(10).
Так и написано ODD, в котором ЧЕТНЫЕ числа. Опечатка возможно.'''
odd = {even for even in range(10) if even % 2 == 0}
print(odd)
|
d4ef2019e8df9edb47c0eaaaf2445a34ed60504b | Alexey929/web-development | /week8/3.1.Цикл for/g.py | 99 | 3.703125 | 4 | x = int(input())
for num in range(2, x + 1):
if x % num == 0:
print(num)
break
|
05a70298fdcb3c6325c099dc778b614d38e40d18 | Alexey929/web-development | /week8/3.1.Цикл for/h.py | 100 | 3.703125 | 4 | x = int(input())
for num in range(1, x + 1):
if x % num == 0 :
print(str(num)+' ',end=' ') |
22a01f34995ec5e69e7179da1de530cafd338da4 | Alexey929/web-development | /week8/3.1.Цикл for/c.py | 163 | 3.828125 | 4 | import math
a = int(input())
b = int(input())
for num in range(a, b + 1):
if math.sqrt(num) - int(math.sqrt(num)) == 0:
print(str(num) + ' ', end='')
|
5f5106c85c99ffa303151c793d5d490844b92977 | rajatsachdeva/Python_Programming | /UpandRunningwithPython/Working with files/OS_path_utilities.py | 1,241 | 4.125 | 4 | #
# Python provides utilities to find if a path is file or directory
# whether a file exists or not
#
# Import OS module
import os
from os import path
from datetime import date, time , datetime
import time
def main():
# print the name of os
print "Os name is " + os.name
# Check for item existence ... |
f848e3d507aaad9c30b0042a17542dc6225e5945 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/04 Syntax/object.py | 921 | 4.25 | 4 | #!/bin/python3
# python is fundamentally an object oriented language
# In python 3 everything is an object
# class is a blueprint of an object
# encapsulation of variables and methods
class Egg:
# define a constructor
# with special name __init__
# All methods within classes have first argument as self
... |
67c6ec8400f29fb402335ac24fc31bdf4a61c461 | rajatsachdeva/Python_Programming | /HackerRank/Sets/no_idea.py | 901 | 3.8125 | 4 | '''
Created on 09-May-2017
@author: Rajat Sachdeva
'''
'''
There is an array of n integers.
There are also 2 disjoint sets, A and B, each containing m integers.
You like all the integers in set A and dislike all the integers in set B.
Your initial happiness is 0.
For each i integer in the array, if i belongs to A... |
377c78d18db40dd93bd16b65a9a1a4547c508216 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/16 Databases/databases.py | 896 | 4.3125 | 4 | #!/usr/bin/python3
# Databases in python
# Database used here is SQLite 3
# row factory in sqlite3
import sqlite3
def main():
# Connects to database and creates the actual db file if not exits already
db = sqlite3.connect('test.db')
# Interact with the database
db.execute('drop table if exi... |
a60b01fd53794fe99b17297df3a4de865b5eed7a | rajatsachdeva/Python_Programming | /HackerRank/Sets/strict_super_set.py | 748 | 3.953125 | 4 | '''
Created on 10-May-2017
@author: Rajat Sachdeva
'''
'''
You are given one set A and a number of other sets, N .
Your job is to find whether set A is a strict superset of all the N sets.
Print True, if A is a strict superset of all of the N sets. Otherwise, print False.
A strict superset has at least one element ... |
33d9a7cc53d070f8575fa5b3b044edd4eb5e9fe4 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/12 Classes/generator.py | 1,218 | 4.46875 | 4 | #!/usr/bin/python3
# A generator object is an object that can be used in the context of an iterable
# like in for loop
# Create own range object with inclusive range
class inclusive_range:
def __init__(self, *args):
numargs = len(args)
if numargs < 1 :
raise TypeError('Requries at lea... |
01e418b3fb1cb785b6db1d1ee3352678e79498bf | rajatsachdeva/Python_Programming | /UpandRunningwithPython/Working with files/System_shell_methods.py | 1,473 | 3.671875 | 4 | #
# Using System Shell Methods
#
import os
import shutil
from os import path
from shutil import make_archive
from zipfile import ZipFile
def main():
# Make a duplicate of an existing file
if path.exists("textfile.txt"):
# get the path to the file in current directory
src = path.realpath("text... |
b572c312a1314e7048b1f596650a724d215b0a63 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/11 Functions/generator.py | 1,290 | 4.125 | 4 | #!/usr/bin/python3
# Generator functions
def main():
for i in inclusive_range(0, 10):
print(i, end = ' ')
print()
for i in inclusive_range2(18):
print(i, end = ' ')
print()
for i in inclusive_range2(0, 25):
print(i, end = ' ')
print()
for i in inclusive_range2(0, 50... |
d2d7d34fa745243c91ab891f0fdd3e28ba8b16d0 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/14 Containers/dictionary.py | 1,397 | 4.28125 | 4 | #!/usr/bin/python3
# Organizing data with dictionaries
def main():
d1 = {'one' : 1, 'two' : 2, 'three' : 3}
print(d1, type(d1))
# dictionary using dict constructor
d2 = dict(one = 1, two = 2, three = 3)
print(d2, type(d2))
d3 = dict(four = 4, five = 5, six = 6)
print(d3, type(d3... |
f33362d646b39360d8bdc20d346a369fdf7d6a19 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/05 Variables/Finding_type_identity.py | 1,300 | 4.3125 | 4 | #!/bin/python3
# Finding the type and identity of a variable
# Everything is object and each object has an ID which is unique
def main():
print("Main Starts !")
x = 42
print("x:",x)
print("id of x:",id(x))
print("id of 42:",id(42))
print("type of x:", type(x))
print("type of 42:", type(4... |
ad69138dd4b5f05e9ae4da0a694965ab18fb3841 | sshilpika/algorithms | /insertion_sort/src/insertion_sort.py | 291 | 3.9375 | 4 | # Insertion Sort
class InsertionSort:
def sort(a_list):
for i in range(1 , len(a_list)):
key = a_list[i]
j = i-1
while j >= 0 and a_list[j] > key :
a_list[j+1] = a_list[j]
j -= 1
a_list[j+1] = key
|
950300061120ecc6a26437851714e5f1bc129ab8 | paulinajewulska/MOOD | /modules/moviestorage/public/MovieRepository.py | 845 | 3.515625 | 4 | from abc import ABC, abstractmethod
class MovieRepository(ABC):
# Return MovieDetails or null
@abstractmethod
def find_by_id(self, movie_id):
raise Exception("Not implemented")
# Return all MovieDetails
@abstractmethod
def find_all(self):
raise Exception("Not implemented")
... |
fa8c7f9129d5735a17ebc4d68d87b4d388272888 | finnhurley/Diffie_Hellman_Key_Exchange | /Diffie_Hellman/dhCrypt.py | 556 | 3.859375 | 4 | '''
@author Finn Hurley
dhCrypt is a custom library for xor encryption logic
'''
#Function that does a bitwise xor on 2 strings and returns result in bytes
#S1 MUST BE THE COMMON KEY
def strXor(s1, s2):
s1 = str.encode(s1)
s2 = str.encode(s2)
while(len(s1) < len(s2)):
s1 += s1
return (bytes(a ^ ... |
c6c434af9b0c20e2dd5757cd9ee75188e6422674 | llcristianaceroll/retos-mintic-2022 | /reto3a.py | 551 | 3.609375 | 4 | def prueba(n):
nombre_vacunas = ""
vacuna_anterior = ""
contador = -1
numero_vacunas = []
for vacunas in n:
if vacuna_anterior != vacunas:
nombre_vacunas += vacunas + " "
vacuna_anterior = vacunas
contador += 1
numero_vacunas.append(1)
... |
acf80468d987cee82aa7c371aabfada46008652d | piyushgairola/daily_code | /three_equal_parts.py | 1,033 | 3.75 | 4 | """
Date: 22-07-2021
Problem: 927. Three Equal Parts [https://leetcode.com/problems/three-equal-parts/]
"""
def threeEqualsPart(arr):
num_ones = 0
n = len(arr)
for i in arr:
if i == 1:
num_ones += 1
if num_ones == 0:
return [0,n-1]
if num_ones%3 != 0:
retur... |
ed55f3f958a177ee40675fe749f8db2fbdcbf8b1 | piyushgairola/daily_code | /longest_common_subsequence.py | 492 | 3.53125 | 4 | """
Date: 08/07/2021
Problem: 1143. Longest Common Subsequence [https://leetcode.com/problems/longest-common-subsequence/]
"""
def longestCommonSubsequence(text1,text2):
n1,n2 = len(text1), len(text2)
dp = [[0]*(n1+1) for _ in range(n2+1)]
for i in range(1,n2+1):
for j in range(1,n1+1):
... |
79d137cb283148c64fd87e8b4d1c156cf5f8dff6 | piyushgairola/daily_code | /max_subarray.py | 195 | 3.5 | 4 | def maxSubarray(nums):
curr_sum = ans = nums[0]
n = len(nums)
for i in range(1,n):
curr_sum = max(curr_sum+nums[i], nums[i])
ans = max(ans, curr_sum)
return ans |
0c7811a35848e5e978a9422418e6bd172afbd35c | johnhalbert/oso | /languages/python/oso/polar/partial.py | 1,373 | 3.5 | 4 | class Partial:
"""A partial variable."""
def __init__(self, name, *constraints):
self.name = name
self.constraints = constraints
def __repr__(self):
return f"Partial({self.name})"
def __str__(self):
return repr(self)
def __eq__(self, other):
return (
... |
0a0214e921d76e4c688d4cb5a4c93662d1258851 | alexmalko/leetcode | /Arrays/Recursion/PY/FibonacciMemo.py | 290 | 3.703125 | 4 | # fibonacci memoization
def fib(n, cache=None):
if cache is None:
cache = {}
if n in cache:
return cache[n]
if n < 2:
return n
else:
result = fib(n-2, cache) + fib(n-1, cache)
cache[n] = result
return result
print(fib(100))
|
597c4720d688f259a5d102e84e01541fe8c90969 | matsuyu/cpy5p4 | /q2_sum_series2.py | 172 | 4.09375 | 4 | #Summing series
def sum_series2(i):
if i!=1:
return (i/(2*i+1))+sum_series2(i-1)
else:
return 1/3
n=int(input("Enter i:"))
print(sum_series2(n))
|
e9c69e8c2ef93b03b3f73a70d650edf660b2c2e2 | JayceSYH/FactorKeeper | /FactorKeeper/Version/Version.py | 1,244 | 3.59375 | 4 | class Version(object):
def __init__(self, main_version, alpha, beta):
self.main_version = main_version
self.alpha = alpha
self.beta = beta
def __gt__(self, other):
if self.main_version > other.main_version:
return True
elif self.main_version < other.main_vers... |
e5bddac5a91f7b2f0be802048f51e0ab856ea9c8 | lucioeduardo/cc-ufal | /ED/1 - Análise de Algoritmos/q2.py | 259 | 3.796875 | 4 | """
2. Contar o número de elementos negativos em um conjunto
*** Análise ***
Operação principal: condição que define se o numero é negativo
T(n) = n
"""
lista = [1,2,3,-1,-2,4]
cont = 0
for i in lista:
if(i < 0):
cont += 1
print(cont)
|
20a46b2b8f01f34c9cced37bd810309cf4808858 | lucioeduardo/cc-ufal | /APC/Listas/02 - Estruturas de Decisão/q6.py | 783 | 4.125 | 4 | """
Escreva um algoritmo que recebe três valores para os lados de um
triângulo (a,b e c) e decide se a forma geométrica é um triângulo ou não e em
caso positivo, classifique em isósceles, escaleno ou equilátero.
– O valor de cada lado deve ser menor que' a soma dos outros dois
– Isósceles: dois lados iguais e um difere... |
a8f6fd7bcab52d077c71226c79c2de1065a1673e | lucioeduardo/cc-ufal | /APC/Listas/01 - Introdução/q2.py | 232 | 4.0625 | 4 | """
Faça um algoritmo que leia uma temperatura
em graus Fahrenheit e apresente-a convertida
em graus Celsius.
"""
temp_f = float(input("Temperatura em Fahrenheit:"))
temp_c = (temp_f-32)*5/9
print("Temperatura em Celsius:",temp_c)
|
1da02d5615565bef05c534db9ef752ff75a6462c | lucioeduardo/cc-ufal | /ED/2 - Algoritmos de Ordenação/quick_sort.py | 680 | 3.796875 | 4 | def quick_sort(lista, beg, end):
if(beg < end):
v = partition(lista,beg,end)
quick_sort(lista, beg, v-1)
quick_sort(lista, v+1, end)
return lista
def partition(lista, beg, end):
pivot = lista[beg]
print(beg,pivot,lista[beg])
left = beg-1
right = end+1
while left < ... |
6403406d601b953afb3e1404aa8d3716a3f853a0 | lucioeduardo/cc-ufal | /APC/Listas/03 - Estruturas de Repetição/q4.py | 254 | 3.84375 | 4 | """
Faça um programa programa que recebe um conjunto de
inteiros e conta quantos elementos maiores que n existem no
conjunto
"""
lista = [1,20,31,14,85,6,17,6,9,25]
n = int(input())
cont = 0
for i in lista:
if(i > n):
cont+=1
print(cont)
|
6894fb4773a2232111ca38eaa533beb4320a16c4 | lucioeduardo/cc-ufal | /ED/6 - Hash Tables/hash_table_list.py | 694 | 3.765625 | 4 | class HashTable():
def __init__(self, size):
self.size = size
self.table = [None]*size
def hash(self, key):
return key % self.size
def insert(self, key):
idx = self.hash(key)
if(self.table[idx] == None):
self.table[idx] = []
self.table[i... |
26a4f95cdc3ebcf2bfa6aaf542aee977c67c0c00 | lucioeduardo/cc-ufal | /APC/Listas/02 - Estruturas de Decisão/q2.py | 400 | 3.984375 | 4 | """
2. Faça um programa que leia a idade de uma pessoa e
imprima sua categoria:
– Criança, se menor de 14 anos
– Adolescente, se entre 14 e 17 anos
– Adulto, se entre 18 e 59 anos
– Idoso, se maior que 60 anos
"""
idade = int(input("Idade:"))
if(idade < 14):
print("Criança")
elif(idade <= 17):
print("Adolescen... |
2dd78a477cee2db1ed0ff3989d4ff99661c7fa17 | lucioeduardo/cc-ufal | /ED/1 - Análise de Algoritmos/q5.py | 323 | 3.640625 | 4 | """
5. Copiar uma lista de inteiros, retirando elementos repetidos
*** Análise ***
Operação principal: comparação j == i
T(n) = n²
"""
conj = [1,2,2,5,2,8,3,4,1,9]
copy = []
for i in conj:
flag = True
for j in copy:
if j == i:
flag=False
if(flag):
copy.append(i)
print(copy)
|
5464a614b6b02186a9139bf6aab72f279ea78099 | lucioeduardo/cc-ufal | /APC/Listas/04 - Funções/q6.py | 609 | 4.25 | 4 | """
6. Percebendo que o método anterior de cálculo
de notas foi muito severo, o professor decidiu
mudar o formato do cálculo. A nova fórmula foi:
– Nota = (nota/max)*10
– Faça um programa para calcular as notas dos
alunos segundo essa nova regra, utilizando
funções
"""
def maior(lista):
res = lista[0]
for i in... |
cd6e6fe998cc54d4710ccdb0f75e5f24bada8d73 | hwang033/geeksforgeeks | /Search_in_an_almost_sorted_array.py | 599 | 3.984375 | 4 | import pdb
def binarySearch(arr, l, r, target):
while l <= r:
mid = l + (r - l)/2
#print mid
#pdb.set_trace()
if mid - 1 >= 0 and arr[mid - 1] == target:
return mid - 1
if mid + 1 <= r and arr[mid + 1] == target:
return mid + 1
... |
fcb835ef447fd697ce1c1fd8fdd733e2b3538d2a | luvforjunk/Python | /Python/211020.py | 1,697 | 3.65625 | 4 | import sys
import keyword
print (3+2)
print ("Hello World") # '문자열' 또는 "문자열"
print('-' * 30) # '-' 30번 반복
print(4 + 5)
print(12 - 32)
print((4 + 5) * 6)
print(4 + 5 * 6)
print(9 / 5)
print(9.0 / 5.0)
print(9 / 5.0)
print('-' * 30)
print(sys.version)
print()
print(sys.version_info)
print('-' * 30)
print(keyword.kw... |
f3e67816ebb9fa34b5c00cadebf404b523d765b2 | TTTriplicate/EG-426-hw-3 | /problem4.py | 1,057 | 3.59375 | 4 | import numpy as np
import math as m
def wheelSpeeds():
return
def robotVelocities(radius, arc, time):
angular = robotAngular(arc, time)
forward = robotForward(angular, radius)
print("Robot's angular momentum is", round(angular, 4), "radians per second.")
print("Forward velocity is", round(forward,... |
a9a1e6045d4a0ba4ff26f662bfc670c4ae007693 | alvintangz/pi-python-curriculum | /adventuregame.py | 745 | 4.34375 | 4 | # Simple adventure game for day 3.
hero = input("Name your hero. ")
print("\n" + hero + " has to save their friend from the shark infested waters.")
print("What do they do?")
print("A. Throw a bag of salt and pepper in the water?")
print("B. Drink up the whole ocean?")
print("C. Do nothing.\n")
option = input("What do ... |
daa18a7946e3c11aedc1961bdb77e13b700ebc4a | danieljustice/AI-Search | /MonitorProblem.py | 4,732 | 3.640625 | 4 | from problem import Problem
import math
from ast import literal_eval as make_tuple
class MonitorProblem(Problem):
def __init__(self, sensors, targets):
self.sensors = make_tuple(sensors)
self.targets = make_tuple(targets)
self.initial = [0 for sensor in self.sensors]
self.time = 0
... |
c479cb503ce5998135dabc16c74e849b71c26729 | kangli-bionic/Microsoft | /main.py | 2,014 | 3.703125 | 4 | # This is a sample Python script.
from typing import List
import math
class Solution:
def equalDistance(self, points: List[List[int]], k: int):
if not points: return None
dis_sum, dis_segment = self.distanceSum(points)
print(dis_sum, dis_segment)
L = dis_sum / k
res = []
... |
be170bd98b85f41ac3e5b65667b9271a3a9bd108 | dsl16/Algorithms | /Fibonnaci.py | 455 | 3.71875 | 4 | # Uses python3
"""
Created on Fri Mar 3 17:17:03 2017
@author: Darrin Lim
"""
import time
def clock(function,*args):
t1 = time.time()
answer = function(*args)
t = time.time() - t1
return answer, t
def calc_fib(n):
if n <= 1:
return n
a = 0; b = 1;
for i in range(n-1):
an... |
8ca0ed2176a8dac59fd50ae330c278b1cf649ac1 | jzaunegger/PSU-Courses | /Spring-2021/CSE-597/MarkovChains.py | 1,804 | 4.3125 | 4 | '''
This application is about using Markov Chains to generate text using
N grams. A markov chain is essentially, a series of states, where each state
relates to one another in a logical fashion. In the case of text generation,
a noun phrase is always followed by a verb phrase.
Lets say we ha... |
dc2bb93642a3e2f0b6564f7bb03cde64ac2794c5 | zeeshan606115/Sorting-Algorithms | /selectionSort.py | 392 | 3.75 | 4 | def selectionSort(l):
for i in range(len(l)):
min_value_index = i
for j in range(i+1, len(l)):
if l[j] < l[min_value_index]:
min_value_index = j
l[i], l[min_value_index] = l[min_value_index], l[i]
return l
numbers = input("Enter multiple number with space: ")
numbers = numbers.split()
n... |
a5f2afa465eda44d795f7808308eafe234bb38bd | sumapapudippu/demo | /exceptionhandlng.py | 497 | 3.78125 | 4 | print("Hai")
#print(10/0)
try:
print(10/0)
#xcept ZeroDivisionError as msg:
except (ZeroDivisionError,ValueError) as msg:
print("exception raised :",msg)
#exception raised not raised handled or not handled
finally:
print("Hello")
#2 example
try:
print('try')
print(10/0)
except:
print('except')
finally:
... |
31189612cc83b8c3a7ce8b4c1aba7ce1cff65690 | sumapapudippu/demo | /nested_dict.py | 1,437 | 3.640625 | 4 | def evaluate_it():
"""
this function evaluates a dictionary of rules and returns a list
of enabled rules to execute in order of priority
param: x:
"""
rules = {
'move':
{
'description': 'move the file',
'fname': 'move_file',
'completion_... |
302f49ce89ab7711cff4ca0d61c020c55faa0f4a | sumapapudippu/demo | /dictionary/ordered_dict.py | 341 | 3.8125 | 4 | from collections import OrderedDict
d={'banana':3,'apple':4,'pear':1,'orange':2}
#print(sorted(d.items(),key=lambda t:t[0]))
print(OrderedDict(sorted(d.items(),key=lambda t:t[0])))
#print(sorted(d.items(),key=lambda t:t[1]))
print(OrderedDict(sorted(d.items(),key=lambda t:t[1])))
print(OrderedDict(sorted(d.items(),key=... |
ca8b96364e9afc89c5a2dfcd6a6480f160d209e3 | OlivettiGiovanni/Software_git | /Software_codes/testlesson2.py | 6,036 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 12 16:18:51 2021
@author: Giovanni Olivetti
"""
#%% UNIT TEST - pytest usage
# Instead of simply running the code on my shell and lose the results the next times
# I can start to compoand this in a more specific test
# for every functionality that my function is suppos... |
daf8a677a1166b01325c74329d6377acc0a868c5 | xudong-li/machine-learning-algorithms | /1_Linear_Regression/linear_regression.py | 3,224 | 3.625 | 4 |
import numpy as np
###############################################
## Function 1: Plain version of Gauss Jordan ##
###############################################
def myGaussJordan(A, m):
"""
Perform Gauss Jordan elimination on A.
A: a square matrix.
m: the pivot element is A[m, m].
Returns a matri... |
1dbbe6ed488e4b1fef5e1a7d7b6a3b072ac2a905 | kbroestl/utilscripts | /py/weekdays.py | 484 | 3.625 | 4 | #! /usr/bin/env python
import datetime as dt
def infdays(start=None):
cur = start if start else dt.datetime.today()
while True:
cur = cur + dt.timedelta(days=1)
yield cur
def due_date(num_days, start=None):
due_date = None
weekdays = (d for d in infdays(start) if d.weekday() < 5)
for i in range(0, ... |
d78e3f934557f2ca704205a350e6a97b11a63255 | ShivamThukral/Modelling-Human-Behaviour-in-Chess | /project/pytorch/models.py | 12,660 | 3.609375 | 4 | """
Model definitions.
Models take a tuple of (board features, stockfish evaluation features, move features) as inputs:
- Board features: details about the game, the current board, and the previous move
- Stockfish evaluation: breakdown of Stockfish's static evaluation of the current position
- Move features: list of ... |
d40667fb210b8e1dda557ed7ccdda268ad82238d | mleong245/project-euler | /01.py | 252 | 3.640625 | 4 | def multiples(below, *args):
multiples = []
sum = 0
for i in range(1, below):
for j in range(len(args)):
if i % args[j] == 0:
if i not in multiples:
multiples.append(i)
for i in range(len(multiples)):
sum += multiples[i]
return sum |
f406fb96d06a8e17d99b8c3d9ac0a90099f8005d | JOHONGJU/johongju | /Quiz6.py | 383 | 3.71875 | 4 | def std_weight(height, gender): #키 = m단위(실수), gender = "남자"/"여자"
if gender == "남자":
return height * height * 22
else :
return height * height * 21
height = 175 # cm단위
gender = "남자"
weight = round(std_weight(height/ 100, gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2}kg입니다".format(height, gender, ... |
f822ae047d2d87eb6dd7311ee4093ebe41dc62d0 | aserdega/VMI-VAE | /test_plot_temperature.py | 470 | 3.53125 | 4 | import numpy as np
from matplotlib import pyplot as plt
'''
tau0=1.0 # initial temperature
np_temp=tau0
ANNEAL_RATE=0.000007#0.000015
MIN_TEMP=0.5
step = 1500
iters = 150000
X = np.array(range(0,iters))
Y = np.zeros(iters)
for i in range(iters):
if i % step == 1:
np_temp=np.maximum(tau0*np.exp(-ANNEAL_RATE*i),MI... |
1eadaf03b3025654a3837a4adb16391e1d0b1e5a | stali1234/python_-practice_-program | /fiel.py | 434 | 3.71875 | 4 | def target_string(filename, target):
try:
fh = open(filename, "r+")
gh = fh.read()
lis = gh.split()
except Exception as a:
print(a)
finally:
count = 0
for i in lis:
if i == target:
count = count + 1
print(count)
pr... |
837cf25336dda610c1ad0207a722cda9289a0a17 | motraor3/NBA_Data_Analytics | /clean.py | 5,017 | 3.53125 | 4 | # Project Phase 2
# Basic Statistical Analysis and data cleaning insight
import numpy as np
import pandas as pd
from scipy import stats
salary_src_file = 'salary_src.csv'
salary_dst_file = 'salary_dst.xlsx'
player_src_file = 'player_src.csv'
player_dst_file = 'player_dst.csv'
player_career_src_file = 'player_career_sr... |
0505da63e8d3159393ec7d0a28a94be9e4ca5b13 | silahi/deeplearningalgos | /RegressionLogistique.py | 2,715 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 26 17:13:01 2021
@author: silahi
"""
import numpy as np
from sklearn.datasets import load_iris
from matplotlib import pyplot as pp
pp.style.use('ggplot')
# Loding iris data
iris = load_iris()
data = iris['data']
target = iris['target']
labels = iris['ta... |
b89de1808c727f5d5f682133afa0821651fa3072 | renaldystw/Renaldy-FundamentalJCDS03 | /soal1-Renaldy.py | 426 | 3.5625 | 4 | # -------------------1-----------------------------
p0 = 1500000
percent = 2.5
aug = 10000
p = 2000000
def nb_year(p0, percent, aug, p):
looping = True
tahun = 0
percent = percent / 100
while looping == True:
calculate = p0 + (p0*percent) + aug
p0 = calculate
tahun += 1
... |
7a272f89adf73468f8378b30881f1b63922b0709 | davidbj/cookbook | /python/python3.x/数据结构/stack.py | 845 | 3.859375 | 4 | class Node:
'''创建一个元素节点'''
def __init__(self, data):
self.data = data
self.next = None
class Stack:
'''实现栈的具体功能.
首先定义一个栈顶,每次push的时候,将新元素节点定义为栈顶.pop的时候,将栈顶的元素pop出来,将栈顶更改为它的 next元素节点.
'''
def __init__(self):
self.top = None
def push(self, data):
no... |
25f52799837dcd2971792d171cc3fe6c7a1700df | JosifV/shadow_mod_app | /server/db_create_table.py | 721 | 3.53125 | 4 | import psycopg2
def db_create_table(query):
#Establishing the connection
conn = psycopg2.connect(
database="tut_db", user='postgres', password='Jozhe$$$1987', host='127.0.0.1', port= '5432'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Doping users... |
28bf44989f72a0a9c14d5a34bb1068437800c72a | mustail/Election_analysis | /practice/python_practice2.py | 1,711 | 4.46875 | 4 | # python practice continued
print("Hello world.")
print("Arapahoe and Denver are not in the list of counties.")
# printing with f string
my_votes = int(input("How many votes did you get in the election?"))
total_votes = int(input("What is the total number of votes in the election?"))
percentage_votes = (my_votes/t... |
b355a1337df1ab5ca736489b4ba13f302b28e1c7 | ItsMeVArun5/Hakerrank | /problem_solving/queenAttack-2.py | 4,651 | 3.84375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Calculating slope.
def getSlope(x1, y1, x2, y2):
if ((y2 - y1) == 0 or (x2 - x1) == 0):
return 0
return (y2 - y1)//(x2 - x1)
# Calculating distance.
def getDistance(x1, y1, x2, y2):
# dist = math.sqrt((x2 - x1)**2 + (y2 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.