blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a6b73a65c6f6e97e5b7ec2d025f64b41ce0abdc7 | DCC-Lab/RayTracing | /raytracing/axicon.py | 4,175 | 4.28125 | 4 | from .matrix import *
import matplotlib.pyplot as plt
class Axicon(Matrix):
"""
This class is an advanced module that describes an axicon lens,
not part of the basic formalism. Using this class an axicon
conical lens can be presented.
Axicon lenses are used to obtain a line focus instead of a po... |
f1d2d8355950ea92a43c15c2a5547193b1cb094f | abhishekshinde2104/Django_Bootcamp | /Course/Python/part2_python/card_game.py | 4,393 | 4.3125 | 4 | #####################################
### WELCOME TO YOUR OOP PROJECT #####
#####################################
# For this project you will be using OOP to create a card game. This card game will
# be the card game "War" for two players, you an the computer. If you don't know
# how to play "War" here are the basic r... |
8d8dc2f91fcaf9faf9f2b0ec60623374292007bc | Vijayenthiran/MITx-6.00.1x | /Quiz/p5_laceString.py | 1,151 | 4.375 | 4 | #Suppose you are given two strings (they may be empty), s1 and s2. You would like to "lace" these strings together, by successively alternating elements of each string (starting with the first character of s1). If one string is longer than the other, then the remaining elements of the longer string should simply be add... |
9ebbd452646e1a97584240c5d9f4b184d16b0c77 | TEAMLAB-Lecture/baseball-bcc0830 | /baseball_game.py | 2,834 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import random
def get_random_number():
return random.randrange(100, 1000)
def is_digit(user_input_number):
res = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}
for i in user_input_number:
if i not in res:
return False
return True
def is_between_100_and... |
8eecdbdefabf0e8f77703bfd41a5a0489fbfd808 | rawanshareef/EX3-OOP | /src/DiGraph.py | 5,657 | 3.84375 | 4 | from src.GraphInterface import GraphInterface
class NodeData:
""" This class represents on a node in a directional weighted graph."""
def __init__(self, key: int = None, tag: int = 0, pos: tuple = None):
"""method is similar to constructor in java. this method used to initialize the node state... |
6a37f4c9a063ef6dff2cee0b3edfe379c076a0a0 | jack19-meet/yl1201718 | /lab5/lab6.py | 773 | 3.796875 | 4 | from turtle import *
import random
import math
tracer()
class Ball(Turtle):
def __init__(self, radius, color, speed):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
self.color(color)
self.speed(speed)
ball1 = Ball(69,"black",9)
ball2 = Ball(30,"red",4)
ball1.for... |
a43e8d0296d10aa22abe6245ec1a21d7d56dce60 | twistedcubic/RNN-Debate | /speechParser/getSpeech.py | 700 | 3.578125 | 4 | """
Preprocesses text to organize words in hash table
"""
import json
import re
with open('trump.txt','r') as f:
data = f.read()
#print data
#convert to list of sentences, determined by period
sentences = data.split('.')
print sentences[0]
dict = {}
for index, sentence in enumerate(sen... |
8bd57a5ac8ed3595b81bfcd2d3a8180c9acc693b | lkrych/cprogramming | /comp_systems/ch_2_manipulating_numbers/any_even_bit.py | 357 | 3.5 | 4 | import sys
def any_even_bit(x):
x = int(x)
print(bin(x)[2:])
mask = 0x55
mask |= (mask << 8)
mask |= (mask << 16)
print(bin(mask)[2:])
return not not (x & mask)
if __name__ == "__main__":
ans = any_even_bit(sys.argv[1])
if ans:
print("An even bit was set to 1")
else:
... |
fe8324652cfdb319eff17ed37a9b31b95a92ba2f | lkrych/cprogramming | /kAndr/ch_2/invert.py | 1,020 | 3.71875 | 4 | # invert(x,p,n) that returns x with the n bits that
# begin at position p inverted (i.e., 1 changed into 0 and vice versa),
# leaving the others unchanged
def invert(x: int, p: int, n: int) -> str:
bin = to_binary_str(x)
rev_bin = reverse_str(bin)
for i in range(p-n, p):
flip_bit(rev_bin, i)
... |
d31e247997bd4020ffae10c869c38696e3c9d104 | standrewscollege2018/2020-year-11-classwork-ead4432 | /movie_prices.py | 480 | 4.15625 | 4 | """ This program calculates how much a movie ticket is for you """
#are they a student
student_status = input("Are you a student y/n")
#get the user age
user_age = int(input("What is your age"))
#give them their price
if student_status == "y":
print("Ticket price is $8")
elif user_age < 5:
print("You need no... |
ffbc01a87f4f3d699bd6b55efc117c4ee47cbb85 | standrewscollege2018/2020-year-11-classwork-ead4432 | /rental_cars.py | 1,893 | 4.25 | 4 | """This program allows the user to book a rental car and allows you to keep track of the cars being borowred"""
#make a listx3
cars = ["Suzuki Van", "Toyota Corolla", "Honda CRV", "Suzuki Swift", "Mitsibishi Airtreck", "Nissan DC Ute", "Toyota Previa", "Toyota Hi Ace", "Toyota Hi Ace"]
seats = [2, 4, 4, 4, 4, 4, 7, 12... |
261289f612436a3233bfc9119da71615821383c6 | Jyothis-P/nw_lab | /lzw_server.py | 1,101 | 3.625 | 4 | """
Aim: Write a socket program to implement LZW compression
Server Program.
"""
import socket
from lzw_utils import decompress
print('\n************ Connection setup - Begin **************')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
PORT = 8080
BUFFER_SIZE = 1024
s.bi... |
793a0c625157aed438f7fb5f0c0c5ce0b9a0fe2e | Jyothis-P/nw_lab | /railfence_client.py | 1,262 | 3.9375 | 4 | """
Aim: Write a client-server program using UDP where the client sends a string to the server. The
server encrypts the string using rail fence algorithm and returns the result to the client. Client
displays the result
Client Program.
"""
import socket
"""
Creating a socket object.
@:param AF_INET -> Specifies that w... |
9e8d1447603669ec519ae5cd4ba98459edd5aab4 | Jyothis-P/nw_lab | /udp_client.py | 1,080 | 3.890625 | 4 | """
Aim: Write a socket program to implement client server programming using UDP
UDP Client Program.
"""
import socket
"""
Creating a socket object.
@:param AF_INET -> Specifies that we'll be using the IPv4 address family.
@:param SOCK_STREAM -> Specifies that we'll be suing a UDP socket.
"""
s = socket.socket(socket... |
199e9b0efbc599f47e4df8fa1a8ecfd19b0be97e | j-rewerts/practice-problems | /cci/count-of-2s/main.py | 594 | 3.578125 | 4 | # Cracking the coding interview 17.6
# @author CodyGramlich and j-rewerts
# Count the number of 2s on the way to a number
import math
def getMajor(num):
x = math.floor(math.log(num, 10))
value = x * math.floor(num / math.pow(10, x)) * math.pow(10, x) / 10
modifiedNum = num - 2*math.pow(10, x) + 1
value... |
65f638238eed81d3b35b7d77570113ca09befb9a | j-rewerts/practice-problems | /misc/bipartite-graph/main.py | 599 | 3.625 | 4 | nodes = [[1,3], [0,2], [1,3], [0,2]]
otherNodes = [[1,2,3], [0,2], [0,1,3], [0,2]]
def isBipartite(nodes):
colors = [0] * len(nodes)
for index, node in enumerate(nodes):
if colors[index] == 0 and not properColor(nodes, colors, 1, index):
return False
return True
def properColor(graph, colors, color, n... |
b15391d0a5df1cb7ad74b1892d227ed9f4856b77 | j-rewerts/practice-problems | /cci/intersect/main.py | 1,937 | 3.8125 | 4 | # Cracking the coding interview. Question 16.3.
# @author CodyGramlich and j-rewerts
# Finds the intersection between 2 lines.
def intersect(i1, i2, j1, j2):
xInt = 0
yInt = 0
if i1[0] == i2[0] and j1[0] == j2[0]:
print('Lines are vertical.')
return None
elif i1[0] == i2[0]:
mj = (j2[1] - j1[1]) / ... |
1a41e393e8756a5b3667a0741cc7d8b4af1c5d02 | otulakdominik/Codewars | /7kyu/Easy Time Convert.py | 464 | 3.90625 | 4 | def time_convert(num):
hour = 0
if num < 0:
return "00:00"
while num >= 60:
num -= 60
hour += 1
if hour < 10 and num < 10:
text = '0' + str(hour) + ':' + '0' + str(num)
elif hour < 10 and num > 10:
text = '0' + str(hour) + ':' + str(num)
elif hour >= 10 an... |
2dd9250c91bfa908a7c24c1d2e7cefa7e287448c | seunomonije/quantum | /python/cirq/Sort.py | 923 | 3.84375 | 4 | class Sort:
def __init__(self, arr):
self.arr = arr
def mergeSort(self, arr):
if len(arr) > 1:
mid = len(arr)//2 # signifies floor division
left = arr[:mid]
right = arr[mid:]
self.mergeSort(left)
self.mergeSort(right)
i=j=k = 0
while i < len(left)... |
30f8a4b828baea24e6ff50979d236bcba6d09ec1 | rcv-legado/markov-music | /ngrams-to-unigrams.py | 714 | 3.640625 | 4 | #!/usr/bin/env python2
#
# Unpack n-grams into unigrams
#
import sys
# Essential constants. See appropriate README to figure out how to adjust these
FILE_NAME = sys.argv[1];
N_UNIGRAMS = 34;
N_GRAMS = 2;
# Compute state-space size
N_STATES = N_UNIGRAMS**N_GRAMS;
# Read file
f = open( FILE_NAME, 'r' );
for line in... |
895043ecde947e4600c14b5e22107cefbb3e006b | lbleal1/CS150_Transpiler_Python-to-C | /Lexer, Translator, Main [JIMUEL]/P_Translator.py | 1,015 | 3.75 | 4 | # Translator class
class P_Translator:
def __init__(self):
self.mapping = { "STRING":"char*",
"INT": "int",
"FLOAT": "float",
"WRITE":"printf",
"READ": "scanf",
"IF": "if(",
"ELSE": "else",
"FOR": "for",
"DEF": "... |
e093dd27dd9e7e82dbe3b1ae3fd673ab21acb892 | GeoffroyG/TDLOG | /Classes.py | 13,798 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 15:36:10 2015
@author: Fatma - Geoffroy - Pierre
"""
"""
0 = Road
1 = House
2 = Factory
3 = Quarry
4 = Sawmill
5 = Wind power plant
6 = Coal power plant
7 = Hydraulic power plant
8 = ENPC
9 = Empty
10 = Mine
11 = Forest
"""
from Constantes import *
from random impor... |
2bf1d7d0d26531b223792038e896789e27d9684b | samiur98/Data-Structures-Python | /LinkedListTests.py | 9,262 | 3.953125 | 4 | import unittest
from LinkedList import *
class LinkedListTests(unittest.TestCase):
#Test Cases for the Singly Linked List Data Structure.
def test_is_empty_single(self):
#Test Cases for the is_empty method.
linked_list=SinglyLinkedList()
self.assertTrue(linked_list.is_empty())
li... |
8622eb9286fead95f0ec9e3b208415575b40675d | BarthJr/tech-code-interview | /permutations.py | 771 | 4.34375 | 4 | # Write a function that takes in an array of unique integers and returns an array of all permutations of those integers.
# If the input array is empty, your function should return an empty array.
"""
>>> getPermutations([1, 2, 3])
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
>>> getPermutations([... |
43dba7a3cefe7143c6ea485cca4b5ed6d6a5a62e | BarthJr/tech-code-interview | /sherlock-and-anagrams.py | 728 | 4.1875 | 4 | # Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string.
# Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
"""
>>> sherlockAndAnagrams("abba")
4
>>> sherlockAndAnagrams("kkkk")
10
>>> sherlockAndAnagrams("abc... |
0f3fe24d979b755b67903f2b10c7421e139bd5ea | BarthJr/tech-code-interview | /spiral_matrix.py | 1,365 | 4.21875 | 4 | # Given an m x n matrix, return all elements of the matrix in spiral order.
# Examples:
"""
>>> spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[1, 2, 3, 6, 9, 8, 7, 4, 5]
>>> spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
>>> spiralOrder([[1, 2, 3, 4], [10, 11, 12, 5... |
d0db56a733b965435a0be23275b1e15127a8eb40 | BarthJr/tech-code-interview | /valid_palindrome.py | 783 | 4.15625 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
# Note: For the purpose of this problem, we define empty string as valid palindrome.
from unittest import TestCase
def isPalindrome(s: str) -> bool:
cleaned_s = [c.lower() for c in s if c.isalnum()]
... |
e3b56d30c24e7641a0f4b8f22a973b55931fbfd3 | BarthJr/tech-code-interview | /minimum-number-of-vertices-to-reach-all-nodes.py | 851 | 3.5625 | 4 | # Given a directed acyclic graph, with n vertices numbered from 0 to n-1,
# and an array edges where edges[i] = [from[i], to[i]] represents a directed edge from node from[i] to node to[i].
#
# Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exist... |
32faf976ac75d1a4b8a5d5d80e7a57a785ad5065 | BarthJr/tech-code-interview | /min_number_jumps_v2.py | 847 | 4.03125 | 4 | # You are given a non-empty array of integers. Each element represents the maximum number of steps you can take forward.
# For example, if the element at index 1 is 3, you can go from index 1 to index 2, 3, or 4.
# Write a function that returns the minimum number of jumps needed to reach the final index.
# Note that ju... |
f4fbcf0818f572bf58a25431a230f49a664cef63 | BarthJr/tech-code-interview | /meeting_rooms.py | 908 | 3.53125 | 4 | # https://www.lintcode.com/problem/meeting-rooms/description
# Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
# determine if a person could attend all meetings.
"""
>>> Solution().canAttendMeetings([Interval(0, 30), Interval(5, 10), Interval(15, 20)])
False... |
430498b8ea2511859ab246eb885c3049bd1e4e3f | BarthJr/tech-code-interview | /intersection_of_two_linked_lists.py | 2,733 | 3.96875 | 4 | # https://leetcode.com/problems/intersection-of-two-linked-lists/
# Write a program to find the node at which the intersection of two singly linked lists begins.
# Notes:
#
# If the two linked lists have no intersection at all, return null.
# The linked lists must retain their original structure after the function ret... |
20189fa9a232f8e2edff7cdfd6ea5a538b9dd2d2 | BarthJr/tech-code-interview | /topological_sort_v2.py | 2,212 | 3.640625 | 4 | # You're given a list of arbitrary jobs that need to be completed; these jobs
# are represented by distinct integers. You're also given a list of dependencies.
# A dependency is represented as a pair of jobs where the first job is a
# prerequisite of the second one. In other words, the second job depends on the... |
7980474ba7bb7d1c44f36c5e6d690c1b0f3dc0a8 | BarthJr/tech-code-interview | /youngest_common_ancestor_v1.py | 2,217 | 3.875 | 4 | # You're given three inputs, all of which are instances of a class that have an "ancestor"
# property pointing to their youngest ancestor.
# The first input is the top ancestor in an ancestral tree (i.e., the only instance that has no ancestor),
# and the other two inputs are descendants in the ancestral tree.
# Write ... |
d16c3edc9e53340436213a49eed8f14072b368ff | BarthJr/tech-code-interview | /find_loop_linked_list.py | 767 | 4.09375 | 4 | # Write a function that takes in the head of a Singly Linked List that contains a loop
# (in other words, the list's tail node points to some node in the list instead of the None (null) value).
# The function should return the node (the actual node - not just its value) from which the loop originates in constant
# spac... |
ffdfa3d74e144634a57dda43444117a24a0c6097 | BarthJr/tech-code-interview | /happy-number.py | 433 | 3.671875 | 4 | # https://leetcode.com/problems/happy-number/
from unittest import TestCase
def isHappy(n: int) -> bool:
memo = set()
while n not in memo:
memo.add(n)
n = sum(int(i) ** 2 for i in str(n))
return n == 1
class TestIsHappy(TestCase):
def test_with_happy_number(self):
self.assert... |
6247b4e44248c818653dfb5383f0f3b7e4ac6ef2 | BarthJr/tech-code-interview | /reverse-integer.py | 610 | 4.125 | 4 | # https://leetcode.com/problems/reverse-integer/
from unittest import TestCase
def reverse(n: 'int') -> 'int':
n = str(n)
if str(n)[0] == '-':
n = n[1:] + '-'
reversed_number = int(''.join(reversed(n)))
if -2 ** 31 <= reversed_number <= 2 ** 31 - 1:
return reversed_number
else:
... |
5e09454f07dd7c1b44cf220c4857235f04846012 | BarthJr/tech-code-interview | /generate_parentheses.py | 847 | 4.09375 | 4 | # Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
# For example, given n = 3, a solution set is:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
"""
>>> generate_parentheses(0)
['']
>>> generate_parentheses(3)
['((()))', '(()())', '(... |
f1fe0c39f172c69319a4be4419a2cfef5dc23767 | maikcosta/Learning | /Python/POO.py | 835 | 3.703125 | 4 | class Pessoa():
def __init__(self, _nome,_sobrenome,_idade):
self.nome = _nome
self.sobrenome = _sobrenome
self.idade = _idade
def apresentar(self):
print(f' O eu sou {self.nome} {self.sobrenome} e tenho {self.idade} anos!')
class Cachorro:
def __init__(self, _nome, _raca,_... |
a0566fffb93ac8ff32e45cfe243da912d5e46042 | zekeyang/inf1340_2015_asst1 | /exercise3.py | 8,148 | 4.03125 | 4 | #!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
Please note:
1) This program take "Y" and "y" as yes, "N" and "n" as no.
2) The following test cases had b... |
e66d9a4ed8e823af1bbd10f61f2790c591595dd9 | xiaoxipangren/algorithm | /ds/KMP.py | 1,907 | 3.59375 | 4 | #! encoding=utf-8
import sys
#kmp算法的核心在于模式串的自我匹配,即利用前后缀来避免
#主串指针的回溯,
# 得到next数组的方式实际上是利用对称的方式来的,
# 不断利用并查集得到最长的前后缀
def next(array):
if array == None:
return None
if len(array) == 1:
return [-1]
if len(array) == 2:
return [-1,0]
next=[1] * len(array)
next[0]=-1
next[1... |
419ce3f9b9d950dc585c6d0479454c7e73cdcd94 | calfdog/python-interview-challenges | /randomize_list.py | 961 | 4.25 | 4 | #!/usr/bin/python
"""
Description: Take a list such as [8,9,10,11,12,13] or ["Alan", "Betty", "David", "Edward", "Frank", "George"]
and return a new randomized list for each time it's run. Check to make sure the list is smaller than 1
print out - list must contain 2 or more items
example1: [12, 9, 11,... |
5c1ba5c72e66a2b52ed5e3a1f6a33616195b3aa9 | taro220/Algorithms | /sorts/insertion.py | 806 | 4.125 | 4 | #is the number greater than max? if it is then move on
# if the number is smaller than max, then take the index and run a loop backwards
# to find the first number that it is greater than. Then append behind it
def insert(arr):
min = arr[0]
for idx in range(1,len(arr)):
if arr[idx] < arr[idx-1]:
... |
ea6c5eeccbac3ede477bfc7c55b66dd25a722fde | Kaph-Noir/Python | /test0815.py | 149 | 3.53125 | 4 | lis1 = [0,1,2,3]
lis2 = [5,6,7,8]
test1 = zip(lis1, lis2)
test2 = list(test1)
test3 = list(zip(lis1, lis2))
print(test1)
print(test2)
print(test3)
|
0e11d1100c328ee5ac043a54746467b1f8780ccd | Kaph-Noir/Python | /test0814.1.py | 179 | 3.515625 | 4 | my_dict = {
0: '0',
1: '1',
2: '2'
}
what = my_dict.items()
print(what)
print(type(what))
what = my_dict.iteritems()
some = what[0]
print(some)
print(type(some)) |
ffd2d5ebc1009502de04b3aae70d4340ccb002da | Kaph-Noir/Python | /test0816.py | 582 | 3.859375 | 4 | class Stack:
def __init__(self):
self.items = []
def __repr__(self):
return "%s" %(self.items)
def push(self, item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
if __name__ == "__main__":
... |
f319049d376a7956cd6e3be791b5e92b04a2adbe | alvas-education-foundation/Jayalakshmi_M | /coding_solutions/8-6-2020/palindrome.py | 345 | 4.3125 | 4 | '''
Description:
Write a python function that will take a string and checks whether it is a palindrome or not. Return If it a palindrome, print true else print false
'''
# Driver code
s = input()
rev = ''.join(reversed(s))
# Checking if both string are
# equal or not
if (s == rev):
print("True")... |
73f47158142643d093ed0489be5934f523e3c9f4 | Bryanlee99/Stock_Forecasting_RF | /Stock_Forecaster/helper_functions.py | 7,336 | 3.90625 | 4 | # Set of helper functions for main algorithm
import numpy as np
import quandl
import pandas as pd
import talib
import datetime
# Adopted from: https://stackoverflow.com/questions/29721228/given-a-date-range-how-can-we-break-it-up-into-n-contiguous-sub-intervals
def date_range(start, end, prop, set_time = "None"):
... |
afe0b13ab1025c6d8b8c19b4642bb7a78536a4c4 | clement-plancq/python-im-2 | /corrections/heures.py | 947 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Python M2. Cours 1 : exercice sur les heures et secondes
correction de Loïc Grobol (voir https://github.com/LoicGrobol/python-im-2)
"""
def heures(secondes):
"""Prend un nombre de secondes (entier) et le convertit en heures, minutes
et secondes sous le format `H:M:S` où `H` est le ... |
d7d32cf4fc8940675c0c0a06aa176630b7514a91 | thefactmachine/3D-Histogram-MayaAPI-Python-R | /SydneyDataFillBlanks.py | 3,506 | 3.9375 | 4 | import csv
import os
import math
'''
This program processes Sydney temperature observations from 1.1.1859 ~
13.5.2012. There are 56016 temperature observations.
The program converts 3 date components to a date in 'dd-mm-yy' format
The program also inserts some missing temperature observations. It
does this, where... |
47f15d3c6ab6da7493463431e4ea8254628dda32 | AlexandraRoss/Algorithmique_et_Programmation | /Projet1_SecondePartie_Version1.py | 1,808 | 3.546875 | 4 | ##Dérivée de la variable de la température
def delta_temperature_capteur1():
"""Cette fonction est la même pour les capteurs 2,3,4,5 et 6 en changeant la variable A. Pour le capteur 2, A=sep_capteur2()[0] et etc pour les capteurs 3,4,5,6"""
A=sep_capteur1()[0]
L=[0]
for i in range(1,len(A)):
j=... |
849f8d7fa263640c3a61f9a99d42b7c02c5d72f8 | heyuhhh/ACM | /contests/2018GCPC/expiredlicense/submissions/accepted/aspectratio_decimal_moritz.py | 441 | 3.765625 | 4 | from fractions import gcd
from decimal import Decimal
def isPrime(x):
if x < 2:
return False
i = 2
while i**2 <= x:
if x % i == 0: return False
i += 1
return True
for _ in range(int(raw_input())):
a,b = map(lambda x: int(Decimal(x) * Decimal(10e5)), raw_input().split(" "))
g = gcd(a,b)
a /= g
b /= g
... |
b5b25de86146e6fce72e462215b17808b8ea458a | SomyaRanjanMohapatra/PYTHON-CODING-REPOSITORY | /calculator.py | 366 | 4.3125 | 4 | operand_1 = input("Enter operand one : ")
operand_2 = input("Enter operand two : ")
operator = input("Enter operator(+/-/*//) : ")
if(operator == "+"):
return operand_1 + operand_2
elif(operator == "-"):
return operand_1 - operand_2
elif(operator == "*"):
return operand_1 * operand_2
elif(operator == "/"):
ret... |
e03d07f4e05ea1b811b58da50be9edf72c495efe | NathanNNguyen/challenges | /leetcode/even_num_of_digits.py | 838 | 4.1875 | 4 | # Given an array nums of integers, return how many of them contain an even number of digits.
# Example 1:
# Input: nums = [12,345,2,6,7896]
# Output: 2
# Explanation:
# 12 contains 2 digits (even number of digits).
# 345 contains 3 digits (odd number of digits).
# 2 contains 1 digit (odd number of digits).
# 6 contai... |
296b6bfca0722f273f3bba2eef9a90ebfc7c1fc5 | NathanNNguyen/challenges | /leetcode/target_arr_with_giv_order.py | 1,367 | 4.375 | 4 | # Given two arrays of integers nums and index. Your task is to create target array under the following rules:
# Initially target array is empty.
# From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
# Repeat the previous step until there are no elements to read in ... |
4dcc4a3d213c3042feb126a2c61c554b6b5869da | NathanNNguyen/challenges | /leetcode/shuffle_the_array.py | 1,399 | 3.765625 | 4 | # Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
# Return the array in the form [x1,y1,x2,y2,...,xn,yn].
# Example 1:
# Input: nums = [2,5,1,3,4,7], n = 3
# Output: [2,3,5,4,1,7]
# Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
# Exam... |
0464cbd4994cc576b5a267a7bd3e604397c0b7b9 | NathanNNguyen/challenges | /interview_questions/num_ways_climb_stairs.py | 583 | 4.15625 | 4 | # You are given a positive integer N which represents the number of steps in a staircase. You can either climb 1 or 2 steps at a time. Write a function that returns the number of unique ways to climb the stairs.
# def staircase(n):
# # Fill this in.
# print staircase(4)
# # 5
# print staircase(5)
# # 8
# Can you f... |
2ce53175fc1d2d1b80a22ef5a8eac5d091b5521b | junlongzhao/lenovo | /bayes/imp.py | 1,516 | 3.578125 | 4 | #工具类
# 传入的应该是文本做成的one-hot矩阵
import math
import numpy as np
def list_sum(sentence_length,do_list,voc):
"""
:param do_list: 此处是传入的是每一个文本的矩阵形式 比如:['my', 'dog', 'has', 'flea', 'problems', 'help', 'please', 'my']
:return:返回矩阵形式 [2. 1. 1. 1. 1. 1. 1. 0.],2代表词语出现的频数
"""
print("词典的长度",len(voc))
# for ... |
967d9f40485dd3ab504173718d57c5bacc9a8c5c | tseibel/ProjectEuler | /ProjectEuler1.py | 273 | 3.875 | 4 | count = 0
total = 0
while count <= 999:
if count//3 == count/3:
print(count, "three")
total = total + count
else:
if count//5 == count/5:
print(count, "five")
total = total + count
count = count + 1
print(total)
|
09dc4ec87c4b910b6df1efe52e2aed873bb29108 | yajacob/algorithms | /std_algorithm/sort/sort_selection.py | 998 | 3.78125 | 4 | import unittest
def selectionSort(input):
for i in range(len(input) - 1):
# assume the min is the first element
idx_min = 1
j = i + 1
# test against elements after i to find the smallest
while j < len(input):
if(input[j] < input[idx_min]):
... |
3d200bb041ef88a0a9dadf3453f10ec9f4e19a98 | KaiserFrost/MEI-1920 | /1ºANO/2ºSemestre/Criptografia/Estruturas Criptograficas/TP4/cshake.py | 3,127 | 4.71875 | 5 | from binascii import hexlify, unhexlify
from CompactFIPS202 import SHAKE128, Keccak
import os
def left_encode(x):
"""function bytepad
left_encode(x) encodes the integer x as a byte string in a way that can be unambiguously parsed from the beginning of the string by inserting the length of the byte ... |
d5972782a10f0778f6aaee615c2bc3fb5e156032 | zongqiqi/mypython | /1-100/31.py | 386 | 3.796875 | 4 | """请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。"""
W = {'M':'Monday','Tu':'Tuesday','W':'Wednesday',
'Th':'Thursday','F':'Friday','Sa':'Saturday','Su':'Sunday'}
a = input('First word')
a = a.upper()
if a =="T" or a =="S":
b=input("second word")
b = b.lower()
a = a+b
print (W[a])
|
77ca5f597643f31833f633ae9b4c58ea2ee85058 | zongqiqi/mypython | /1-100/78.py | 261 | 3.828125 | 4 | """找到年龄最大的人,并输出。请找出程序中有什么问题。"""
if __name__=='__main__':
dic={"li":18,"wang":6,"zhang":20,"sun":22}
m ='li'
for key in dic.keys():
if dic[m]<dic[key]:
m=key
print (dic[m])
|
8df2b207b92dd9d14c67357122af5c50d32e4977 | zongqiqi/mypython | /1-100/37.py | 244 | 3.5625 | 4 | """对10个数进行排序。"""
import random
l=[]
for b in range(10):
l.append(int(random.random()*100))
print (l)
for a in range(len(l)):
for b in range(a+1,len(l)):
if l[a]>l[b]:
l[a],l[b]=l[b],l[a]
print (l)
|
a2caad1c45479afdccfe67f31283ac22e3236f9f | zongqiqi/mypython | /1-100/32.py | 157 | 4.21875 | 4 | """按相反的顺序输出列表的值。"""
a = ['one', 'two', 'three']
for i in range(1,len(a)+1):
print(a[-i])
for b in a[::-1]:
print (b)
|
c3aae772f4b000caeb7bd332451ec82112afd98d | danviv/edX | /EX101x/video7.x-bacon-half-python-incomplete.py | 1,870 | 3.546875 | 4 | def getSheetLength(sheet):
size = 1
while(True):
if(Cell(sheet,size,"A").value == None):
return size-1
else:
size = size+1
num_movie_actors = getSheetLength("Movie_Actor")
num_actors = getSheetLength("Actor")
def AllSteps(m,step):
List = []
source_co... |
0e5659460fe260e50dcda637617a2dfa4a881560 | predigame/mazes | /maze-4.py | 1,167 | 3.859375 | 4 | WIDTH = 30
HEIGHT = 18
TITLE = 'MAZE'
# a callback that keeps the player from running
# into walls. it's only acceptable to walk into
# an object marked as a "destination"
def evaluate(action, sprite, pos):
obj = at(pos)
if obj:
if obj.tag == 'destination':
return True
else:
... |
5fc71297ad8091475f3a0b22bfe3b1ce1e4a29af | unfo/graveyard-of-inspiration | /python/crackmes/beatme.py | 1,601 | 3.78125 | 4 | def create_password(username):
len_user = len(username)
if len_user <= 3 or len_user >= 0xc:
return "Invalid username length!"
password = chr(len_user + 0x30)
password += username[2]
len_shifted = len_user >> 1
for x in username:
x_o = ord(x)
x_o += len_shifted
x_... |
718a10ab91892970e78ea8b4edc85d1a867e2bab | ozgegunay/LFDHomework2 | /Question4.py | 2,556 | 3.515625 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
#hypothesis function
def g(weight, x):
return np.sign(np.dot(x, weight))
#learning algorithm
def learn(weight, trainingSet, trainingClassification):
iteration=0
while True:
iteration += 1
misses = findMissclassified(trainingS... |
5856c0ca7bf0fdd57ba64f6579829c2018893467 | aliwo/yappy-dev | /homework/homework1/ye_moon/hw2.py | 488 | 3.875 | 4 | import re
# p = re.compile(r"([a-z]+[A-Z]+[0-9]+)")
print("설정할 비밀번호를 입력해주세요.")
password = input()
def checkio(data: str) -> bool:
match = re.match("(?=.*\d[a-zA-Z])", data)
# match = re.match("[A-Z]+", data)
# match = re.match("[0-9]+", data)
if (len(password) < 10):
print("FALSE")
retu... |
1f460d51f0a3cad273b143827ab6901a1fadd380 | yyyyyykkk/Algorithms-and-Data-Structures | /MIT Python/binaryGuess.py | 923 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 19:16:42 2017
@author: XPS 13 9350
"""
print('Please think of a number between 0 and 100!')
print('Is your secret number 50?')
left=0
right=100
guess=50
s=input('Enter \'h\' to indicate the guess is too high. Enter \'l\' to indicate the guess is too low. Enter \'c\' t... |
30ddab71796e64f3df5e0cbfa2dc91bea8813518 | yyyyyykkk/Algorithms-and-Data-Structures | /MIT Python/fibonacci.py | 198 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 24 17:24:52 2017
@author: XPS 13 9350
"""
def fibnacci(x):
if x==0 or x==1:
return 1
else:
return fibnacci(x-1)+fibnacci(x-2) |
b7fd41eed521a8b729196ed2e7a32131a1ed5e4f | Arpan61/Design-4 | /Problem1.py | 3,311 | 4.09375 | 4 | # Time Complexity : O(nlogn) where n is the total number of tweets made by all the users
# Space Complexity : Confused between O(n) where n is the total number of tweets made by all the users
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : Yes. I have problem implementing ... |
ccdbc91b67af1dbad5770b8b19e1cef8c5bb7690 | lakshmick96/python-practice-book-chapter3 | /problem7.py | 583 | 3.96875 | 4 | #Write a function make_slug that takes a name converts it into a slug. A slug is a string where spaces and special characters are replaced by a hyphen, typically used to create blog post URL from post title. It should also make sure there are no more than one hyphen in any place and there are no hyphens at the biginnin... |
8ae5a181e364952681bc73875c877be44901b69b | yousefmasry4/CDLL-in-py | /1.py | 1,413 | 3.625 | 4 | class node:
def __init__(self,cdll,data,prev_node,next_node):
self.next=next_node
self.data=data
self.prev=prev_node
if cdll.isempty() :
self.next=self
self.prev=self
else:
(self.prev).next=self
(self.next).prev=self
... |
529cd7701e2d2cda7e5f48836ade436288794119 | jiangjianqing/python-demo | /helloWorld.py | 1,127 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import calendar
import time
import module_test
import os
from module_test import addmoney
from myclass import MyClass
sys.stdout.write("fole测试")
print "你好hello world!!!!!!!!!!!!!!!!",1!=2
def printcalenar():
cal = calendar.month(2008, 1)
print "Here is the cal... |
7cf88a43ad35de344bbe2a91cae503be39da68de | irimina/Python_Lsts | /BeforeStartingReviewThese.py | 1,324 | 4.09375 | 4 | '''
task 1
The print() function outputs text to the screen.
On line 2, print Welcome to AP CSP.
On line 5, use input() to ask the user for their name and store it in a variable called name.
On line 6, print out Nice to meet you [...] where [...] is the name the user types in.
task #2
calculator
#This prints out the... |
f517efff383355e4fcf5365306fc493ff46857de | Mihir123-hash/audiobook | /main.py | 970 | 3.921875 | 4 | #step1: In order to make python speak, GO to terminal> type pip install pyttsx3
#pyttsx3 stands for python text to speach version(3)
#step2
import pyttsx3 #import in order to make python speak
import PyPDF2 #to read a pdf file in python
book = open('AI.pdf' , 'rb') # book name that user wants to read
... |
02e58e7f4e7743456d273c8c7fdc1233d9e81fb7 | eebmagic/phy214_enterprise_online | /coding_physics_problem/21.15/script.py | 1,081 | 3.625 | 4 | import math
class point:
def __init__(self, charge, position):
self.charge = charge
self.position = position
def force(k, q1, q2, r):
numerator = k * (abs(q1 * q2))
denom = r * r
return numerator / denom
def dist(x1, x2):
return abs(x2 - x1)
def point_force(x, y, k):
d = ... |
a34dfa71daf5940b9f5197f5792fe67b9a96da9a | eebmagic/phy214_enterprise_online | /python_functions/optics/graphs.py | 1,345 | 3.65625 | 4 | import turtle
import lenses
import time
def draw(position, height, focal_distance):
# make turtle
t = turtle.Turtle()
t.speed('fastest')
t.home()
t.clear()
# draw center of lens
t.left(90)
t.fd(100)
t.back(200)
t.fd(100)
t.right(90)
# draw axis
t.fd(300)
t.back... |
9181762b1031ba3dbc2112a121d6e97b388bb4c8 | bezova/fastml | /sorting.py | 1,061 | 3.703125 | 4 | '''
You can get the data via:
wget http://pjreddie.com/media/files/cifar.tgz
Important: Before proceeding, the student must reorganize the downloaded dataset files to match the expected directory structure, so that there is a dedicated folder for each class under 'test' and 'train', e.g.:
* test/airplane/airplane-1... |
fbb3e69e4b66cf35da291d8469272afcadb73935 | Jafet438/LimniJafet | /practicapython.py | 299 | 4.15625 | 4 | print(#1)
for x in range(1,8):
print("*" * x)
print()
print(#2)
for y in range(8,0,-1):
print("*" * y)
print()
print(#3)
for m in range(1,8):
print("*" * m)
print()
for n in range(8,0,-1):
print("*" * n)
print()
print(#4)
for z in range(1,8):
print("*" * 8)
print()
|
ca27476eb73b038c3f1c9d17190e2c983066f58a | vkunal1996/Python | /GuessTheNumber.py | 584 | 4.0625 | 4 | import random
print('I am thinking of Number 1 and 20')
number=random.randint(1,20)
guessNumber=0
counter=0
while counter<=6:
print('Take a guess')
guessNumber=int(input())
counter+=1
if(guessNumber==number):
print('You Guess the Number Correct in '+str(counter)+' turns')
break
elif(... |
7307b6468cdf2889641ea2bab6f4cdb66068bf36 | vkunal1996/Python | /dictionaryExample.py | 416 | 3.953125 | 4 | animal={'dog':'black',
'cat':'black',
'horse':'black'
}
while True:
print('Enter the Animal Name ')
name=input()
if name=='':
break
if name in animal:
print('We have '+name+' in '+animal[name]+' color')
else:
print('We do not have requested animal')
... |
01bfb9541a7d17285ff4fa831269f42a4654c72b | slewer/genetic-salesman | /greedy.py | 1,659 | 3.796875 | 4 | import genetics2
import random
import math
def distance(city1,city2):
x1 = city1.getX()
y1 = city1.getY()
x2 = city2.getX()
y2 = city2.getY()
return math.sqrt((y2-y1)*(y2-y1) + (x2-x1)*(x2-x1))
def totalLength(tourmanager):
length = 0
for i in range(tourmanager.numberOfCities()):
... |
7b08256155e0c5c599c03d41c0d729880dec22be | saumyasinha023/PythonProgramming | /Practice/Tree/PathSum3.py | 1,214 | 3.71875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(1)
# root.right.right = TreeNode(11)
# root.left.left = TreeNode(3)
# root.left.right = TreeNode(2)
#... |
2a15d2c4fb49ff5fd0e2638142a72097d393ef6b | saumyasinha023/PythonProgramming | /Practice/Miscellaneous/MergeIntervalsAND.py | 771 | 3.640625 | 4 | class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
intervals = []
class Solution():
def merge(self,intervals):
intervals.sort(key=lambda x:x.start)
final=[]
for each in intervals:
if final and each.start<final[-1].end:
... |
f4c934b2bcb46d5937640b0071d45c87818efdbc | saumyasinha023/PythonProgramming | /Practice/Tree/FindMinHeightRootedTree.py | 432 | 3.640625 | 4 | class Solution():
def findMinHeightTrees(self, n, edges):
nodes=[set() for _ in range(n)]
for i,j in edges:
nodes[i].add(j)
nodes[j].add(i)
print(nodes)
leaves = []
for i in range(len(nodes)):
if len(nodes[i])==1:
leaves.a... |
a52c24d5cf7b0bce4e37df112dd6057d58068e6c | saumyasinha023/PythonProgramming | /Practice/RightSideView.py | 932 | 3.875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
level=0
... |
8cf3eb857896cbc375abc32720dbda1e9371ed6b | saumyasinha023/PythonProgramming | /Practice/Tree/BalancedBinaryTree.py | 894 | 3.703125 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution():
def isBalanced(self, root):
return (self.helper(root)!=-1)
def helper(self, root):
if root == None:
return 0
leftHeight = int(self.helper(r... |
fc9f584c838ccc21433c799687ec158917f76d7d | saumyasinha023/PythonProgramming | /Practice/Tree/FlattenBinaryTreeToLinkedList.py | 948 | 3.734375 | 4 | class ListNode(object):
def __init__(self, val):
self.val = val
self.next = None
class Tree(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
root = Tree(3)
root.left=Tree(9)
root.right=Tree(20)
root.right.left=Tree(15)
root.right.rig... |
95940d3c40db5413f64bb6f25d294b609bdc8feb | saumyasinha023/PythonProgramming | /Practice/Tree/ConstructBinaryTree.py | 675 | 3.515625 | 4 | # Inorder sequence: D B E A F C
# Preorder sequence: A B D E C F
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder, inorder):
if inorder:
ind = inorder.index(preorder.pop(0))
... |
58a5702696e536d7c6dacd5f573b828343cadf68 | sylwesterszykula/PythonZajecia | /6 pazdziernika 2016/script5.py | 217 | 3.6875 | 4 | napis = "Wiek: " + str(18)
print napis
print napis.replace("W","w")
print napis.lower()
print napis.upper()
napis = "Ta liczba %f to %s" % (3.23, "liczba")
print napis
print '{0}, {1}, {2}'.format('a', 'b', 'c') |
c58aaf7f03e289b98b17a546d1bca53ed7c15eae | BAltundas/linklist_asc_order | /List_Insert_Data_ASC_Order.py | 2,621 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 17:34:58 2021
@author: Bilgin Altundas
"""
# function to insert a Node at required position
def insertPos(root, position, data):
cur_node = root.head
# This condition to check whether the
# position given is valid or not.
if (position < 1): ... |
dc751b906e7dbbc51667dfe0f0ea95ce4318d25a | rg7000/Todo | /todo.py | 1,544 | 3.515625 | 4 | #!/usr/bin/env python3
import argparse
import os
import pdb
file_name = "task.txt"
parser=argparse.ArgumentParser(description="To create/modify/delete a Todo List")
parser.add_argument("-a", "--add", help="To add a task to Todo List")
parser.add_argument("-l", "--list", help="Displays the tasks in Todo List", action="s... |
a598aa09cfaafebbfc0e2566d4b1f0f76b7d0dd6 | YatingLi98/cs170proj | /project-sp19-skeleton-master/route.py | 2,553 | 3.765625 | 4 | from MST import *
from priority_queue import *
def route(G, S1, S2):
"""
This modified dijsktra's takes in a graph G and a set S.
It runs dijkstra's from the node with index 0.
:param G: A dictionary indexed by nodes. The value of G[v] is also a dict indexed
by adjacent nodes. For any edge (u,v), ... |
d98c28c97ef61ac9001a8e272ed439724e52f841 | hejj16/Introduction-to-Algorithms | /Algorithms/counting_sort.py | 967 | 4.09375 | 4 | def counting_sort(list):
'''a function to sort a list of integers, the function will NOT change the original list'''
max_int = list[0]
min_int = list[0]
for i in list:
if int(i) != i:
print("Must be a list of integers")
return None
if i > max_int:
... |
65d1e9732417a06e8bfe00f6897749ede83e5a13 | AyWhite22/Public-Python-1.2writingSimple | /1.2writingSimple/convert/convert(fahren-cel).py | 569 | 4.34375 | 4 | # A. White Dec 10, 2018
# December 10, 2018
# Part 9 of 1.2
#defining script.
def main():
#telling reader what program does.
print("This program converts a temperature in Fahrenheit to a temperature in Celcius.")
#asking reader what amount they want to convert.
fahrenheit = eval(input("What is the Fahr... |
49b66d736bdc3c4292e28d54294be176cf1c33da | AyWhite22/Public-Python-1.2writingSimple | /1.2writingSimple/futval/futval2.py | 801 | 4.1875 | 4 | # futval2.py
# A program to compute the future value of an investment
#with number of years determined by the user.
# Part 6 of 1.2
#defining the script.
def main():
#telling the reader what the script does.
print("This program calculates the future value")
print("of a multi-year investment with non-compou... |
3c9ffbcc5ea3c4320ee390528fe45590f3b22997 | nanahyunpark/python_study | /424.py | 826 | 3.765625 | 4 | class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return "(" + str(round(self.x, 1)) + ', ' + str(round(self.y, 1)) + ")"
class Triangle:
def __init__(self, points):
self.points = points
def get_centroid(self):
sum... |
999ac5819c519c7683b9c07efedded226fb072bb | nanahyunpark/python_study | /421.py | 518 | 3.796875 | 4 | class Student:
def __init__(self, name, school, grade):
self.name = name
self.school = school
self.grade = grade
def get_msg(self):
return "Name : " + self.name + "\n" + "School : " + self.school + "\n" + "Grade : " + self.grade
def main():
info = input().split()
studen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.