blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
622802c2c4585b44f964610ad45cec590093be48
pvr30/Python-Tutorial
/HackerRank Questions/swapstring.py
990
4.09375
4
""" def swap_case(s): temp = '' for str in s: if ord(str) >= 65 and ord(str) <= 91: temp += str.lower() elif ord(str)>=97 and ord(str)<=123: temp += str.upper() else: temp += str return temp if __name__ == '__main__': s = input() result = ...
4677f719b8fb4ab8598472a3ce534062c324d36a
pvr30/Python-Tutorial
/Python Fundamentals/lambda function.py
1,860
4.75
5
# lambda function. # Lambda functions are functions that are almost solely used to get inputs and return outputs. # That means we don't often use them to make actions. # For example, the `print()` function is a function # that performs an action. As such, it would not be suitable for lambda function. # If we wanted a ...
628ec65ce6ca76660fe819eb6e0363fc2531f850
yikeanna/Co2-Emissions
/add_continents.py
3,645
3.8125
4
#Anna Zhang #260985734 def get_iso_codes_by_continent(filename): """ (str)->dict The function returns a dictionary mapping continents’ names (all upper case) to a list of ISO codes (strings) of countries that belongs to that continent. >>> d = get_iso_codes_by_continent("iso_code...
a61bbe85afeefd1d3625e6cde6814281c8d4e9e3
hermetikos/algorithms-python
/tests/test_linked_list.py
6,006
3.53125
4
import unittest import data_structures import linked_lists.linked_list_sum from linked_lists.linked_list_with_arbitrary_pointer import LinkedListNodeWithArbitraryPointer, deep_copy_linked_list_with_arbitrary_pointer class TestLinkedListSum(unittest.TestCase): def test_linked_list_sum(self): # note the va...
d2e3905322f2f6ee19c3478f995683495d7e8eaf
hermetikos/algorithms-python
/trees/connect_all_siblings.py
1,347
4.34375
4
# "Given the root to a binary tree where each node has an additional pointer called sibling (or next), # connect the sibling pointer to the next node in the same level. # The last node in each level should point to the first node of the next level in the tree." # taken from: # https://www.educative.io/m/connect-all-sib...
779d923dc2304632a3750c0f79a9cb1b7c6f702c
hermetikos/algorithms-python
/graphs/dungeon_problem.py
3,504
3.71875
4
# the dungeon problem is a pathfinding problem # a r * c grid of of n rows and columns # represents a "dungeon" that must be navigated from the start square to the end # if possible, and each grid squares may be empty or obstructed from data_structures import GraphAdjacencySet as Graph from collections import deque # ...
dff9fd3964b6656515e252db50d790e1adbc13f0
hermetikos/algorithms-python
/swap/adding_swap.py
407
3.953125
4
# counting sort def swap(input, i, j): input[i] += input[j] input[j] = input[i] - input[j] input[i] -= input[j] # x = x + y # y = x - y # x = x - y # OR # x := x + y # y := (x + y) - y = x # x := (x + y) - x = y def driver(): data = [10, 5] print("Before swap:") ...
d61438461e5746cc2ae7cf0435e096f6bc46a6cf
tesladodger/Temperature-Converter
/tempformulas.py
1,224
3.640625
4
def celcius(temp_c) : try: temp_c = float(temp_c); except ValueError: print('\n\nNot a number, idiot...\n\n') return; in_k = temp_c + 273.15; if (in_k < 0) : print('\n\nNice try, fag...\n\n') return; in_f = temp_c*(9/5)+32; print('\n_______________________\n') print("In Kelvin: ", in_k...
89338c22797622c2730db5d936ffd564daf3bc48
msunij/base
/Python/Trivial Math Funcitons/6.2.py
174
3.6875
4
def sqrt (n): approx = n/2.0 better = (approx + n/approx)/2.0 while better != approx: print better approx = better better = (approx + n/approx)/2.0 sqrt(25)
83f745315a0db3923ac1d4cd31388ee18c622f48
msunij/base
/Python/Trivial List Functions/lab7Test.py
296
3.796875
4
#listC = [[1,2],[3,4]] listC = [['a','b'],['c','d']] def doublelist(listC): for indexC in range(len(listC)): listD = listC[indexC] for indexD in range(len(listD)): listD[indexD] = listD[indexD] * 2 listC[indexC] = listD print listC doublelist(listC)
8888d46889946f988eb20fc501f535f5c8b0bd90
brandonartner/algorithms-python
/mcs-tree/kruskal.py
2,178
3.59375
4
import pprint import re import sys import math def has_edge(edges,start,end): contains_edge = 0 for edge in edges: if edge[0] == start and edge[1] == end: contains_edge = 1 break return contains_edge def display(T, n): for i in range(n): if i > 0: ...
f707d0f3c18fab509a4c21a45be513250a51b533
jeongwook/python_work
/ch_08/8_4_large_shirts.py
291
3.953125
4
def make_shirt(size='large', message='I love Python'): """Summarize the size of the shirt and the message printed on it.""" print("Your shirt size is " + size + " and has " + '"' + message + '"' + " written on it.") make_shirt() make_shirt('medium') make_shirt('small', 'I love coding')
642d435844ef25188ae6a8acef44a77bd143fef5
jeongwook/python_work
/ch_07/7_5_movie_tickets.py
299
4.0625
4
prompt = "How old are you?" prompt += "\nEnter 'quit' when you are finished. " while True: age = input(prompt) if age == 'quit': break elif int(age) < 3: print("Your ticket is free.") elif int(age) < 13: print("Your ticket is $10.") elif int(age) >= 13: print("Your ticket is $15.")
2588aceb689a54fffb73aa6ec4390f9514d7a74e
jeongwook/python_work
/ch_03/3_6_more_guests.py
576
3.8125
4
list = ['Jason', 'Dave', 'Josh'] print(list[0] + ", you are invited to dinner.") print(list[1] + ", you are invited to dinner.") print(list[2] + ", you are invited to dinner.") print("\nI have found a bigger table\n") list.insert(0, 'Jin') list.insert(2, 'Rodney') list.append('Kevin') print(list[0] + ", you are invi...
df049bec134bf731569b65e0e0b7dc004f647fc4
jeongwook/python_work
/ch_03/3_8_seeing_the_world.py
759
3.90625
4
places_to_visit = ['Korea', 'Japan', 'Hawaii', 'Buenos Aires', 'Jackson Hole'] print("Original list:") print(places_to_visit) print("\nTemporarily sorted alphabetically:") print(sorted(places_to_visit)) print("\nOriginal list again:") print(places_to_visit) print("\nTemporarily sorted in reverse (alphabetically)") p...
dead3b2bf81eaf18544143d9a388a66f2d22f8ca
jeongwook/python_work
/ch_09/users.py
569
3.875
4
"""Class to represent all kinds of users.""" class Users(): """User object.""" def __init__(self, first_name, last_name, sex, age): """Initialize user attributes""" self.first_name = first_name self.last_name = last_name self.full_name = first_name + " " + last_name self.sex = sex self.age = age def ...
d72b378f3c8f9971a19fc7d71eb34c92961b60f4
jeongwook/python_work
/ch_08/8_12_sandwiches.py
241
4.40625
4
def sandwiches(*items): """Output the type of sandwich based on items given""" print("Making your sandwich which consists of: ") for item in items: print("- " + item) print() sandwiches('lettuce', 'tomato', 'onions', 'cheese', 'ham')
88186f7db9004722d0ced920b4ff682a13673756
jeongwook/python_work
/ch_12/12_3_rocket.py
2,357
3.734375
4
import sys import pygame class Ship(): def __init__(self, screen): """Initialize the ship and set its starting position.""" self.screen = screen # Load the ship image and get its rect. self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect...
40d087870e39fa3b560e80a6e315814a02618a99
jeongwook/python_work
/ch_11/test_employee.py
503
3.625
4
import unittest from employee import Employee class TestEmployee(unittest.TestCase): """Tests for class Employee""" def setUp(self): self.employee = Employee('Juan', 'Yu', 115000) def test_give_default_raise(self): """Test default raise""" self.employee.give_raise() self.assertEqual(self.employee.annual_s...
9117769c3046e04e3a75fd6f7364b11de26ab1a9
jeongwook/python_work
/ch_04/4_11_my_pizzas_your_pizzas.py
292
4.25
4
pizzas = ['meat lovers', 'avocado pesto', 'hawaiian'] friend_pizzas = pizzas[:] pizzas.append('cheese') friend_pizzas.append('veggie') print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("\nMy friend's favorite pizzas are:") for pizza in friend_pizzas: print(pizza)
ce1d7c7f5b147090cf9f825c56ecfc4e9698993e
JWHanna/Election-Analysis
/PyPoll.py
3,451
4.25
4
# Program Outline # 1. The total number of votes # 2. A complete list of candidates who recieved votes # 3. The percentage of votes each candidate won # 4. The total number of votes each candidate won # 5. The winner of the election based on popular vote # Add dependencies import csv import os # Assign a variable fo...
4baf01f860895f856884dd656d4b3e0f10f4a447
NikitaSUAI/NeuralLib
/NN.py
4,645
3.515625
4
import numpy as np import json # plt - need to take away import matplotlib.pyplot as plt from typing import List, Dict class NN: """Class provides an opportunity to create and train your own neural network. """ def __init__(self, **params): """Configure your own network with key-word args ...
1180b26f6e6d466b6c3e2c11f10bfdd2f78e7dd9
sdurgut/HackerRank
/Algorithms/fibonacci.py
300
3.578125
4
def fib(n): a,b = 0,1 for _ in range(n): a,b = b,a+b return a def fibR(n): if n==0: print("AAAAAAAAAAAAAAAA") return 0 elif n==1: return 1 else: return fibR(n-1) + fibR(n-2) # for i in range(100): # print(fib(i)) print("######################") for i in range(10): print(fibR(i))
43eeb5588f50e81ce53ddaefe4cedd54929ea61a
sdurgut/HackerRank
/Algorithms/MergeLists.py
382
4.03125
4
l1 = [1, 3, 4, 7] l2 = [0, 2, 5, 6, 8, 9] def mergeSortedLists(l1,l2): result = [] list1 = l1[:] list2 = l2[:] while list1 and list2: if list1[0]<list2[0]: result.append( list1.pop(0) ) else: result.append( list2.pop(0) ) if list1: result.extend(list1) else: result.extend(list2) return result ...
282e0f7e989af10dc0ff8de99679737b45308953
sdurgut/HackerRank
/Algorithms/BalancedBrackets.py
482
3.609375
4
import sys def isBalanced(s): pairs = { ')':'(',']':'[','}':'{','(':')','[':']',"{":"}" } stack = [] for i in s: if len(stack)==0: stack.append(i) if i in "([{": stack.append(i) else: if stack[len(stack)-1] == pairs[i]: stack.pop() else: stack.append(i) if len(stack) ==0 : return 'Y...
b60f96be562c4f9ba1b797dbaab7bdcabe2e9414
sdurgut/HackerRank
/Algorithms/SteppingStonesGame.py
378
3.953125
4
# https://www.hackerrank.com/challenges/stepping-stones-game import math def isTriangular(x): n = (math.sqrt(8 * x + 1) - 1) / 2 if int(n) == n: return int(n) return -1 if __name__ == "__main__": T = int(input().strip()) for i in range(T): N = int(input().strip()) steps = isTriangular(N) print ('Go On B...
0e6d0d630c19278fe0955ad54ac738841e019a88
theseanathan/leetcode
/medium/coin_change_2_WIP.py
1,613
3.875
4
""" You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. Note: You can assume that 0 <= amount <= 5000 1 <= coin <= 5000 the number of coins is les...
fd55d6a3bc50c7d2f939338e0b0dbf94c4eb9c1e
allmonday/tour-of-python
/inherit/sub.py
664
3.984375
4
class Father(object): '''father class''' def __init__(self, name): '''init''' self.name = name def sayName(self): return self.name class Child(Father): def __init__(self, name, age): Father.__init__(self, name) self.age = age def sayName(self): ret...
7ace9c598339d1ffe923176798f438761d44d5fd
prateeksahu10/assignment2
/assignment2.py
581
3.9375
4
# q1 print something print("jai bhadrakali") # q2 concatinate strings a=("jai ") b=("bhadrakali") print(a+b) # q3 print 3 user variables x=input("enter 1st var") y=input("enter 2nd var") z=input("enter 3rd var") print(x,y,z) # q4 print lets get started a1="Let's Get Started" print(a1) # q5 print given value using p...
67b8d60d7de838d11d94b47dcfd7f0ca95258689
jrc0rey/Learning-Python-The-Hard-Way
/ex40.py
577
3.859375
4
#Modules, Classes, and Objects #Classes are Uppercase class Song: def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print(line) happy_bday = Song(["Happy Birthday to you", "I don't want to get sued", "So I'll stop right there" ]) b...
cb6ead74c69a2ff2709cf64b9a81b40d6142ebe6
jrc0rey/Learning-Python-The-Hard-Way
/My_Projects/api_connect_weather.py
1,384
3.671875
4
#Attempts to connect to Open Weather api via python import requests import json api_key = '10e0eab204568320634ff5d1096bc32f' # res = requests.get('http://api.openweathermap.org/data/2.5/weather?zip=%r,us&appid=%s' % (zip_code, api_key)) # if res: # print("Boom shaka laka!") # else: # print("Epic fail :(") ...
b7c2b9b70359368625b3bd03520816340b049635
jrc0rey/Learning-Python-The-Hard-Way
/ex16.py
787
4.03125
4
#Reading & Writing Files from sys import argv script, filename = argv print " We are gonna erase %s." % filename print "If you don't want that hit CTRL-C." print "If you do want that, hit RETURN." raw_input("?") answer = raw_input("Are you sure you want to erase %s?: " % filename) if answer == "yes": target = ...
2bddc3b8824061b5b36b319b7e9f6716c68f42d8
zby0902/CV-guru
/Module1/drawing.py
2,153
3.71875
4
#!/usr/bin/env python import numpy as np import cv2 canvas = np.zeros((300,300,3),dtype="uint8") #draw a green line from top left to bottem right green = 0,255,0 cv2.line(canvas, (0,0),(300,300),green,5) cv2.imshow("Canvas",canvas) cv2.waitKey(0) # now, draw a 3 pixel thick red line from the top-right corner to th...
f0661b22f8577ec641834904a5f3b936c91b2740
baton10/lesson_001
/HW_001/002_for.py
1,450
3.65625
4
# FOR word = 'irresponsible' for word_test in word: print(word_test) # № 1 numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: number +=1 print(number) # № 2 line = input('введите строку ') for letter in line: print(letter) """ school = [ {'school_class': '4a', 'scores': [3, 4...
22860ea81e7c65fca1c7407387b7531c78e16886
baton10/lesson_001
/002_hello.py
89
3.609375
4
name = input ("введите ваше имя") print ("Привет, {}".format (name))
436bb2e3adf5228e3442ed147abe3aed559e3a26
Adi1729/Coding_100
/buy_and_sell_stock2.py
1,162
3.953125
4
# -*- coding: utf-8 -*- ''' Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and...
4555091a5725d040873bf7239c97a8b84de0bfdc
Adi1729/Coding_100
/Nth_magical_number.py
1,492
3.765625
4
''' A positive integer is magical if it is divisible by either A or B. Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7. Example 1: Input: N = 1, A = 2, B = 3 Output: 2 Example 2: Input: N = 4, A = 2, B = 3 Output: 6 Example 3: Input: N = 5, A = 2, B = 4 Output: 10 Ex...
c37d45b19543d3e6cf4cd6c27646b63aa2faab7f
Vinitpal/devsnest-dsa-problems
/day22/01_graphs.py
1,465
3.65625
4
# A graph is a data structure that consists # of the following two components: # -> Nodes (a,b,c,d) # -> edges (ab, ac, ad, bc, bd, cd) # now edges may also include its weight/cost/value # suppose we have 4 nodes (a,b,c,d) # so those four nodes could be connected like this # (ab, ac, ad, bc, bd, cd) #...
778d1262484d07bc656989d639ea892fb32a0ce4
Vinitpal/devsnest-dsa-problems
/day13/width_of_binary_tree.py
934
3.640625
4
Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def getWidth(root, rootlevel, rootIndex, widthMap): if root: if rootlevel not in widthMap: widthMap[rootl...
dcde3e9a5841419718da51eb607b979ec294fc62
Vinitpal/devsnest-dsa-problems
/day18/inorder_successor.py
798
3.71875
4
#User function Template for python3 ''' class Node: def __init__(self, val, k): self.right = None self.data = val self.left = None self.key = k ''' class Solution: # returns the inorder successor of the Node x in BST (rooted at 'root') def inorderSuccessor(self, ...
c7a1a2e6aa63ab60c6325d7e863721fd54587d8a
Vinitpal/devsnest-dsa-problems
/day5/sum_of_two_integers.py
3,518
3.984375
4
# This is the best explanation for this problem I could find: # Following is an excerpt form Cracking the Coding Interview book: https://www.careercup.com/book # Our first Instinct in problems like these should be that we're going to have to work with bits. # Why, Because when you take the + sign, what other cho...
ad758ada4f31d3f785699fe4620f87429f7126fb
Vinitpal/devsnest-dsa-problems
/day24/generate_a_graph_using_py_dict.py
1,230
3.953125
4
# graph = { "a" : ["c"], # "b" : ["c", "e"], # "c" : ["a", "b", "d", "e"], # "d" : ["c"], # "e" : ["c", "b"], # "f" : [] # } from collections import defaultdict class Graph: def __init__(self): # default dictionary to store graph ...
b679d7ce1265354ae399bf469536686468534285
Vinitpal/devsnest-dsa-problems
/day24/find_the_town_judge.py
621
3.609375
4
from collections import defaultdict N = 3 trust = [[1,3],[2,3]] def findJudge(n, trust): graph = defaultdict(list) new = defaultdict(list) for i in range(len(trust)): # graph is dictionary of peoples who trust judge graph[trust[i][1]].append(trust[i][0]) ...
cdf8bd936eaf3f5c6645734cdded292587cf56b2
Vinitpal/devsnest-dsa-problems
/day19/insert_in_levelOrder_in_BT.py
1,357
4.28125
4
# Given a binary tree and a key, insert the # key into the binary tree at the first position available in level order. class TreeNode(): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def inorder(root): if root: in...
ac6fe946a602f759b3d22309daff7b3d27385760
HashimMufti/ff7b5985-6cd4-4c60-ab99-79b3c767f74e
/kmartRunner.py
2,263
4.125
4
import argparse def runFromFile(inputFile): """Runs findLongestLength on each line in input file, returning an array of arrays as solution. Args: inputFile (String): Name of inputfile to run on Returns: Array: An array containing n number of arrays (where n represents the...
f2fcbcb2062f947d7daafdd8e7b754b81764b3f6
UNR-Teaching/class-activity-3-evanbrown-unr
/tictactoe.py
2,729
3.75
4
# class for gameboard structure and logic class Gameboard(): def __init__(self): self.board = [['-','-','-'], ['-','-','-'], ['-','-','-']] def show(self): for i in range(len(self.board)): print(self.board[i]) def spot_exists(self, r...
8bce0786240c5ac44ce5cea4fac1417811529ecc
marth00165/pythonBasics
/balance.py
439
3.734375
4
def is_balanced(s): map = { '(':')', '{':'}', '[':']' }; stack = []; for b in s: if b == '{' or b == '[' or b == '(': stack.append(b) elif len(stack) == 0: return 'NO'; else: last = stack.pop(); if b != map[...
6d92793437dafdad8d4e088d15cefd1c044e3ab0
marth00165/pythonBasics
/lesson4.py
956
4.3125
4
print("Lesson 4 - Strings\n") # prints a new line after the string print("\"Print a quotation\"\n") print("Print a \\\n") word = "jawn" print("Print the variable: " + word + "\n") caps = "WE DONT LIKE BOULS WHO CAP" print("Lower Case: " + caps.lower() + "\n") low = "my Flow highkey" print("Upper Case: " + low.upper() +...
0f315a5830832745c2be219f6e16a526cf6d8cdb
marth00165/pythonBasics
/numberswithevenamountofdigits.py
206
3.703125
4
def findNumbers(nums): total = 0 for number in nums: size = len(str(number)) if size % 2 == 0: total += 1 return total print(findNumbers([12, 345, 2, 6, 7896]))
1284506279317d07487786ad5fd59f7ab95023dc
marth00165/pythonBasics
/squareArr.py
282
3.90625
4
arr1 = [5, 10, 20, 30] arr2 = [] arr3 = [] def square_arr(arr): for x in arr: arr2.append(pow(x, 2)) print(arr2) square_arr(arr1) print("") def square_arr_2(n): return pow(n, 2) def answer(arr): print(list(map(square_arr_2, arr))) answer(arr1)
49349d013c874922197b2950f1697943ec43dbba
marth00165/pythonBasics
/lesson6.py
1,032
4.25
4
from math import * name = input("Enter your name: ") team = input("Hello, " + name + " who do you work for.. ") print("ahh you're a member of the, " + team + " I see...") print("") print("") print("Basic Calculator\n\n") # Basic Calculator num1 = input("enter the first number: ") num2 = input("enter the second number...
46bc45bb39b651cebe525f460cb3428a66e3948e
marth00165/pythonBasics
/badgeMaker.py
66
3.71875
4
name = input('enter your name: ') print(f'Hi my name is {name}')
7939f6bc1ace1c06ecb9e83afd6810b9d8edafa4
nodata21/rockpaperscissors
/rockpaperscissors.py
1,692
3.671875
4
import random import colorama from os import system, name from colorama import Fore, Style from time import sleep aiwin = 0 playerone = 0 lastcatch = 0 hand = ["rock","paper","scissors"] def catch(hand, aihand): beats = {"rock": "scissors", "paper": "rock", "scissors": "paper"} if hand == aiha...
968dfb79c3c03f24089df45346d88cfb63c53ea5
deyvison/jogoDaForcaPython
/bibForca.py
592
3.6875
4
def Entrada (): print('Bem Vindo ao jogo da forca!!') print('Objetivo do jogo: descobrir uma palavra adivinhando as letras que ela possui.') print('O jogo acaba quando você acerta a palavra ou suas possibilidades se esgotam!\n') def ValidaJogada(letra,jogadas): if letra in jogadas: return True...
7af7bde502c28d7114ec295a2286b0ad2db3fcbe
pauladepinho/clube-de-programacao
/2019-10-22/removerElementosDuplicados.py
740
3.625
4
# Remove elementos duplicados da lista def removerElementosDuplicados (lista): if (len (lista) == 0): return 'A lista está vazia.' indice = 0 proximoIndice = 1 while (indice < len (lista) - 1): elemento = lista [indice] while (proximoIndice < len (lis...
08bfba4c4c2bc95d0a077f46388a70bead104855
pauladepinho/clube-de-programacao
/2019-10-29/maiorValor.py
747
4
4
# 2 - Recebendo três valores do usuário. # Faça um programa que indique qual o maior valor dos inputs recebido. def maiorValor (inputs): maiorElemento = inputs [0] proximoIndice = 1 print (maiorElemento) while (proximoIndice < len (inputs)): if (inputs [proximoIndice] > maiorElemento): ...
6b843dd51409992b8e85d2fa6c67b35b4aff788e
renato-bombardelli/Biopython-learning
/5.1.py
1,322
3.59375
4
from Bio import SeqIO ''' with open("ls_orchid.fasta") as handle: for seq_record in SeqIO.parse(handle, "fasta"): print(seq_record.id) print(repr(seq_record.seq)) print(len(seq_record)) ''' #5.1.2 Iterating over the records in a sequence file ''' first_record = next(SeqIO.parse("ls_orchid.fasta", "fasta")) print...
484f0c55bdd90405fcafead289a81e9e97fd356b
alllllli1/Python_NanJingUniversity
/2.6.1/example2.py
294
3.5
4
# -*- coding: utf-8 -*- # @Time : 2020/3/20 15:02 # @Author : wscffaa # @Email : 1294714904@qq.com # @File : example2.py # @Software: PyCharm def f2(n): if n >= 2 : f2(n//2) print(n%2,end=' ') f2(8) #n%2是先求出来的最后打印,将十进制换成二进制 #8---> 1000
efdb2089767a25418f638ec9c2e9e7d63ab310ab
alllllli1/Python_NanJingUniversity
/2.9.1/finally.py
520
3.671875
4
# -*- coding: utf-8 -*- # @Time : 2020/3/21 9:48 # @Author : wscffaa # @Email : 1294714904@qq.com # @File : finally.py # @Software: PyCharm #finally子句: 无论异常发不发生,都会被执行 def finallyTest(): try: x=int(input('Enter the first number :')) y=int(input('Enter the second number : ')) print(x...
5ac3371621974979353b78b1be8b869526e0a9ba
alllllli1/Python_NanJingUniversity
/2.5.1/Prime_number.py
506
3.875
4
# -*- coding: utf-8 -*- # @Time : 2020/3/20 11:05 # @Author : wscffaa # @Email : 1294714904@qq.com # @File : Prime_number.py # @Software: PyCharm #输出1-100之间的素数 from math import sqrt def isprime(x): if x == 1 : return False k = int(sqrt(x)) for j in range(2,k+1): #假如j不是素数就不返回False ...
11bfb9a54f82f5f09f5b698ff9fadcaef50ecc7f
alllllli1/Python_NanJingUniversity
/2.8.1/Random.py
805
3.765625
4
# -*- coding: utf-8 -*- # @Time : 2020/3/20 19:54 # @Author : wscffaa # @Email : 1294714904@qq.com # @File : Random.py # @Software: PyCharm import random a = [1,2,3,4,5] print(random.choice(a)) #从序列a中抽取一个随机值 print(random.randint(1,100)) #随机生成一个1~100的一个值 print(random.randrange(0,10,2)) #random.randrange (...
778039a6a5413c186284d56691596d79571eacd4
sac-colorado/my_project1
/list.py
559
3.59375
4
import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker # 'engine' is an object that manages connections to the SQL database engine = create_engine(os.getenv("DATABASE_URL")) db = scoped_session(sessionmaker(bind=engine)) def main(): book_data = db.execute("SELECT i...
dfa6d7dc45710d57fb259b5caf14a930df27c8ec
wangkangchn/machine-learning-Andrew-Ng
/machine-learning-ex6/Python/spam/spam_email.py
6,100
3.609375
4
""" 机器学习---支持向量机进行垃圾邮件的分类 """ import os import re import numpy as np import scipy.io as sio from matplotlib import pyplot as plt from svmutil import * import spamFunctions as sf # ~ ## ==================== Part 1: 对邮件进行预处理 ==================== # ~ # # ~ print('预处理样本邮件 (emailSample1...
64ea06c536d25c2efa94fe84743265f2ec26f467
wangkangchn/machine-learning-Andrew-Ng
/machine-learning-ex1/python/linear_regression.py
5,123
3.828125
4
""" 机器学习: 线性回归算法 """ import numpy as np from matplotlib import pyplot as plt class LinearRegression: """ 机器学习: 线性回归(单, 多变量) 参数: m - 训练集大小 X - 训练集 y - 标签 theta -  训练参数 alpha - 学习率 num_iters- 迭代次数 mu - 每列特征的均值 sigma - 每列特...
99914ba194dde64ead9bb8be9239c0018c7b2b58
onelharrison/labs
/python-collection-dig/dig.py
1,198
3.90625
4
from functools import reduce def get(collection, key): if isinstance(collection, dict): return collection.get(key) elif isinstance(collection, list): try: return collection[key] except (IndexError, TypeError): return None return None def dig(collection, *k...
d6a87d983af37fe1e2e1770609c1d1a8dc1962ba
vanderleik/Logica
/Programacao_Dinamica.py
3,325
4.53125
5
# Programação dinâmica # Para vários exemplos de programaçãço dinâmica acessar o link: # https://www.geeksforgeeks.org/dynamic-programming/ # Programação Dinâmica - Partição de Strings # Input: marceloachaqueoclimapodemudar # Output: marcelo acha que o clima pode mudar # Dicionário com as palavras disponíveis dici...
1b5b07a6245aa49a03062cd5261ec7ac7ce43299
vanderleik/Logica
/Fibonacci1.py
1,079
4.09375
4
""" Os números de Fibonacci compõem a seguinte sequência: 0,1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, ... Em termos matemáticos: Fn = Fn-1 + Fn-2 """ # Pseudo-código # 1 Definir uma variável "n" que representa a posição do número na Sequência de Fibonacci. # 2 Se "n" < 0, será inválido ...
6691f6a4b7349eca3181cc3423e60f62c87f27d4
yafeile/Simple_Study
/Simple_Python/standard/doctest/doctest_5.py
296
3.8125
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- keys = ['a','aa','aaa'] d1 = dict((k,len(k)) for k in keys) d2 = dict((k,len(k)) for k in reversed(keys)) print 'd1:',d1 print 'd2:',d2 print 'd1==d2:',d1==d2 s1=set(keys) s2=set(reversed(keys)) print print 's1:',s1 print 's2:',s2 print 's1==s2:',s1==s2
63e701da1d7b9958b51775c79fffc008e29a8b3f
yafeile/Simple_Study
/Simple_Python/algorithm/linear.py
270
3.53125
4
#coding:utf-8 def linear(data,value): num=0 size=len(data) while num<size: if data[num]==value: print '找到了',value,'它的位置是',num else: print '没有找到' num=num+1 if __name__ == '__main__': new=[1,2,3,4,5,6,2] linear(new,2)
14fcf32c0de7202ce9c4a2518124eaba114d5ec4
yafeile/Simple_Study
/Simple_Python/standard/codecs/codecs_22.py
1,046
4.03125
4
#! /us/bin/env/python # -*- coding:utf-8 -*- import string import codecs # Map every character to itself decoding_map = codecs.make_identity_dict(range(256)) # Make a list of pairs of ordinal values for the lower and uppercase letters pairs = zip([ord(c) for c in string.ascii_lowercase], [ord(c) for ...
27a7a1474a37d888d29ee00c2ced0fca2190de7a
yafeile/Simple_Study
/Simple_Python/standard/bisert/bisect_1.py
460
3.5625
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- import bisect import random #Use a constant seed to ensure that the same pseudo-random numbers #are used each time the loop is run,random.seed(1) print 'New Pos Contents' print '---'*3 #Generate random numbers and insert them into a list in sorted order l = [] for i in ...
035e7bcf180ffd59a31ae3e2dc3542a601f019df
yafeile/Simple_Study
/Simple_Python/algorithm/Stack.py
699
3.78125
4
# -*- coding:utf-8 -*- class Stack: """docstring for Stack""" def __init__(self, arg): self._top=None self._size = 0 def isEmpty(self): return self._top is None def __len__(self): return self._size def peek(self): assert not self.isEmpty(),'Cannot peek at an empty stack' return self...
ee1279626e00e6bf5658f985971812db23a2652f
yafeile/Simple_Study
/Simple_Python/standard/sqlite3/sqlite3_8.py
565
3.5
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- import sqlite3 import sys db_filename = 'todo.db' project_name = sys.argv[1] with sqlite3.connect(db_filename) as conn: cursor = conn.cursor() query = """select id,priority,details,status,deadline from task where project = :project_name order by deadline,prio...
6f06a9ec521dc658344d050112e85482fc885ea2
yafeile/Simple_Study
/Simple_Python/standard/re/new/re_5.py
811
3.796875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import re def test_pattern(text,patterns=[]): """Given source text and a list of patterns,look for matches for each pattern within the text and print them to stdout.""" # Look for each pattern in the text and print the results for pattern,desc in patterns: ...
de0c4b8bba13aa808bfd606bfbe08ffa38728e26
yafeile/Simple_Study
/Simple_Python/standard/gc/gc_1.py
575
3.828125
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- import gc import pprint class Graph(object): def __init__(self,name): self.name = name self.next = None def set_next(self,next): print 'Linking nodes %s.next = %s' %(self,next) def __repr__(self): return '%s (%s)' % (self.__clas...
4a97ef75822cd948c069e39b25e4cc23dff5a8f3
yafeile/Simple_Study
/Simple_Python/standard/re/new/re_3.py
216
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import re text = 'abbaaabbbaaaaa' pattern = 'ab' for match in re.findall(pattern,text): print 'Found %s' % match print 'Found "%s at %d times"' % (match,len(match))
924e0f1816919a7682f7404383c20833c3bcb3ea
yafeile/Simple_Study
/Simple_Python/standard/math/math_2.py
290
3.8125
4
#! /us/bin/env/python # -*- coding:utf-8 -*- import math print '{:^3}{:6}{:6}{:6}'.format('e','x','x**2','isinf') print '{:-^3}{:-^6}{:-^6}{:-^6}'.format('','','','') for e in range(0,201,20): x = 10.0 ** e y = x*x print '{:3d}{!s:6}{!s:6}{!s:6}'.format(e,x,y,math.isinf(y),)
a4994ea268f19acb41d5d35feff21632eda04dfe
yafeile/Simple_Study
/Simple_Python/standard/shlex/shlex_4.py
232
3.578125
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- import shlex text = """|Col 1|Col 2|Col 3|""" print 'ORIGINAL:',repr(text) print lexer = shlex.shlex(text) lexer.quotes = '|' print 'TOKENS:' for token in lexer: print repr(token)
532a2f26d039f9466a3ca8e000eace63e7bd2906
yafeile/Simple_Study
/Simple_Python/standard/sqlite3/sqlite3_2.py
943
3.625
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- import os import sqlite3 db_filename = 'todo.db' schema_filename = 'todo_schema.sql' db_is_new = not os.path.exists(db_filename) with sqlite3.connect(db_filename) as conn: if db_is_new: print 'Creating schema' with open(schema_filename,'rt') as f: ...
63d736372eae00a269f0702446192810f1d0e0c3
yafeile/Simple_Study
/Simple_Python/standard/collection/namedtuple_1.py
361
3.53125
4
import collections Person=collections.namedtuple("Person","name age gender") print "Type of Person:",type(Person) bob=Person(name="bob",age=30,gender="male") print "\nRepresentation:",bob jane=Person(name="Jane",age=29,gender="female") print "\nField by name:",jane.name print "\nField by index:" for p in [bob,j...
855c135d86ac344f20b23855131ec1cf4ce9dc5a
yafeile/Simple_Study
/Simple_Python/standard/functools/functools_6.py
709
3.71875
4
#! /usr/bin/env/python # -*- coding:utf-8 -*- import functools class MyObject(object): def __init__(self,val): self.val = val def __str__(self): return 'MyObject (%s)' %self.val def compare_obj(a,b): """Old-style comparison function.""" print 'comparing %s and %s' %(a,b) return cm...
a9a22b71e20c9ffa460889da28c78bba1a9439eb
niweshkumarsuman/PythonPrograms
/Lucky.py
292
3.59375
4
Lucky,Num=map(int,input("Enter a Number: ").split()) Sum=0 Org=Num while(Num!=0 or Sum>9): if Num==0: Num=Sum Sum=0 rem=(Num%10) Sum=Sum+rem Num=(Num//10) if Lucky==Sum: Lucky=Lucky+9 print("Suggested Number is {}".format(Org+abs(Lucky-Sum)))
59b12a3feea3e0a26cf21b28c96040db957ecb08
niweshkumarsuman/PythonPrograms
/sum.py
112
3.5
4
sum1=0 num=[24,54,78,65,89,45,89,42] for i in range(len(num)): sum1=sum1+num[i] print("Sum of nos",sum1)
1cec13722834d5385bc7e1864539e685fa7ddde4
vincenzorm117/hackerank
/time-conversion/solution.py
386
3.921875
4
import re def timeConversion(s): s = s.strip() hour, minute, second, pm = re.findall(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(AM|PM)$", s)[0] time = list(map(int, [hour,minute,second])) time[0] %= 12 print(time) if pm == 'PM': time[0] += 12 return ':'.join(['%02d' % x for x in time]) ...
503d0bc07e98513a505fcf40db310537e3b2309f
pykaldi/pykaldi
/kaldi/util/options.py
1,527
3.6875
4
import argparse import sys from . import _options_ext class ParseOptions(_options_ext.ParseOptions): """Command line option parser. Args: usage (str): Usage string. """ def parse_args(self, args=None): """Parses arguments. This method is used for parsing command line options...
a38ebb81ae1732b360da1c4b6521bf1deafa660a
CalvinYudaTama/python-modularisasi
/modularisasi-luas-segitiga.py
773
3.71875
4
""" Menghitung Segitiga Dengan Fungsi Dengan Rumus alas * tinggi / 2 """ print("Menghitung luas segitiga cara sederhana 1") alas = 10 tinggi = 6 luas = alas * tinggi / 2 print(f'Menghitung luas segitiga dengan alas = {alas} dan tinggi = {tinggi} dengan hasil luasnya yaitu {luas}') print("\nMenghitung luas segitiga c...
2b6de986637394ec70ff2a73c9d940b105d5b228
n1balgo/algo
/second_smallest_linkedlist.py
5,030
4.0625
4
#!/usr/bin/env python3 class Node: def __init__(self, val): # value at this node self.val = val # sibling ptr for linked list self.sibling = None # child ptr, maintains nodes knocked by this node self.child = None def create_linked_list(Arr): "...
9f3232179f99928ae2609dab738ffd3dc028dd56
Eliherc1/fundamentos-python
/2-For_loop_basic1.py
1,215
3.515625
4
#1. Básico : imprime todos los enteros del 0 al 150. for x in range (150+1): print(x) #2. Múltiplos de cinco : imprime todos los múltiplos de 5 de 5 a 1,000 for x in range (5,1000+1,5): print(x) #3. Contar, Dojo Way - imprime enteros del 1 al 100. Si es divisible por 5, imprima "Coding" # en su lugar. Si es di...
1948666ba6573507cb71065a3d7b1334c1557a0a
kushrami/Python-Crash-Course-book-Exercise
/Exercise_10_7.py
579
4.125
4
#Addition Calculator: ExitFlag = True while ExitFlag: FirstNumber = input("Please enter first number or 'q' to exit:") if FirstNumber == 'q': break else: SecondNumber = input("Please enter second number or 'q' to exit:") if SecondNumber == 'q': break else:...
7af2b0f099cd41965770f5a4cf9c77f9cc61fdb3
kushrami/Python-Crash-Course-book-Exercise
/Exercise_4_11.py
333
3.734375
4
#My pizzas, your pizzas: mypizzas = ['margerita','thincrust','peripiri'] friend_pizzas = mypizzas[:] mypizzas.append('cheese') friend_pizzas.append('burst') print("so like, i love pizza. My favorite pizzas are :") for pizza in mypizzas: print(pizza) print("Tony's pizzas are :") for pizza in friend_pizzas: pr...
86cc278747fd7e5390f1cd4d2de57645677e67cf
kushrami/Python-Crash-Course-book-Exercise
/Exercise_6_9.py
308
3.921875
4
#Favorite Places: favorite_places = { 'tony': ['newyork','delhi','paris'], 'thor': ['asgard','newyork','austin'], 'nessa': ['huawai','tokyo','mumbai'], } for keys,values in favorite_places.items(): print("The favorite places of",keys,"is:") for value in values: print(value)
34582677d4aefe4bd0fe7ecf20037dc47d666456
kushrami/Python-Crash-Course-book-Exercise
/Exercise_3_9.py
1,163
3.921875
4
#Shrinking guests list: names = ['tony','steve','thor'] message = ", You are invited!" attendeemessage = " is not coming." print(str(len(names))+" People are invited.") print(names[0]+message) print(names[1]+message) print(names[2]+message) print(names[1]+attendeemessage) del names[1] names.insert(1,'peter') print...
3440252c8dcfefc3524b16328af52df8c92eafea
kushrami/Python-Crash-Course-book-Exercise
/Exercise_4_10.py
197
4.15625
4
#slices list = [] for number in range(1,11): list.append(number**3) print("first three element in list are",list[:3]) print("middle items are :",list[4:7]) print("last items are :",list[8:])
aa1fae873f7d5fb41e56914527fd1dee27667797
kushrami/Python-Crash-Course-book-Exercise
/Exercise_5_10.py
305
3.984375
4
#checking usernames: current_users = ['aes','bes','ces','des','ees','admin'] new_users = ['Ees','mes','les','kes'] for user in new_users: if user.lower() in current_users: print("Please enter new user name.") else : print("hello",user,". Username is available.")
d1c478b5fb74f028d28b2de4a1515d90c5f34dd6
kushrami/Python-Crash-Course-book-Exercise
/Exercise_6_1.py
215
3.6875
4
#Person: person = { 'firstname' : 'Tony', 'lastname' : 'stark', 'age' : 32, 'city' : 'newyork' } print(person['firstname']) print(person['lastname']) print(person['age']) print(person['city'])
a9f0ee591f962427fd47549d6422d5ee8728b94b
kushrami/Python-Crash-Course-book-Exercise
/Exercise_9_4.py
1,438
4.1875
4
#Number served: #Restaurant: class Restaurant(): """A simple attempt to make class restaurant. """ def __init__(self, restaurant_name, cuisine_type): """ This is to initialize name and type of restaurant""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type ...
82f0260929649fd7a998ddf8c8cdb074bfe7f1e7
kushrami/Python-Crash-Course-book-Exercise
/Exercise_4_2.py
164
3.875
4
#Animals animals = ['tiger','lion','jaguar'] for animal in animals: print(animal) print(animal,"is very dangerous.") print("so they all are dangerous")
462b48a8ae58ab71c56712cc7e61e21b1bdb30f1
kushrami/Python-Crash-Course-book-Exercise
/Exercise_9_5.py
1,277
4.03125
4
#login attempts: class User(): """ Making a USER class.""" def __init__(self, first_name, last_name, age, gender): self.first_name = first_name.title() self.last_name = last_name.title() self.age = age self.gender = gender.title() self.login_attempts = 0 d...
831c131459764228f7a12a89e912255d63d77b53
kushrami/Python-Crash-Course-book-Exercise
/Exercise_7_9.py
439
3.796875
4
#No pastrami: sandwich_orders = ['maxican','pastrami','aloo','pastrami','spicypoteto''pastrami','lulu'] finished_sandwich = [] while sandwich_orders: sandwich = sandwich_orders.pop() if sandwich == 'pastrami': print("We are out of pastrami.") continue print("I made your",sandwich,"sandwich...
3f5f8dfd116cac6aab5dd9c38d36f4ff9d47e4b4
What-After-College/Python-MTA
/day01/python02.py
1,224
4.125
4
# a = 2 # b = 5 # # 10^2 # power operator # print(a**b) # a = int(input('Enter a number')) # b = int(input('Enter another number')) # print(a**b) # Modulus Operator # a = 10 # b = 3 # # 105 / 10 = 10.5 , q = 10, rem = 5 # print(a%b) # a = int(input('Enter a number: ')) # b = int(input('Enter another numb...