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
81963f0a9909dcc26aac6a6f76c2379684f0e8a1
bsofcs/interviewPrep
/DuplicateAndMissingNumber.py
1,851
3.65625
4
import math def findMissing(arr): if arr is None: return None n=len(arr) #Take sum of numbers from 0 to n res=(n*(n+1))/2 res_a=0 #Take sum of all elements for i in range(n): res_a+=arr[i] return(res-res_a) def findDuplicate(arr): if arr is None: return None n=len(arr) res=0 #taking XOR from 0 to n-1...
b729488edc2155ac3c3d76977adb46464b3b35bc
IgorMaiaSales/MetodosNumericos
/Lista 2/1_a.py
255
3.65625
4
# 1. Determine a raiz real da equação f(x) = 5x³ - 5x² + 6x - 2: # # (a) Graficamente # # Resposta: Aproximadamente 0.4. import numpy as np import matplotlib.pyplot as plt x = np.arange(-5, 5, 0.1) plt.plot(x, 5*x**3 - 5*x**2 + 6*x - 2) plt.show()
46f360e2ece2d5195fe417c92cc1b91cd1f467ae
Chauhan98ashish/Hacktoberfest_2020
/newton_sqrt.py
219
4.34375
4
print("*****Square Root By Newton's Method*****") x=int(input("Enter the number::>>")) r=x a=10**(-10) while abs(x-r*r)>a: r=(r+x/r)/2 print(r) r=round(r,3) print("Square root of {} is {}".format(x,r))
50b40d11a0068383b12510c5cb381a7e0f6517fb
abhimanyu-bitsgoa/Coco
/main_scripts/dictionary.py
344
3.546875
4
from PyDictionary import PyDictionary from speak import say def findMeaning(str): dictionary=PyDictionary() meaningDict=dictionary.meaning(str) if meaningDict!=None: meaningList = [elem[0] for elem in meaningDict.values()] return meaningList[0] else: return "Sorry no meaning found" if __name__ == '__main__':...
694fb4994a1444d130a5e356109dfff865557bb3
shuklaprachi21/Learning-Python
/built_in_abs.py
220
3.84375
4
def distance_from_zero(a): if(type(a)==type(1) or type(a)==type(1.5)): return abs(a) else: return "Nope" print distance_from_zero("Hi") print distance_from_zero(-1) print distance_from_zero(-2.6)
312f0545ac850271d264010afab3d67b20f31e03
shuklaprachi21/Learning-Python
/anagram.py
458
3.828125
4
import re def is_anagram(a, b): a_l = a.lower() b_l = b.lower() s1 = ''.join(re.findall(r"[\w]+",a_l)) s2 = ''.join(re.findall(r"[\w]+",b_l)) if len(s1) != len(s2): return False s1_list = list(s1) s2_list = list(s2) s1_list.sort() s2_list.sort() # print s1_list # print...
49a37d1de3745759c603099e888ac6fd74fccbb4
sairaj225/Python
/Lists/item_exists.py
109
3.8125
4
l = ["sai", "raj", 225] if "sai" in l: print("sai exist") if "hai" not in l: print("Hai not in l")
6e23a74dfe14ed098efb7faedc01ccebd87ae885
sairaj225/Python
/Utilities/alarm_reminder.py
715
3.59375
4
import time import winsound from win10toast import ToastNotifier def timer ( message, minutes ): notificator = ToastNotifier() notificator.show_toast( "Alarm", f"Alarm will go off in {minutes} minutes...", duration=50 ) time.sleep( minutes * 60 ) ...
c7aa27a1bd3cb900533845dd60eada06f6773b7f
sairaj225/Python
/Regular Expressions/5Find_a_word_in_string.py
307
4.28125
4
import re # if re.search("hello", "we have said hello to him, and he replied with hellora hello"): # print("There is hello in the string") # findall() returns list of all matches words = re.findall("hello", "we have said hello to him, and he replied with hellora hello") for i in words: print(i)
6c7e393680152b14a04838a6406298cce3e9e3fb
sairaj225/Python
/Generators/1demo.py
774
4.5625
5
''' Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way. ''' # If a function contains at least one yield statement # It becames a Generator function. # Generator function contains one or more yi...
0ffdfec42224f7361d216e35e0c5453e06819073
sairaj225/Python
/Dictionaries/checkkeyexits.py
157
3.765625
4
d = { "name" : 'sairaju', "roll no" : 225, "class" : "MCA" } # Checking key exits or not if "name" in d: print("name exist in dictionary")
0812bf3e02aab77cd81877643d436f0f615564e1
sairaj225/Python
/Regular Expressions/7match_range_characters.py
231
3.578125
4
import re str = "Sat, hat, mat, pat, lat" match_words = re.findall("[h-m]at", str) for i in match_words: print(i) print("**********************") match_words = re.findall("[^h-m]at", str) for i in match_words: print(i)
afc839d183e205f373d0d0431261cb9d26a2035c
sairaj225/Python
/Regular Expressions/12verify_phone_number.py
251
4.125
4
import re # \w = [a-zA-Z0-9_] # \W = [^a-zA-Z0-9_] phone_number = "412-555-1212" if re.search("\w{3}-\w{3}-\w{4}", phone_number): print("It is a phone number") if re.search("\d{3}-\d{3}-\d{4}", phone_number): print("It is a phone number")
65d380c3a9a7e96e88682e0d935fa3eb61f5eebd
sairaj225/Python
/Dictionaries/accessing.py
299
4.25
4
d = { "name" : 'sairaju', "roll no" : 225 } print(d) # Accessing the dictionary print(d['roll no']) print(d.get('name')) # Changing the value of the dictionary key d['name'] = "raje" print(d) # Adding new item into dictionary d["class"] = "MCA" print(d) # Dictionary length print(len(d))
7de0721452adecebfe21d1f941bedc98efd0bec5
jelena3214/UniPythonProject
/second.py
290
3.515625
4
import math def kvadratniKoren(broj): brojac=0 if broj>=0: while brojac**2<broj: brojac=brojac+1 if brojac**2!=broj: print("Nije savrsen koren") print (None) else: return brojac else: print("Broj je negativan ili nula") m=kvadratniKoren(25) print(m)
6d5c4d281d67e0cd5813acae975cfe7d6de6d8a4
2heeesss/Problem_Solving
/BOJ/DFS_BFS/1260.py
913
3.515625
4
from collections import deque def dfs(graph, v, visted): visted[v] = True print(v, end=' ') for i in graph[v]: if not visted[i]: visted[i] = True dfs(graph, i, visted) def bfs(graph, start, visted): queue = deque([start]) visted[start] = True while queue: ...
c830baad8cd44befc91355f1a39f22cbc73f86f8
2heeesss/Problem_Solving
/reBOJ/1769.py
455
3.578125
4
import sys input = sys.stdin.readline s = input().rstrip() cnt = 0 def sumStr(str): result = 0 for num in str: result += int(num) return result def isLessTen(str): if len(str) < 2: return True return False while True: if isLessTen(s): print(cnt) if int(s) % ...
5ef1ca0c3a4377ea23027a121387a51c5fead6ff
2heeesss/Problem_Solving
/BOJ/그리디/BOJ_기초.py
894
3.796875
4
# a = 10 # b = 20 # print(a/b) # print(a//b) # 몫 # print(a % b) # 나머지 # print(a**b) # 거듭제곱 # 리스트 # a = [100, 200, 1, 2, 3, 4.12, 500000] # a.insert(3, 100) # array = [100] * 10 # array.insert(9, 1) # array.insert(0, 2) # print(array) # array.remove(100) # array.remove(100) # array.remove(100) # array.remov...
0e9627dc4153c741f9d10f42eab3419f13d7bdd6
2heeesss/Problem_Solving
/동빈북/BFS.py
803
3.546875
4
from collections import deque # BFS 는 큐 자료구조 사용. 기본적으로 append, popleft로 구현함 def BFS(graph, start, visted): queue = deque([start]) # 큐에 시작노드 저장 visted[start] = True # 시작노드 방문처리 while queue: # 큐가 없어질때까지 v = queue.popleft() # 먼저 들어간 노드 없애기 print(v, end=' ') for i in ...
7648e5f06ee9e52686d3a7a0099dd436a2a216d6
mhassanist/python-samples
/002-read-csv-to-dict-manual-parse.py
2,303
3.640625
4
#The file conents ''' Title,Released,Label,UK Chart Position,US Chart Position,BPI Certification,RIAA Certification Please Please Me,22 March 1963,Parlophone(UK),1,-,Gold,Platinum With the Beatles,22 November 1963,Parlophone(UK),1,-,Platinum,Gold Beatlemania! With the Beatles,25 November 1963,Capitol(CAN),-,-,, Introdu...
f7917d704ac0e45d8b0ffc804eeac7dc65eac66b
Dnavarro805/Python-Programming
/Data Structures - Arrays/StringReverse.py
358
4.1875
4
# Problem: Create a funciton that reverses a string. # Input: "Hi My Name is Daniel" # Output: "lienaD si emaN yM iH" def reverse(str): reversed = [] for x in range (len(str)-1, -1, -1): reversed.append(str[x]) return ''.join(reversed) def reverse2(str): return str[::-1] print(reverse...
e3e8cefd3816dbe6ee76b6054a36baf2d7f0286a
19PalaceWinston/WinstonPalace-Python
/WordMaker/WordMaker.py
800
3.640625
4
import random def randWord(word): constants = ["q","w","r","t","p","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"] vowels = ["i","e","a","o","u"] for y in range (len(word)): for x in range(20): if word[y] == constants[x] or word[y] == constants or word[y] == word: ...
f1137a8d138d38c08f4fb799156dce44f3635a4f
19PalaceWinston/WinstonPalace-Python
/unit1Lab/unit1Lab.py
131
3.765625
4
print("I love Python\n") myName = input("Enter Your Name") print (myName + "\n") num = input("Enter a Number") print(int(num) + 5)
8b5eb3202623dee7afd078beedee3ea02ebda6e0
19PalaceWinston/WinstonPalace-Python
/Unit6ALab/Unit6ALab.py
1,823
4.0625
4
def check(textCodes): go = "true" while go == "true": ans = input("Name a text code - ") if ans == "/menu": main(textCodes) return if ans in textCodes: print(textCodes[ans]) else: define = input("What does that mean?") i...
b37f442ea1ae6beaff7fdbdbe03e6c2037fc91f3
Phinnik/n-queens-solutions
/n_queens_solver/n_queens_solver.py
1,822
3.921875
4
from typing import List, Tuple import copy def get_possible_positions(n_queens: int, queens_positions: List[Tuple[int, int]] = None) -> List[Tuple[int, int]]: """ Returns possible queen positions :param n_queens: number of queens :param queens_positions: known queens positi...
0d8179fd7dfa075da99a4a560f88d6aa3dc670ff
miubisystems/IOT-Using-NodeMCU-MicroPython
/Lab7/Lab 3 - Animation on OLED Display/main.py
1,769
3.578125
4
# Necessary Libraries to be Imported from machine import I2C, Pin import ssd1306 import time import framebuf #Creation of I2C Bus Object Using I2C Library #Specifiy Desired Pins For CLK and DATA respectively i2c = I2C(-1, Pin(5), Pin(4)) #Creation of Display Object using SSD1306 Library and binding it to I2C ...
7b0335c7c0655c78ec3a534324c471483c2ba7d7
VictorCastao/Monitoria_PS
/Trabalho02.py
671
3.796875
4
#Inicializando variáveis correspondentes ao número de dias e a soma soma_total = 0 soma_parcial = 0 dias = 0 resposta = 0 n = 0 indicador = False #Lendo número de dias n = int(input()) #Obtendo somas de cada dia while dias < n: #Atualizando dia atual dias = dias + 1 #Acessos do dia soma_parcial = in...
2ab652213076ad2cbb4ce9832434f47fbc72cf10
mariachevez/ejerci
/ejercicios de estructura/eje30.py
360
3.953125
4
print("""Almacenar en un vector los Factoriales""") lista=[] factorial = 0 for i in range (1, 21): print ('Numero',i) n = int (input ("digite un valor: ")) for i in range (1, n + 1): 6 if i==1: factorial=1 else: factorial=factorial*i list...
e1d7965387216f087aa8b1e8fb611af92948ee13
mariachevez/ejerci
/ejercicios de estructura/eje34.py
699
3.75
4
for i in (1,2): mqtriz =int(input("ingrese la matriz[i,j]: ")) for j in (1,2): matriz= int(input("ingrese la matriz[i,j]: ")) mayor=0 menor=1000 posicion_mayor_i=0 posicion_mayor_j=0 posicion_memor_i=0 posicion_memor_j=0 for i in (1,2): for j in (1,2): if matriz>mayor: ma...
862c67f1395069bed6126d5b795403db862ecb6d
mariachevez/ejerci
/ejercicios de estructura/eje29.py
137
3.90625
4
print("""Buscar si un numero se encuentra en el vector""") lista=[4,3,23,11,44,5,6,7,45,2,54,55,62,8,9] print(lista) print(5 in lista)
de4b7a2803984777b7da76852efb05bdcbf41565
mariachevez/ejerci
/ejercicios de estructura/eje26.py
154
3.75
4
print("""Suma de dos Vectores""") lista1=[4,3,3,2,4,5,6,7,5,2,4,5,6,8,9] lista2=[1,42,1,34,5,38,7,5,4,3,7,4,5,6,9,] suma=(lista1+lista2) print(suma)
1175d19359fbca1453f24840c6cd27d5de69e782
IMDingDong/sorting_algorithm
/quick_sort.py
535
4.03125
4
def quick_sort(arr): if len(arr) > 1: pivot = arr[len(arr)-1] left, mid, right = [], [], [] for i in range(len(arr)-1): if arr[i] < pivot: left.append(arr[i]) elif arr[i] > pivot: right.append(arr[i]) else: m...
474c0a0e3b6a5b554c5cfe2e2a307bb166934a46
karlek/avant-graph
/load.py
1,678
3.6875
4
import parse import sqlite3 # graph_db retrieves values from our database and parses the name field to # make a relational graph based on the collaboration of researchers. The graph # groups researchers based on wich faculty they belong to and weighs edges # based on repeated collaborations. def rows(db_path, query): ...
f7d06cba65aeb2982ed5a8c7b23a6ac8111bf679
Diamond-Bagel/Cool_Python_Stuff
/password_generator.py
667
3.953125
4
# The string module is very useful # string.ascii_letters is A-Z and a-z # string.digits is 0-9 # string.punctuation is everything else except for whitespace characters def generate_password(length): import random, string chars = string.ascii_letters + string.punctuation + string.digits password = ''.join(...
b0bf05668ed30c4d38b60e3807863d5db4231585
nzevgolisda/tavli.py
/main.py
1,635
3.515625
4
from Dice import Dice from Square import Square from Board import Board from Player import Player from Game import Game import time from datetime import datetime #from Game1 import Game1 #from Game2 import Game2 player1 = Player('p1') player2 = Player('p2') game0 = Game(player1, player2) #game0 = Game1(player1, playe...
f4cbfb4ad57f17bd252d930196d2a2a629921a67
llewyn-jh/data_structure-algorithm
/ls_palindrome_linked_list.py
847
3.875
4
"""Palindrome linked list, #234, level 1 A script won't be able to run. Use only it for a reference.""" def is_palindrome_v1(head) -> bool: """Use slicing""" pal = [] node = head # Change a linked list for a list while node is not None: pal.append(node.val) node = node.next # ...
a83c877280e39bc959ff63f14f579f7102cafbb0
llewyn-jh/data_structure-algorithm
/ls_reverse_linked_list2.py
783
3.796875
4
"""Reverse linked list 2, leetcode #92""" # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverse_between(self, head, left, right): """ :type head: ListNode ...
1d29dd32b340d788ede38ff56d99145227d11fbe
mcuntz/jams_python
/jams/apply_undef.py
4,990
3.609375
4
#!/usr/bin/env python from __future__ import division, absolute_import, print_function import numpy as np __all__ = ['apply_undef'] def apply_undef(func, undef, *args, **kwargs): """ Use a function on arguments masked with undef. Arguments will be masked with undef (masked arrays) and then ...
f7d2325673054824be29ed8108cf0f79ec2d626f
mcuntz/jams_python
/jams/closest.py
2,689
3.859375
4
#!/usr/bin/env python """ closest : Index of an array (arr) at which the entry is closest to a given number (num), which is `argmin(abs(arr-num))`. This module was by Matthias Cuntz while at Department of Computational Hydrosystems, Helmholtz Centre for Environmental Research - UFZ, Leipzig, Germany, and con...
a9c6c8bb053072d44cba19631d285b7f07e8c6ee
mcuntz/jams_python
/jams/pi.py
9,591
3.796875
4
#!/usr/bin/env python from __future__ import division, absolute_import, print_function import numpy as np def pi(s=None, m=None, norm=None, b=False, evalues=False, ematrix=False): """ Calculates the parameter importance index PI or alternatively the B index. The indices can be normalised and the no...
f24198b63d72436073af24013c36a61e796ccec8
mcuntz/jams_python
/jams/division.py
4,531
3.71875
4
#!/usr/bin/env python """ division : Divide two arrays, return `otherwise` if division by 0. This module was written by Matthias Cuntz while at Department of Computational Hydrosystems, Helmholtz Centre for Environmental Research - UFZ, Leipzig, Germany, and continued while at Institut National de Recherche pour l'Agr...
0066896061f4a591cdabd63cda13251929f325be
mcuntz/jams_python
/jams/heaviside.py
3,625
3.71875
4
#!/usr/bin/env python from __future__ import division, absolute_import, print_function import numpy as np def heaviside(x, value=1., unitstep=False, zero=False): """ Heaviside (or unit step) operator H = 0 for x < 0 H = 1/2 for x = 0 H = 1 for x > 0 if u...
086fe0d83e480342c30a3789b349f2c069adc5de
jin/project-euler
/python/0007.py
508
3.90625
4
# 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 10001st prime number? import math import time start = time.time() def isPrime(val): i = 3 while (i<(val/2)): if (val % i == 0): return False else: i += ...
a602bd8636c97ca2eb71d391c29d170cb43bdfc2
jin/project-euler
/python/0002.py
546
3.625
4
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. maxLi...
593563b016a81afcb921a52c656f8b19fd87f67f
jin/project-euler
/python/0010.py
664
3.859375
4
#=============================================================================== # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. #=============================================================================== import time import math start = time.time() p...
609eefe85ef993b1bdb08d9c00f430776ed55078
migsmartinez/PyCollab
/Personal/MarkC/Challenge_295_Easy/Challenge_295_Easy.py
497
3.5
4
def challenge295(strA: str, strB: str) -> None: #always print the original first argument print(strA) #testing enumeration by zipped strings just for fun for i, v in enumerate(zip(strA, strB)): #do not print if chars in the same position are the same if (v[0] != v[1]): #test...
e9e022150f330c19b39acb60ff3b424df66f4517
ijly188/pythontraining
/modules/geometry.py
250
3.921875
4
# 在 geometry 模組中定義幾何運算功能 # 計算兩點的距離 def distance(x1, y1, x2, y2): return ( ( x2 - x1 ) ** 2 + ( y2 - y1 ) ** 2 ) ** 0.5 # 計算線斷的斜率 def slope(x1, y1, x2, y2): return ( y2 - y1 ) / ( x2 - x1 )
e026dd48661755cad86e02682cd3002189cbd602
ijly188/pythontraining
/7_loop-control.py
990
3.703125
4
# break 的簡易範例 # n=0 # while n < 5: # if n == 3: # break # print(n) # 印出迴圈中的 n # n+=1 # print("最後的 n:", n) # 印出迴圈結束後的 n # continue 的簡易範例 # n = 0 # for x in [ 0, 1, 2, 3 ]: # if x % 2 == 0: # 取餘數除以二為零,取偶數的概念 # continue # print(x) # n += 1 # print("最後...
b3d4d9941b1947380a3618025590a81811277e25
ijly188/pythontraining
/10_module.py
1,681
3.625
4
# 獨立的程式檔案 # 把一段程式寫在一個檔案中,讓這段程式可以被重複載入使用 # 載入模組的基本語法 # 就是import 模組名稱(不加.py) # import 名稱 as 別名 # 基本語法 # import 模組名稱 as 模組別名 # import 模組名稱 # 模組名稱/別名.函式名稱(參數資料) # 模組名稱或別名.變數名稱 # 內建模組 # sys 模組 # 取得系統重要資訊 # 載入 sys 模組 # import sys # 使用 sys 模組 # print(sys.platform) # 印出作業系統 # print(sys.maxsize) # 印出整數型態的最大值 # print...
e45c4624b7741e2a1e76f1a7421df1cbe8f8a43a
PierreAbouSerhal/Jeu_De_La_Vie
/board.py
4,565
3.84375
4
import tkinter as tk from tkinter import * from cell import Cell # Game board object class Board: BG = "grey30" BGALIVE = "red" BGDEAD = "white" def __init__(self, frame, cellD=70, col=10, row=10): ''' Board have 3 argumetns: frame: parent of the canvas cellD: s...
43287eef521298dd2712322c66f4b7665d2010bf
dietherdayondon/CSC124
/lcsubsequence.py
653
3.546875
4
def lcs(X , Y): m = len(X) n = len(Y) string = "" L = [[None]*(n+1) for i in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0 : L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 ...
9879e0f311e9c2426cbc0803fa7053963aa3d580
Dualve/XO-new-version
/start_game.py
5,891
3.859375
4
x = "X" o = "O" empty = " " tie = "Ничья" num_squares = 9 def Start_instruction(): """ Документирующая инструкция: Вывод правил игры. """ print( """ Добро пожаловать в игру крестики нолики.Эта игра была создана очень давно. Наверное ваши бабушки и дедушки играли в неё.Прави...
5b24c0125222d86364463ad1ceb2c4131b100afd
rachelzachariash/DNA-command-line
/sequence_creation/dup.py
1,430
3.65625
4
from general.command import Command from general.dnaSequence import DnaSequence '''get a id or name and gets the id and duplicate it and add new dna ''' class Dup(Command): def __init__(self, command): super().__init__(command) ''' check if the command is valid and find the dna of the name of i...
9fd80e8662a3ee1933c9cd55e40e9f8c5614a631
rachelzachariash/DNA-command-line
/sequence_analysis/count.py
1,055
3.609375
4
import re from general.command import Command from general.dnaSequence import DnaSequence ''' count how many times a dna sub string in a dna string''' class Count(Command): def __init__(self, command): super().__init__(command) ''' check that the input in valid id of name of DNA and s...
18d50476009cbd4138786d0a356562474060e763
SUBATHRAMURUGAN/code
/s27.py
133
3.71875
4
nm=int(input()) sm=0 tem=nm while tem>0: digi=tem%10 sm += digi**3 tem//=10 if nm==sm: print("yes") else: print("no")
11c73a430c3ed543725bbdc717e0cf5fcee741ae
SUBATHRAMURUGAN/code
/pros2q9.py
173
3.5625
4
sz=int(input()) array=[] for i in range(sz): t=input() t=list(map(int,t.split(" "))) l=len(t) for j in range(l): array.append(t[j]) array.sort() print(*array,sep=" ")
2fa1081a19185eb58d429b0494a55005fe077c0c
luisito1295/Python
/Numero mayor.py
412
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 17 20:39:51 2018 @author: luisl """ print("Adivinar cual es el numero mayor"); a=int(input("Ingrese el numero A: ")) b=int(input("Ingrese el numero B: ")) c=int(input("Ingrese el numero C: ")) if a>b and a>c: print("A es el mayor") elif b>a and b>c: print("B es...
8b02a7cbadf04c46a53456b4b9442fa70ff849e3
dcarrot2/lastcstproject
/mysite/populate.py
2,690
3.9375
4
##The purpose of this script is to populate database with data we need. ##It's a more autonomous process that can immediately populate the database ##in case the database file is deleted or needed to be deleted #This script crawls a webpage with countries and stores the countries into a list import os def populate...
9f386c152d98fe3eb636d770997e0a790d51a765
yujianyuanhaha/Radar-DQN
/PyClass2.py
1,230
3.5
4
class VehicleClass(): def __init__(self,*argv): #constructor #*Argv is a variable number of inputs #nargin does not exist (as far as i know) #can make by #nargin = len(argv) import numpy as np self.Velocity = np.array([0,0],dtype=float) try: self...
dee9b44b301c333cd39a4f05808b6e3aa1621075
LeeSinCOOC/My_File_Library
/Python_排序算法/selection.py
729
4.125
4
def selection_sort(arr): ''' 1.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置 2.然后,再从剩余未排序元素中继续寻找最小(大)元素 3.然后放到已排序序列的末尾。 4.以此类推,直到所有元素均排序完毕。 ''' for i in range(len(arr)-1): minIndex=i for j in range(i+1,len(arr)): if arr[minIndex]>arr[j]: minIndex=j if i=...
430f1e6ba46bae103eeeebd76c8c450b9437911b
SSevenTwo/data_visualization
/data_visualization/dice_roll_probability/dice.py
324
3.5625
4
from random import randint class Die(): """Class representing a die""" def __init__(self,sides = 6): """Initializes die attributes""" self.sides = sides def roll(self): """Return a value between 1 and the number of sides""" return randint(1,self.side...
018dad95258701854f038bb19ab2c5605c6ffdb8
lisa0826/pyDataAnalysis
/02/fun.py
1,920
3.953125
4
# -*- coding: utf-8 -*- #1. 编写函数,要求输入x与y,返回x和y的平方差 def squarefeet( arg1, arg2 ): # 返回2个参数的和." res = arg1 ** 2 - arg2 ** 2 return res; # 调用平方差函数 res = squarefeet( 5, 8 ); print("平方差 : ", res) #2. 计算1到100的平方的和 i = 1 sumVal = 0 while (i<=100): sumVal += i ** 2 i += 1 print(sumVal) #3. 编写函数,若输入为小于100的数,返回T...
0ef3a2a725390bd949c87f3e3062acaed138d47b
YorickSpenrath/PKDD2020
/functions/data_integrity.py
4,815
4.21875
4
import hashlib import os from pathlib import Path from functions import file_functions """ Creates, prints, and verifies 'hash_dict's, Which capture the structure of a folder and save hashes of files in the folder A Hash Dict is a dictionary, created from a folder. The keys of the Hash Dict are the children (folders...
c88009f54dc9205a942e4f87c1cb948a087e8541
auhide/mp-tictactoe
/src/guest_client.py
7,724
4.03125
4
'''The client side for my Server-Client Tic-Tac-Toe Application.''' import re import os import socket from tictactoe_constants import (BUFFER_SIZE, IP, PORT, GAME_DISPLAY, WINNING_COMBOS, ...
42789dff94668227520ab186bfc1353c341fbb54
pacellyjcax/ProgrammingChallenge
/URI/1329 - Cara ou Coroa.py
251
3.5
4
res = [] while 1: n = int(raw_input()) if n == 0: break e = [int(x) for x in raw_input().split()] res.append((e.count(0),e.count(1))) for e in res: print "Mary won {0:d} times and John won {1:d} times".format(e[0],e[1])
4cc214e94e8b35071a3a4768f20065fc68a52bce
pacellyjcax/ProgrammingChallenge
/URI/1064 - Positivos e Média.py
190
3.515625
4
en = [float(raw_input()) for i in range(6)] vp = 0 vc = 0 for i in range(6): if en[i]>0: vp+=en[i] vc+=1 print str(vc)+" valores positivos" print "{0:.1f}".format(vp/vc)
69e46eee87f3f27ccf4eb2e2a4f4cae4ba72a364
pacellyjcax/ProgrammingChallenge
/URI/1131 - Grenais.py
748
3.578125
4
def addGrenal(l): if l[0]>l[1]: g["Inter"]+=1 elif l[0]<l[1]: g["Gremio"]+=1 else: g["Empates"]+=1 g = {"Inter":0,"Gremio":0,"Empates":0} addGrenal([int(x) for x in raw_input().split()]) while 1: print "Novo grenal (1-sim 2-nao)" n = int(raw_input()) if n == 2: ...
c3f400abc0408494223bbdcc7d0d261763ac8fb0
pacellyjcax/ProgrammingChallenge
/URI/1040 - média 3 (1).py
553
3.578125
4
line = raw_input().split() a = float(line[0]) b = float(line[1]) c = float(line[2]) d = float(line[3]) media = (a * 2 + b * 3 + c * 4 + d * 1) / 10 print "Media: %.1f" % media if (media > 7.0) : print "Aluno aprovado." elif (media < 5.0) : print "Aluno reprovado." else : print "Aluno em exame." nota = f...
9869f1cffbbe33cdbebfdc9d907d328597fae7f1
pacellyjcax/ProgrammingChallenge
/URI/1221 - Primo Rápido.py
387
3.796875
4
import math def ehPrimo(i): if i%2 ==0: return False rqi = math.ceil(math.sqrt(i)) for x in xrange(3,int(rqi),2): if i%x ==0: return False return True e= int(raw_input()) res = [] for i in xrange(e): d = int(raw_input()) if ehPrimo(d): res.append("Prime") ...
29d4c211a77a143da3511aeee1fc75ad86319568
pacellyjcax/ProgrammingChallenge
/URI/1129 - Leitura Ótica.py
368
3.5625
4
def verificaQuestao(l): v=["A","B","C","D","E"] lrm = [x for x in l if x<=127] if len(lrm)>1 or len(lrm) == 0: return "*" return v[l.index(lrm[0])] res = [] while 1: n = int(raw_input()) if n == 0: break for i in range(n): res.append(verificaQuestao([int(x)for x in ra...
3ec026290473b204b452a7265853da1803a8e883
pacellyjcax/ProgrammingChallenge
/URI/1566 - Altura.py
509
3.84375
4
def qsort(inlist): if inlist == []: return [] else: pivot = inlist[0] lesser = qsort([x for x in inlist[1:] if x < pivot]) greater = qsort([x for x in inlist[1:] if x >= pivot]) return lesser + [pivot] + greater n = int(raw_input()) for i in xrange(n): raw_input() ...
a6ac35456b9ee4ec4b86944be2cf50138ee121ca
pacellyjcax/ProgrammingChallenge
/URI/1043 - Triângulo.py
203
3.5
4
a = [float(x) for x in raw_input().split()] if a[0]+a[1]>a[2] and a[0]+a[2]>a[1] and a[2]+a[1]>a[0]: print "Perimetro = %.1f" %(a[0]+a[1]+a[2]) else: print "Area = %.1f" %(((a[0]+a[1])*a[2])/2)
8cc842e9bf6fa548de18d3879de1431e2a1fa2d7
pacellyjcax/ProgrammingChallenge
/URI/1323 - Feynman.py
198
3.5
4
def f(n): r = 0 for i in range(1,n+1): r+=i**2 return r lf = [] while 1: N = int(raw_input()) if N == 0: break lf.append(f(N)) for a in lf: print a
2402ee630147b2b855b0d5b0413bf1bbbdad179c
memomora/Tarea2
/E3_S4.py
2,221
4.3125
4
''' Escriba una función en Python que permita determinar si un número es perfecto o no. Un número perfecto es un número entero positivo cuyo valor es igual a la suma de todos sus divisors enteros positivos. (https://es.wikipedia.org/wiki/Número_perfecto) ''' print("========================================") print("= ...
668d238dafe1d88006a537460769a7385cdab714
Sanchita210507/Class-111-Single-Sample-z-tests-
/school.py
4,198
3.515625
4
import plotly.figure_factory as ff import plotly.graph_objects as go import statistics import random import pandas as pd import csv df = pd.read_csv("school2.csv") data = df["Math_score"].tolist() fig = ff.create_distplot([data],["Math Scores"], show_hist= False) #fig.show() mean = statistics.mean(data) std_deviation...
fffe1fd12b94533ae7703e1ad3f9e6436e383f04
Bluemavim/Data-Analysis
/Numpy/ExerciseNumPy4.py
570
3.890625
4
#Encontrar los índices que no son ceros del arreglo [1,2,4,2,4,0,1,0,0,0,12,4,5,6,7,0]. import numpy as np numeros = [1,2,4,2,4,0,1,0,0,0,12,4,5,6,7,0] arreglo = np.array(numeros) print(np.nonzero(numeros)) #Other way using list comprehension: indices_de_ceros = [index for index in range(len(arreglo)) if arreglo[ind...
bce7400f514af1f037f655f12c760bbed48b8d22
Bluemavim/Data-Analysis
/Numpy/ExerciseNumPy13.py
314
3.859375
4
#13.Crear dos arreglos de 6 elementos de valores aleatorios entre 0 y 1 y # luego realizar las operaciones lógicas and y or con los métodos de NumPy. import numpy as np array_1 = np.random.randint(6) array_2 = np.random.randint(6) print(np.logical_and(array_1, array_2)) print(np.logical_or(array_1, array_2))
b6cc8430b13ab9861cd8a34d10e9473fe4479ba2
olgut/Python
/findunique.py
253
3.828125
4
# finds the unique element of a given array def findunique(array): if len(array)==1: return array for i in range(len(array)): duplicate =[j for j in array if j==array[i]] if len(duplicate)<2: return duplicate
53f1c9eee659d35d7ed4b563d21a6e4502d811e5
nolanroosa/intermediatePython
/hw21.py
1,835
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 12 16:59:35 2020 @author: nolanroosa """ # Question 1 import pandas as pd pop = pd.read_csv("/Users/nolanroosa/Desktop/Python/pop.csv") def menu(): print (''' Population Menu: 1. Display the entire...
2e237dde16ed0cede5ca655726d8e27198d200bb
ms2020bgd/malick_g
/Lesson2/exo_cc_lesson1.py
6,422
3.875
4
import math import unittest # Given a string and a non-negative int n, return a larger string # that is n copies of the original string. # Example: string_times("hey", 3) should return "heyheyhey" def string_times(string, n): return string*n # Write a function which returns True if a year is a leap year. # A ye...
3740aaa8dedc7e039c4b77ef1776f1dabfb6529f
alexsmith922/higher-or-lower-game
/main.py
1,231
3.625
4
#import logo art from art import logo import random # data range = range(0,49) #import vs art from art import vs #import game data from game_data import data print(logo) random1 = random.randint(0,49) random2 = random.randint(0,49) #pick two instagrammers to compare def game(): influencer_a_name = data[random1]...
a919da9070e704a1df745ab968c36bbe6a1776f0
DRZN/Algorithms
/DynamicProgramming/generate_parentheses.py
1,054
3.65625
4
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ d={} d[0]=[""] d[1]=["()"] for num in range(2,n+1): prev=num-1 k=[] for combination in d[prev]: for i ...
e50af84ac8ce77f08597c3ef94481e5aef55fd48
yogeshBsht/CS50x_Plurality
/Plurality.py
1,469
4.34375
4
# Plurality max_candidates = 5 candidates = ['Lincoln', 'Kennedy', 'Bush', 'Obama', 'Trump', 'Biden'] # Taking number of candidates as input flag = 1 while flag: num_candidates = int(float(input("Enter number of candidates: "))) if num_candidates < 2: print("Value Error! At least 2 candidate...
64e85949c240bb136e22d39e7971830597da1625
wubinbai/2019
/b/book/trick_python/template_string.py
170
3.625
4
from string import Template t = Template("Hey, $name!") print(t.substitute(name='wubin')) print('When to use t emplate string? When yoiu need security. E.g. user input')
4366f612f2126cd4ff9b38d1e88d53fd53e8b621
wubinbai/2019
/a/1_winter_2019/proj/Andrew_Ng/Regularization_and_Overfitting/overfitting.py
1,050
3.875
4
import numpy as np import matplotlib.pyplot as plt # Assuming we have dataset x=np.linspace(0,10,20) y=np.sqrt(x)+np.random.random(20) # First plot them plt.plot(x,y) # plt.show() # Suppose we want to fit them to the 6th polynomial y = theta0 + theta1 * x + theta2 * x**2 + ... + theta6 * x**2 # Using Gradient Descent #...
dea1eabbb34f626b0ea179c659160ddab4803a0b
wubinbai/2019
/b/book/trick_python/classPizza.py
687
3.703125
4
import math class Pizza: def __init__(self, radius, ingredients): self.ingredients = ingredients self.radius = radius def __repr__(self): return (f'Pizza({self.radius!r}, ' f'Pizza({self.ingredients!r})') def area(self): return self.circle_area(self.radius)...
80871e0420188918a7038e86194d7785ccf62f5e
chrylzzz/first_py
/day10/4.高阶函数.py
1,159
3.921875
4
""" 高阶函数:把函数作为参数传入 内置高阶函数: """ import functools # 绝对值 print(abs(-10)) # 四舍五入 print(round(1.2)) # f为函数 def sum_num(a, b, f): return f(a) + f(b) res = sum_num(-1, -4, abs) print(res) ############# print('-------内置 高阶 函数') # map(func,lst): 传入的函数 作用到每个元素中,并将结果组成新的 列表(py2)/迭代器(py3) 返回,可以用list(转换列表) list1 = [1, 2,...
43b109550c3fff67beac8fc6c0a769e06599d1f2
chrylzzz/first_py
/day13/8.类方法和静态方法.py
687
4
4
""" 类方法: @classmethod来表示为类方法,第一个参数是类对象,一般用cls作为第一个参数 类方法一般用作 私有类属性/类属性,定义类方法 静态方法: @staticmethod来修饰,可以通过类和对象访问 当一个方法不需要参数传递(形参无self/cls),就可以定义为静态方法,减少参数传递,减少内存占用 """ class Dog(object): __tooth = 10 @classmethod def get_tooth(cls): return cls.__tooth @staticmethod # 注意不传递...
a257bf444797ac8d17c43fefd19455c3778b54ab
chrylzzz/first_py
/day4/3.切片.py
883
3.640625
4
""" 切片:操作对象其中的一部分操作:字符串,列表,元组都支持切片 序列[开始位置下标:结束为止下标:步长] 注意: 不包含结束为止下标对应的数据,正负数都可以, 步长是选取的间隔(每隔多少个字符),正负数均可以,默认为1 """ str1 = "aksircmw" print(str1[2:4]) print(str1[2:4:1]) print(str1[2:4:2]) print(str1[2:8:2]) # 特殊写法 print(str1[:5]) # 不写开始默认从0开始 print(str1[2:]) # 不写结束默认选取到结束 print(str1[:]) # 从头选到尾,选取所有 ...
e36ffd54fad728f11cafe5e8201084b97c79d8e0
chrylzzz/first_py
/day11/2.文件备份.py
762
3.859375
4
""" 文件备份: 组织备份的文件名 数据写入 """ old_name = input('输入文件名: ') # 文件后缀下标 index = old_name.rfind('.') # 判断文件是否有效 if index > 0: # 获得文件名 --切片 file_old_name = old_name[:index] # 获得文件的后缀名 file_old_type = old_name[index:] # 新文件名字 new_name = file_old_name + '[备份]' + file_old_type # 操作文件 # 打开旧文件 2进制打开 old_fi...
a4689a39d44e8419b4e872687588e5ac33d4e9d6
chrylzzz/first_py
/day5/3.元组.py
858
4
4
""" 元组: 不可修改 一个元组内的数据是不能修改的,只支持查找,不支持修改,()里的️支持修改, 但是([],[]),元组里的列表,是可以修改的. 查找操作: 下标查找:t1[0] 查找某个数据:t1.index(数据) , 没有数据就报错 .count(数据)统计数据在元祖出现的次数 len(tuple元组) 元组的长度 """ t1 = (1, 2, 3, 77, 22, 443) # 多个数据 print(t1) t2 = (1,) # 单个数据,必须放一个, 才能保证是一个元组 t3 = (1) t4 = ('loo') # 不加, 数据类型为唯一的这个数据的数据类...
9a8686df420357ee5df29a2d351bc47d9502c9af
chrylzzz/first_py
/day14/3.自定义异常.py
550
4.15625
4
""" 抛出自定义异常的语法为 raise 异常类对象 """ ##长度小于3抛出异常 class SIError(Exception): def __init__(self, len, min_len): self.len = len self.min_len = min_len def __str__(self): return f'你输入的长度是{self.len},不能少于{self.min_len}' def main(): try: con = input('输入密码: ') if len(con) < ...
aa50f32abc68026c21e57f4fd45f6ae6d8f6a46f
chrylzzz/first_py
/day11/3.文件操作函数.py
597
4
4
""" 文件和文件夹: os """ import os # 文件/文件夹 重命名 # os.rename('1.c.txt', '10.c.txt') # 文件/文件夹 删除 # os.remove('10.c.txt') # 创建文件夹, 文件和文件夹不能重名 # os.mkdir('aa') # 删除文件夹 # os.rmdir('aa') # 获取当前目录:返回当前文件所在的目录 # getcwd = os.getcwd() # print(getcwd) # 改变默认目录:进入目录 # os.mkdir('bb') # os.chdir('bb') # os.mkdir('zz') # 获取目录列表:...
0351418fc2da90e015b3ccaf0e183de4ec3f7784
chrylzzz/first_py
/day8/1.运算符.py
337
3.765625
4
""" """ str1 = 'aa' str2 = 'aba' list1 = [1, 2] list2 = [5, 2] # +: 合并 ,支持:字符串,列表,元组,不支持字典 print(str1 + str2) print(list1 + list2) # *: 复制 ,支持:字符串,列表,元组 print(str2 * 4) print(list1 * 4) # in /not in :元素是否存在 ,支持:字符串,列表,元组,字典 print('a' in str2)
ed298e320078bac8ea3d6fe56a57ab5f1db0f98e
vning93/AI_HW3
/testers.py
20,150
3.625
4
from negotiator_base import BaseNegotiator from random import random, shuffle, randint from functools import reduce # Example negotiator implementation, which randomly chooses to accept # an offer or return with a randomized counteroffer. # Important things to note: We always set self.offer to be equal to whatever # w...
a1572eb8973d038e057ed025ba8db15c32bcd6b9
space4pratyush/Python
/averageweight.py
732
3.890625
4
w1=int(raw_input("Enter First person weight")) w2=int(raw_input("Enter second person weight")) w3=int(raw_input("Enter third person weight")) w4=int(raw_input("Enter fourth person weight")) w5=int(raw_input("Enter fifth person weight")) w6=int(raw_input("Enter sixth person weight")) w7=int(raw_input("Enter seventh pers...
1b5d3c01b9caaa7cb2f02c3b2a48ba449e4dcb9f
Coriaa/Mision_03
/Trapecio.py
678
3.625
4
#Mariana Coria Rodríguez A01374765 # Área y perimetro de un trapecio def area(bm, bn, a): areatotal = ((bm+bn)/2)*a return areatotal def hipotenusa(bm, bn, a): base = (bm - bn)/2 hipo = (base**2 + a**2)**0.5 return hipo def perimetro(bm, bn, hipo): perimetroTotal = bm + bn + hipo*2 retu...
5108563f9559908a107ed997a4705a7bf6bc81bb
ismailm98/Password-Generating-program
/password_generator.py
636
3.765625
4
import random chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456!@#$%^&*()" users = ['user1', 'user2', 'user3'] users_count = 0 for i in users: users_count = users_count + 1 pass_len = int(input("Password length = ")) pass_count = users_count user_passwords={} for user in users: # ...
b09d37f42a6b4ece7d86614097e72cb6be8ac85d
R29yZG9u/maths
/fibonacci.py
554
3.9375
4
def fib(n1,n2,count,n_len,a): if n_len <= 0: print("Please enter a positive integer") elif n_len == 1: print("Fibonacci sequence upto",n_len,":") print(n1) else: pass if count < n_len: a.append(n1) nth = n1 + n2 # update values ...
5895ac1c8e04d5dea7702a5780c461be6cb9c38b
pgr2015/algorithm_practice
/sorting/quick_sort.py
1,061
3.609375
4
import numpy def quickSortRecursive1(arr, low, high): if low >= high: return pivot = arr[low] left, right = low, high while left < right: while left < right and arr[right] > pivot: right -= 1 arr[left] = arr[right] while left < right and arr[left] <= pivot: ...