blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fd59d679b32ac6b46ea77ac0097db5771f97b8f2
shubhamg97/Merge-Sort
/mergeSort.py
1,059
3.984375
4
def merge(leftHalf, rightHalf, array): i = 0 j = 0 k = 0 while (i < len(leftHalf) and j < len(rightHalf)): if leftHalf[i] <= rightHalf[j]: array[k] = leftHalf[i] i += 1 k += 1 elif leftHalf[i] >= rightHalf[j]: array[k] = rightHalf[j] j += 1 k += 1 while (i < len(l...
b9214f6dec2918b3b0c3ac54d88ff27e2ecbed23
ankitsharma07/100PythonQuestions
/keyboard.py
361
3.78125
4
def keyboard(direction, string): keys = 'qwertyuiopasdfghjkl;zxcvbnm,./' if direction == 'R': directionValue = -1 elif direction == 'L': directionValue = 1 msg = "" for i in string: msg = msg+keys[keys.find(i)+directionValue] return msg direction = str(input()) string =...
28494f2d2e252bb1d35da377aa1f2f2c0254cb16
nikunjbadjatya/tautology
/tautology.py
5,425
4.03125
4
''' tautology.py Program to verify whether the given INPUT_PROPOSITION is a tautology or not. Example of valid tautologies: 'a | !a' and '(a & (!b | b)) | (!a & (!b | b))' How to Execute: Modify INPUT_PROPOSITION as per your needs below. python tautology.py Algorithm: 1. Parse the input string and count the number o...
de3d733dae2a034aeededc812e337126003d4784
JWooni/python-study
/src/test.py
209
3.75
4
a = [1,2,3,4] b = a[:] print(a == b) print(a is b) print(id(a)) print(id(b)) print(a[1] == b[1]) print(a[1] is b[1]) print(id(a[1])) print(id(b[1])) print(id(a[1])) print(id(b[1])) print(a[1]) print(b[1])
a753a7edcfb85e506c55d9332e86082ab1d6a743
phyvivek-pan/python-coding
/fizzbuzz.py
106
3.703125
4
for num in range(1,100): if num%3==0: print('fizz') if num%5==0: print('buzz') else: print(num)
b3c7ba006be67b70c1042dffd4f3c9ccc36a0097
rlijbers/CSD2
/python_basics/list_example.py
419
3.734375
4
import time values = [0.5, 0.25, 0.5, 2, 1] numValues = 5 numValues = len(values) print("forloop 1") for index, value in enumerate(values): print(index, value) print("forloop 2") for index in range(len(values)): print(index) print(values[index]) print("forloop 3") for value in values: print(value) ...
c93158c930241ca8bd86e4e3e5d7d614bce0fccf
Sabbir185/Data-Structure-Algorithms
/python DS and Algorithms/simpleRecursion.py
253
3.84375
4
# def showDoll (doll): # if doll == 1: # print('Doll number 1 is found!') # else: # showDoll(doll-1) # showDoll(10); def rec(n): if n<1: print("n is less then 1") else: rec(n-1) print(n) rec(5)
8c3cf2f30acab17a796d6a20413cbf0ddbb9bf22
pug/pug
/pug/nlp/regex_patterns.py
515
3.65625
4
#!/usr/bin/env python """ Compiled Regular Expression Patterns >>> scientific_notation_exponent.findall(' 1E10 and 1 x 10 ^23 ') ['E', 'x 10 ^'] >>> scientific_notation_exponent.findall(' 1 x 10 ^23 ') ['x 10 ^'] >>> scientific_notation_exponent.split(' 1 x 10 ** 23 ') ['1', '23'] """ import re nonword = r...
2797c97919910e988f3f42d6e990806e943e950d
kdolic/cs-guided-project-tree-traversal
/src/demonstration_2.py
1,803
3.953125
4
""" You are given the values from a preorder and an inorder tree traversal. Write a function that can take those inputs and output a binary tree. *Note: assume that there will not be any duplicates in the tree.* Example: Inputs: preorder = [5,7,22,13,9] inorder = [7,5,13,22,9] Output: 5 / \ 7 22 / \ ...
e6542d25aea03dc0e9b431eab9bae463b0ba0c00
TheGoodall/cpt-bio
/q1.py
3,866
3.5
4
#!/usr/bin/python import time import sys # YOUR FUNCTIONS GO HERE ------------------------------------- # 1. Populate the scoring matrix and the backtracking matrix # ------------------------------------------------------------ # DO NOT EDIT ------------------------------------------------ # Give...
29dcd939e4c047706ee05eca0ad99c310362c4ad
lebinyu/ComputationalAstrophysics2021
/17. LSEs/CramersRule.py
855
3.671875
4
''' Eduard Larrañaga Computational Astrophysics 2020 Cramers Rule ''' import numpy as np def CramersRule(A, b): ''' ------------------------------------------ CramersRule(A,b) ------------------------------------------ Returns the solution fo the Linear System A x = b where A: nxn mat...
2d6c58180beb66252d84ef15540a84329c81c1b1
goutamiiyer/Design-and-analysis-of-Algorithms
/Dynamic Programming programs/subsetsum.py
2,436
3.90625
4
''' Given a set of non-negative integers and a value sum, find if there is a subset of the given set with sum equal to the given sum. subset[i][j] stores i rows, each row [i] corresponds to a size of N, the subset, elements in the subset each col [j] corresponds to a value of sum For Sum = 7 and subset with 3...
b2808248dcc834cb26f4f20a1d0522ddb450a2d7
SPZAnalytics/NBA
/nba_stats_github/python-machine-learning-book-master/code/optional-py-scripts/ch08.py
8,258
3.65625
4
# Sebastian Raschka, 2015 (http://sebastianraschka.com) # Python Machine Learning - Code Examples # # Chapter 8 - Applying Machine Learning To Sentiment Analysis # # S. Raschka. Python Machine Learning. Packt Publishing Ltd., 2015. # GitHub Repo: https://github.com/rasbt/python-machine-learning-book # # License: MIT # ...
6d959cd0f71aa7d2bdd3399291dcc7981992619a
Christian-B/my_spinnaker
/slots_test.py
2,322
3.6875
4
from collections import namedtuple import time from typing import NamedTuple class Foo(object): __slots__ = ("alpha", "beta", "gamma") def __init__(self, alpha, beta, gamma): self.alpha = alpha self.beta = beta self.gamma = gamma Bar = namedtuple('Bar', ['alpha', 'beta', 'gamma']) ...
c51cc2a3a07f4e2fc16f81205c0ec74e4f07b6ab
Smart-IoT-Lab/study-for-machine-learning
/week_2/구현자료/이미미_Lec3_2_191120.py
946
3.5
4
#Gradient descent import tensorflow as tf tf.enable_eager_execution()#그래프를 생성하지 않고 함수를 바로 실행하는 명령형 프로그래밍 환경 tf.compat.v1.set_random_seed(0)#set_random_seed를 통해 모든 random value generation function들이 매번 같은 값을 반환함 x_data = [1., 2., 3., 4.] y_data = [1., 3., 5., 7.] W = tf.Variable(tf.random_normal([1], -100., 10...
6b5cddc73e8e83958a5db88a61bdb0eacc583835
cyrobin/patrolling
/wrg.py
1,709
4
4
""" Inspired by : http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python Cyril Robin -- LAAS-CNRS -- 2014 The WeightedRandomGenerator class aims at efficiently select a random element from some kind of container, with the chances of each element to be selected not being equal, but defined by rel...
067e42518c453174dae1df8322b55983ee5a555d
jucimarjr/zelda
/design_pattern/15_Interpreter/InterpreterExample.py
318
3.59375
4
from Number import Number from Evaluator import Evaluator def InterpreterExample(): expression = "w x z - +" sentence = Evaluator(expression) variables = dict (w = Number(5), x = Number(10), z = Number(42)) result = sentence.interpret(variables) print(result) InterpreterExample()
b1097f8bacd2dbc59941ded0acd8dd00a60a885a
jucimarjr/zelda
/design_pattern/15_Interpreter/Evaluator.py
951
3.671875
4
from Expression import Expression from Plus import Plus from Minus import Minus from Variable import Variable class Evaluator(Expression): syntax_tree = Expression() def __init__(self, expression): expression_stack = [] for i in range(len(expression)): if expression[i] == "+" : ...
b4d29bf6dc99a5e3611dd9d80dc9f78df55ba778
jucimarjr/zelda
/design_pattern/06_Adapter/turkey_adapter.py
625
3.90625
4
# * # * Agora, digamos que você queira usar um objeto do tipo Turkey # * no lugar de um Duck. Obviamente você não pode, pois eles possuem # * interfaces diferentes. Então, vamos criar um Adapter. # * # * # * Primeiro, você precisa implementar a interface do tipo que deseja # * adaptar. Essa é a interface...
297ba4472aa91063c525783c567ae85ed908fca9
jucimarjr/zelda
/design_pattern/16_Iterator/diner_menu_iterator.py
638
3.953125
4
from menu_item import MenuItem class DinerMenuIterator (Iterator<MenuItem>) : self.list = [] self.position = 0 def __init__(self, list): self.list = list def next(self): menu_item = list[position] self.position = self.position + 1 return menu_item def has_next(self): if position >= len(list) or ...
62c3e154955446e508f286e235dd9333faa5a255
jucimarjr/zelda
/design_pattern/24_ModelViewController/view/view.py
772
3.53125
4
# -*- coding: utf-8 -*- class View(): def inicio(self): print ("Bem vindo a Agenda\n") return self.menu() def menu(self): print ("1 - Para adicionar uma pessoa na agenda") print ("2 - Para exibir as pessoas da agenda") print ("3 - Para apagar uma pessoa da agenda") ...
eea8b5d84c405eb82b05b360458633a33548069a
jucimarjr/zelda
/design_pattern/14_Command/CeilingFan.py
653
3.515625
4
class CeilingFan: HIGH = 2 MEDIUM = 1 LOW = 0 def __init__(self, location): self._location = location self._level = 0 def high(self): self._level = CeilingFan.HIGH print (self._location + "ceiling fan is on high") def medium(self): self._level = Ceilin...
fdcd288b36a3fe5006f654a44a2fa859ab29514a
N-Verma/Learning-Python-GUI-tkinter-
/Test1.py
689
4.1875
4
import tkinter as tk //the module is been imported and given a short name tk r = tk.Tk() //the command Tk() is used to stablish a main working windows for the app r.title("TEST 1") //name of the app button1=tk.Button(r,text='Start',width=25,bg='red',activebackground='blue') //Button() fucntion is used to create a butto...
b68bab06ea2da04ca44ff5c17c2938f152f3dec7
eternaltc/test
/Test/Oop/oop07_call_().py
436
3.59375
4
#测试可调用方法__call__() class SalaryAccount: '''工资计算类''' def __call__(self, salary): print("算工资啦...") yearSalary = salary*12 daySalary = salary // 22.5 #国家规定每个月的平均工作天数 hourSalary = daySalary // 8 return dict(yearSalary=yearSalary,monthSalary= salary,daySalary=daySalary,hou...
8765832c80f9ee9c31feea3845ace7ad36a2e986
eternaltc/test
/Test/Oop/oop08_dynamic.py
294
3.625
4
#测试方法的动态性 class Person: def work(self): print("努力上班!") def play_game(s): print("{0}在玩游戏".format(s)) def work2(s): print("好好工作,努力上班!") Person.play = play_game p = Person() p.work() p.play() Person.work = work2 p.work()
b71bfc582f583800c2cb13f7b5ddb4cd4bfb87dc
eternaltc/test
/Test/Function/func07_copy.py
541
4.28125
4
#测试浅拷贝、深拷贝 import copy def copyTest(): a = [1, 2, [3, 4]] b = copy.copy(a) print("a", a) print("b", a) print("浅拷贝...........") b.append(5) b[2].append(7) # 浅拷贝只拷贝字对象的引用a,改变子对象里面的值 print("a", a) print("b", b) def deepCopyTest(): a = [1, 2, [3, 4]] b = copy.deepcopy(a) ...
e7ae7fb9efb3c29f25c3a0406c29aa92621c67df
eternaltc/test
/Test/Basis/mypy01.py
123
3.703125
4
a = input("请输入一个小于10的数字:") if int(a)<10: print(a) b = [] if not b: print("空列表是false")
952826f69a860aec2b469427c2af65ce8b998fd1
eternaltc/test
/Test/Function/func06_parameter_mutable.py
171
3.796875
4
#测试可变对象的参数传递 a = [10,20] print(id(a)) print("*************") def test01(m): print(id(m)) m.append(30) print(id(m)) test01(a) print(a)
b7da43520e986c6cf42d9fba0243978a20821d08
eternaltc/test
/Test/Basis/mypy16_zip.py
373
4.40625
4
#测试zip()并行迭代 for i in [1,2,3]: print(i) names = ("tc","one","tow","san") ages = (23,35,67,45) jobs = ("teacher","it","sir","polic") #只有三个是则下面for只遍历三次 for name,age,job in zip(names,ages,jobs): print("{0}--{1}--{2}".format(name,age,job)) print() for i in range(3): print("{0}--{1}--{2}".format(names[i],ag...
bae64dac8c84dbd6c919832666ff9966765f8155
eternaltc/test
/Test/Oop/oop15_dir.py
242
3.640625
4
class Student: def __init__(self,name,age): self.name = name self.age = age def say_age(self): print(self.name ,"年龄:",self.age) object = object() print(dir(object)) s = Student("tc",18) print(dir(s))
b5af83c12bdde3887a8c79bb72d795703672efe4
DAndreChampagne/CCSU
/cs463/midterm-practice.py
530
3.53125
4
# def largest(x, left: int, right: int): # if left == right: # return left # m = int((right+left)/2) # y = largest(x, left, m) # z = largest(x, m+1, right) # return y if x[y] > x[z] else z # # # data = [1, 2, 10, 3, 4, 5] # print(largest(data, 0, len(data)-1)) def test(n): result = 0 ...
467f258814bdb681b7b9ee82a2fc987d9e3ffa69
AlexKeyMAD/Study_py
/Udemy/Less_031/Game_guess_the_number.py
692
3.640625
4
import random our_number = random.randint(1,50) life = 0 print('Игра "Угадай число"') while life < 6: life+=1 user_number = int(input('Введите число от 1 до 50:')) if user_number == our_number: print(f'Число угадано, за {life} попыток') break else: if user_number > our...
b9636867dc0eaa6867631d0c0131b6fd8d4c9c99
jpowellstm/Text-Based-Adventure
/text_based_adventure_1.py
802
3.84375
4
""" This is part of a series of files that builds up a text based adventure programme based on https://projects.raspberrypi.org/en/projects/rpg. The rest of the files can be found at https://github.com/jpowellstm/Text-Based-Adventure This file will: 1) Define a function to print the commands that you can execute in t...
49a0f72b0b109a5b4008a66e33a2aa737d2204c5
sunliang5211/work
/language/python/func.py
715
3.546875
4
def hello_1(greeting,name): print('%s,%s!' % (greeting,name)) def hello_2(name,greeting): print('%s,%s!' % (name,greeting)) hello_1('hello','world') hello_2('hello','world') hello_1(greeting='Hello',name='world') hello_1(name='world',greeting='Hello') def hello_3(name='sunliang',greeting='hello'): print(...
abc4ec24e86425c25c0e342ccad887079213428c
sunliang5211/work
/language/python/paramtest.py
903
3.6875
4
def story(**kwds): return 'Once upon a time.there was a ' \ '%(job)s called %(name)s.' % kwds def power(x,y,*others): if others: print('Received redundant parameters:',others) return pow(x,y) def interval(start,stop=None,step=1): 'Imitates range() for step > 0' if stop is None: ...
4f43191e153d36f17f597bab863a72035722af97
MartinChan3/CyComputerNote
/Python/Examples/pyex_28.py
131
3.640625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- def age(n): if n == 1: c =10 else: c = age(n - 1) + 2 return c print age(5)
d95d8571029bb99107c8495ba49dbdaf840422f7
MartinChan3/CyComputerNote
/Python/Examples/pyex_40.py
128
3.515625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': a = [9,6,5,4,1] for i in a[::-1]: print i
9ffe361ca19720feea0552d3366c674b3f453b65
MartinChan3/CyComputerNote
/Python/Examples/pyex_37.py
203
3.8125
4
#!usr/bin/python # -*- coding: UTF-8 -*- print 'Please enter into 10 numbers' a = [] for n in range(10): a.append(int(raw_input('Please enter the %d number: ' % n))) a.sort(reverse = False) print a
b96eaf7d828e8052a4da0ecda68413980dab10b9
MartinChan3/CyComputerNote
/Python/Examples/pyex_30.py
296
3.578125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- a = int(raw_input('input a num ')) x = str(a) flag = True for i in range(len(x)/2): if x[i] != x[ -i - 1]: #python允许负数索引,来进行索引的倒序指定,-1为右侧第一个索引 flag = False break print flag
c9730dece9635ca9f19a2074e0a1c359c71cf1e5
marble-git/python-laoqi
/chap5/average_std_deviation.py
1,607
3.6875
4
#coding:utf-8 ''' filename:average_std_deviation.py chap:5 subject:8 conditions:names and scores solution:fun average std_deviation ''' import math import random import operator def average(iterable): return sum(iterable)/len(iterable) def std_deviation(iterable): aver = average(it...
87c6d368b234121c99b6d456b12aafee07736a62
marble-git/python-laoqi
/chap4/deta.py
512
3.828125
4
#coding:utf-8 ''' filename:deta.py chap:4 subject:7 conditions:a,b,c of equation solution:print roots | tips messages ''' import math a,b,c = eval(input('Enter a,b,c of equation "a*x^2 + b*x + c = 0" : ')) if (deta:= b**2 - 4*a*c) < 0: print('deta < 0 ,there is no roots') else: root1 ...
9efff1f707a27f0edb089f1b3b897a139b973c63
marble-git/python-laoqi
/chap3/countwords.py
701
3.75
4
#coding=utf-8 ''' filename:countwords.py chap:3 subject:36 conditions:textstring solution:words's times ''' import re text = '''You raise me up,so I can stand on mountains You raise me up to walk on stromy seas I am strong when I am on your shoulders You raise me up to more than I can be''' #wor...
e487f489345aab33cb25c046b3d938956d642c45
marble-git/python-laoqi
/chap3/index.py
474
3.53125
4
#coding=utf-8 ''' filename:index.py chap:3 subject:19 conditions:target_string='Hello',char='l' solution:indexs of char in target_string ''' target_string = 'Hello' char = 'l' result = [] start = 0 while True: start = target_string.find(char,start) if start == -1: break result.append(...
0287b3bfe9884740c8f78e89db15d45ed0ae565c
marble-git/python-laoqi
/chap9/data2sqliteDB.py
2,430
3.609375
4
#coding:utf-8 ''' filename:data2sqliteDB.py chap:9 subject:convert data to sqliteDB from excelfile conditions:modules: xlrd,sqlite3 solution: ''' import sqlite3 import xlrd class Excel2SQLiteDB(): '''convert every sheet in excelfile to tables in sqliteDB sheet name -> table name ...
8033dbb3a126e93e4212bf0b2fe1ac88420e09c6
marble-git/python-laoqi
/chap5/sort_filenames.py
535
3.6875
4
#coding:utf-8 ''' filename:sort_filenames.py chap:5 subject:20 conditions:list of filenames solution:sorted list of filenames ''' import re filenames = ['py1.py','py14.py','py10.py','py2.py',] fl = filenames.copy() fl.sort() print('filenames:',filenames) print('fl:',fl) def sort_filena...
94bce899a16cbec1376190f02691cd61371f54ec
marble-git/python-laoqi
/docs/chap6/code/physicist.py
1,388
3.78125
4
#coding:utf-8 ''' filename:physicist.py single inheritance Physicist ''' class Physicist: def __init__(self,name,iq=120,looks='handsom',subject='physics'): self.name=name self.iq=iq self.looks=looks self.subject=subject def research(self,field): print('{0} rese...
b275bcc02f05d3676e4985357ee6805f399a2daa
marble-git/python-laoqi
/chap4/vowel_counts.py
571
3.796875
4
#coding:utf-8 ''' filename:vowel_counts.py chap:4 subject:9 conditions:chap3_35 string solution:count a,e,i,o,u ''' text = '''You raise me up,so I can stand on mountains You raise me up to walk on stromy seas I am strong when I am on your shoulders You raise me up to more than I can be''' v...
c0376f6c92ad1d3e2b82154c40ab57e674033b01
marble-git/python-laoqi
/chap6/relationship_of_point_circle.py
963
3.90625
4
#coding:utf-8 ''' filename:relationship_of_point_circle.py chap:6 subject:8 conditions:Point(),Circle() solution:relationship between circle and point ''' from circle import Circle from point import Point import math class Relationship: def __init__(self,circle:Circle,point:Point): ...
bb670f3c6eaba366b573e838768f9f33e4a1fd34
lin1870772330/python
/Python(二考)/Python。程洁/test03.py
86
3.609375
4
def int(input()) s=0 a=1 for a in range(1,20) b=2 for b in range(2,20) s=a/b print(s)
6782b91ccf86c2ceda5f2dd78e984d034c2950fc
lin1870772330/python
/Python(二考)/Python。程洁/test02.py
61
3.53125
4
def int(input()) a=0 b=n! for i in range(1,21) a+=a print(a)
c38ad8eb948b3f18bf2e69c7950cd012d36b8d09
shaoxiang-zheng/bpp
/utility/node.py
902
3.609375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/11/21 20:06 # Author: Zheng Shaoxiang # @Email : zhengsx95@163.com # Description: class TreeNode: def __init__(self, key, value=None): self.key = key self.value = value self.left, self.right = None, None self.height = 0 c...
42c94b6f05edb8ed14ba857e5f802499297132f4
TheShubham-K/Algorithmic_Toolbox
/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.py
1,377
3.71875
4
# Uses python3 import sys import random def get_fibonacci_huge_naive(n, m): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % m def get_fibonacci_huge_fast(n, m): if n <= 1: return n ...
0cb474c21fdfbbecff35219985cc8380819e71e4
TheShubham-K/Algorithmic_Toolbox
/week3_greedy_algorithms/3_car_fueling/car_fueling.py
2,774
3.796875
4
""" /* * This program has Loop nested within another loop * So, it seems to have O(n * n) run-time * But, the run time of the program is O(n) => currentRefills can be atmost n - 1 => numRefills can be atmost n => So there will be atmost n + 1 operations ...
3049d60b47c62713bf021359d3e6ea21c60e1b26
TheShubham-K/Algorithmic_Toolbox
/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.py
609
3.59375
4
# Uses python3 import sys def optimal_weight(W, w): # write your code here n = len(w) value = [[0 for col in range(W + 1)] for row in range(n + 1)] for i in range(1, n + 1): for cp in range(1, W + 1): value[i][cp] = value[i-1][cp] if w[i-1] <= cp: val = v...
8bd399ac27683a51ce5c77379971169e91f264a2
TheShubham-K/Algorithmic_Toolbox
/data-structures/week2_priority_queues_and_disjoint_sets/1_make_heap/build_heap.py
2,109
3.9375
4
# python3 # def build_heap(data): """Build a heap from ``data`` inplace. Returns a sequence of swaps performed by the algorithm. """ # The following naive implementation just sorts the given sequence # using selection sort algorithm and saves the resulting sequence # of swaps. This turns the given array into...
96feb19abb221e77fe5643912a7f1e209e01e73e
mehzabeen000/Function_python
/calculator.py
430
4.0625
4
#we have to make one function of calculator def calculator(num1,operator,num2): if operator=="+": print(num1+num2) elif operator=="-": print(num1-num2) elif operator=="*": print(num1*num2) elif operator=="/": print(num1/num2) calculator(5,"*",3) def multiply(list1,list2...
36f59fd059e6012acfc95d14e0de124e16178492
mehzabeen000/Function_python
/name_increment.py
414
3.609375
4
#Function to print the following pattern (Mehzabeen = M_ Ee_ Hhh_ Zzzz_ Aaaaa_ Bbbbbb_ Eeeeeee_ Eeeeeeee_ Nnnnnnnnn) def user(name): j=1 b='' for i in name: a=i*j b=b+a+'_' j+=1 b=b[:-1] i=0 while i<len(b): if b[i]=='_': i+=1 print('_',b[i...
7edb449ded0944308ac9f6b9c9124ae2dd988346
bvi1994/Pokemon-type-predictor
/test_script.py
1,926
3.5625
4
# This program runs type_predict.py as a test. Basically it gets training sets # which then the tree is built from type_predict.py and does a comparision # to see if the predicted type is the same as the actual type. A plot of # number of training set vs correct prediction is then shown. import numpy as np import m...
41e2e35dda0c3a10d700644f7e4f96deaff08a4e
GanpatiRathia/hackerrank-10-days-of-statistics
/Day1/standard-deviation.py
701
3.71875
4
# problem link -> https://www.hackerrank.com/challenges/s10-standard-deviation/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen import math def mean(data): return sum(data) / len(data) def stddev(data, size): sum = 0 for i in range(size): sum = sum + (data[i] - mean(data)) ** 2 re...
7c4cec922e7922e8bdc1187e8c9ddbb379700a0b
HiteshGarg/codingeek
/Python/Python Examples/Solve Quadratic Equation.py
1,463
4.34375
4
# Python program to solve quadratic equation using formula import math # Finding the roots using the Function def roots_of_equation(a, b, c): # Finding the value of Discriminant D D = b * b - 4 * a * c # other way, D = b**2 - 4*a*c sqrt_D = math.sqrt(abs(D)) # checking Discriminant condition if D > 0: ...
aa42eeacaea066851f0a813d7f97fb7e7217a62e
HiteshGarg/codingeek
/Python/Python Examples/Add Two Numbers.py
1,366
4.5
4
# Add two numbers using + operator num1 = int(input("Enter the First number: ")) num2 = int(input("Enter the Second number: ")) res = num1 + num2 print("The result after adding the given two numbers is: ", res) ##################################################################### # Add two numbers using + operator ...
9ca3cb5454f54b8c00997cbbae8857082dafd424
HiteshGarg/codingeek
/Python/String in Python.py
3,926
4.46875
4
#An example of string str = "This is single line string" print(str) str = """This is multiple line string""" print(str) ######################################################## #An example of string str="This is 'single' line string" print(str) s='This is "single" line string' print(s) #######################...
31c065f72d2b82c0155d47195db525438fad0729
HiteshGarg/codingeek
/Python/Recursion in Python.py
1,948
4.1875
4
# Binary search in Python by recursion def binarysearch(arr, start, end, x): if end >= start: # base condition mid = (start + end) // 2 if arr[mid] == x: # If value found at the mid return mid elif arr[mid] > x: # If value is smaller than mid return binarysearch(arr, start, mid-1, x) ...
4c307609475390c0e21c52e07c90f81620b6d42f
HiteshGarg/codingeek
/Python/Exception Handling.py
1,762
3.609375
4
list_1 = [10, 9, 8, 7] try: print("First element in the list is= %d" %(list_1[0]) print("second element in the list is= %d" %(list_1[1]) print("Fourth element in the list is= %d" %(list_1[3]) print("Fifth element in the list is= %d" %(list_1[4]) #Throws error except IndexError: print("Exceeded Out of...
c209ffd0dc6018c073e23f5c191c0a522b110626
HiteshGarg/codingeek
/Python/Get Current Time.py
1,353
3.96875
4
from datetime import datetime import pytz set_timezone1 = pytz.timezone('Asia/Kolkata') set_timezone2 = pytz.timezone('America/New_York') set_timezone3 = pytz.timezone('Europe/London') time1 = datetime.now(set_timezone1).time() time2 = datetime.now(set_timezone2).time() time3 = datetime.now(set_timezone3).time() print...
0a80e3c118f8558408b7789c237a0e5529acf982
HiteshGarg/codingeek
/Python/for_loop.py
1,302
4.3125
4
def looping_through_list(): x = [1,2,3,4,5,7] #using range() function for i in range(len(x)): print(x[i]) #without using range() function for i in x: print(i) def looping_through_string(): x = "Codinggeek" #using range() function for i in range(len(x)): print(x[i]) #without using ran...
b806939223725102b3a7467dd0cb8e569d99282b
HiteshGarg/codingeek
/Python/Operators/Relational_operator.py
277
4
4
a = 12 b = 3 print("Equality", a == b, sep=": ") print("\nLess than", a < b, sep=": ") print("\nLess than or equal to", a <= b, sep=": ") print("\nGreater than", a > b, sep=": ") print("\nGreater than equal to", a >= b, sep=": ") print("\nNot equal to", a != b, sep=": ")
8fa91fcd56edde1f86f55a33b05906e3cd967c11
world4jason/UniversityRank
/UniversityRanking/src/algorithms.py
21,745
3.625
4
""" @description: algorithms to rank the universities based on graph @author: Bolun """ import math from numpy import linalg as la import numpy as np class bipartite_graph: def __init__(self): self.v_hub = {} self.v_auth = {} self.edge = {} def convert(self, graph): """...
855b23b921fc73a9afa36dfdb9c369862b3d85f2
0x22d/GB_Python
/learn4/4.6.py
999
4.15625
4
#а) итератор, генерирующий целые числа, начиная с указанного, #б) итератор, повторяющий элементы некоторого списка, определенного заранее. from typing import Iterable from itertools import cycle def get_repeated(iterable: Iterable, count: int): """ Создает генератор на count раз с iterable :param iterabl...
3470bc29926923d2cd330c61f92ea6350b916953
jiangnanboy/recommendation_methods
/com/sy/reco/similarity/manhattan.py
440
3.625
4
#!/usr/bin/Python # -*- coding: utf-8 -*- __author__="yan.shi" from scipy.spatial.distance import cityblock #曼哈顿 class Manhattan(): #def similarity(self,vec1,vec2): #return cityblock(vec1,vec2) def similarity(self,vec1,vec2): distance=0.0 for i in range(len(vec1)): if vec1...
2ffa3336cbc749989efec3a0c336e530f62ac69b
yashpatil1998/PCS_Mini_Project
/Project/PCSCopy.py
4,508
3.65625
4
import cv2 #An Image Processing Library import numpy as np #A Library used to store arrays of images import time #A Library for time related operations face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #set the colour parameters here(RGB),"l" is the lower boundary and "h" is the uppe...
07b25d5641e9bc5242188dc43c690fce1021b47d
soAl16/ipc20161
/lista5/ipc_lista5.05.py
262
3.6875
4
#Introducao a programacao de computadores #Professor: Jucimar Junior #Nickso Patrick Façanha Calheiros - 1615310059 # # from matriz import* m = int(input( )) n = int(input( )) matriz = [] matriz = gerar_matriz(m,n) arrumar_matriz(matriz, m) x = verificar_permutacao(matriz,m,n) print(x)
80a73d924799745aaa5d7fb7ff37595330b805ec
wxyj3496/Thermistor_calculator
/generic_liutao.py
449
3.75
4
# define the generic function of liutao # is_number : Determine whether the string is a number import re def is_number(num): pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$') result = pattern.match(num) if result: return True else: return False def mai...
10a7e0b765b800e7cd8edaaf2cdf52508d64c30f
nestor2502/Modelado
/python/Tuplas.py
972
3.921875
4
miTupla = ("A", "B", "C") print("tupla inicial:") print(miTupla) print("\n") #convertir tupla a lista miLista = list(miTupla) #acceder a un elemento en concreto print("elemento en la posicion 2: ", miTupla[2]) print("\nse convierte tupla en lista: ") print(miLista[:]) #convertir lista en tupla miTupla2 = tuple(miLis...
b09b78353dc21f1f94d4da83de4605c07d4db8b2
nestor2502/Modelado
/python/Generador2.py
521
3.890625
4
#!/usr/bin/env python # -*- coding: Windows-1252 -*- # -*- coding: cp1252 -*- # -*- coding: utf-8 -*- # -*- coding: IBM850 -*- #siusamos * antes del argumento le estamos diciendo que recibirá un numero indeterminado de argumentos #los cuales recibira en forma de tupla def devuelve_ciudades(*ciudades): for elemento in...
a60f02904845cf60d131ab9d60e5a55de80739f4
sagallagher/FSA_GA
/lib/GeneticAlgorithm/GeneticOperator/Mutation/RandomTransitionMutation.py
954
3.734375
4
# replace a random transition with a random transition in the FSM # of each chromosome in a given genotype from random import randint class RandomTransitionMutation(): def __init__(self, dp): self.alphabet_size = dp.alphabet_size def mutateGenotype(self, genotype): for chromosome in genotype...
477b41042109c439fd906de3bcf023a2bcc1fe0f
sagallagher/FSA_GA
/lib/Test/DataParser/DataParser.py
1,111
3.6875
4
class DataParser(): # constructor def __init__(self, data_file): self.data_file = data_file self.learning_data = {} self.alphabet_size = 0 self.readDataFile() # string respresentation of data_matrix def __str__(self): result = '' for key in self.learni...
240138d6f7b6b7a5170ee680ca591592d76e22ca
serenastater/learningPython
/stringSlicing.py
377
4
4
# Write code using find() and string slicing (see # section 6.10) to extract the number at the end # of the line below. Convert the extracted value # to a floating point number and print it out. text = "X-DSPAM-Confidence: 0.8475"; firstDigit = text.find('0') lastDigit = text.find('5') number = text[firstDigit:la...
e8d431ce95c3ca47963e3f229e918851ea5b8101
serenastater/learningPython
/parsingXML.py
1,580
4.25
4
# # In this assignment you will write a Python program somewhat # # similar to http://www.pythonlearn.com/code/geoxml.py. The # # program will prompt for a URL, read the XML data from that # # URL using urllib and then parse and extract the comment # # counts from the XML data, compute the sum of the numbers # # in the...
a265627a92b558d74b02e229e153d910546d6019
serenastater/learningPython
/geoJSON.py
1,666
4.125
4
# In this assignment you will write a Python program somewhat # similar to http://www.pythonlearn.com/code/geojson.py. The # program will prompt for a location, contact a web service # and retrieve JSON for the web service and parse that data, # and retrieve the first place_id from the JSON. A place ID # is a tex...
4bd949d772423ee4acb3cb69c57f70db76ffc176
priyanka-punjabi/Leetcode
/Trees/binaryTreeTilt.py
841
3.578125
4
tilt = 0 sumL = 0 sumR = 0 class Node: def __init__(self, data): self.left = None self.right = None self.data = data def getTilt(root): global tilt if root: sumL, sumR = 0, 0 sumL = getTilt(root.left) sumR = getTilt(root.right) tilt += abs(sumL - sumR...
d6b98cab4a9b50de1821f8839f47087369a49df0
12wb/python-0JC
/第五章 字典/5.1~5.2小知识.py
5,511
3.84375
4
""" # 字典键值具有唯一性 P77 d3 = {1:'car',2:'bus',2:'bus'} # 定义字典变量,其中两个键值一样 len(d3) # 字典对象把重复的元素归成了一个 print(len(d3)) """ """ # 利用赋值给字典添加元素 P78 d1 = {'Tom':2,'Jim':5} d1['Mike'] = 8 # 字典变量添加新元素"Mike:8 print(d1) """ """ # 利用setdefault()方法给字典增加元素 P79 d1 = {'Tom':2,'Jim':5,'Mike':9} d1.setd...
ce9fea690c7dd8f2b392ad549a04b0bfbf8da091
12wb/python-0JC
/第二章 变量和简单数据类型/2.5 三酷猫记账单.py
1,404
3.875
4
num1,num2,num3 = 5,6,9 # 定义三种鱼数量的数字变量并赋予初始值 price1,price2,price3 = 8.1,8.2,8 # 定义三种鱼单价变量并赋予初始值 fish1,fish2,fish3 = '鲫鱼','鲤鱼','草鱼' # 定义三种鱼的名称变量并赋予初始值 date = '2017年12月' # 定义日期字符串变量 Total_Num = num1+num2+num3 # 总的鱼数 Total_Amount = num1*price1+num2*price2+num3*price3 # 总金额 print("----...
ce0ebcbc427f179ede561d099461c5eb613b1b87
12wb/python-0JC
/第七章 类/7.1~7.6小知识.py
6,374
4.25
4
''' # 7.1.2案例[编写第一个类] P127 求立方体的类 class Box1(): # 类定义,类名为Box1 def __init__(self,length1,width1,height1): # 传递类参数的保留函数__init__ self.length = length1 # 长数据变量 self.width = width1 # 宽数据变量 self.height = height1 # 高数变量 def volume(self): # 求立方体体积的函数volume,并供实例调用 re...
0e22aad650b6a439f32a72d33646fee1731562ba
12wb/python-0JC
/第六章 函数/text_function.py
795
3.84375
4
def find_factor(nums): # 带参数nums的求因数的自定义函数 ''' find_factor('a') nums是传递一个正整数的参数 以字符串形式返回一个正整数的所有因数''' # 用一个三个单引号来包括描述文档 if type(nums)!=int: # 不是整数,提示出错,并终止函数执行 print('输入值类型出错,必须是整数!') # 提示传递值类型出错 return # 终止函数执行 if nums <= 0: print('输入值范围出错,必须正整数!') i ...
ffb21186da7422f8dd3c5d214b884faa0c847d3d
crisbernf/Openstack-plugin
/shamirs.py
1,309
3.671875
4
import math import random import itertools ''' def isprime(n): for m in range(2, int(n**0.5)+1): if not n%m: return False return True ''' file = open ('a.txt', "r") content = file.read() asci = [ord(c) for c in content] file.close() #for asci[0] in range (000,099) if 0 <= asci[0] <= 99 or...
32af7a132ec6ae78b04db4f0a19542931385a21f
mikewesthad/WikipediaDataViz
/PullRevisionInfo.py
5,491
3.53125
4
""" A script to calculate revision information for a wikipedia article. It queries the API and then creates two csv files. There's no GUI or command line interface, so if you want to search for a different article, you need to change the article variable below. You can alter the API parameters by modifying the payl...
4c4f0871876efd22caa62453e81c3e9256726227
BhushanGarware/ML-Workshop
/Unsupervised Learning/kmeans.py
710
3.640625
4
import numpy as np import matplotlib.pyplot as plt def plot_clusters(orig,pred,nx,ny,legend=True): data = orig import matplotlib.pyplot as plt ylabels = { 0:'Male life expectancy in yrs',1:'Female life expectancy in yrs',2:'Infant mortality, per 1000'} # plot data into three clusters based on value of c p...
9008406e0779a82dc8df149bfe815a18e33d6e84
jfmario/mcpi_collection
/teleport.py
809
3.546875
4
''' This file moves you to a specified location in x/y/z coordinates. Note that the Y-coordinate is up and down. python teleport.py -x X -y Y -z Z ''' import argparse from mcpi.minecraft import Minecraft parser = argparse.ArgumentParser () parser.add_argument ( "-x", action='store', dest='x', type=int, default=0, ...
dcb47fdb4582e50821ca8aecc48efbab0ea64283
LucianoBartomioli/-EDU-POO_IRESM_2021
/ejercicios_obligatorios/ejercicio_3.py
3,370
3.765625
4
import random opcion_menu = int(input(""" -----------------MENU--------------- (1) Calcular suma de cuadrados (2) Determinar cantidad de palabras que finalizan con vocales en un texto (3) Determinar mayor cantidad de pares e impares (0) Salir INGRESE SU OPCION: """)) if opcion_menu == 1: numeros_generados = []...
af0fb3b76568c92b1f46d863d54d4f9cf3628cd4
saieesh1997/AdisPRoblemSTatement
/main.py
1,327
4.0625
4
# functions # function for additon def add(x, y): return x + y # function for subtraction def sub(x,y): return x-y # function for multiplication def mul(x,y): return x*y # function for division def div(x,y): if(y==0): print("number cannot be divided by zero") else: ...
34a98165a546334345ae75f0a3bffb1c51ba0432
sirifox/lesson2.2_homework
/venv/lesson 2.2.py
2,918
3.671875
4
class Farm_animal: instances = [] satiety = 50 # сытость по шкале 0-100 max_satiety = 100 character = 'neutral' mood = 5 # настроение по шкале 1-10 condition = 'standing in the pen' def __init__(self, weight, name='unnamed'): self.instances.append(self) self.weig...
215ac7cfe60289fff5332bd9dec84295c884428f
dillonp23/CSPT19_Sprint_1
/1.1/module_project.py
4,730
4.5625
5
# CodeSignal assignment for module 1.1 # """ Exercise 1: What are the steps in Lambda's U.P.E.R process? 1. Understand 2. Plan 3. Execute 4. Reflect """ """ Exercise 2: What to do in the "Plan" step of UPER? (multiple choice question) Create an actionable/easy to comprehend method of attacking the problem, ofte...
72a256e4d4506e093f3039c371702af26a34626a
gregorulm/advent_of_code_2016
/07/part2.py
1,694
3.71875
4
# Advent of Code 2016: Day 7, Part 2 # Gregor Ulm def findABA(s, acc): if len(s) <= 2: return acc else: top = s[0:3] if top[0] == top[2] and top[0] != top[1]: return findABA(s[1:], acc + [top]) else: return findABA(s[1:], acc) def makeBABs(abas): ...
548e9b4ffef6093b45072f7d0a471987659ec02b
gregorulm/advent_of_code_2016
/07/part1-recursion.py
1,194
3.765625
4
# Advent of Code 2016: Day 7, Part 1 # Gregor Ulm def hasAnnotation(s): if len(s) <= 3: return False else: top = s[0:4] if top[0] == top[3] and top[1] == top[2] and top[0] != top[1]: return True else: return hasAnnotation(s[1:]) def outside(s, out...
d36c5bbe01f71baf2f89c5d5326bafde2c6b00a0
gregorulm/advent_of_code_2016
/08/part2.py
1,639
3.734375
4
# Advent of Code 2016: Day 8, Part 2 # Gregor Ulm def rect(m, x, y): for col in range(x): for row in range(y): m[row][col] = 1 return m def rotateRow(m, row, c): # extract row, replace by shift version old_row = m[row] new_row = rotate(old_row, c) m[row] = new_row ...
1ad837f5d5024e9b36c8e4724ab1c1008a39aea3
tristanbriseno/functions
/functions.py
523
3.96875
4
def area(width, height): result = width * height return result result = area(5, 6) result_2 = area(3, 4) result_3 = area(2, 8) print(result) def subtract(num1, num2): result = num1 - num2 return result result = subtract(10,5) result_2 = subtract(9,3) print(result, result_2) def divide(num1, num2) ...
ef3dd307218756833f8c3ec10b551b9b9a9a4ae9
quadraticmuffin/discord-ftw
/main.py
3,753
3.546875
4
""" Math problem generator for practice and competition. Inspired by Art of Problem Solving's FTW, which was deprecated when Adobe Flash was phased out after 2020. """ import discord from discord.ext import commands import os import random import time import asyncio import json import problem_gen as pg RECORDS_PAT...
7403ab7cce485bdf34c5c19b618f57220dca1139
DavidKalitko/----Python
/HW_lesson2/HW_namber6.1.py
491
3.8125
4
goods = int(input("Введите количество товара: ")) n = 1 my_dict = [] my_list = [] while n <= goods: my_dict = dict({'название': input("введите название: "), 'цена': input("Введите цену: "), 'количество': input('Введите количество: '), 'eд': input("Введите единицу измерения: ")}) my_list.appe...
9a86adff1125243661b68d1617b4691b6fb64e40
Sanjay3234/Assignment
/class10.py
450
4.21875
4
# Question 1 :Write a program to create a user defined dictionary. User should enter the name of the key and the #name of the value he wants for any number of keys.? dic={} a="yes" while a=="yes": key=input("enter your key =") value=input("enter the value for the key =") if value.isdigit()==True: value=int(valu...