blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1d8b1bac521dfdfd75d71fb04dfc72af0ec84147
brendon977/programas_Python
/conversão_números.py
730
4.34375
4
#Escreva um programa que leia um numero inteiro qualquer #e peça para o usuario escolher qual será a base de conversão. #-1 para binário #-2 para octal #-3 para hexadecimal num= int(input("Digite um número inteiro: ")) print('''Escolha uma das bases para conversão: [1] converter para BINÁRIO [2] converter para OCTAL [...
9a4cfbfe012515eeba7d803fe42cb55bfa451a24
YordanPetrovDS/Python_Fundamentals
/_5_BASIC SYNTAX, CONDITIONAL STATEMENTS AND LOOPS/_4_Number_Between_1_and_100.py
240
4
4
number = float(input()) # while number not in (range(1, 101)): # number = float(input()) # else: # print(number) while number < 1 or number > 100: number = float(input()) print(f'The number {number:.0f} is between 1 and 100')
c62f85784072398e38232c9d866c58c1af2ebb4f
alephist/edabit-coding-challenges
/python/test/test_lowercase_uppercase_map.py
682
3.828125
4
import unittest from typing import Dict, List, Tuple from lowercase_uppercase_map import mapping test_values: Tuple[Tuple[List[str], Dict[str, str]]] = ( (["a", "b", "c"], {"a": "A", "b": "B", "c": "C"}), (["p", "s", "t"], {"p": "P", "s": "S", "t": "T"}), (["a", "v", "y", "z"], {"a": "A", "v": "V", "y": ...
505c4002f9c64f409dfca66aa86c35f511848d56
haoccheng/pegasus
/leetcode/bst_lca.py
582
3.609375
4
# LCA of BST. # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ def lca(root, p, q): if root is None: return None small = p.val if p.val < q.val else q.val large = p.val if p.val > q.val else q.val pcurr = root while pcurr is not None: if (small < pcurr.val) and (pcurr....
a69179a59508b2292e0b986c423257f7c494e970
andrew-yt-wong/ITP115
/ITP 115 .py/Assignments/ITP115_A1_Wong_Andrew.py
1,155
4.15625
4
# Andrew Wong, awong827@usc.edu # ITP 115, Spring 2020 # Assignment 1 # Description: # This program creates a Mad Libs story. # It gets input from the user and prints output. def main(): # Read in each word individually animal = input("Enter an animal: ") adj = input("Enter an adjective: ") adj2 = inp...
3f611464bcaf3903390e6805299ccd4cc2c7805c
Cbkhare/Codes
/IB_Linked_List_Swap_Pair.py
603
3.609375
4
class Solution: # @param A : head node of linked list # @return the head node in the linked list def swapPairs(self, A): swap = False old = None told = None head = None while A: nxt = A.next if swap: if told: told.next = A ...
00d31adfac08c34e575b0a66cab50636ef43083e
ansoncoding/CTCI
/Python/01_Strings_Arrays/CompressString.py
882
3.796875
4
def compress(string): length = len(string) if (length < 2): return string result = "" i = 0 while i < length: count = 0 char = string[i] result += char while ((i < length) and (char == string[i])): count += 1 i += 1 result +=...
982cbde5707b3e740ef329acd31a288c55b609e1
lapatka-py/mipt_course_ap
/homework5/ex_4_w5.py
415
3.8125
4
class Shape(): def __init__(self, number_1, number_2): self.height = int(number_1) self.wide = int(number_2) class Triangle(Shape): def area(self): return 0.5 * self.height * self.wide class Rectangle(Shape): def area(self): return self.height * self.wide ...
19ab29a46e6f58045323d02bde897c7d21a58aab
pengyuhou/git_test1
/leetcode/147. 对链表进行插入排序.py
885
3.71875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def insertionSortList(self, head: ListNode) -> ListNode: cur1 = head ret = [] while cur1: ret.append(cur1.val) cur1 = cur1.n...
c3e690c68704c30d71d6cfa2ea1b38bc3970fcc8
hz336/Algorithm
/LintCode/Binary Tree/Tweaked Identical Binary Tree.py
1,359
4.03125
4
""" Check two given binary trees are identical or not. Assuming any number of tweaks are allowed. A tweak is defined as a swap of the children of one node in the tree. Notice There is no two nodes with the same value in the tree. Example 1 1 / \ / \ 2 3 and 3 2 / ...
8d1ef27c358fa79247a38d318a5edb7f2b3ad7cc
pravallika231980/python_fullstack
/PythonFiles/prime.py
328
4.15625
4
num=int(input("enter the value:")) if num>1: if num==2: print("number is prime") for i in range(2,num): if num%i==0: print("Given number is not prime") break else: print("it is prime number") break else: print("Given number is not prime number") ...
472cc1dd14550479022ba75e76b5c764677cd1dc
marceloFA/grafos
/graph.py
8,510
3.921875
4
from vertice import Vertice from operator import itemgetter from random import choice class Graph: ''' Represents a graph through python's dictionaries''' def __init__(self,vertices=[]): ''' Creates a graph Arguments: vertices: A list of vertices to be added to the graph. Can be empty ''...
af147450919f42199fc9a22d3bfd6f6ef8bf5778
kayartaya-vinod/2020_SEP_ABB_ADV_PYTHON
/Day3/ex05.py
663
3.515625
4
class MyMetaClass(type): def __new__(mcs, *args): # <-- args is always a tuple consisting of class_name, bases, attrs # print(f'args is {args}') class_name, bases, attrs = args if '__str__' not in attrs: raise Exception(f'__str__ is missing in {class_name} class, but required.')...
b50205b56be000aa798192fe8f96188c15b5fbdb
AndongWen/cs2019
/07排序/05归并.py
2,449
3.5
4
def merge(old, new, low, mid, high): '''用于相邻的两个子序列的归并''' ''' old:原来的列表 new:用来转移用的新列表 low, mid, high:两个子序列的下标,采用左开右闭''' i, j, k = low, mid, low while i < mid and j < high: if old[i] <= old[j]: new[k] = old[i] i += 1 else: new[k] = old[j] j += 1 k += 1 # 上述循环结束时,两个子序列必有一个其中的元素没有全部转移完,此时只要 # 将剩...
592ea7171b293c5948bdef3bb27f370260989c01
sprax/1337
/python3/test_l0280_wiggle_sort.py
444
3.546875
4
import unittest from l0280_wiggle_sort import Solution class Test(unittest.TestCase): def test_solution(self): l = [3, 5, 2, 1, 6, 4] Solution().wiggleSort(l) self.assertTrue(l[0] <= l[1] and l[1] >= l[2] and l[2] <= l[3]) self.assertTrue(l[3] >= l[4] and l[4] <= l[5]) ...
fd4fbfc4f52b214957336dcef1d2f69026bb1047
NoxDineen/Hangman
/Hangman.py
602
3.703125
4
class Hangman: def __init__(self): pass def setPhrase(self, phrase): '''set the phrase for this game''' pass def realPhrase(self): '''return the real phrase without modification''' pass def hiddenPhrase(self): '''return the phrase with letters replaced ...
b2f9be19276fcc89f338bd2873d71fd441992977
amit-jaisinghani/PythonAssignments
/lab3/polygons.py
4,750
3.859375
4
import sys __author__ = 'asj8139,ass7436' """ Assignment 3: Polygons Author: Amit Shyam Jaisinghani, Aditi Shailendra Singhai This program draws polygons of decreasing sides, recursively until the shape is a triangle. It also calculates sum of all sides of the polygons drawn. """ import turtle # global constants...
c5fb97b11240d4d4d1352f3e585c8e4f0ffcd279
weirdwizardthomas/bi-zum-b182
/state-space-search-maze/src/navigator/navigator.py
4,386
4.1875
4
from abc import abstractmethod from src.exception.no_path_found_exception import NoPathFoundException from src.maze import Maze class Navigator: """ A class that handles finding a path from start to finish Attributes ---------- maze: Maze The maze to navigate edges: dict Edge...
34805aa6f086d475e128d146aa8c4b7b6057914b
varshajoshi36/practice
/leetcode/python/medium/searchRange.py
2,100
4.0625
4
""" Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3...
3c680495c7f8407d8b7cd8909c766a84fc85a39f
marwasha/vehicleControl
/include/vehicleControl/recordTestData.py
1,047
3.65625
4
import csv class recordTestData(object): """Class to print desired information""" def __init__(self, gps, state, input, savefile="test"): '''Sets up the csv writer and header''' data = self.merge(gps, state, input) csv_columns = list(data.keys()) csv_file = "/home/laptopuser/mk...
29bc8f763d05f89cac084a1f5a9875a7726536f1
ibykovsky/findMin
/main.py
1,225
3.734375
4
from math import sin from time import sleep # This is a sample Python script. # Press Ctrl+F5 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug you...
525a0b07710a6b64b83e37570cffe5b43d36c074
mnshkumar931/python-program
/list_p.py
281
3.75
4
l=[1,2,3,10,56,23,87,4,5,6,7] print(l[0:3]) print(l[::-1]) print(l[-1::]) l.append(8) print(l) l.pop() print(l) l.sort() print(l) l.reverse() print(l) l1=[2,3,4,[2,4,6,8],7] print(l1[3]) l2 = ['manish','ashish''nitesh'] print(l2[0]) print(min(l)) print(max(l))
3e9f9d0886a4a63a8ff556428981c0496fd50ecc
zzz136454872/leetcode
/reverseWords3.py
208
3.5
4
class Solution: def reverseWords(self, s: str) -> str: l=s.split() l=[i[::-1] for i in l] return ' '.join(l) sl=Solution() print(sl.reverseWords("Let's take LeetCode contest"))
cfb4c80fb6ba6436a9c3397012d1b3c7a141a125
offbynull/offbynull.github.io
/docs/data/learn/Bioinformatics/output/ch8_code/src/Stepik.8.15.FinalChallenge.py
6,020
3.71875
4
# As we mentioned earlier, gene expression analysis has a wide variety of applications, including cancer studies. In # 1999, Uri Alon analyzed gene expression data for 2,000 genes from 40 colon tumor tissues and compared them with data # from colon tissues belonging to 21 healthy individuals, all measured at a single t...
b84a22cef859f05578bb8120d23f40262d597baf
ovsienko/Itea-python
/2_lesson/shop.py
577
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Shop: _total = 0 def __init__(self, name, sells): self.name = name self.sells = sells Shop._total += sells def get_total(self): return self._total def set_sells(self, sells): self.sells += sells Shop._...
14258acf8fd2484435a0080983af3a0be88df7cd
TimMKChang/AlgorithmSampleCode
/DynamicProgramming/PalindromePartitioning.py
1,008
3.8125
4
from typing import List class Solution: def __init__(self): self.is_palindrome = None self.ans = None def find_palindrome(self, s): self.is_palindrome = [[False for _ in range(len(s)+1)] for _ in range(len(s)+1)] for j in range(len(s)): for i in range(0, j+1): ...
5849e4679bd8f30e39ba3a474a49589c2d722286
haodayitoutou/Algorithms
/ch2_heap_sort.py
626
3.734375
4
def sink(nums, idx, length): while idx <= length // 2: j = idx * 2 if j < length and nums[j] < nums[j + 1]: j += 1 if nums[idx] >= nums[j]: break nums[idx], nums[j] = nums[j], nums[idx] idx = j def heap_sort(nums): length = len(nums) - 1 for...
aefe8015d0ba257eda2ef2b9461c09b7af58fb9c
Abdullahtmk/Coursera-interactivePython
/week3/Exercisea/user46_DvNYgHst4Y_0.py
396
4.25
4
# Display an X ################################################### # Student should add code where relevant to the following. import simplegui # Draw handler def draw(canvas): canvas.draw_text("X",[0,36],48,"Red") # Create frame and assign callbacks to event handlers frame=simplegui.create_frame("Display X",96...
d5078743a5d6e107bc91e77e557bbb731979e8af
XisnZhang/learning
/machine_learning/ensemble_learning/bootstrap.py
442
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import random def bootstrap(samples): """ 有放回地随机选择 """ length = len(samples) result = [] for _ in range(length): result.append(random.choice(samples)) return result if __name__ == '__main__': samples = [1, 2, 3, 4...
4356c8675b998a1013f1c4b3487a9cbac18302e6
lzwjava/curiosity-courses
/oj/items.py
469
3.625
4
class Solution: def countMatches(self, items: [[str]], ruleKey: str, ruleValue: str) -> int: i = 0 if ruleKey == "type": i = 0 elif ruleKey == "color": i = 1 else: i = 2 n = 0 for item in items: if item[i] == ruleValue: n +=1 return...
1076ac74ba4d3d884ec4279172d4505bee9fc079
KipTheFury/Python
/RedditDailyChallenges/EasyChallenges/bottles_of_beer.py
759
4.125
4
''' write a program that will print the song "99 bottles of beer on the wall". for extra credit, do not allow the program to print each loop on a new line. Created on 12 Aug 2014 @author: kbennett ''' bottles = 99 while bottles > 0: if bottles > 1: print "%d bottles of beer on the wall\n%d bo...
3c05a24f309169a753b3574a2c5f5a00e9fe4046
undersfx/python-para-zumbis
/exerc_word_count_alice.py
809
3.75
4
#Importa lib de string para utilizar as pontuações import string word = 'alice' #Abre arquivo alice.txt em alice with open('alice.txt', encoding="utf8") as alice: #carrega o texto de alice em uma variavel. texto = alice.read() #Converte tudo para minusculo texto = texto.lower() #Substitui todos...
325f802eab1f2add538e97debbb27c85cde2e500
deltonmyalil/MachineLearningAndDS
/MachineLearning/Machine Learning A-Z Template Folder/Part 2 - Regression/Section 4 - Simple Linear Regression/mySimpleLinearRegression.py
1,833
4.0625
4
# My own Simple Linear Regression import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') # Replace with filename X = dataset.iloc[:, :-1].values # It's fine because most datasets will contain depVar in the last col y = dataset.iloc[:, 1]....
fcceb7dc417bb263806409e26acad72ba2d2c4ab
ShriSiva/ShriGitHub
/gameknock_codes.py
3,120
3.859375
4
## Primary Project 1 - "Python program to create a user-interface driven 'knock Knock' jokes" ## Name - Shriram Sivaraman ## Course - Introduction to Python Programming ## Course code - MSIT 3440 ## Description - The objective of the program is to present a user-interface driven “knock knock” jokes where both the...
b960c8bbd2c6cf29b5a1dca2f06965f503fc8365
Pankaj145-pb/Front-technologies
/anacom.py
484
3.640625
4
from collections import Counter def removeChar(str1, str2): dict1 = Counter(str1) dict2 = Counter(str2) keys1 = dict1.keys() keys2 = dict2.keys() count1 = len(keys1) count2 = len(keys2) set1 = set(keys1) commonKeys = len(set1.intersection(keys2)) if commonKeys == 0: ret...
6f1b8e97279fbd49c208bf8877a0fa56a45f186c
jfcjlu/APER
/Python/Ch. 09. Python - Weighted Mean and Standard Deviations.py
708
3.828125
4
# Python - WEIGHTED MEAN AND STANDARD DEVIATIONS from __future__ import division import numpy as np import math # Enter the values given as the components of the vector x: x = np.array([100.1, 100.2, 99.8, 100.3, 99.9, 100.2, 99.9, 100.4, 100.0, 100.3]) # Enter the corresponding weights w of the x values:...
8d9bd2f5b730a398713a9e670dc7e0e85762abbc
Viper-code/HeadsTails_Dice
/Random_Dice_or_Head_and_tails.py
688
4.15625
4
#Please enter roll, dice or flip, coin and nothing else! import random import time Dice = random.randint(1,6) f_coin = random.randint(1,2) start = input('please type roll to roll a dice, enter "filp" to flip a coin, enter "num" to get a random number: ') if start.lower() == 'roll': print(' Rolling........
aaeccaab32cd02154216fbd26e1d73d24bf7b0c8
RanjanShrivastva/PythonSeleniumAutomation
/PythonPrograms/PythonPrograms/Inheritence/P08_MultipleInheritance.py
659
4.25
4
""" Multiple Inheritance = Many parent classes but only child classes Multiple Inheritance is also called Diamond access Problem P_ = Parent C = Child GC = Grand Child """ class P1: def m1(self): print("I am parent-1 class") class P2: def m1(self): print("I am Parent-2 class") class C(P1...
3d45f82e7ae6b199b98c35376f6993983c5e562c
XiongQiuQiu/leetcode-slove
/Algorithms/741-Cherry-Pickup.py
3,542
4.25
4
''' In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you can pick up and pass through; -1 means the cell contains a thorn that blocks your way. Your task is to collect maximum num...
c5ecaf96d11f4164fc3b47f430a14a70c62602b9
Paker211/parker40105_sti
/sti_py/chapter8/8_1/9.py
412
3.703125
4
class Leg(): def __init__(self, num, look): self.num = num self.look = look class Animal(): def __init__(self, name, leg): self.__name = name self.leg = leg def show_name(self): return self.__name def show(self): print(self.show_name(), ' have ', self.leg...
8be4678833aa3625e2038207267038f1ba35347a
rafaelgama/Curso_Python
/CursoEmVideo/Mundo3/Exercicios/ex075.py
1,194
4.1875
4
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: # A) Quantas vezes apareceu o valor 9. # B) Em que posição foi digitado o primeiro valor 3. # C) Quais foram os números pares. cores = {'limpa':'\033[m', 'bverde':'\033[1;32m', 'roxo':'\03...
ee1549b65baa08c85953437516aba2245171c94c
Programmable-school/Python-Training
/lesson/lessonListTuple/main.py
1,909
3.859375
4
""" リスト型_タプル型 """ """ リスト型 データの配列。同型のデータを複数扱える """ nums1 = [0, 1, 2, 3] print(nums1) # [0, 1, 2, 3] print(nums1[0], nums1[3]) # 0 3 # 最後に新しい要素を追加 nums1.append(4) print(nums1) # [0, 1, 2, 3, 4] # 先頭に新しい要素を追加 nums1.insert(0, 5) print(nums1) # [5, 0, 1, 2, 3, 4] # 最後の要素を取...
a6b87045f14e7c7001f15ea00ab81516c5c7138f
qianli2424/test11
/qianliProject/day4/demo1.py
576
3.75
4
# -*- coding=utf8 -*- #@author:qianli # 文件说明: userlist = [['admin',123456],['test',123456],['root',123456],['mysql',123456],['sa',123456]] for user in userlist: for a in user: print(a,end='\t') print() #什么都不做,但会换行 for x in 'abcdefg': print(x,end='\t') print() for x in [1,2,3,4,5,6,7,8]: pr...
c484e4a92f6ae320794ae80c0b3c7503e62d4695
lijubjohn/python-stuff
/algorithms/linkedlist/linkedlist.py
1,301
4.3125
4
""" Pros Linked Lists have constant-time insertions and deletions in any position, in comparison, arrays require O(n) time to do the same thing. Linked lists can continue to expand without having to specify their size ahead of time (remember our lectures on Array sizing form the Array Sequence section of the course!) ...
4edeac1f718d5c1f152bd0e70783c82fcc7820dc
Jerry-Bang/python-learn
/lesson3/regex.py
414
3.65625
4
import re reg_exp = r"(\(.*\))|[A-Za-z0-9._-]+" rc = re.compile(reg_exp) def search_all(f): pos = 0 rlt = [] while pos < len(f): x = rc.search(f, pos) if x: rlt.append(x.group()) pos = x.end() else: break return rlt if __name__ == "__mai...
734ffe9daf7a08576dcd9b98f8aca490107f3418
Esteban-Hastamorir/calculadora
/calculadora.py
564
3.953125
4
def sumar (a,b): return a + b def restar (a,b): return a - b def multiplicar (a,b): return a*b def dividir (a,b): return a/b print ("Hola, como estas\n") a1 = float (input("Ingresa la primera cifra\n")) operacion = input ("Ingrese la operacion\n[+]Sumar\n[-]Restar\n[*]Multiplicar\n[/]Dividir\n") b2 = f...
941b1e4cadb9c055b586ba8039f026ecaa81e54f
laogenglgll/python
/33.PY
1,091
3.9375
4
#__ iter__():返回迭代器本身; #__ next__():这里写迭代的规律 import datetime as dt class IteR: def __iter__(self): return self class YeaR: def __init__(self,before): self.now = dt.date.today().year self.before = before self.c=[] def RyeaR(self,year): if (year%4 == 0 and year%100 != 0)...
c9960530e5d04484924c3f870c1696019c72c3d1
kickass9797/Testing
/rand/graph.py
4,025
3.515625
4
#Undirected, unweighted Graph class Graph(object): def __init__(self, graph_dict=None): if graph_dict in [0,None]: graph_dict = {} if type(graph_dict) is int: if graph_dict < 0: raise ValueError("Number of nodes can't be negative") self._...
76e54d70654b259cc906077fec519ca3eccad3d8
Zedmor/hackerrank-puzzles
/leetcode/73.set-matrix-zeroes.py
1,982
3.71875
4
# # @lc app=leetcode id=73 lang=python3 # # [73] Set Matrix Zeroes # # https://leetcode.com/problems/set-matrix-zeroes/description/ # # algorithms # Medium (42.40%) # Total Accepted: 300.7K # Total Submissions: 706.1K # Testcase Example: '[[1,1,1],[1,0,1],[1,1,1]]' # # Given a m x n matrix, if an element is 0, set ...
8ab1d7cab9b4ce8b2b506dab3184e5fa284aa8ae
dsushanta/learning-python
/com/bravo/johny/practice/class_and_objects.py
201
3.828125
4
class tree : name = "" fruit = "" def fruit_name(self): print(self.name+" gives : "+self.fruit) mango = tree() mango.name = "Mango Tree" mango.fruit = "Mango" mango.fruit_name()
349229f4d7cf8ab7c210285d89994c218dca770a
tsabbasi/data-structures-and-algorithms
/Python/linkedListImplementation.py
1,474
3.953125
4
class Node: def __init__(self, data): self.data = data self.next_node = None def traverse(self): # set current node # iterate through linked list, print nodes, until reached end of list node = self while node != None: print(node.data) node...
b4275909fc6f2e714909cdffe973b9f3459f2db6
CX4Life/AdventOfCode
/advent-5.py
784
3.921875
4
"""Day 5 of the 2017 Advent of Code challenge!""" __author__ = 'Tim Woods' INPUT_FILENAME = 'advent5-input.txt' def array_from_input(): ret = [] opened = open(INPUT_FILENAME, 'r') for line in opened: ret.append(int(line.rstrip())) return ret def go_through_instructions(list_of_inst): in...
84c6f6880ebe3b5cad80e02f6d5fdc3a2bd3447b
Wangchangchung/pystart
/day1/func.py
1,072
3.953125
4
# Author: Charse # 函数 def func1(): """testing1""" print('in the func1') return 0 # 过程 def func2(): '''testing2''' print('in the func2') x = func1() y = func2() print('from func1 return is %s' % x) # 没有返回值时None print('from func2 return is %s' % y) def test1(): pass def test2(): retur...
f1da618a1bbe74d9f03f1567b0f8c14eaeadb0e5
gastonpalav/frro-soporte-2019-08
/practico_01/ejercicio-06.py
230
3.828125
4
def inversa(cadena): index = 0 invertida = "" cant = len(cadena) for index in range(cant): cant -=1 invertida += invertida.join(cadena[cant]) print(invertida) inversa(input('ingresar cadena'))
295f002f8a48987a7714e2fc219010e77593fc2e
GuilhermeGGM/Estudos-python
/Calculdora de fatorial.py
159
4.0625
4
f = int(input('Digite o número que quer ver o fatorial: ')) for c in range(f, 1, -1): fa = f fat = fa*(fa-1) fato = fa*(fa-2) print(fat, fato)
3a7b17620816f816a30426f718ce87b28f5dc2cb
evacaiy/gy-2006A
/7/test.py
3,305
3.75
4
# a = 1 # b = 10 # print(a+b) # # # # a,b,c = [1,2,3] # print(a) # print(b) # print(c) # # x,y,*z = (1,2,3,4,5) # print(x) # print(y) # print(z) # # a = 10 # b = 20 # print(a+b) # print(a-b) # print(a*b) # print(b/a) # print(b % a) # print(3**3) # print(a//b) # # print(a==b) # print(a!=b) # print(a>b) # print(a<b) # pr...
9ea2497ab2bd1a1bb9a47c1c2af6ca463f376e6d
taufanpr/ora-py-py
/B.1.1. Python Fundamental for Data Science/09. for (1).py
548
3.78125
4
for i in range (1,6): #perulangan for sebagai inisialisasi dari angka 1 hingga angka yg lbh kecil drpd 6 print("Ini adalah perulangan ke -", i) #perintah jika looping akan tetap berjalan #Maksud dari fungsi for i in range (1,6): #jika kita konversi pada JAVA atau C sama dengan for(i=1;i<6i++). #J...
0e992ab97b1d93a0ccac9cabe751c81442df96f3
jiangxinyang227/leetcode
/热题HOT100/中等/105,从前序与中序遍历构造二叉树.py
1,274
3.890625
4
""" 根据一棵树的前序遍历与中序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / \ 9 20 / \ 15 7 """ from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class ...
6f530b7b9ed1eb94b29dcc46fe7f951c62d29a1b
imtiaz-mamun/bongo
/Question_2/Solution_Q2.py
3,328
3.671875
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 person_a = Person("User", "1", "") person_b = Person("User", "2", person_a) def print_depth(data): print("Current Parameter and Level:") ...
73e1dfc65a897ee05fcf0bc4389cc1b66202567c
mingddo/sunday_algorithm
/4일차_Stack1/서녕/SWEA_4873_반복문자지우기_정선영.py
395
3.65625
4
def erase(sentence): i = 0 tmp = [] while True: if i == len(sentence) -1: break if sentence[i] == sentence[i+1]: del sentence[i:i+2] i = 0 else: i += 1 return len(sentence) T = int(input()) for test_case in range(1, T+1): sente...
f724be7993345bb7dec2700288a4b9cf8879ecdd
simeongs/codeclub
/introductory_course/lessons/lesson_5-standard_library/standard_functions.py
1,311
4.03125
4
#abs() returns the absolute value of a number print(abs(-1)) print(abs(-100)) print(abs(0)) print(abs(45)) #all() returns True if all items in an iterable object are True print(all([True, True, True])) print(all([True, False, True])) print(all([False, False, False])) #any() returns True if at least one item in the i...
ff25329fb34d0312d49da28bc83e4a5b31b16bfc
mgperson/cauchy
/SIGN/src/tests/TestSIGN.py
518
3.71875
4
import unittest from ..SIGN import SIGN class testSIGN(unittest.TestCase): def setUp(self): self.sign = SIGN(2) def test_get_positive_and_negative_permutations(self): expected_len = 8 expected_permutations = [[-1, -2],[-1, 2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1]] self.asse...
be9c0a615342c6ff0dedf47fa6fe39958bd4cbb4
wpy-111/python
/DataAnalysis/day01/demo05_shape.py
319
3.890625
4
""" 维度操作 """ import numpy as np ary = np.arange(1,9) print(ary,ary.shape) b = ary.reshape(2,4) print(b,b.shape) ary[0] = 999 print(b) #ravel()变为一维数图 c = b.ravel() print(c) #复制变维 d = c.flatten() c[0] = 12 print(d,d.shape) print(c) #就地变维 c.shape = (2,4) c.resize(2,2,2) print(c)
cf6b6c959824a052e365d413640fbf4f8baaeb8b
hoque-nazmul/codingbat-problem-solving
/list-1/problem-8.py
194
3.828125
4
def max_end3(nums): larger_num = 0 first_num = nums[0] last_num = nums[-1] if first_num > last_num: larger_num = first_num else: larger_num = last_num return [larger_num] * 3
43af5390f668d96503f9c9bd8583e4dbc2f89464
noozip2241993/learning-python
/csulb-is-640/deitel-text/exercises/ch05/ex501.py
2,920
4.03125
4
''' (What’s Wrong with This Code?) print('c) name = 'amanda' name[0] = 'A' d) numbers = [1, 2, 3, 4, 5] numbers[3.4] e) student_tuple = ('Amanda', 'Blue', [98, 75, 87]) student_tuple[0] = 'Ariana' f) ('Monday', 87, 65) + 'Tuesday' g) 'A' += ('B', 'C') h) x = 7 del x print(x) i) numbers = [1, 2, 3, 4, 5] numbers.index...
29f894ae29d361069dcb3999d6c02fec42ffe81a
vinhpham95/python-testing
/BasicEditor.py
1,287
4.21875
4
# Vinh Pham # 10/11/16 # Lab 7 - Basic Editor # Reads each line from word.txt and copy to temp.txt unless asked to change the line. # Open appopriate files to use. words_file = open("words.txt","r") temp_file = open("temp.txt","w") line_counter = 0 # To count each line; organization purposes. # Read each line seperat...
0a350fd6687592569469c497c568ba2d52ee614e
sainadhreddy92/dsImplementations
/trie.py
2,087
3.734375
4
class trienode(object): def __init__(self): self.map = {} self.isCompleteword = False class solution(object): def addName(self,rootNode,word): for i in range(len(word)): if word[i] in rootNode.map: if i==len(word)-1: rootNode.isCompleteword = True rootNode = rootNode.map...
af929c9aedc86b034c20dc1f4f7efd081d522324
HYUNMIN-HWANG/LinearAlgebra_Study
/LinearAlgebra_Function/3.04.LeastSquares_matplotlib.py
1,372
3.6875
4
# Least Squares # 해방정식을 근사적으로 구하는 방법 : 구하려는 해와 실제 해의 오차의 제곱의 합이 최소가 되는 해를 구하는 방법 # 샘플 데이터 import numpy as np import matplotlib.pyplot as plt def make_linear(w=0.5, b=0.8, size=50, noise=1.0): # w : 기울기, b : y 절편 x = np.arange(size) y = w * x + b noise = np.random.uniform(-abs(noise), abs(noise), size...
cb1592b8103398fa4e4c9ea0611fb2840ea05651
puneetgupta4java/python-codes
/Dictionary.py
263
3.828125
4
dict1 = dict() print dict1 dict2 ={'a':1,'b':2} print(dict2) dict2['a'] = 1000 print dict2 for i in dict2: dict1[dict2[i]]= i print dict1 print dict1.clear() print dict1 print dict2.items() print dict2.keys() print("hello "*5)
e023c2df1882592401c96db5b8908efd6569e07c
jtenhave/AdventOfCode
/2019/Day6/c.py
956
3.5
4
import re orbitPattern = re.compile("(\w*)\)(\w*)") # Class that represents an orbiting object. class Object: def __init__(self, id): self.id = id self.parent = None # Total number of orbits this object has around the central mass. def totalOrbits(self): if not self.parent: ...
6096543c5575803e54df28fadf6ed9300fd86fe3
lsclike/Python_Practice
/GoodBook/heap_sorting.py
724
3.6875
4
def sort(unordered): leng = len(unordered) k = leng // 2 while k >= 1: sink(unordered, k, leng) k -= 1 while leng > 1: exch(unordered, 1, leng) leng -= 1 sink(unordered, 1, leng) def sink(arr, s, e): while 2 * s <= e: j = 2 * s if (j < e) and...
04805cc067fc741c6ab181a4c1056235b4fddc4f
rafaelgama/Curso_Python
/Udemy/Secao4/aula103/classes.py
1,255
3.875
4
# Herança sempre vem de cima para baixo na hierarquia. # Sobreposição de membros class Pessoa: def __init__(self, nome, idade): self.nome = nome self.idade = idade self.nomeClasse = self.__class__.__name__ def falar(self): print(f'{self.nomeClasse} falando...') # Herda os atri...
c350a998faf5281901712f8fccf7d21c9d70cd98
charliechocho/py-crash-course
/x7_multiples_of_10.py
226
3.875
4
check_for10 = input("Fyll i ett nummer så ska vi se om det är jämnt delbart med 10: ") if not int(check_for10) % 10: print("Ditt nummer är en multipel av 10") else: print("Ditt nummer är inte en multipel av 10")
7e5e21ba73680ead465ca34d4963d2b3e5332759
St3451/Linux_Python_Programming
/assignment5/handin5_test.py
1,057
3.53125
4
# 2. Create a new file, called handin5_test.py where you import the handin5 module. Then call the read_fasta function and save the result in a variable called fasta_dict import handin5 fasta_dict = handin5.read_fasta("Ecoli.prot.fasta") print(fasta_dict.keys()) # 4. In the handin5_test.py file, call the find_prot fun...
7a6075a2951805bbcb3800b4d2c0b3820cc8f6b4
AdityaRavipati/algo-ds
/set_matrix_zeros.py
507
3.671875
4
def set_matrix_zeros(A): C = len(A[0]) R = len(A) row = [1] * R col = [1] * C for i in range(0, R): for j in range(0, C): if (A[i][j] == 0): row[i] = 0 col[j] = 0 for i in range(0, R): for j in range(0, C): if row[i] == 0 ...
3e09251aba825259ca4e73beb7911d2da1978d59
gudduarnav/Acceleratron-Python-Workshop-Assignments
/assignment02/program_19.py
444
3.921875
4
# 19. Write a program to find greatest common divisor (GCD) or highest common factor (HCF) of given two numbers a, b = map(int, input("Enter 2 numbers:").split()) print("Numbers are",a,b) # find gcd gcd = a div = b while True: remainder = div % gcd if remainder == 0: # gcd found break e...
5cc75b21a38a021e8e18c238417e7b8b9f8430cc
CiscoDevNet/devnet-express-cloud-collab-code-samples
/itp/collab-python-parsing-json-itp/json_parse_1_sol.py
1,163
4.3125
4
var={"car":"volvo", "fruit":"apple"} print(var["fruit"]) for f in var: print("key: " + f + " value: " + var[f]) print() print() var1={"donut":["chocolate","glazed","sprinkled"]} print(var1["donut"][0]) print("My favorite donut flavors are:", end= " ") for f in var1["donut"]: print(f, end=" ") print() print() #Usin...
5ac246af231584ff2a2d8aaa8a3e5d3f0baab047
alinaromanenko/project5
/main.py
1,034
4.1875
4
letter_list = ['а', 'о', 'и', 'е', 'ё', 'э', 'ы', 'у', 'ю', 'я', 'А', 'О', 'И', 'Е', 'Ё', 'Э', 'Ы', 'У', 'Ю', 'Я'] answer = input('Нужно ли перевести фразу? ') while answer.lower() == 'да': letter = input('Введите первую букву цвета языка: ') text = input("Введите текст: ") for i in letter_list: ch...
afd69dac333a56966028cd3eb21cd1e69ac0f8ef
waltman/advent-of-code-2020
/day06/custom_customs.py
653
3.578125
4
#!/usr/bin/env python3 from sys import argv from collections import defaultdict questions = defaultdict(int) num_groups = 0 num_all = 0 group_size = 0 filename = argv[1] with open(filename) as f: for line in f: line = line.rstrip() if line: group_size += 1 for q in line: ...
b13e6d11f4f0d10a3c65ee37b8330a8e6618b106
theYBFL/20.21.10.1
/10a-if3.py
299
3.71875
4
#0-50 1 #50-60 2 #60-70 3 #70-85 4 #85-100 5 n1=int(input("1.not ")) n2=int(input("2.not ")) ort=(n1+n2)/2 #90 - 0-100 print(ort) if ort>0 and ort<50: print("1") elif ort>=50 and ort<60: print("2") elif ort>=60 and ort<70: print("3") elif ort>=70 and ort<85: print("4") else: print("5")
22a816e983aa603c92587d206b5720801198ff81
ColinWilder/pythonBasics
/Ch04-exs.py
1,669
4.15625
4
## Exercise 1 if 0==True: print("0 is true.") else: print("0 is false.") if 1==True: print("1 is true.") else: print("1 is false.") if 2==True: print("2 is true.") else: print("2 is false.") print("\n") ## Exercise 2 v=9 if v>=0 and v<=9: print("V passes the 0-9 test.") else: print("V...
b8dd24628a15e76de6690100fd750be909f9044c
nihalgaurav/Artificial-Intelligence
/ai_package01/AI_Practical24.py
194
4.1875
4
import matplotlib.pyplot as plt x = [1, 2, 3, 4] plt.plot([1, 2, 3, 4], list(a**2 for a in x)) plt.xlabel("-------some numbers-------->") plt.ylabel("-------squared value------->") plt.show()
c6088a32c9f861497abf91eead314a991fab7b4c
Sreenitti/Python-Projects
/Credit_Card_Validator.py
1,458
3.625
4
from tkinter import * def validate(card_no) : odd_sum = 0 even_sum = 0 double_list = [] number = list(card_no) for index, val in enumerate(number) : if index%2 !=0 : # odd index number odd_sum += int(val) else : # even index number double_list.append(int(va...
994a1c28df3a078037728433c97817fcd09e3597
Friction-Log/learning_python_frictionlog
/lessons/syntax.py
2,197
4.34375
4
# Print hello world print("Hello World") # create a string variable my_string = "Hello World" # concatenate two strings print(my_string + "!!!") # interpolate a string print("Hello %s" % "World") # interpolate a string with a number print("Hello %s %d" % ("World", 42)) # interpolate a string and assign to a varia...
2e73743f752f326f598879041f516dec1cac7c30
sutariadeep/datastrcutures_python
/Arraysandstrings/itoa.py
460
4.15625
4
#http://www.geeksforgeeks.org/implement-itoa/ def convert_to_string(num, base=10): if num == 0: return '0' if num < 0 and base == 10: num = -num elif num // base == 0: return chr(num + ord('0')) return convert_to_string(num // base, base) + chr(num % base + ord('0')) print convert_to_string(1567,10) prin...
b5ae9c4b8fe0e9a8e173dfe3b1d1b3f002a79311
zosopick/mathwithpython1
/Excersises/Chapter 4/1. Factor Finder.py
784
4.25
4
''' Make a program which asks the user to input an expression, calculates its factors and prints them It ought to handle invalid input by making use of exception handling ''' from sympy import symbols,factor,sympify from sympy.core.sympify import SympifyError def factorizer(expr): x,y=symbols('x,y') ...
4275701e04a54af336043eb9b1a13404a0fd9e6d
rachelrly/dsa-python
/solutions/linked-list-drills.py
1,702
3.671875
4
from ll import LinkedList from dll import DoublyLinkedList # llist = LinkedList() # llist.__insert_first__('one') # llist.__insert_last__('two') # llist.__insert_last__('three') # llist.__insert_last__('four') # llist.__insert_last__('five') dllist = DoublyLinkedList() dllist.insert_first('five') dllist.insert_last('...
a1143b729bfff1d0255a65352d7b04d9677be55f
lordpews/python-practice
/oops12.py
510
3.765625
4
class A: class_var1 = "i am a variable in class A" def __init__(self): self.var1 = "i am inside class A's contructor " self.class_var1 = "i am an instance variable in class A" self.sp = "spigot" class B(A): class_var1 = "i am a variable in class b" def __init__(self): ...
adaa91ae15d293cf27771f0a49725f1343883e36
daisykha/MultipleChoiceMarking
/load_file.py
1,373
3.71875
4
import tkinter as tk from tkinter import filedialog as fd from tkinter.messagebox import showinfo # create the root window class LoadFileDialog: def __init__(self): self.root = tk.Tk() self.root.title("Select an image") self.root.resizable(False, False) self.root.geometr...
dc29a1e01a2eeac9ef9dc3620f2dece96fd59398
jianhui-ben/leetcode_python
/265. Paint House II.py
2,066
3.65625
4
#265. Paint House II #There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. #The cost of painting each house with a certain color is repre...
44aed6b67e2e9c9556f9c655b0420ec2999c8f07
jennypeng/python-practice
/Web/horoscope.py
1,700
3.6875
4
import urllib2 import sys from bs4 import BeautifulSoup def getHoroscope(sign, horoscope_type): """ Retrieves horoscope from site according to SIGN and HOROSCOPE_TYPE. """ url = "http://www.elle.com/horoscopes/daily/" + sign + "-" + horoscope_type + "-horoscope" page = urllib2.urlopen(url).read() ...
bd61d20f5dedbe3996c9abba3dc68acc067cd61f
numberjun/numberfirst
/pillow/生成验证码.py
1,840
3.53125
4
#代码借鉴了廖雪峰的官方网站 from PIL import Image, ImageDraw, ImageFont, ImageFilter import random # 随机字母: def rndChar(): return chr(random.randint(65, 90)) # 随机数字: def rndNum(): return str(random.randint(0,9)) #随机中文 def rndChinese(): pass # 随机颜色1: def rndColor(): return (random.randint(64, 255), random.randint...
321c4fe59eab1cded00ca25285c03d582f499a00
VrushitG/Py_Cwh
/tut5.py
646
3.828125
4
import flask #Pleas Dont remove this line """ Pleas Dont remove this line this is multi - line comment """ print("Hello World""This is vrushit G") print("Hello World","This is vrushit G") #this is for adding space betweent two statment print("Hello World", end=" Joker ") #end function for adding somthing in new...
13d1c2eed60d53c799b78e0e1aba7ffc8645a251
Vampirskiy/helloworld
/venv/Scripts/Урок4/why_funk_param.py
207
3.609375
4
def my_filter(numbers): result = [] for number in numbers: if number % 2 == 0: result.append(number) return result numbers = [1, 2, 3, 4, 5, 6, 7, 8] print(my_filter(numbers))
060039d16dd15ad334c507dc359f275aa2462c4f
AdityaGudimella/python_practice
/python_practice/iterables.py
664
4.46875
4
import typing # Implement every function in functools and more_itertools and itertools using python loops # Write a function that finds the length of an iterable without storing it in memory. def iter_len(iterable: typing.Iterable) -> int: """ Return len of iterable without storing it in memory """ # Write a fun...
c58e4cccf6a7debe210ee51e79b60c3eb0a774b9
krsthg/python3
/문제300/211~220.py
756
3.515625
4
#211 #안녕 Hi #212 #7, 15 #213 #함수에 인수가 없기 때문이다 #214 #문자와 정주는 더할 수 없기 때문이다. #215 def print_with_smile(): a = input() print(a+ " :D") #216 print_with_smile() #217 def print_upper_price(): a = int(input()) print(a*1.3) #218 def print_sum(): a = int(input()) b= int(input()) print(a+b) #21...
bcbda1e7458cb35c5df43ace3c3d3dba563a4543
piazentin/programming-challenges
/hacker-rank/implementation/caesar_cipher.py
691
3.890625
4
# https://www.hackerrank.com/challenges/caesar-cipher-1 alpha_max = ord('z') - ord('a') + 1 def round_char(c, rounds, limit): c = ord(c) + rounds if c > ord(limit): return chr(c - alpha_max) else: return chr(c) def cipher_char(c, rounds): if 'a' <= c <= 'z': return round_ch...
7d673f7bc713efa81643359430071d234860ecf1
kyuugi/saitan-python
/やってみよう_必修編/chapter09/9_15_lottery_analysis.py
2,150
3.671875
4
from random import choice def get_winning_ticket(possibilities): """当選したくじの番号を返す""" winning_ticket = [] # 同じ数字や文字を繰り返さないために while ループを使用する while len(winning_ticket) < 4: pulled_item = choice(possibilities) # 存在しない数字や文字の場合だけ、当選した番号のリストに追加する if pulled_item not in winning_ticket...
85fff930ebc26a8527c481d3d20fa5aa95d77b49
debolina-ca/my-projects
/Python Codes 1/Formatting Date Time Objects in Print.py
1,239
3.84375
4
# Formatting time objects from datetime import time t = time(hour = 10, minute = 15) # display as 10:15 AM # string passed to strftim includes all necessary spaces and semicolons formatted_string = t.strftime("%I:%M %p") print("First format: ", formatted_string) # display as 10:15:00 (24 hour clock, no AM/...
342a47f223a8445dc5a4a74defbd9a99881f3027
ryndovaira/leveluppythonlevel1_300321
/topic_02_syntax/examples/03_bool.py
762
3.75
4
print("type(True) = >", type(True)) print("True + 3 = >", True + 3) print("False + 3 = >", False + 3) print("True == 1 = >", True == 1) print("True == 77 = >", True == 77) print("False == 0 = >", False == 0) print("False == '0' = >", False == '0') print("bool(77) = >", bool(77)) print("bool(-77) = >", bool(-77)) print...