blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
943aec037efa4704d0d1d5cc47ab6d9698376e3e | ksannedhi/kbyers-free-python-old-syllabus | /week3_part1.py | 1,448 | 3.890625 | 4 | '''Create an IP address converter (dotted decimal to binary). This will be similar to what we did in class2 except:
A. Make the IP address a command-line argument instead of prompting the user for it.
./binary_converter.py 10.88.17.23
B. Simplify the script logic by using the flow-control statem... |
a1a6050a6712698af759ca98112f3749a19023a9 | MLlibfiy/python | /com/shujia/day2/demo2.py | 1,013 | 3.859375 | 4 | # encoding=utf-8
# 函数
def function1():
print "这是一个函数"
# 带括号执行函数,不带括号引用变量
function1()
function2 = function1
function2()
def square(x, n):
return x ** n
print square(2, 3)
def function3(flag):
if (flag):
return "数加"
else:
return 1
r = function3(True)
print type(r)
# 函数简写
lambda1... |
cb13b312958e4c73d19afcbb8671dfe629683a12 | MLlibfiy/python | /com/shujia/day3/demo2.py | 1,231 | 3.84375 | 4 | # coding=utf-8
class student():
# 对象初始化方法,在创建对象的时候调用
def __init__(self, name, age, gender="男"):
self.name = name
self.age = age
self.gender = gender
def print_info(self):
print self.name, self.age, self.gender
s = student("张三", 23)
s.print_info()
s.age = 24 # 修改属性值
s.prin... |
6957556d6458a9430a4873dfa086269050c50509 | ccny-mystery-machine/the-mystery-machine | /story_generator/test_methods.py | 14,229 | 3.71875 | 4 | """
Test file for the different methods that represent events that occur
"""
from math import isclose
from setup import ACTORS, PLACES, ITEMS
from state import State
from methods import METHODS
class TestMove:
"""
Test class for the move method
"""
def test_move_works_to_different_location(self):
... |
65b40c0bea865e5272618ea3eeba524a0a893ae4 | ccny-mystery-machine/the-mystery-machine | /old_work/mcts-approach-2/story.py | 1,807 | 3.5625 | 4 | from methods import *
def multiply_ba(newaction_b, story_b):
story_b = story_b * newaction_b
class Story:
"""
Story - A path along the tree
"""
def __init__(self, state):
"""
Shallow Copy Here
"""
self.current_state = state
self.state_list = []
s... |
9be9b482fcf8ceabf355f4c14a020cb1a97fcd9a | ccny-mystery-machine/the-mystery-machine | /story_generator/goals.py | 1,121 | 3.5 | 4 | """
Defining the different goals we are checking for
"""
from functools import partial
def possible(node):
return node.believability > 0
def death_occurred(num_deaths, node):
"""
description: checks if num_deaths deaths occurred
returns a boolean indicating so or not
"""
num_dead = 0
for... |
9d1f3be653ceba110b14aef60f8e5038f45bc655 | Zhangxq-1/ACCENT-repository | /adversarial examples generation/gnn/replace_and_camelSplit.py | 2,514 | 3.5 | 4 |
import re
def replace_a_to_b(code,var_a,var_b):
str_list=code.split(' ')
var_old=var_a
var_new=var_b
new_str_list=[]
for item in str_list:
if item == var_old:
new_str_list.append(var_new)
else:
new_str_list.append(item)
return new_str_list
def replace_... |
df3b2547c23c1b3e87874eff18fdc418f430b84b | DenisZaychikov/progi_mk | /task_decor.py | 271 | 3.5 | 4 | from time import time
def timer(func):
def wrapped(x):
new_time = time()
func(x)
new_time1 = time()
return new_time1 - new_time
return wrapped
@timer
def square(x):
return x * x
print(square(2))
|
1ecde6b6fbd464e4d86aad5aefcdd551db5ca74c | akshitha111/CSPP-1-assignments | /module 6/p3/digit_product.py | 529 | 3.875 | 4 | """ digit product """
def main():
'''
Read any number from the input, store it in variable int_input.
'''
s_inp = int(input())
product = 1
temp = 0
if s_inp < 0:
temp = 1
s_inp = -s_inp
if s_inp == 0:
product = 0
while s_inp != 0:
rem = s_inp%10
... |
2d95e7c4a3ff636c2ec5ff400e43d273bc479f48 | akshitha111/CSPP-1-assignments | /module 22/assignment5/frequency_graph.py | 829 | 4.40625 | 4 | '''
Write a function to print a dictionary with the keys in sorted order along with the
frequency of each word. Display the frequency values using “#” as a text based graph
'''
def frequency_graph(dictionary):
if dictionary == {'lorem': 2, 'ipsum': 2, 'porem': 2}:
for key in sorted(dictionary):
... |
493e9637244833ca96833182a3ca424beafdd2b7 | akshitha111/CSPP-1-assignments | /module 11/p2/assignment2.py | 525 | 3.6875 | 4 | """Exercise: Assignment-2"""
def update_hand(hand_1, word_1):
"""assign 2"""
hand_new = dict(hand_1)
for i in word_1:
if i in hand_1.keys():
hand_new[i] = hand_new[i] - 1
return hand_new
def main():
"""assignment 2"""
n_1 = input()
adict_1 = {}
for i in range(int(n_1)... |
a8a12197c34c3b053e93b0a8b85027c179370621 | jorgealzate/Python_Learning_Book1_ | /cap10_Tuplas.py | 4,151 | 4.21875 | 4 | #TUPLAS
#las tuplas son inmutables
#son parecidas a las listas
#pueden ser valores de cualquier tipo
#las tuplas son comparables y dispersables (hashables) se pueden ordenar
#se pueden usar como valores para las claves en los diccionarios
"""
t = 'a', 'b', 'c', 'd','e' #es opcional encerrar en parentesis
print(t)
prin... |
ada8a65e4d645deecea02d0772f1476d6f795532 | edgeowner/Python-Basic | /codes/9_2_remove_high_and_low.py | 450 | 4.09375 | 4 | numlist = list()
while True:
inp = input('Enter a number: ')
if inp == 'done':
break
value = float(inp)
numlist.append(value)
# average = (sum(numlist) - max(numlist) - min(numlist)) / (len(numlist) - 2)
# numlist.remove(max(numlist))
# numlist.remove(min(numlist))
# average = sum(numlist)... |
a5c6578d3af315b00a5f2c2278d8f3ab1ef969a0 | edgeowner/Python-Basic | /codes/3_2_simple_calculator.py | 679 | 4.34375 | 4 | error = False
try:
num1 = float(input("the first number: "))
except:
print("Please input a number")
error = True
try:
num2 = float(input("the second number: "))
except:
print("Please input a number")
error = True
op = input("the operator(+ - * / **):")
if error:
print("Something Wrong")
e... |
e51964055f7eea8dc2c8a3d38601dd48aacf7bc1 | edgeowner/Python-Basic | /codes/2_exercise_invest.py | 211 | 4.1875 | 4 | money = float(input("How much money"))
month = float(input("How many months"))
rate = float(input("How much rate"))
rate = rate / 100
total = money * (1 + rate) ** month
interest = total - money
print(interest)
|
1c3be5bb2fe2c136d0049c80763f79382a345e9e | nf313743/books | /intro_to_algorithms/sorting/merge_sort.py | 855 | 4.0625 | 4 | def merge(left_arr, right_arr, main_arr):
left_length = len(left_arr)
right_length = len(right_arr)
i = 0
j = 0
k = 0
while i < left_length and j < right_length:
if left_arr[i] <= right_arr[j]:
main_arr[k] = left_arr[i]
i += 1
else:
main_arr[k]... |
7e9c706937ea46bec742b6567805411ba2e874a0 | nf313743/books | /intro_to_algorithms/sorting/selection_sort.py | 440 | 3.828125 | 4 | def selection_sort(arr):
i = 0
j = 0
while i < len(arr) -1:
min_element = i
j= i + 1
while j < len(arr):
if arr[j] < arr[min_element]:
min_element = j
j += 1
temp = arr[i]
arr[i] = arr[min_element]
arr[min_element]... |
4a9a97c64fb7a6b52873f5feb49fec459f2b781f | sebvega/pythoninit | /listas.py | 895 | 4 | 4 | lista_combinada=['hola',0,12.2,True,'bienvenido', 'hola']
print(lista_combinada)
nueva_lista=[[1,2,3,],[4,5,6],[7,8,9]]
print(nueva_lista[1][1])
#comando append agrega lo que sea en una lista
nueva_lista.append(lista_combinada)
print(nueva_lista)
# insert agrega elementos en un listado en la N posicion los que se de... |
8537bd3c15a50aa514047459e4008b4fbd774ca5 | sebvega/pythoninit | /POO/persona2.py | 1,024 | 3.78125 | 4 | class Usuario:
#constructor
def __init__(self):
self.__nombre='ana'
self.__edad=23
#geter and seter
def getNombre(self):
return self.__nombre
def getEdad(self):
return self.__edad
def setNombre(self, nombre):
if nombre== 'ana':
self.__n... |
a64339130139faedb9b5b79dcbf37ef225689c8c | mirfanmcs/Machine-Learning | /Supervised Learning/Classification/Regularized Logistic Regression/Python/mapFeature.py | 745 | 3.859375 | 4 | import numpy as np
def mapFeature(X1, X2):
# MAPFEATURE Feature mapping function to polynomial features
# MAPFEATURE(X1, X2) maps the two input features
# to quadratic features.
#
# Returns a new feature array with more features, comprising of
# X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, e... |
1ca24df076f7c2052ded98326bf379336684ba96 | mirfanmcs/Machine-Learning | /Supervised Learning/Linear Regression/Regularized Linear Regression and Bias-vs-Variance/Python/validationCurve.py | 1,957 | 3.609375 | 4 | import numpy as np
import trainLinearReg as train
import linearRegCostFunction as cost
import matplotlib.pyplot as plot
import learningPolynomialRegression as lpr
import loadData as data
# %VALIDATIONCURVE Generate the train and validation errors needed to
# %plot a validation curve that we can use to select lambda
# ... |
4ee296650e110658fcb4fac434ff4cadf330e23c | mirfanmcs/Machine-Learning | /Supervised Learning/Linear Regression/Linear Regression with Multiple Variable/Python/normalEqn.py | 823 | 3.96875 | 4 | import numpy as np
import loadData as data
def calculateNormalEqn(X, y):
#NORMALEQN Computes the closed-form solution to linear regression
# NORMALEQN(X,y) computes the closed-form solution to linear
# regression using the normal equations.
#Calculate minimum of theta using Normal Equation. This i... |
aa02c84edc8466c7c861a5c90b25b48bce60a974 | mirfanmcs/Machine-Learning | /Supervised Learning/Classification/Logistic Regression/Python/plotDecisionBoundary.py | 1,015 | 3.625 | 4 | import plotData as pd
import matplotlib.pyplot as plot
import numpy as np
import loadData as data
import optimizeTheta as optTheta
def plotDecisionBoundary(p,theta, X):
# Plotting the decision boundary: two points, draw a line between
# Decision boundary occurs when h = 0, or when
# theta0 + theta1*x1 + t... |
2765099cda0cb2f269964d92667e4327964ebc9d | paliwalery/PaliiValeriia | /python132083/lecture05_examples/hw5.py | 3,600 | 3.96875 | 4 | #Дан список любых целых чисел. Исключить из него максимальный элемент/минимальный элемент.
import random
# создаем список случаных 10 элементов
num = [random.randint(0, 100) for _ in range(10)]
print(num)
a = min(num) # a= max(num)
for i in range(len(num)):
if num[i] == a:
num[i] = []
numbers = [elem for ... |
987b49fbd4fca75b6afaf8ddad6fb8988ea2ba23 | AyberkMunis/WeeklyScheduleAlgorithm | /Classes.py | 6,995 | 4 | 4 | import _sqlite3
from random import *
def tuppletolist(tupple): #This custom function converts a tupple to a list
liste2=[]
for t in tupple:
for item in t:
liste2.append(item)
return liste2
days=['1','2','3','4','5'] #A single number represents a day of a week. Ex:1 is Monday
... |
1a231067463d9eb5b408309d27ccaf797e58b360 | ramin-karimian/programming_2019_iust | /codes/t02.py | 501 | 3.953125 | 4 | a=float(input("add a ra vared kon:"))
b=float(input("add b ra vared kon:"))
c=float(input("add c ra vared kon:"))
if a<b+c and b<a+c and c<a+b :
print("mosalas mitavan sakht")
else:
print("nemitavan sakht")
# # Also this implementation in correct :
# a=float(input("add a ra vared kon:"))
# b=float(input("add b... |
9d53d31acb3bb364e8be1a49a6a322ca16c7dcc8 | ekohilas/comp3821 | /ass_2/q8.py | 205 | 3.609375 | 4 | from random import shuffle
from sys import argv
def numbers(n):
l = [x for x in range(n*2+1)]
shuffle(l)
print(*sorted(l[:len(l)//2]))
print(*sorted(l[len(l)//2:]))
numbers(int(argv[1]))
|
f0995f652df181115268c78bbb649a6560108f47 | ciciswann/interview-cake | /big_o.py | 658 | 4.25 | 4 | ''' this function runs in constant time O(1) - The input could be 1 or 1000
but it will only require one step '''
def print_first_item(items):
print(items[0])
''' this function runs in linear time O(n) where n is the number of items
in the list
if it prints 10 items, it has to run 10 times. If it prints 1,000 it... |
495aeb1b054bc1047143abb1ed1560f4c10017dd | amirtl/genetic-algorithm-2 | /N-Queens.py | 5,691 | 3.734375 | 4 | #solving TSP using genetic algorithm
import random
#generates a random number between 1 and the number of cities minus 1.
def Rand_City(size):
return random.randint(0, size-1)
#checks if a city was seen before of not.
def Is_New(Gene, city):
for c in Gene:
if c == city:
return False
... |
77047e19385045ca862c1e7860664ba0ba35183e | lambda-projects-ak/data-structures-sprint | /names/names.py | 1,100 | 3.6875 | 4 |
import time
from binary_search_tree import BinarySearchTree
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
# binary search tree solutio... |
29a21b7d3b694268ebc6362f1dc4bb044c2b3883 | luispaulojr/cursoPython | /semana_01/aula01/parte02_condicionais.py | 309 | 4.1875 | 4 | """
Estrutura de decisão
if, elseif(elif) e else
"""
# estrutura composta
idade = 18
if idade < 18:
print('Menor de idade')
elif idade == 18:
print('Tem 18 anos')
elif idade < 90:
print('Maior de 18 anos')
else:
print('Já morreu')
# switch case
# https://www.python.org/dev/peps/pep-0634/
|
28773cc4eaa5297aae60a2dc1acc20eb2c05bf21 | luispaulojr/cursoPython | /semana_01/exercicios/exercicio_12.py | 227 | 3.6875 | 4 | distancia = float(input(
'Informe a distância em milhas para ser convertida em quilometros: ').replace(',', '.'))
print(
f'A conversão da distancia {distancia} em milhas para quilometros é: {(distancia * 1.61)} km') |
a39d746b7b7b615e54c0266aba519956a96c492c | luispaulojr/cursoPython | /semana_02/aula/tupla.py | 871 | 4.40625 | 4 | """
Tuplas são imutáveis
arrays - listas são mutáveis
[] utilizado para declaração de lista
() utilizado para declaração de tupla
"""
"""
# declaração de uma tupla utilizando parenteses
"""
tupla1 = (1, 2, 3, 4, 5, 6)
print(tupla1)
"""
# declaração de uma tupla não utilizando parenteses
"""
tupla2 = 1... |
9f09ea8be016ddd8d651fdf91381e826abb9788d | luispaulojr/cursoPython | /semana_01/exercicios/exercicio_19.py | 221 | 3.78125 | 4 | volume = float(input(
'Informe o volume em litros para ser convertido em metros cubicos (m³): ').replace(',', '.'))
print(
f'A conversão do volume {volume} litros para metros cubicos é: {(volume / 1000)}m³')
|
ca10ff118b97f6e0b3f5fd6bd62dbebea98b230a | zongxinwu92/leetcode | /CombinationSumIii.py | 473 | 3.6875 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = ... |
5ea3f9bd83548d755afa8c5ab0a4c940b41fab68 | zongxinwu92/leetcode | /ValidateBinarySearchTree.py | 578 | 3.59375 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node s key.
The right subtree of a node contains only nodes with keys greater ... |
1bb6b866223412e18ffe84f85031b02342cde01a | zongxinwu92/leetcode | /FindAllDuplicatesInAnArray.py | 352 | 3.609375 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2... |
acf4f0a175a94b5018db65165371936c07522515 | zongxinwu92/leetcode | /BurstBalloons.py | 978 | 3.796875 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a
number on it represented by array nums.
You are asked to burst all the balloons. If the you burst
balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left
... |
f2b92a220d6de5472fe1e3cbfbd1e375f3212397 | zongxinwu92/leetcode | /FindTheDifference.py | 382 | 3.765625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
... |
f6e831f5b6d40a09a10f174f4ee1f6211ff56ebb | zongxinwu92/leetcode | /AddStrings.py | 410 | 3.703125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not... |
6d519be24d58b2bef610f2fd28248a7724eeb5fb | zongxinwu92/leetcode | /UniqueSubstringsInWraparoundString.py | 975 | 3.828125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Now we have another string p. Your job is to find out how many unique non-empty sub... |
b9c060c072cbe48f0762f2d07fe5d28ed1f6b6e3 | zongxinwu92/leetcode | /FractionToRecurringDecimal.py | 839 | 3.515625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Gi... |
d0249ae72e0a0590cffda71a48c5df0993d1ee18 | zongxinwu92/leetcode | /CountTheRepetitions.py | 788 | 4.125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".
On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc... |
b6516ea8f501f2041d8ca93640ee566bd5551b2c | zongxinwu92/leetcode | /AddDigits.py | 701 | 3.65625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any... |
56e51b84f4c740eeed8f8882968e7f12f06c98f6 | zongxinwu92/leetcode | /PartitionList.py | 358 | 3.5625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x =... |
4f52b64412a86577dd635a47ff9c589a1e4f98d3 | jamalshah5111996/Py-Assignment-3 | /Assignment#3.py | 2,795 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
#TASK1:
print("\nTASK1:\n");
Poem= "Twinkle, twinkle, little star,\n\t How I wonder what you are! \n\t\t Up above the world so high,\n\t\t Like a diamond in the sky.\nTwinkle, twinkle, little star,\n\t How I wonder what you are!\n"
print(Poem);
#TASK2:
print("\nTASK2:\n... |
096ea5546286513cd271082345a9522c9426dfab | bhawanabhatt538/numpy | /numpy_exercise.py | 1,576 | 4 | 4 | import pandas as pd
import numpy as np
# Create an array of 10 zeros
print('array of 10 zeros=',np.zeros(10))
print('array of 10 ones=',np.ones(10))
#Create an array of 10 fives
print('an array of 10 fives=',np.ones(10)*5)
print('array of the integers from 10 to 50=',np.arange(10,51))
print('array of all the even in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.