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
e8a5411cedb4dad3a1946f7d38a691b198d95afd
baranmcl/HackerRank_Solutions
/Algorithms/Sorting/Insertion_Sort_Part_II/Insertion_Sort_Part_II.py
357
3.546875
4
def insert(s): for i in range(1, len(s)): val = s[i] j = i - 1 while (j >= 0) and (s[j] > val): s[j+1] = s[j] j = j - 1 s[j+1] = val print(*s, sep=" ") if __name__ == '__main__': a = int(input()) b = input() b = b.strip().split() b...
f6e27fe36b0440ee35b2cc2cd1943384d30d6190
grapheo12/decision-tree
/tests/test_learner.py
1,096
3.609375
4
import pandas as pd from dtree.learner import entropy, id3Categorical from dtree.api import plot def test_entropy(): df = pd.read_csv("tests/test.csv") print(df) print(entropy(df["Pclass"], list(range(1, 100)))) def test_id3Categorical(): df = pd.read_csv("tests/test.csv") y = df["Pclass"] X...
11a66ef9bd846c63e294dd87a34ac1c7e91072e1
d0dders/phrase-hunter
/phrasehunter/game.py
2,576
3.625
4
from phrasehunter.phrase import Phrase import random class Game: STARTING_LIVES = 5 def __init__(self): self.missed = 0 self.phrases = [Phrase('A New Hope'), Phrase('The Empire Strikes Back'), Phrase('Return of the Jedi'), ...
75b6079cf4f3ffebb97d2e0a786cfffd6d529ea6
SaifulAbir/bongo-python-test
/src/task_2.py
1,108
3.890625
4
class Person(object): def __init__(self, first_name, last_name, father): self.first_name = first_name self.last_name = last_name self.father = father def print_depth(data, depth=0): if type(data) is Person: print_family_info(data.__dict__, depth) elif isinstance(data, dict)...
d9acb35b8fd9aefc6b7b67952924105ea7db4e48
Prathamesh247/WeatherProject
/weather.py
2,362
3.78125
4
# -*- encoding: utf-8 -*- """ Spyder Editor and VS Code Editor """ import requests, json from tkinter import * from tkinter import messagebox from config import API_KEY degree_sign= u'\N{DEGREE SIGN}' def check(): # Take city name as input cityname = name.get() # Error for blank entry ...
14c6649f7403073328d07ed9f8394e6004be2ff1
DewsDavid31/CS4050PythonVsSwift
/assign2-DewsDavid31.py
8,844
4.4375
4
""" Assign 02 - David Dews Directions: * Complete the sorting algorithm functions that are given below. Note that it okay (and probably helpful) to define auxiliary/helper functions that are called from the functions below. Refer to the README.md file for additional info. * NOTE: Remember t...
b00baec7032a4cd3d1b5345fc899ac69b886420f
loc-trinh/Graphics
/Fractals/Dragon.py
1,440
3.828125
4
import Tkinter as tk from math import cos, sin, pi class Point(): def __init__(self, x, y): self.x = x self.y = y def __sub__(self, other): return Point(self.x-other.x, self.y-other.y) def __add__(self, other): return Point(self.x+other.x, self.y+other.y) def __rmul__(self, n): return Point(n*self.x, ...
4c72c3c82fb64814b6139d0f57c0444a8fe829ae
ThiagoN13/Game-of-Python
/playForca.py
1,288
3.6875
4
from jogo import limpaTela from ranking import * from regras import regras limpaTela() print("===================================================") print("\n") print("======= TECLE ENTER PARA COMEÇAR O JOGO ! =========") print("\n") print("===================================================") input() limpaTela() de...
4e98f2a6239f98cef70e976e145d8b22e5d05bf7
Ionuut08/Password-manager
/encryption.py
1,155
3.5625
4
import hashlib from itertools import cycle from random import randint def encrypt_password(plain_text, password): encoded_password = bytes(password, 'utf-8') hashed_password = hashlib.md5(encoded_password).hexdigest() addition_char = randint(0, 0x100) if len(plain_text) > len(hashed_password): ...
1e8befcc64709ffaf40cd265fec8810c44d146af
tahsin-github/ml-algorithms-python-numpy
/1. Codes/naive_bayes_classifier.py
3,400
3.5625
4
# Training of the model. def train_naive_bayes(train_data, label): """ Input: 1. train_data: the train data with the label column. The data must be in 2d array(not matrix). 2. label: the column index of the label in the train_data Output: 1. mean: the mean vector of the features in di...
2ff4e164e15623a045036ad189bfab2280086e68
kpatel1293/CodingDojo
/DojoAssignments/Python/PythonFundamentals/Assignments/12_ScoresAndGrades.py
907
4.375
4
# Assignment: Scores and Grades # Write a function that generates ten scores between 60 and 100. # Each time a score is generated, your function should display what the grade # is for a particular score. # Here is the grade table: # Score: 60 - 69; Grade - D # Score: 70 - 79; Grade - C # Score: 80 - 8...
fac7cceb04d13dc68e238e969a306522b51c73e9
kpatel1293/CodingDojo
/DojoAssignments/Python/PythonFundamentals/Assignments/9_FooBar.py
1,623
4.1875
4
# Optional Assignment: Foo and Bar # Write a program that prints all the prime numbers and all the perfect # squares for all numbers between 100 and 100000. # For all numbers between 100 and 100000 test that number for whether # it is prime or a perfect square. If it is a prime number, print "Foo". # If it is a pe...
309807d9d91dd5beb10bd5e22c9a0806eed71f0b
m358807551/Leetcode
/code/questions/251~260/253.py
549
3.515625
4
""" https://leetcode-cn.com/problems/meeting-rooms-ii/ """ class Solution(object): def minMeetingRooms(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ arr = [] for interval in intervals: arr.append((interval[0], 1)) arr...
f50b72972436d03a3f34fb5c2a89763f7288dbd2
m358807551/Leetcode
/code/questions/101~200/151~160/156_收费.py
1,033
3.9375
4
""" https://leetcode-cn.com/problems/binary-tree-upside-down/ 给定一个二叉树,其中所有的右节点要么是具有兄弟节点(拥有相同父节点的左节点)的叶节点,要么为空, 将此二叉树上下翻转并将它变成一棵树, 原来的右节点将转换成左叶节点。返回新的根。 例子: 输入: [1,2,3,4,5] 1 / \ 2 3 / \ 4 5 输出: 返回二叉树的根 [4,5,2,#,#,3,1] 4 / \ 5 2 / \ 3 1 说明: 对 [4,5,2,#,#,3,1] 感到困惑? 下面详细介绍请查看 二叉树是如何被序...
3e0156e98ac4f92b8e65883bd11fe1a1bbb2c4e1
m358807551/Leetcode
/code/questions/291~300_/295.py
1,083
3.625
4
""" https://leetcode-cn.com/problems/find-median-from-data-stream/ """ from heapq import heappush, heappop class MedianFinder(object): def __init__(self): """ initialize your data structure here. """ self.h1 = [] self.h2 = [] def addNum(self, num): """ ...
fddf5605f9248653635937679d23f25f2e16274e
m358807551/Leetcode
/code/questions/1~100/16~20/20.py
539
3.6875
4
""" https://leetcode-cn.com/problems/valid-parentheses/ """ class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ d = {')': '(', ']': '[', '}': '{'} stack = [] for letter in s: if letter in d.values(): st...
35dc688d3008f0ab4a702ba81eea4194eb419b16
m358807551/Leetcode
/code/questions/281~290_/283.py
538
3.734375
4
""" https://leetcode-cn.com/problems/move-zeroes """ class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ left = 0 for right in range(len(nums)): if nums[righ...
d589968a2c230c4535ea1faeb3e49d81ca6f0c43
m358807551/Leetcode
/code/questions/271~280/275.py
619
3.703125
4
""" https://leetcode-cn.com/problems/h-index-ii """ class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ left, right = 0, len(citations)-1 while left < right: mid = left + (right-left) // 2 if ci...
2f22b0cb40f601376432de2ebb3435851e2a263b
m358807551/Leetcode
/code/questions/251~260/257.py
913
3.890625
4
""" https://leetcode-cn.com/problems/binary-tree-paths/ """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type...
ff71dea0fdd8146d09acfc3e2a02ae79f94935a7
m358807551/Leetcode
/code/questions/281~290_/282.py
1,040
3.546875
4
""" https://leetcode-cn.com/problems/expression-add-operators/ """ class Solution(object): def addOperators(self, num, target): """ :type num: str :type target: int :rtype: List[str] """ self.rst = [] self.target = target self.backtrace('', num) ...
6a4b24021cf78f2a3cc434ec8621e46e064dc950
m358807551/Leetcode
/code/questions/231~240_/231.py
259
3.78125
4
""" https://leetcode-cn.com/problems/power-of-two """ class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ return n > 0 and n & (n-1) == 0 print( Solution().isPowerOfTwo(0) )
a3b664d4fa3abcccc3cd93690ffe40b053ccf044
prkhrv/mean-day-problem
/meanday.py
1,050
4.53125
5
""" Mean days Problem: You are given a list with dates find thee mean day of the given list Explanation: Given that the range of day values are 1-7 while Monday = 1 and Sunday = 7 Find the "Meanest Day" of the list . "Meanest Day" is the sum of values of all the days divided by total number of days For Example:- ...
f9dd0432a7cb2b4563bdca02c9d53d3696bd835c
n-anw/python-playground
/superheroes.py
1,060
3.609375
4
# Nick Anway # import packages import json import csv # read json file to superheroes variable with open('superheroes.json', 'r') as f: superheroes = json.load(f) # write the header row into a new csv file with open('superheroes.csv', 'w') as f: writer = csv.writer(f) headers = ["name", "age", "secretIdentity"...
9057a694d1d4364cbf0e027e5642f5b10b69c0ca
m50/college-work
/c1114 - Intro to Programming/labs/rec08/colourStuff.py
471
3.8125
4
import random def pickRandomColour( ): ''' PARAMETERS: none RETURNS: string DESCRIPTION: Picks a random color from colours. ''' rand = random.randint( 0, 7 ) if rand == 0: return "red" elif rand == 1: return "orange" elif rand == 2: return "yellow" elif rand == 3: return "green"...
b2469ef60c3af42745eb04092ecc03f50f64fbd0
m50/college-work
/c1114 - Intro to Programming/homework/hw00.py
2,454
3.90625
4
#!C:\python27\python.exe ''' cs1114 Submission: hw00 Programmer: Marisa Clardy purpose of program, assumptions, constraints: To answer questions about the class, found on the website, with python. ''' #Get the OS module to pause import os #Answer all the questions def main(): print( "-> What is you...
8c621a9fbd7af69032ebced9f949096542be2b87
fengyu0712/myclone
/python_space/1.py
607
3.5
4
# def result(score): # if score.isdigit(): # if score >=0 and score<60: # print ("输入成绩不及格") # elif score >=60 and score <80: # print ("输入成绩及格") # elif score >=80 and score <=100: # print ("输入成绩为优秀") # else: # print ("输入成绩无效") # else...
41ef17654f3f9430337db2e55626c68f70b662d9
dhruv-colosus/SCHOOL-LEVEL-PROJECTS
/NASA HACK.py
1,043
3.515625
4
import math import random #Lets Hack Nasa IP ="2e89239e23cn389e2389e82r7" iii=0 DNS_PROTOCOL="HACKING NASA" l1=[1,2,3,4,5,6,7,8,9,"a","D","G","g","B","c","!","$","&",";","(",")"] print("-------------------------NASA HACKING IN PROCESS----------------") print("----------------------GETTING IP AND DNS FROM THEIR SQL SERV...
174edd7f447043e733fa9c1c7d5adad4632038d9
dhruv-colosus/SCHOOL-LEVEL-PROJECTS
/patterns.py
87
3.578125
4
print("Hey NOOBSS, Here are some patterns") i=1 while i<=5: print("*"*i) i=i+1
84fb52ae71819a3a9914d4cc42fb01f47a816e54
lisu1222/towards_datascience
/frequency_table.py
388
4.03125
4
''' creating a frequency table ''' from collections import Counter def frequency_table(numbers): table = Counter(numbers).most_common() print('Number\tFrequency') for num in table: print('{0}\t{1}'.format(num[0],num[1])) if __name__ == '__main__': scores = [7, 8, 9, 2, 10, 9, 9, 9, 9,...
61895160c36dbfbaafb426cfdbdecc280d6475c9
lisu1222/towards_datascience
/jumpingOnClouds.py
1,833
4.28125
4
""" Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of...
486f1bded5859f347ec0da35f5d69f77e9b86d92
lisu1222/towards_datascience
/binary_search.py
370
3.9375
4
def binary_search(l, item): low = 0 high = len(l) - 1 while low <= high: mid = (low + high) // 2 guess = l[mid] if guess == item: return mid if guess < item: low = mid + 1 else: high = mid -1 return None if __name__ == "__main__": my_list =[1,3,5,6,9] print (my_list) print (binary_search(...
cdd51cb29bed43de203fbbd2ad0ec891bb85c8a5
hhy5277/LeetCode-9
/058_最后一个单词的长度/Solution.py
430
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/5/5 21:29 # @Author : zenRRan # @Version : python3.7 # @File : Solution.py # @Software: PyCharm class Solution: def lengthOfLastWord(self, s: str) -> int: s = s.strip().split() if s == []: return 0 return len(...
736e0707563726542644738f2be060ccf3dd93c8
hhy5277/LeetCode-9
/024_两两交换链表中的节点/Solution.py
726
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/4/10 21:38 # @Author : zenRRan # @Version : python3.7 # @File : Solution.py # @Software: PyCharm # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def s...
19ef05150369da8748d52c530d1e6536030e454b
hhy5277/LeetCode-9
/069_x的平方根/Solution.py
589
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/5/5 21:41 # @Author : zenRRan # @Version : python3.7 # @File : Solution.py # @Software: PyCharm class Solution: def mySqrt(self, x: int) -> int: if x == 0 or x == 1: return x l = 1 r = x while l <= r: ...
aa8890612c27658fe0a5e2b75cf6eb067305279d
hhy5277/LeetCode-9
/094_二叉树的中序遍历/Solution.py
597
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/4/17 21:34 # @Author : zenRRan # @Version : python3.7 # @File : Solution.py # @Software: PyCharm # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.rig...
01c591c32142f0cb206fbee55375e77ee798121e
momentum-cohort-2019-02/w2d3-word-frequency-rob-taylor543
/word_frequency.py
1,769
4.125
4
STOP_WORDS = [ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he', 'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were', 'will', 'with' ] import string def clean(file): """Read in a string and remove special characters and stop words (keep spaces). Return the r...
e28296ad3771ac155d68f9d5e8dd7527c96c24b7
vivekshingate/feature_engineering_project
/q04_encoding/build.py
796
3.5
4
# %load q04_encoding/build.py # Default imports import pandas as pd from sklearn.preprocessing import LabelEncoder ny_housing = pd.read_csv('data/train.csv') housing_data = ny_housing[['MasVnrArea', 'GrLivArea', 'LotShape', 'GarageType', 'SalePrice']] # Write your code here: def encoding(dataset): #Label En...
eb7b36611800983547b94f0444a0a980bb354b0e
Mohan1387/DataStructureAlgo
/DsAlgo/sorting.py
1,683
4.0625
4
#Bubble Sort def bubble_sort(lt): temp = 0 for i in range(0,len(lt)-1): for j in range(0,len(lt)-1-i): if lt[j] > lt[j+1]: temp = lt[j] lt[j] = lt[j+1] lt[j+1] = temp return lt #Selection Sort with execution prints def selection_sort(lt): for...
016d3c340a4e30bbee8f7fbc621a5823eeccec4c
hemanth/android-py
/android-sms.py
846
3.734375
4
"""Send jokes to your loved ones""" __author__ = 'Hemanth H.M <hemanth.hm@gmail.com>' __copyright__ = 'Copyright (c) 2010, h3manth.com.' __license__ = 'Apache License, Version 2.0' import urllib2 import json import android """ URL to fetch a random joke """ JOKES_URL = 'http://api.icndb.com/jokes/random' """ List...
fb68e1655248613b97e50349cd968bad85fd5209
Navaneeth311/prcat
/array2.py
723
3.6875
4
string_count = int(input("Enter the number of strings = ")) strings = [] for _ in range(string_count): string_items = input("Enter strings = ") strings.append(string_items) query_count = int(input("Enter the query count = ")) query = [] for _ in range(query_count): query_item = input("Enter the quries = ...
f1e8442afb9877249caa677d0f816c2be5e7c39e
legalrick2/CS235FlixWebsite
/skeleton/domainmodel/genre.py
1,652
3.578125
4
class Genre: def __init__(self, inigenreName: str): if inigenreName == "" or type(inigenreName) is not str: self._genreName = None else: self._genreName = inigenreName.strip() @property def genre_name(self) -> str: return self._genreName def __repr...
52a27d2fce14eaf1bd8459ccd236cca7f94cebb5
jigi-33/checkio
/end_zeros.py
566
3.53125
4
def end_zeros(num: int) -> int: lst = [int(i) for i in str(num)] a = 0 while len(lst) != 0: if lst[-1] == 0: a += 1 lst.pop() else: break return a if __name__ == '__main__': print("Example:") print(end_zeros(0)) asser...
7094f9f8b425948b14600d1e5d53ef304156e198
jigi-33/checkio
/digits_multiplication.py
558
3.6875
4
def checkio(number: int) -> int: lst = [int(num) for num in str(number)] a = 1 for i in lst: if i != 0: a = a * i return a if __name__ == '__main__': print('Example:') print(checkio(123405)) # These "asserts" using only for self-checking and not necess...
92b2fbc0a7b48b7531146a05bb19b13736734901
jigi-33/checkio
/common_words.py
493
3.78125
4
def checkio(first, second): lst_1 = first.split(',') lst_2 = second.split(',') lst_3 = [] for i in lst_1: if i in lst_2: lst_3.append(i) return ','.join(sorted(lst_3)) if __name__ == '__main__': assert checkio("hello,world", "hello,earth") == "hello", "Hello"...
51a34231ffddac2ac4a554f46d38e2947809238e
AdityaSP/ora-py-jun25-28
/proj25-27/csvhandling.py
187
3.59375
4
import csv # fh = open('data.csv') # for line in csv.reader(fh): # print line # fh.close() with open('data.csv') as fh: for line in csv.reader(fh): print line
4b80272294fd4c1b8e74241b0ad91973a63b4a44
AdityaSP/ora-py-jun25-28
/proj25-27/inh.py
687
3.578125
4
# HB is inheriting from LB # HB.breathe overrides LB.breathe class LB(object): def breathe(self): print "I breathe" class HB(LB): def breathe(self): # like a super call LB.breathe(self) print "Through lungs" def metathink(self): print "I think therefore...
6dbdc0aec155836ff9f62a66e7ce0dcda97b4c1d
lbarrios/practicas-programacion-competitiva
/a2oj/2017-09-02_2/balloons.py
445
3.625
4
#!/usr/bin/env python3 T = int(input()) for t in range(T): N, c_easy, c_hard = map(int, input().split()) colors = list(map(int, input().split())) easy_ok = True hard_ok = True if colors[0]==c_easy: easy_ok = False if colors[-1]==c_hard: hard_ok = False if easy_ok and hard_ok: print("OKAY") if easy_ok a...
fa9aaa4468b1cb52c18f12eed42fd6d2283f89e4
lbarrios/practicas-programacion-competitiva
/old/ej2/src/argsparser.py
625
3.609375
4
import argparse parser = argparse.ArgumentParser(description='''Given a size N and i,j positions this program outputs the movements corresponding to a closed "Knight Tour" from a (i,j) starting position on a NxN board.''') parser.add_argument('N', type=int, help='The size of the board') parser.add_argument('i', ty...
a7bb27b2aae94fcd16a93fd415ff716f319ec39a
victor-felipe-code/projetos_trybe
/project_algorithms/challenges/challenge_palindromes_recursive.py
810
3.953125
4
def change_letter(low_index, high_index, word): word_1 = list(word[1]) temp = word_1[low_index] word_1[low_index] = word_1[high_index] word_1[high_index] = temp low_index += 1 high_index -= 1 word_1 = str("".join(word_1)) word[1] = word_1 return low_index, high_index, word def is_p...
cb63929079692ed0205ab82893bd39bf4e9f82ed
yayapa/MARS-Praktikum
/a1/cagd/vec.py
2,426
3.640625
4
#!/usr/bin/python import math class vec3: def __init__(self, a, b, c): self.x = a self.y = b self.z = c def __str__(self): return "(" + str(self.x) + "," + str(self.y) + "," + str(self.z) + ")" def __add__(self, other): return vec3(self.x + other.x, self.y + oth...
7a6b1d965c351fdb9636aadffdb1ee4cbd0a8d3c
jimin4017/python_project
/gui_basic/3_label.py
766
3.5625
4
from tkinter import * root = Tk() root.title("jimin project") ## 콘솔창 이름 설정 root.geometry("640x480+100+300") ## tkinter에서 콘솔 크기 설정가로 * 세로 ## + " x,y" 좌표 label1 = Label(root,text=" 안녕하세요") label1.pack() # photo = PhotoImage(file="C:/Users/정지민/Desktop/python_project/python_proj...
cec4b8438e743ddce8a680a2d4791b3e75dcbb93
Nas-Islam/qa-python-exercises
/programs/gradecalc.py
687
4.21875
4
def gradeCalc(): print("Welcome to the Grade Calculator!") mathsmark = int(input("Please enter your maths mark: ")) chemmark = int(input("Please enter your chemistry mark: ")) physicsmark = int(input("Please enter your physics mark: ")) percentage = (mathsmark + chemmark + physicsmark) / 3 if p...
d0402a757ccb537d9916f827f061d2e55ea696e1
Dex4n/avaliacao-linguagem-II-n1
/ex_02.py
1,568
4.40625
4
#2 - Crie um classe Funcionário com os atributos nome, idade e salário. Deve ter um método aumenta_salario. # Crie duas subclasses da classe funcionário, programador e analista, implementando o método nas duas subclasses. # Para o programador some ao atributo salário mais 20 e ao analista some ao salário mais 30, mo...
1723434ad5883c87dd75d5f14bab80cc874aa52b
SIMAABAMIR/yfinance
/yahoo_finance_python.py
1,082
3.5625
4
import requests import json from requests.exceptions import HTTPError try: url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-summary" # MSFT for Microsoft ticker = input("Please enter ticker symbol to know it's last closing price :\n") querystring = {"symbol":ticker,"region":"US"} ...
b79293531edb30b52ab3e3d4cb83abece2e2b7a9
BeepBoopYeetYourScoot/GeneralPython
/basic_python/1_variables/numberTypes.py
781
4.1875
4
x = 2 y = 3 print(x/y) # В python 2 получился бы ответ 0, т.к. там было бы целочисленное деление print(type(y % x)) # Модульное деление всегда даёт целое число (остаток от деления числа на число) print(y // x) # Целочисленное деление реализовано отдельным оператором x = 4 y = 2 print(x/y) # В любом случае получа...
adbbb4bef54dd25d3bba058e87d0fe52af614455
BeepBoopYeetYourScoot/GeneralPython
/intermediate_python/2_algorithms/permutation_generation.py
1,007
4.09375
4
# Алгоритм генерирует все возможные перестановки множества чисел # def find_in_prefix(num, pref): """Ищет num в pref и возвращает True, если такой есть; False, если такого нет""" for x in pref: if num == x: return True return False def generate_permutations(c_sys_base: int, num_...
b41e834e2f7ec45f6abee0d4b4e3b277409f07be
BeepBoopYeetYourScoot/GeneralPython
/intermediate_python/2_algorithms/merge_sort.py
2,066
3.875
4
# На любой выборке сложность алгоритма - O(N*ln(N) # Сортирующее действие выполняется на обратном ходу рекурсии # Требует дополнительной памяти # Сортирующее действие - слияние отсортированных массивов в один # Сортировка называется устойчивой, если она не меняет порядок равных элементов import random def generate...
fff87a0aa35c151e1e4c94b3a43e44ace36287f2
BeepBoopYeetYourScoot/GeneralPython
/intermediate_python/2_algorithms/bubble_sort.py
929
4.28125
4
import random def generate_random_array(length: int): """Функция генерирует список длины *length*, который состоит из случайных целых чисел""" temp = [] for i in range(length): temp.append(random.randint(0, 101)) return temp array = generate_random_array(10) print(array) def bubble...
da785fbd6a17fa38518bdc5e42e30bf28cd0c302
Leonardo612/Entra21_Leonardo
/01-Exercicios/Aula001/Ex1.py
633
4.15625
4
#--- Exercício 1 - Variáveis #--- Crie 5 variáveis para armazenar os dados de um funcionário #--- Funcionario: Nome, Sobrenome, Cpf, Rg, Salário #--- Deve ser usado apenas uma vez a função print() #--- Cada dado deve ser impresso em uma linha diferente #--- O salário deve ser de tipo flutuante nome = input('Digite o ...
4322bf7ae752c2441c4cefaa0798494c8985ad07
Leonardo612/Entra21_Leonardo
/exercicios_uri/teste.py
336
3.90625
4
idades_menores = [] nome_menores = [] for i in range(3): idade = int(input()) nome = (input()) if idade < 18: print(f"Mais um menor de idade {i+1}") idades_menores.append(idade) nome_menores.append(nome) print(f"Idades dos menores {idades_menores}") print(f"Nomes dos menores {nome_...
4cee8d49a7696a6a22e2e9e52215d97f94c25b44
jRhoades7989/RPG-Exercise
/attack.py
4,760
3.65625
4
from classes.game import Person, bcolors magic = [{"name": "Fire", "cost": 10, "dmg": 100}, {"name": "Thunder", "cost": 10, "dmg": 124}, {"name": "Blizzard", "cost": 10, "dmg": 100}] magic_color = [bcolors.FAIL, bcolors.OKYELLOW, bcolors.OKBLUE] player = Person(460, 65, 60, 34, magic) enemy = Pers...
c6a8e11cc3bde81e8345919b290eea6ac56f5e90
HyunJungChoe/Python
/0509stylecode1/04.py
101
3.6875
4
word_1 = "Hello" word_2 = "World" result = [i+j for i in word_1 for j in word_2] print(result)
3e78a58721321c43c737427a32dd9a0c62e93181
AlanPadi95/neural-networks-python
/Text Classification/text_classification_trainer.py
5,160
4.40625
4
""" Another large application of neural networks is text classification. We will use a neural network to classify movie reviews as either positive or negative. """ import tensorflow as tf from tensorflow import keras import numpy """ The dataset we will use for these next tutorials is the IMDB movie dataset from kera...
2f54cafff2a1e5747d952bbfbfa1dddc1ac15c6f
ArtemGrom/PY111-task
/Tasks/e0_breadth_first_search.py
976
3.78125
4
from collections import deque from typing import Hashable, List import networkx as nx def bfs(g: [dict, nx.Graph], start_node: Hashable) -> List[Hashable]: """ Do an breadth-first search and returns list of nodes in the visited order :param g: input graph :param start_node: starting node for search ...
120cd4001575b771eeec89e9364e2fe5b3d022e8
ArtemGrom/PY111-task
/Tasks/g1_merge_sort.py
1,131
3.84375
4
from random import randint from typing import List def sort(container: List[int]) -> List[int]: """ Sort input container with merge sort :param container: container of elements to be sorted :return: container sorted in ascending order """ if len(container) > 1: mid = len(container) //...
5a9feee8dc19ee89048119c6273df9ef584c5410
meahow/adventofcode
/2017/12/solution1.py
703
3.546875
4
# python3 def solve(graphtxt, node=0): nodes = dict() for line in graphtxt: line = line.split() nodeid = int(line[0]) children = list(map(lambda s: int(s.strip(',')), line[2:])) nodes[nodeid] = children print(nodes) visited = set() nodes_to_process = [node] whi...
f68a1c9afe8a230e2b9e5ef79982be601a9b97bb
meahow/adventofcode
/2017/06/solution1_test.py
1,348
4.28125
4
import solution1 """ For example, imagine a scenario with only four memory banks: The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution. Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 b...
3b9ec31634d774a77c815327572e4eecb2c8501a
meahow/adventofcode
/2018/02/solution2.py
1,226
3.765625
4
# python3 def str_distance(s1, s2): distance = 0 common = [] for i in range(len(s1)): if s1[i] != s2[i]: distance += 1 else: common.append(s1[i]) return distance, "".join(common) with open('input1.txt') as infile: box_ids = set() for box_id in infile.r...
ef8a4c4e94963e080581356e3f3a9a9c06cd63b1
lakip/i-m_codeTest
/prime_numbers.py
307
3.640625
4
class Prime: def prime_numbers(self): prime = [] for num in range(1, 100): for i in range(2, num): if (num % i) == 0: break else: prime.append(num) print(prime) prime = Prime() prime.prime_numbers()
db24ab1118f123e32ba2b40ed6c3b1350829086a
vilay1702/PythonPrograms
/ticTacToe.py
5,520
3.640625
4
import random import math class Game: def __init__(self): self.board = [' ' for i in range(9)] self.winner = None def __str__(self): return str(''.join(self.board)) def displayBoard(self): print() print('\t' + self.board[0], '|', self.boa...
37f5689f1bde0db9063b8eb8286619a5a9a519b7
Iliyakarimi020304/darkT-Tshadow
/term 2/dark shadow34.py
50
3.671875
4
txt = "THIS IS NOW!" x = txt.isupper() print(x)
8be730e16b5908841ccd648956ab806f83fd1d25
Iliyakarimi020304/darkT-Tshadow
/term 2/dark shadow69.py
1,382
3.515625
4
import tkinter as tk def up(): global temp temp += 1 fan() def dn(): global temp temp -= 1 fan() def fan(): temprature.set("Temperature: " + str(temp)) if temp >= 30: fan_state.set("Fan is on") label2['background'] = 'green' else: fan_state.set("Fan is off...
24cab64adff4d0da92ad5b941b501e355dacfd98
Iliyakarimi020304/darkT-Tshadow
/term 2/dark shadow51.py
320
4.125
4
number = input("Enter Number: ") counter = 0 numbers = [] sums = 0 while number != '0': if number.isdigit(): numbers.append(number) counter += 1 number = input("Enter Number: ") for n in numbers: sums += int(n) print(f"Your numbers{numbers}") print(f"Average of your numbers {sums/counter}")
3eb39c39a13710a701644f0a387ce98868de9ee4
tosmak16/kodierung-muster
/slidingWindow/find_word_concatenation.py
2,113
4.0625
4
# Words Concatenation (hard) # Given a string and a list of words, find all the starting indices of substrings in the given string that are a # concatenation of all the given words exactly once without any overlapping of words. It is given that all words are # of the same length. # # Example 1: # # Input: String="catfo...
834a72f26dc2ed04ec1782015b6d3c42cc96dbf9
datarail/concat-docker
/concat.py
965
3.734375
4
#!/usr/bin/env python ''' Application that concatenates files listed in /input/concat_config.yml. Optionally, converts the output file to all-uppercase if a given environment variable ("UPPERCASE") is set. Outputs to /output/concatenated.txt. ''' import os import ruamel.yaml as yaml # Check for the environment var...
22966395f11044c900810939ea7cd9944b703d6a
ankur198/AishPythonPractice
/factorial.py
697
3.515625
4
# n = int(input('Enter no.:')) # if n % 2 == 0: # if n == 2 and n == 5: # print('not Weird') # elif n == 6 and n == 20: # print('weird') # else: # print('not weird') # else: # print('weird') # n = [5,6,6,2,3] # for i in range(len(n)): # n[i] = n[i]**2 # print(n) # def sq(e...
ed4fe85d1310410c437c6978e50a0f4adb9c3640
HELLO-world8999/python
/minions efficient.py
621
3.625
4
def minion_game(string): stuart=[] kevin=[] for i in range(len(string)): if string[i] not in ("A","E","I","O","U"): for j in range(i,len(string)): s=string[i:j+1] stuart.append(s) else: for x in range(i,len(string)): ...
6301ebd5b1807a1275da4c25028e787230b43870
manukrishna123/Programming-Lab
/SI.py
169
3.765625
4
P=int(input("Enter the Principal Amount: ")) R=int(input("Enter the Rate: ")) T=int(input("Enter the TIme: ")) si=((P*R*T)/100) print("The Simple Interest is ",si)
23691716c3889e842791378d7f519cb03dd8a6e4
manukrishna123/Programming-Lab
/length string.py
71
3.984375
4
str=input("Enter a string:") print("Length of a string is",len(str))
403dde60b834733c15c766f2b72091f38fbf8c74
mburr9/movie_website
/media.py
894
3.75
4
import webbrowser class Movie(): """ This class provides a way to store movie related information""" def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): ''' Behavior: contructor used to create space to store movie title, storyline, poster im...
596c5d0884808cb9e837476bb2440016d40a71e1
sharmaatul9654/python-program
/add.py
143
3.625
4
t=() while 1: item=input('enter the item') t=t+(item,) c=input('do you want continue') if c.lower()=='n': break print(t)
54bb36532da49d050745a8bf980a3fd1db5c7e72
sharmaatul9654/python-program
/pattern.py
115
3.828125
4
n=int(input('enter n') for i in range(1,n+1): print('*') for j in range(1,n-i): print('*',end='') print(/n)
8122a59984641727fdc40d7042bc846bc93f08ae
MerchenCB2232/backup
/dice.py
1,835
4.0625
4
# Cameron Merchen # Period 6 # Dice Rolling Simulator import random x = 1 one = 0 two = 0 three = 0 four = 0 five = 0 six = 0 def printRolls(): percRolls1 = (one / rolls)*100 percRolls2 = (two / rolls)*100 percRolls3 = (three / rolls)*100 percRolls4 = (four / rolls)*100 percRolls5 = (five / rolls)*100 percRoll...
5c64470d7d305603eb43654528cb7fd6ea78c1cb
MerchenCB2232/backup
/todolist.py
814
4.125
4
import pickle print ("Welcome to the To Do List :))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))") todoList = [] while True: print("Enter a to add an item") print("Enter r to remove an item") print("Enter l to load list") print("Enter p to print the list") print("Enter q to quit") choi...
841afedd86c99f14b0cf35537edfb41a19898e13
maximzec/py_lab2
/DLL.py
2,278
3.875
4
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def __str__(self): return str(self.data) class DoublyLinkedList: def __init__(self): self.head = None def size(self): count...
64b8718c992320ddc1650100417cd4dcc5689b3e
davideduardo001github/tarea1python
/p4.py
1,416
4.625
5
""" 4.- Elabora un programa que me permita realizar la suma de dos matrices de 3x3. Cada uno de los elementos de la matriz deberá ser ingresado por el usuario. Una matriz en Python puede implementarse con listas dentro de listas. """ ## DECLARACIÓN DE MÉTODOS # Impresión de matrices nxn def printmatrix(mat): for i...
4dc0727d5219269bbde42d50dddc2778695ce3bd
rundong-zhou/PHY407-Projects
/Lab10/Q2&3/Lab10_Q3a_functions.py
594
3.53125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 26 19:38:19 2020 @author: rundo """ import numpy as np from numpy import random def p(x): return x**2 def f_w(x): return 1 / (np.exp(x) + 1) def f(x): return x**(-0.5) / (np.exp(x) + 1) def w(x): return x**(-0.5) def mean(N): ...
3b006dec0fbff72bc747490ae3273733d45728eb
rundong-zhou/PHY407-Projects
/Lab1/Submission/Q2/Lab1_Q2_function.py
524
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 18 15:28:32 2020 @author: rundo """ import numpy as np def calculate_x(x0, r, pmax): """This function calculates the array of x INPUT: x0[float]: the initial normalized population x0 r[float]: the maximum reproduction rate r pmax[int]: the total numb...
e7b6b850c948d8566bf02e5d40918a7e2fd7a0fc
matiboux/epita-s6-fmsi
/rho_pollard.py
1,380
4.0625
4
# -*- coding: utf-8 -*- # Pollard's Rho algorithm to decrypt rsa. import math import time from rsa import RSA def f(x): return x * x + 1 """ Pollard's rho algorithm @param n the RSA ciphering modulus """ def rho_pollard(n, x1 = 2): x = x1 y = f(x) % n p = 1 start_time = time.perf_counter() ...
b281f3396319901873d2c883144d35344336d2a8
jessemin/POS-Object-Tagging
/fileUtil.py
1,304
3.859375
4
""" Helper module for file IO """ import pandas as pd import sys def readFile(filename): """ Read file and returns list of lines. :param filename :return list of lines """ try: with open(filename, 'rb') as f: return f.readlines() except IOError: print >> sys.st...
7848e9a330f17a5aebb41a810c7d4f0112db62da
mjouvenot/tradespace-yusen
/permutations.py
2,541
3.515625
4
# Let's assume the csv rows are structured as decision,choice,choice,choice,etc. import itertools import csv def check_feasible(option_dict): """ Check if a combination (given as a dict) is feasible :param option_dict: :return: boolean (True if feasible, False if not) """ unfeasible_combina...
2956fa5eb06da1714b146eadbdb265f509fd2917
Tamaghno/baby-steps-to-learning-python
/new.py
1,921
3.703125
4
def convert(s): new = "" for x in s: new = new + x return new s = ['t', 'a', 'm', 'a', 'g', 'h', 'n', 'o'] print(convert(s)) def sublists(list1): sublist = [] for i in range(len(list1) + 1): for j in range(i + 1, len(list1) + 1): sub = list1[i:j] print(s...
737263f3bdd1c1d0a6c64a021c9c125fe944a557
ldd257/python_ai
/com/learn/python/十、类/2. self.py
2,989
4.25
4
""" Python 的 self 相当于 C++ 的 this 指针。 类的方法与普通的函数只有一个特别的区别 —— 它们必须有一个额外的第一个参数名称(对应于该实例,即该对象本 身),按照惯例它的名称是 self 。在调用方法时,我们无需明确提供与参数 self 相对应的参数。 """ class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt() # <__main__.Test object at 0x000000BC5A351208> # <class '__main__.Test'> ...
1e28ec16c5b6cddee1488f6cdcd54f1ede67e92b
ldd257/python_ai
/com/learn/python/十一、魔法方法/1. 魔法方法.py
3,562
3.5625
4
""" 魔法方法 魔法方法总是被双下划线包围,例如 __init__ 。 魔法方法是面向对象的 Python 的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的 Python 的强大。 魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用。 魔法方法的第一个参数应为 cls (类方法) 或者 self (实例方法)。 1. cls :代表一个类的名称 2. self :代表一个实例对象的名称 """ """ __init__(self[, ...]) 1. 构造器,当一个实例被创建的时候调用的初始化方法 __new__(cls[, ...]) 1. __new__ 是在一个对象实例化的时候所调用的第一个方法,在调...
89d0dd0ba995056e2c9ef2e73e05c949c83eb702
ldd257/python_ai
/com/learn/python/二、语句/4、其它语句.py
1,186
3.609375
4
""" break 语句可以跳出当前所在层的循环。跳出循环 continue 终止本轮循环并开始下一轮循环。跳过本次循环 """ for i in range(1, 4): print("start=======", i) if i % 2 == 0: print("我是偶数,我可以跳过本次循环", i) continue if i == 3: print("当是3,我结束循环", i) break print("end=======", i) """ pass 语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解...
0c36ffd6c9739331d6504afb575260afa030aaa8
alexwaweru/sets-implementation
/set_impl_1.py
4,468
3.640625
4
class Superset(): def __init__(self): self.slots = [] '''Adds an element into the set''' def add(self, element): element = str(element) self.slots.append(element) def __str__(self): if len(self.slots) > 0: string = '{' + str(self.slots[0]) newlis...
527d2d3692b6043333b1f50f0e49b03859443a37
AnastasiiaDm/Py_FourteenthProject
/create_file.py
507
3.828125
4
'''2. Создать текстовый файл, записать в него построчно данные, которые вводит пользователь. Окончанием ввода пусть служит пустая строка. Каждая введённая строка, в файле, должна начинаться с новой строки.''' f = open('output_file.txt','w') while True: s = input() f.write(s+'\n') if s == '': ...
df1a5647ba6cd504cf5e6dba183ca4aed1f276d5
jimbuho/hiring-test
/tests/test_stack.py
1,250
4.1875
4
""" Un Stack o Pila: el primer elemento en entrar es el primero en salir. Nota: En el siguiente codigo hay cuatro lineas que deben corregirse para que las tres pruebas sean superadas """ class Stack: def __init__(self, initial_items=[]): self.items = initial_items def shift(self): ...
31163f00415372a77dd23cba3edd34ad4004c053
harishbommakanti/learningML
/CNN_coding/simple_neural_nets.py
2,597
3.765625
4
import numpy as np class Neuron: #very very loose model of how sigmoid is an activation function def neuron_tick(self,inputs): cell_body_sum = np.sum(inputs * self.weights + self.bias) firing_rate = 1/(1 + np.exp(-cell_body_sum)) return firing_rate #writing a very simple 20 line version of a 2 layer neural net...
c0d1f2201c3dc6a715ba9994214db7c1d535b453
cpvp20/bubblesort
/del.py
378
4.21875
4
def sortit(numbers): for i in range(len(numbers)): if i[1]>i[2]: i[1],i[2]=i[2],i[1] return(numbers) #ACTIAL CODE x=list(input("type some integers randomly, separating them with spaces ")) #creates a list with the numbers the user gives y=[int(i) for i in range(len(x))]#turns list ...