blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
25a39a23d66108f8909741e94c7e9e290479c044 | fatmazehraCiftci/GlobalAIHubPythonCourse | /Homeworks/homework2.py | 482 | 4.1875 | 4 | """
Create a list and swap the second half of the list with the first half of the list and
print this list on the screen
"""
def DivideandSwap(list):
length=len(list)
list1=[]
list2=[]
for i in range(int(length/2)):
list1.append(list[i])
remainder=length-int(length/2)
... |
7897b5bda08cd20480ad6f0ec81d1d85474acf67 | hmortonsmith/hmwk2 | /hmwk1.py | 800 | 3.875 | 4 | #Instance
instancedef = 'Definition: an example or single occurrence of something. Or to cite (a fact, case, etc.) as an example.'
print(instancedef)
print(type(instancedef))
#Variable
variabledef = 'Variable: memory locations to store values. This means that when you create a variable you reserve some space in mem... |
3766e43d653c9e92a2fdb946a34de44c0e43905c | shivamagrawal3900/Python-crash-course | /chapter5-if_statements.py | 1,249 | 4.1875 | 4 | cars = ['Audi', 'BMW', 'Jaguar', 'LandRover']
for car in cars:
if car == 'Jaguar':
print(car.upper())
else:
print(car)
# == is case sensitive
print(cars[1]=='bmw')
# > False
# !=
print(cars[1]!='Audi')
# > True
# Numerical Comparisions
# ==, !=, <, >, <=, >=
# Checking multiple values
# 'and' and 'or' ope... |
715b959e8aaf156691736cb1b588efa25c395eac | stephenvsmith/Moisture-Sensor-Project | /led_blink.py | 423 | 3.640625 | 4 | import RPi.GPIO as GPIO
from time import sleep
channel = 8
GPIO.setmode(GPIO.BOARD) # This sets the board numbering scheme (channel 17 for BCM)
GPIO.setup(channel, GPIO.OUT) # We are saying that the channel is an output
for i in range(10):
GPIO.output(channel,1)
sleep(2.2)
GPIO.output(channel,GPIO.LOW)
... |
b34db77eb11ccf1182f5580292199badb298842d | varoonravi/HelloWorld | /baby.py | 300 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 01 23:12:33 2016
@author: Varoon
"""
import re
string = 'hhhhhllo bro, he this is just a test strinng'
match = re.search(r'\bword\b',string)
if match:
print 'Match found ', match.group()
else:
print 'Match not found'
print match.group() |
06715c888e9ddfabe8d47f636557564c09bafb31 | varoonravi/HelloWorld | /anagram.py | 599 | 4.09375 | 4 |
print "Enter a String to find out if it is an anagram"
a=raw_input("Enter any String")
b=raw_input("Enter any String")
d1={}
d2={}
boolean = False
if len(a) != len(b):
print "Not an anagram"
for char in a:
if char in d1:
d1[char] += 1
else:
d1[char] = 1
for char in b:... |
0e47f03bdb02d8a56743fafb5478fd2cf84acf36 | danieleambrosino/HashTableTest | /hash_tables.py | 3,238 | 3.71875 | 4 | from linked_list import *
from math import sqrt
def is_prime(number):
if number == 2:
return True
if number <= 1 or number % 2 == 0:
return False
square_root = int(sqrt(number)) + 1
for divisor in xrange(3, square_root, 2):
if number % divisor == 0:
return False
... |
99a719f08047588e8407a089505520939c9a167e | zzo2741/STUDY_CodingTest | /if/if.py | 1,056 | 3.796875 | 4 | # 두 수 비교하기
# num = input()
num = "1 2"
num1 = num.split(" ")
A = int(num1[0])
B = int(num1[1])
if(A > B):
print(">")
elif(A < B):
print("<")
else:
print("==")
print()
# 시험 성적
score = 100
# score = int(input())
if(90 <= score and score <= 100):
print("A")
elif(80 <= score and score <= 89):
print("B")... |
b3e06ce457025fd3a0bbc933bd1e16e7f97c091b | p-vishad/apriori-python | /apriori.py | 7,303 | 3.71875 | 4 | # Vishad Pokharel
# vpokhare
# vpokhare@u.rochester.edu
# CSC 240 Project 1
import pandas as pd
import itertools
# class for Item to wrap items properly without loss of the column name
class Item:
def __init__(self, col_name, value):
self.col_name = col_name
self.value = value
df = pd.read_csv('a... |
3639137e1ea98213c91d626df75154a85b863e6c | nirmalshajup/Sample | /test.py | 164 | 4 | 4 | a = int(input("Enter the number : "))
b = int(input("Enter another number : "))
sum = a + b
dif = a -b
print("Difference = "+str(dif))
print("Sum = " +str(sum))
|
45202ac845816e7635b0d387c7683b3b119cdd16 | veershah-sh/Weight_Convertor | /weight.py | 225 | 4.0625 | 4 | from convertors import *
weight = int(input("Weight: "))
unit = input("(L)bs OR (k)g: ")
if unit.upper() == "L":
print(f"You are of {lbs_to_kg(weight)} KiloGrams")
else:
print(f"You are of {kg_to_lbs(weight)} Pounds")
|
b81a939ec19e27cbfed7c70842058bd90718a509 | theSaab/leetcode | /valid_palindrome_2.py | 1,027 | 3.671875 | 4 |
def valid(s):
if len(s) <= 4:
if s[0] == s[-1]:
return True
else:
return False
else:
if len(s) % 2 != 0:
middle = s[len(s)//2]
first_half = s[:len(s)//2]
second_half = s[len(s)//2+1:]
else:
first... |
ffef86cfe30ce434b30ca84769a7500e588a147d | theSaab/leetcode | /minimum_genetic_mutation.py | 565 | 3.796875 | 4 |
def row(list):
bank = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
for element in list:
count = 0
i = 0
position = 0
while i < len(element):
print(element[position])
if element[position] in bank[count]:
i += 1
position += 1
... |
6afb0b1198fedd9fb703a849d6a40d3b89f40b16 | theSaab/leetcode | /car_fleet.py | 633 | 3.65625 | 4 |
def fleet(target, position, speed):
if len(position) == 0:
return 0
else:
enum_pos = {}
for i,pos in enumerate(position):
enum_pos[pos] = speed[i]
fleet_num = 0
position.sort()
for i,node in enumerate(position):
... |
d7deff9d033c7fd8046901e177fb77c9430c280e | theSaab/leetcode | /consecutive_chars.py | 467 | 3.578125 | 4 |
def consecutive( s ):
count = 0
new_count = 0
for i,char in enumerate(s):
try:
if s[i+1] == char:
new_count += 1
else:
if new_count >= count:
count = new_count
new_count = 0
except:
if n... |
ca64fc9b11150bbf0147295103002524979d27d0 | theSaab/leetcode | /Rotate_Matrix.py | 650 | 3.71875 | 4 |
'''
given a NxN matrix, rotate the numbers by 90 degrees
difficult
'''
# input matrix
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# assigning variables
len_matrix = len(matrix)
cols = 0
ret_matrix = []
# creating the blank matrix
for i in range(len_matrix):
ret_matrix.append([])
# a... |
a29010b091711a23d5231047626c47d360ba9081 | theSaab/leetcode | /testGraphic.py | 649 | 3.890625 | 4 |
# # arr nums[int]
# # running sum
# # non empty
# # non infinite
# # return arr[int]
# # input [1,2,3,4]
# # ex: [1,3,6,10]
# # 1. empty arr[]
# # 2. for i,element in enum(nums)
# # 3. try: new_num = arr[i-1] + element
# # 4. except: new_num = element
# # 5. arr.append(new_num)
# # 6. return arr
# # 1. for i,ele... |
ee82cc437b471eaf44b5cefc4cd572d95df630b4 | theSaab/leetcode | /valid_anagram.py | 360 | 3.640625 | 4 |
s = "anagram"
t = "nagaram"
def anagram(s, t):
dik = {}
dik2 = {}
for i,n in enumerate(s):
if n in dik:
dik[n] += 1
else:
dik[n] = 1
for i,n in enumerate(t):
if n in dik2:
dik2[n] += 1
else:
dik2[n] = 1
re... |
32d177c77cd1792ff483297e70b3161114d426ac | theSaab/leetcode | /nth_digit.py | 346 | 3.5 | 4 |
def digit(digit):
dik = {}
count = 0
for i in range(digit+1):
for i,n in enumerate(str(i)):
# print(str(n) + ' n')
# print(str(i) + ' i')
dik={}
dik[count ] = n
# print(str(count) + ' count')
count += 1
return dik[digi... |
5aaf627131286897823e944f8b7e205a47d9c864 | theSaab/leetcode | /power_of_two.py | 176 | 4.125 | 4 |
number = 14
def power(num):
while num != 1 and num != 0:
num = num / 2
if num == 0:
return False
else:
return True
print(power(number)) |
693a3615e4be52322998b00a47e1380e021ceea8 | theSaab/leetcode | /check_N_and_double.py | 239 | 3.734375 | 4 |
def check( arr ):
for i,num in enumerate(arr):
for elem in arr[i+1:]:
if elem * 2 == num:
return True
elif elem == num * 2:
return True
else:
return False |
301eeee9e0ae012ff98ec31aa1bcc409250a5e83 | theSaab/leetcode | /degree_of_array.py | 991 | 3.734375 | 4 |
def degree(nums):
first = int(nums.index(nums[0]))
last = int((len(nums) -1) - list(reversed(nums)).index(nums[0]))
count = nums.count(nums[0])
degree = last - first
arr = [nums[0]]
for element in nums[1:]:
if element not in arr:
arr.append(element)
... |
c59dc47c84ea6e0ff3e2756e7a9fe64e7581e3ee | xielidong/linux_net_py_homework | /ex_03_01.py | 150 | 3.84375 | 4 | hour=input("Enter hour:")
money=input("Enter money:")
h=(float)(hour)
m=(float)(money)
if h<=40 :
print(h*m)
else:
print(40*m+(h-40)*1.5*m)
|
f294e486dbe05099953060322c1e983582a015db | whbpt/coursera | /data_structures_and_algorithms/4_dynamic_programming_starter_files/knapsack/knapsack.py | 490 | 3.578125 | 4 | # Uses python3
import sys
import numpy as np
def optimal_weight(W, w):
# write your code here
result = 0
n= len(w)
array_=np.zeros([n+1,W+1])
for j in range(0,n):
for i in range(1,W+1):
if i-w[j]>=0:
if array_[j,i-w[j]]+w[j]<=W:
array_[j+1,i]=max(array_[j,i-w[j]]+w[j],array_[j,i])
else:
array_... |
136cc5aefb6a03c96d84589080122392ff8afc6a | saravananmsk/Bigdata | /Python/python_win/stringformatter.py | 307 | 4.09375 | 4 | # to print username and host name from given mail id
emailid=input("Enter the mail id:")
print(emailid)
username=emailid[:emailid.index("@"):]
print(username)
host=emailid[emailid.index("@")+1:emailid.index(".")]
print(host)
output="Username is {1} and host name is {0}"
print(output.format(host,username)) |
7344c9f39784db4556cb8750d89962dc4098ad33 | saravananmsk/Bigdata | /Python/evenoddpython.py | 164 | 4.21875 | 4 | # Even odd program in python
a=int(input("please enter the number"));
if(a%2==0):
print("Entered number is even")
else:
print("Entered number is odd")
|
88dd5591cd309ed46bf4132e7ca12c4f856348ff | saravananmsk/Bigdata | /Python/python_win/fun3.py | 343 | 3.625 | 4 | username=input("Enter user name:").strip()
password=input("Enter password:").strip()
def loginValidation(uname,upass):
print("User login details:",username,password)
if(username=="admin" and password=="admin"):
return "Success"
else :
return "Failure"
x=loginValidation(uname=username,upass=... |
85677c6534585110b2b48d2fcdd08ea709c2bdb7 | zhuliyi10/algorithm | /merge_sort.py | 1,342 | 3.609375 | 4 | # 归并排序
def mergerSort(arr, l, r):
"""
把序列分成元素尽可能相等的两半。
把两半元素分别进行排序。
把两个有序表合并成一个。
稳定性:稳定
时间复杂度O (nlogn)
"""
if l < r:
m = int((l+r)/2)
mergerSort(arr, l, m)
mergerSort(arr, m+1, r)
merge(arr,l,m,r)
def merge(arr, l, m, r):
n1 = m-l+1
n2 = r-m
... |
0e2da0dac6f7e1a0ca072f6502d00771b4181bd2 | meeseeksss/hello_world | /argv.py | 340 | 3.75 | 4 | import sys
def func(number=10):
'prints a multipul times'
for i in range(number):
print('a')
try:
args=sys.argv[1]
except IndexError:
args=input('number?')
if args.startswith('-'):
obtion=args.strip('-')
if obtion=='help':
print(help(func))
else:
print('invailed order')
else:
... |
e2160cf76e40ae5d4fba91bf29fad9d424f47c6a | Pytools786/backdoor_trojan | /pyauto.py | 866 | 3.671875 | 4 | import requests,subprocess
def download_my_file(url): # this function will download my file
get_responce = requests.get(url)
with open(file_name,'wb') as file:
file.write(get_responce.content)
def execute_my_file(file_name): # this function execute my file after downloading
subprocess.ru... |
26fe398dc36f756a7afef1d65961d1dd952dd7eb | md1023/olivetti | /trials/bfs.py | 688 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
graph = OrderedDict([("ROOT", OrderedDict([
("A", OrderedDict([
("A1", OrderedDict([("A11", False), ("A12", False)])),
("A2", False),
("A3", OrderedDict([("A31", False)])),
("A4", False)])),
("B",... |
a71a86adc2a1240bfd051fe0cd26f9c3d560c49a | md1023/olivetti | /trials/acronis/numbers.py | 6,203 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
NULL_NAME = u"нуль"
class Number(object):
small_names = u"один два три четыре пять шесть семь восемь девять \
десять одинадцать двенадцать тринадцать четырнадцать \
пятнадцать шестнадцать семнадцать восемнадцать девятнадцать".split()
small_names... |
8f9adcc7d07f94f96c43625405dd4f0336b4db9c | grifmang/CS50-Python | /vigenere.py | 1,668 | 4.09375 | 4 | import string
def vigenere():
while True:
key = input('Please enter a key string: ')
if not key:
print('Key cannot be blank.')
continue
elif not key.isalpha():
print('Only letters in the key, please.')
continue
break
... |
47f38be344dcb60c9dce81e2496e6ebf3efcdfe8 | Brilliant-Kwon/PythonEx | /Jan_28_29/quiz01/quiz01_3.py | 397 | 3.671875 | 4 | students = [
{
"name": "Kim",
"kor": 80,
"eng": 90,
"math": 80
},
{
"name": "Lee",
"kor": 90,
"eng": 85,
"math": 85
}
]
print(students[0])
for i in range(0, 1):
students[i]["sum"] = students[i]["kor"] + students[i]["eng"] + students[i][... |
da2fa0cc36df2510057f86e5c12b1904daee630e | morry48/algorithm-python-practice | /select.py | 436 | 3.796875 | 4 | from typing import List
def select_sort(numbers: List[int]) -> List[int]:
len_numbers = len(numbers)
for i in range((len_numbers)):
min_idx = i
for j in range(i+1, len_numbers):
if numbers[min_idx] > numbers[j]:
min_idx = j
numbers[i], numbers[min_idx] = num... |
6452686c1f9736244865ac7c0b682fe254fa09d2 | huntreslogan/Skills1 | /skills1_speed.py | 2,666 | 4.0625 | 4 | # Things you should be able to do.
number_list = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"]
# Write a function that takes a list of numbers and returns a new list with only the odd numbers.
def all_odd(number_l... |
9d774064e170164bf831c996fed7cdbe0e2b1cbc | Avis20/learn | /python/_ya/youtube/lecture4/can_number.py | 1,178 | 3.90625 | 4 | class Solution:
# Основание системы
system_found = 10
def is_digit_permutation(self, x: int, y: int) -> bool:
digits_x = self.digits(x)
digits_y = self.digits(y)
return digits_x == digits_y
def digits(self, num: int) -> dict:
result = {}
while num > 0:
... |
ea483bb8ab0fd35a05da2eb3a39a16a979f8bfca | Avis20/learn | /python/_ya/leetcode/alg/easy/binary_tree/bfs with none.py | 1,686 | 3.6875 | 4 | # breadth-first search, BFS = Поиск в ширину
# https://ru.wikipedia.org/wiki/%D0%9F%D0%BE%D0%B8%D1%81%D0%BA_%D0%B2_%D1%88%D0%B8%D1%80%D0%B8%D0%BD%D1%83
from collections import deque
class TreeNode:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.r... |
50085e6c67d2019fc6b2d8bd3de5d8498d18edd5 | Avis20/learn | /python/_ya/leetcode/alg/easy/power_of_four.py | 496 | 3.5 | 4 |
class Solution:
def isPowerOfFour(self, n) -> bool:
if n < 1:
return False
if n == 1:
return True
return self.isPowerOfFour(n / 4)
if __name__ == "__main__":
"""
Ссылка:
Дано:
Необходимо:
Примечание:
Решение:
Сло... |
46a5d4f143a277a6982e6e5f6b2b07b87f037f99 | Avis20/learn | /python/_ya/youtube/lecture2/simple_rle.py | 875 | 3.546875 | 4 |
class Solution:
def simple_rle(self, s: str):
if not s:
return ""
last_sym = s[0]
answer = []
for i in range(1, len(s)):
if last_sym != s[i]:
answer.append(last_sym)
last_sym = s[i]
answer.append(last_sym)
retu... |
7dd53836bddb25a0403a427cee6f94628913b560 | Avis20/learn | /python/core/_iterations/cycle_iterator.py | 888 | 4.0625 | 4 | from typing import Any
# Итератор должен итерироваться по итерируемому объекту
# (list, tuple, set, range, Range2, и т. д.), и когда достигнет последнего элемента, начинать сначала.
class CyclicIterator:
def __init__(self, items: Any):
self.curr_index = -1
self.last_index = len(items) - 1
... |
d40c5e93adbaace45b26072ebe8fe30aec35bc34 | Avis20/learn | /python/_ya/leetcode/alg/easy/linked_list/convert_to_binary.py | 1,273 | 3.765625 | 4 |
from typing import Optional
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class Solution:
def getDecimalValue(self, head: Optional[ListNode]) -> int:
node = head
num = node.val
while node.next:
num = num * 2 + node.next.val... |
cdfc61603dac109372d52235c33b139920fc26f6 | Avis20/learn | /python/books/groming_algo/ch1-welcome/binary_search.py | 833 | 3.75 | 4 | class Solution:
def binary_search(self, nums: list, target: int) -> int:
low = 0
high = len(nums) - 1
while high >= low:
# (0 + 10) // 2 = 10 // 2 = 5
# (6 + 10) // 2 = 16 // 2 = 8
# (6 + 7) // 2 = 13 // 2 = 6
mid = (low + high) // 2
... |
c8707f6e099e8481c51f431eaa600a0531045db4 | Avis20/learn | /python/_ya/leetcode/alg/easy/remove_element.py | 1,172 | 3.578125 | 4 | from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
n = len(nums)
while n > i:
if nums[i] == val:
nums[i] = nums[n - 1]
n -= 1
else:
i += 1
return n
if __n... |
6ca10df5919477199a9bad88be518ee1a92536ac | Avis20/learn | /python/_ya/youtube/lecture2/find_min_even.py | 842 | 3.75 | 4 | class Solution:
def find_min_even(self, nums: list[int]):
find_min = False
min_even = nums[0]
for n in nums:
if n % 2 == 0 and n < min_even:
find_min = True
min_even = n
return min_even if find_min else -1
if __name__ == "__main_... |
d25c3f554ab6edc09aa1624b320f7be65fc83943 | Avis20/learn | /python/_ya/leetcode/alg/easy/range_sum_query.py | 969 | 3.65625 | 4 |
class NumArray:
def __init__(self, nums):
sums = []
# Создадим заранее массив со всеми суммами пред. чисел включая это число
counter = 0
for i in range(len(nums)):
counter += nums[i]
sums.append(counter)
self._sums = sums
def sumRange... |
649b7e0fdf161de3b6b8bfa004f8d707b3e73e8a | Avis20/learn | /python/_ya/leetcode/alg/easy/add_digits.py | 1,042 | 3.71875 | 4 |
class Solution:
def addDigits(self, num):
while num >= 10:
curr = num
sum_num = 0
while curr:
curr, div = divmod(curr, 10)
sum_num += div
num = sum_num
return num
def addDigits2(self, num):
res, ... |
d9d121a9240b4712f6cbacb802064f235ff57413 | Avis20/learn | /python/books/essential_algo/ch3-linked_list/main.py | 2,286 | 4.125 | 4 | class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, head: Node | None = None):
self.head = head
def add_after(self, search_val: int, new_node: Node):
node = self.head
while node:
if n... |
09ea43cd396693c775912dd83794f43c38de8ee5 | deepikaasharma/Parallel-Lists-Challenge | /main.py | 1,333 | 4.125 | 4 | """nums_a = [1, 3, 5]
nums_b = [2, 4, 6]
res = 0
for a, b in zip(nums_a, nums_b):
res += a * b"""
"""Write a function called enum_sum which takes a list of numbers and returns the sum of the numbers multiplied by their corresponding index incremented by one.
Ex: enum_sum([2, 4, 6]) -> (index 0 + 1)*2 + (index 1 ... |
dbe82345afdc270acf6e19085cefffa05bb82976 | GreatRaksin/sat3pm | /svetofor.py | 544 | 3.765625 | 4 | from turtle import *
from shapes import *
t = Turtle()
rectangle(t, 'black', 100, -50, 50)
t.goto(0, -30)
t.down()
t.color('red')
t.circle(35)
t.up()
t.goto(0, -140)
t.down()
t.color('green')
t.circle(35)
t.up()
minutes = int(input('Введите число: '))
if minutes % 2 == 0:
t.goto(0, -140)
t.down()
t.fill... |
0a15ba5ab50d99b52901e18206117e549ff6866d | ComputationalReflection/stypy | /stypy/sgmc/sgmc_cache/testing/test_programs/without_classes/idioms/idiom_simple_if_not_type.py | 95,420 | 3.90625 | 4 |
# -*- coding: utf-8 -*-
"""
ORIGINAL PROGRAM SOURCE CODE:
1: theInt = 3
2: theStr = "hi"
3: if True:
4: union = 3
5: else:
6: union = "hi"
7:
8:
9: def simple_if_not_base1(a):
10: b = "hi"
11: if not type(a) is int:
12: r = a / 3
13: r2 = a[0]
14: b = 3
15: r3 = a / 3
16:... |
b143f315f2cd999437afb91489b0ee76d8e35d1a | ComputationalReflection/stypy | /testing/test_programs/with_classes/class_declaration/class_inherits_union.py | 418 | 3.5 | 4 |
class A:
a_Att = 3
def ma(self):
return "A"
class B:
def mb(self):
return "B"
if True:
base = A
else:
base = B
class Simple(base):
sample_att = 3
(a,b) = (6,7)
def from_a(self):
return self.a_Att
def sample_method(self):
self.att = "sample"
... |
7ad481ded65b1544ffe35a8714484e0da172106e | ComputationalReflection/stypy | /stypy/sgmc/sgmc_cache/testing/test_programs/benchmark_suite/shedskin/dijkstra.py | 144,282 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
"""
ORIGINAL PROGRAM SOURCE CODE:
1: # dijkstra shortest-distance algorithm
2: #
3: # (C) 2006 Gustavo J.A.M. Carneiro, licensed under the GPL version 2
4:
5: import random
6:
7: random.seed()
8:
9: G = None
10:
11: class Vertex(object):
12: __slots__ = ('name',)
13: def __init__(s... |
71168ca95e3f4afb7fc7ea34d8c9258dffbfdda6 | ComputationalReflection/stypy | /testing/test_programs/without_classes/functions/function_call_lambda_closures.py | 257 | 3.671875 | 4 |
d = dict()
d[1] = "one"
d[2] = "two"
cast = dict()
for key in d.keys():
cast[key] = lambda x, k=key: str(k) + str(x)
r = cast[key](10)
print r
for key, val in d.items():
if val not in cast:
cast[val] = key
print d
print cast |
275845625b20e2f31515ad14bf9229ea88320bed | ComputationalReflection/stypy | /testing/test_programs/without_classes/for_statements/for_string.py | 89 | 3.59375 | 4 |
string = "this is an string"
s = ""
a = 0
for c in string:
s = s + c
a = a + 1
|
d27129eab54fc8799f03e3c0085a6621a44f5415 | ComputationalReflection/stypy | /testing/test_programs/numpy/basic_numpy/functions/numpy_cumsum.py | 379 | 3.53125 | 4 | # http://www.labri.fr/perso/nrougier/teaching/numpy.100/
import numpy as np
def moving_average(a, n=3):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
r = moving_average(Z, n=3)
# l = globals().copy()
# for v in l:
# print ("'" + v + "'" + ": ... |
9295633e6b03999c4e01ddbf3574015f2163e279 | ComputationalReflection/stypy | /testing/test_programs/stypy_code_copy/stypy_copy/python_lib_copy/python_types_copy/type_inference_copy/no_recursion_copy.py | 1,003 | 3.71875 | 4 | # -------------------
# Recursive functions
# ------------------
import traceback
class RecursionType:
pass
def norecursion(f):
"""
Annotation that detects recursive functions, returning a RecursionType instance
:param f: Function
:return: RecursionType if the function is recursive or the passe... |
7a6642ee5d6d97d09577a13046992bfdd6f8d1b7 | ComputationalReflection/stypy | /testing/test_programs/without_classes/subscripts/stypy_test_files/basic_subscripts__type_annotation.py | 145 | 3.546875 | 4 |
# l: list[int]
l = [1, 2, 4, 5]
# a: int
a = 2
# x: int
x = l[1]
# y: int
y = l[a]
# z: int
z = l[(a + 1)]
# s: str
s = 'abcd'
# c: str
c = s[2] |
cc46b212efba53e480d36ced41f9f0a90ad26016 | ComputationalReflection/stypy | /testing/test_programs/without_classes/with/stypy_test_files/simple_with_usage_no_var__type_annotation.py | 544 | 3.71875 | 4 |
# controlled_execution: controlled_execution
class controlled_execution:
# self: instance
# __enter__() -> int
def __enter__(self):
# self: instance
print 'enter the with class'
return 0
# __exit__(type: NoneType, value: NoneType, traceback: NoneType) -> None
def __exi... |
4dd5e4c7d7016545b2293bb2c4dda8687d1df96d | ComputationalReflection/stypy | /testing/test_programs/numpy/basic_numpy/numpy_mathematical_functions_exponents.py | 1,666 | 3.640625 | 4 | # https://docs.scipy.org/doc/numpy/reference/routines.math.html
import numpy as np
x = 2.1
x1 = 3.4
x2 = 5.6
# Exponents and logarithms
r1 = np.exp(x) # Calculate the exponential of all elements in the input array.
r2 = np.expm1(x) # Calculate exp(x) - 1 for all elements in the array.
r3 = np.exp2(x) # Calculate ... |
fa09179a68a5b6c061f0e3b39ffa082d2e10a018 | ComputationalReflection/stypy | /stypy/sgmc/sgmc_cache/testing/test_programs/benchmark_suite/shedskin/pisang.py | 158,297 | 3.5 | 4 |
# -*- coding: utf-8 -*-
"""
ORIGINAL PROGRAM SOURCE CODE:
1: # pisang - a simple sat solver in Python
2: # (c) mark.dufour@gmail.com
3: import os
4:
5:
6: def Relative(path):
7: return os.path.join(os.path.dirname(__file__), path)
8:
9:
10: argv = ['', Relative('testdata/uuf250-010.cnf')]
11:
12: cnf = [l.st... |
f7a6a9c3bba87ac11ed4b8ab8b5b52bcca5fd55a | ComputationalReflection/stypy | /testing/test_programs/numpy/basic_numpy/functions/numpy_arange.py | 368 | 3.640625 | 4 | # http://www.python-course.eu/numpy.php
import numpy as np
a = np.arange(1, 10)
# compare to range:
x = range(1, 10)
# some more arange examples:
x2 = np.arange(10.4)
x3 = np.arange(0.5, 10.4, 0.8)
x4 = np.arange(0.5, 10.4, 0.8, int)
# l = globals().copy()
# for v in l:
# print ("'" + v + "'" + ": instance_o... |
eaea50c98733839184abd9a969122e737b204cd1 | ComputationalReflection/stypy | /testing/test_programs/numpy/basic_numpy/arrays/numpy_arrays.py | 581 | 3.953125 | 4 | # http://cs231n.github.io/python-numpy-tutorial/
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
r = type(a) # Prints "<type 'numpy.ndarray'>"
r2 = a.shape # Prints "(3,)"
r3 = a[0], a[1], a[2] # Prints "1 2 3"
a[0] = 5 # Change an element of the array
r4 = a # Prints "[5, 2, 3]"
b = np.arra... |
792a80a9d3ead5f3c39142ffa7bd0afb533e2c69 | ComputationalReflection/stypy | /stypy/sgmc/sgmc_cache/testing/test_programs/without_classes/idioms/idiom_simple_if_hasattr.py | 86,300 | 3.796875 | 4 |
# -*- coding: utf-8 -*-
"""
ORIGINAL PROGRAM SOURCE CODE:
1: theInt = 3
2: theStr = "hi"
3: if True:
4: union = 3
5: else:
6: union = "hi"
7:
8:
9: def simple_if_hasattr_base1(a):
10: b = "hi"
11: if hasattr(a, '__div__'):
12: r = a / 3
13: r2 = a[0]
14: b = 3
15: r3 = a ... |
8976ba885b018f928284de9128f6b2ce4725c4dc | BibhuPrasadPadhy/Python-for-Data-Science | /Python Basics/100_Python_Programs/Question2.py | 501 | 4.4375 | 4 | ##Write a program which can compute the factorial of a given numbers.
##The results should be printed in a comma-separated sequence on a single line.
##Suppose the following input is supplied to the program:
##8
##Then, the output should be:
##40320
##
##Hints:
##In case of input data being supplied to the ques... |
47d22c2eaa4743e63d2f038c4c4586de663866e7 | BibhuPrasadPadhy/Python-for-Data-Science | /ifelseelif.py | 684 | 3.859375 | 4 | language = input('Enter your coding Language: ')
if language == 'Python':
print('Language is Python')
elif language == 'Java':
print('Language is Java')
elif language == 'C++':
print('Language is C++')
elif language == '.Net':
print('Language is .Net')
elif language == 'JavaScript':
prin... |
42aabb928d1a626fc7621d27729a9d72442b49e1 | oselyuti/Projects | /Path_finder/main_dfs.py | 10,804 | 3.65625 | 4 |
import sys
import getopt
class node:
def __init__(self, i=-1, j=-1):
self.value = -1 # 0 if possible to move there 1 if not
self.bottom = None
self.right = None
self.left = None
self.top = None
self.i = i
self.j = j
self.neighbors = []
self... |
6df13046788202c94fc5a6d369d77da822067081 | OlyaPinchuk/Python | /lesson1_code.py | 2,478 | 3.71875 | 4 | # # sdfjkhsdf
# # """
# # sdfs
# # sddf
# # sdf
# # sdf
# # """
# # '''
# # sdfsdf
# # sdfsdf
# # '''
# # '''
# #
# # '''
# print(1, 2, 3, 4, 6, sep='-', end=' Finish')
# print()
#
# i = 3
# f = 1.3
# b = False # True
# s = "text"
# n = None
#
# print(type(i))
# print(type(f))
# print(type(b))
# print(type(n))
#
# a ... |
b73206949bf0b78ca311df385c39c57cae2807a3 | icelighting/leetcode | /数组与字符串/存在重复元素.py | 616 | 3.65625 | 4 | '''
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。
如果数组中每个元素都不相同,则返回 false
'''
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
length1 = len(nums)
length2 = len(list(set(nums)))
if length1 == length2:
... |
00bbd145994b22dc4508c56999e3aacf4e3c0549 | icelighting/leetcode | /排序与搜索/两个数组的交集.py | 526 | 3.953125 | 4 | '''
求两个数组元素的交际
'''
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1 = set(nums1)
nums2 = set(nums2)
x = nums1 & nums2## set集合可以直接使用& 来寻找交集
r... |
e31f963bd7200373aee9479e02782cae753f58de | icelighting/leetcode | /数组与字符串/判断括号输出.py | 1,692 | 3.53125 | 4 | '''给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。'''
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
d = {'{':'}','(':')','[':']'}
stack ... |
a0634beef978ebb97c4f72c079c8a264d5d8a82c | icelighting/leetcode | /动态规划/爬楼梯.py | 908 | 3.8125 | 4 | '''
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
'''
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
if n == 2:
return 2
s1 = self.climbStair... |
ad6052f8294286278f9c13f690ac652a66042e28 | icelighting/leetcode | /链表/反转链表.py | 1,029 | 3.6875 | 4 | '''
反转一个单链表。
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
re... |
05417a7dfae06dc4220c46805ba435c84e8ef627 | icelighting/leetcode | /数组与字符串/螺旋矩阵2.py | 1,325 | 3.734375 | 4 | '''
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,
且元素按顺时针顺序螺旋排列的正方形矩阵。
'''
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
nlist = list(range(1,n**2+1))
matrix = []
for i in range(n):
matrix.append(list(range(n)))
... |
22c6eec29a6602e9e744ed8aa7f34736ee85a4e5 | icelighting/leetcode | /链表/旋转链表.py | 784 | 3.78125 | 4 | '''
给定一个链表,旋转链表,
将链表每个节点向右移动 k 个位置,
其中 k 是非负数。
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
... |
adec167493d0401567662b7107f44eb6661ad22a | zhangtm2016/python_test | /.idea/copyright/exercises_5.py | 391 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
x=int(raw_input('X:'))
y=int(raw_input('Y:'))
z=int(raw_input('Z:'))
#判断法
if (x >= y and y >= z ):
print x,y,z
elif(x >= z and z >= y):
print x,z,y
elif(y >= x and y >= z):
print y,x,z
elif(y >= z and z >= x):
print y,z,x
elif(z >= x and x >= y):
print z,... |
ea612707b88797bbdaffef4def3a1936460bd648 | zhangtm2016/python_test | /.idea/copyright/exercises_6.py | 422 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
# 输出前 10 个斐波那契数列
print fib(10)
f1 = 1
f2 = 1
for i in range(1,22):
print '%12ld %12ld' ... |
6b68f861e8ba815ad33e546ca6d5ff28b2fb3add | navjo7/DataStructure | /python/sorting/sort.py | 489 | 4.1875 | 4 | unsortedArray = [ 5, 3, 6, 8, 2, 1, 4, 5, 6 ]
print("unsorted : ",*unsortedArray)
# selection sort
for i in range(len(unsortedArray)):
minimumIndex = i
for j in range(i+1,len(unsortedArray)):
if unsortedArray[j] < unsortedArray[minimumIndex]:
minimumIndex = j
temp = unsortedArray[i]
... |
c028ce1efe49670e222fda5e9392bc2f90ef6aee | kirawrath/RP | /first_project/voronoi.py | 793 | 3.53125 | 4 | from circle import *
class Voronoi:
def __init__(self):
pass
def find_polygons(self, dots):
circles = []
polygons = []
ldots=len(dots)
for i in range(ldots):
for j in range(i+1,ldots):
for k in range(j+1,ldots):
circle = Circle([dots[i],dots[j],dots[k]])
#checking if collinear
if circ... |
54811a1a28cdd6d73e7d92a58dcfca515ffb7038 | delphinBlue/LeetCode | /Tree/236_LowestCommonAncestorOfBinaryTree.py | 1,697 | 3.96875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
# 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):
"""
Recursive method: DFS.
If the... |
96e92e4bc07517376e5e7e639b177b6833067939 | driphub/IncreaseCsdnPv | /src/strategy/time_strategy.py | 543 | 3.5 | 4 | """
time_strategy.py
function: provide view frequency according to time
"""
import datetime
class TimeStrategy(object):
@staticmethod
def get_sleeptime_by_hour():
now_hour = datetime.datetime.now().strftime('%H')
now_hour = int(now_hour)
if now_hour >= 11 and now_hour < 24:
... |
d68c9cf85a4f6a2cb377a94c2c124a55feccd66c | pmk2109/Week0 | /Code2/dict_exercise.py | 1,513 | 4.28125 | 4 | from collections import defaultdict
def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pyth... |
388bd6b7042634a2bc98cb55bc4ee8fc9cb53988 | Addibro/word_count | /wordcount.py | 689 | 4.0625 | 4 | import sys
import re
from collections import Counter
# Read a file and count the words
file = open(sys.argv[1])
# Data structure to store the words
word_occurrences = {}
# Get usual words
stopwords = open('ignore').read().split()
# Split punctuations (.,")
text = file.read().lower()
text = re.sub('[^a-z]+'," ", te... |
a63908c918a6b0cbd35b98485fc79683c3923138 | joy-joy/pcc | /ch03/exercise_3_8.py | 1,075 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:17:17 2018
@author: joy
"""
# Seeing the World
visit_list = ["Machu Picchu", "Phuket", "Bali",
"Grand Canyon", "Santorini", "Dubai",
"New York City", "Paris", "London", "Sydney"]
print("\nVisit List:")
print(vi... |
093fbab0a28da1fb96ac4cf105847729dccf9a35 | joy-joy/pcc | /ch03/exercise_3_10.py | 2,229 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 21:38:45 2018
@author: joy
"""
# Every function
countries = ['USA', 'UK', 'USSR', 'Brazil', 'India', 'Bangladesh',
'Pakistan', 'Mexico', 'Saudi Arabia', 'Australia']
print("\nHere's our initial list of countries:\n", countries)
#... |
124711b41088039a1dc39310442fac2ba5bbb7e2 | math974/brainfuck_interpreter | /my_brainfuck.py | 5,903 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: UTF8 -*-
import sys
import re
"""
Date : 18/06/2021
Auteur : Mathias BALLOT
Project : brainfuck interpreter
Licence : MIT
"""
class Node:
"""
Linked List in python
"""
def __init__(self, value):
"""
construct list
"""
self.value = va... |
f72e84962131b9403b5cffd09363da56365f2ff2 | YashMishra96/Neural-Conversational-Model | /All codes/Multi_Task.py | 2,490 | 3.578125 | 4 | from config import *
def single_layer_model(hidden_units,feature_size,vocab_size,units_dense_1,l_r,decay):
"""
Inputs:hidden_units-->number of hidden units in lstm(right now we are taking it to
be the same in both encoder and decoder lstm)
feature_size--> size of the word embeddings
vocab_size--> n... |
f2ca785bf731dc4d5d78b90901b4506db8addd2a | Florian16100/kholles | /LYS_Florian_kholle_1.py | 981 | 3.8125 | 4 | # Projet Kholle
# Maitriser des simples opérations en Python
# 25/11/18
# Lys Florian
import csv
# Lecture du fichier
def read_file():
with open('file.csv', "r") as r:
spamreader = csv.reader(r)
for row in spamreader:
print(', '.join(row))
# Ecriture dans le fichier
def write_file(message... |
d6d46c954bf3065ecfb87d4b40a3dcb07693b738 | annaship/BPC-scripts | /compare_regast4_gast_check_454_res.py | 1,291 | 3.546875 | 4 | import sys
filename = sys.argv[-1]
def compare_res(num0, num1):
if num0 == num1:
return True
else:
return False
# print line.rstrip()
# print "num = %s" % num
# print "total_trimseq = %s" % total_trimseq
# print all_ok
with open(filename) as in_file:
for line in in_file:
if lin... |
5b7497df24c39635443de94ab60848af7c52e279 | cameronreese/project-euler | /PE007/PE007_solution.py | 558 | 3.828125 | 4 | # PE007 Project Euler Problem: 10001st Prime
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#
# What is the 10 001st prime number?
def is_Prime(num) -> bool:
i = 2
if num == 2 or num == 3:
return True
while (i <= num/2):
if num % i ==... |
7ed03ad3aa9bcbaa338568a3b54c612740da8dd7 | lordjavac/6-Nimt | /nimt6/card_collection.py | 570 | 3.75 | 4 | from .card import Card
class CardCollection(object):
""" Creates a collection of cards """
def __init__(self):
super(CardCollection, self).__init__()
self._cards = list()
def add(self, card):
if not isinstance(card, Card):
raise TypeError('Only Cards may be added to a ... |
27cc437a945520ce0cc02631064e31420304ca71 | flztiii/numerical_optimization_test | /steepest_gradient_descent.py | 1,278 | 3.984375 | 4 | # /usr/bin/python3
# -*- coding: utf-8 -*-
'''
Steepest Gradient Descent to Solve Linear Function Example
author: flztiii
'''
import numpy as np
Q = np.array([[6, 3, 5],[3, 2, 2],[5, 2, 7]])
b = np.array([5.2, 1.3, 4.4]).T
# the objective funtion
def f(x):
return 0.5 * np.dot(np.dot(x.T, Q), x) - np.dot(b.T, ... |
93455d29c3a5ee2f9a63896824027925d5c1fc8d | AlexeyZibinsky/Zabavbl | /some turtle stuff/turtle_star_maker.py | 3,355 | 4.34375 | 4 | """
This programm paints a regular Star!
"""
import turtle
import math
import typing as ty
Point = ty.Tuple[float, float]
def find_points(radius: int, vertices_count: int) -> ty.List[Point]:
"""
Calculates
coordinates of vertices
of a regular polygon with
a Radius equal to Radius and number
... |
7705715e8e7b21cfbc6b0b3c32d44f9463333c80 | janbalaz/ds | /selection_sort.py | 1,048 | 4.28125 | 4 | from typing import List
def find_smallest(i: int, arr: List[int]) -> int:
"""
Finds the smallest element in array starting after `i`.
:param i: index of the current minimum
:param arr: array of integers
:return: position of the smallest element
"""
smallest = i
for j in range(i + 1, l... |
72385e51495ed17597e19bd13f49992ef96df332 | karlmanalo/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,243 | 4.5 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Handling empty arrays
if len(arr) == 0:
return -1
# Setting midpoint
midpoint = (start + end) // 2
if target == arr[midpoint]:
return midpoint
# Recursion if target i... |
fbb99279410300d18b04e4206e9c9b043a4c0866 | egbea123/Math | /Test_REMOTE_389.py | 281 | 4.1875 | 4 | #!/usr/bin/env python
def main ():
num1 = 10.5
num2 = 6.3
# Subtract two numbers
sum = float(num1) - float(num2)
# Display the result
print('The sum of {0} and {1} is {2}',num1, num2, sum )
#division of two numbers
result = 10.5 / 6.3
print ("Result :",result) |
0bc1dc9490f8a58b17d26520671143e8f6b4aef2 | brunostandard/OLD-osu-data-analysis-visualizations | /Python code/test_csv_gen.py | 465 | 3.84375 | 4 | """
For learning purposes. Just demonstrating how we can write on a csv file.
"""
import csv
with open('data.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
filewriter.writerow(['Name', 'Profession'])
filewriter.... |
fe4db7b12b8ccd31a023ea6c43bf010afcec0c89 | hira66it/pyProject | /I_learned_today/2_os_path.py | 1,076 | 3.75 | 4 | import os
path = r'/Users/Hinyong_Mac/Downloads/L12.pdf'
#0. 현재 디렉토리 출력
print(os.getcwd)
#1. Join the path
print(os.path.join(r'/Users/Hinyong_Mac/Downloads/','L12.pdf'))
#2. Split the file name from path of folder
print(os.path.split(path))
# 확장자만 따로 떨어트린다.
print(os.path.splitext(path))
#3. Change the working dir... |
b6ad2c813f102387a3aaf3a37723aad2f5ba9aac | eMostyn/Project-Euler-Problems | /problem 51.py | 2,705 | 3.65625 | 4 | import eulerlib
#Function to generate numbers given then number and indexs to replace
def generateNums(n,toReplace):
#Nums will be the list of numbers generated
nums = []
#Having the number as a string so as to index
string = str(n)
#For each digit 0-9
for k in range(0,10):
#For each po... |
82f118cb1e618034590226cf72eb0fedf84f42eb | eMostyn/Project-Euler-Problems | /problem 45.py | 593 | 4.0625 | 4 | import math
#Function to check if n is a pent number using inverse function
def isPent(n):
num = (1+math.sqrt(1+24*n))/6
return num == int(num)
#Function to check if n is a hex number using inverse function
def isHex(n):
num = (1+math.sqrt(1+8*n))/4
return num == int(num)
#Main function to compute
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.